Open History to see the last commit
1import { BindingFlags } from 'yuku-analyzer'
2import { b, bindingIdentifiers, is, nameOf, walk } from 'yuku-ast'
3import { generatedReferenceOf } from './ast'
4import type { Binding, Module, Scope } from 'yuku-analyzer'
5import type { Expression, Node, Program } from '@yuku-toolchain/types'
6β
7export interface ModuleDeclarationGraph {
8 /** The statement of its own scope declaring each binding, if any. */
9 declarations: Map<Binding, Node>
10 dependencies: Map<Binding, Set<Binding>>
11 /** Every removable declaration, including `var` nested in statements. */
12 declarationSymbols: Map<Node, Set<Binding>>
13}
14β
15/** Runtime references resolved by Yuku, including JSX and excluding shadowed names. */
16export function collectModuleReferences(
17 module: Module,
18 node: Node,
19): Set<Binding> {
20 const references = new Set<Binding>()
21 module.walk(
22 {
23 enter(current) {
24 const reference = module.referenceOf(current)
25 if (
26 reference &&
27 !reference.inTypePosition &&
28 reference.binding?.scope === module.rootScope
29 ) {
30 references.add(reference.binding)
31 }
32 },
33 },
34 node,
35 )
36 return references
37}
38β
39/** The node that declares an identifier and goes when its bindings do. */
40function declarationOf(module: Module, identifier: Node): Node | undefined {
41 let current: Node | null = identifier
42 while (current) {
43 if (is.VariableDeclarator(current)) {
44 // A for-in or for-of loop assigns its head on every iteration
45 const statement = module.parentOf(current)
46 const parent = statement && module.parentOf(statement)
47 return is.ForInStatement(parent) || is.ForOfStatement(parent)
48 ? undefined
49 : current
50 }
51 if (is.TSEnumDeclaration(current) || is.TSModuleDeclaration(current)) {
52 return current.id === identifier ? current : undefined
53 }
54 if (
55 is.FunctionDeclaration(current) ||
56 is.ClassDeclaration(current) ||
57 is.TSDeclareFunction(current)
58 ) {
59 return current.id === identifier ? current : undefined
60 }
61 if (
62 is.ImportSpecifier(current) ||
63 is.ImportDefaultSpecifier(current) ||
64 is.ImportNamespaceSpecifier(current)
65 ) {
66 return current
67 }
68 if (is.Function(current) || is.Class(current) || is.Program(current)) {
69 return undefined
70 }
71 current = module.parentOf(current)
72 }
73 return undefined
74}
75β
76/**
77 * Whether a declaration is a statement of its binding's own scope. A `var`
78 * nested in another statement, such as a block or a loop head, initializes as
79 * part of that statement: its declarator can be removed from it, but the
80 * binding has no declaration to move or import on its own.
81 */
82function declaresInOwnScope(
83 module: Module,
84 binding: Binding,
85 declaration: Node,
86): boolean {
87 if (!is.VariableDeclarator(declaration)) {
88 return true
89 }
90 let container = module.parentOf(module.parentOf(declaration)!)
91 if (is.ExportNamedDeclaration(container)) {
92 container = module.parentOf(container)
93 }
94 const scope = module.scopeOf(declaration)
95 return (
96 (is.Program(container) ||
97 is.BlockStatement(container) ||
98 is.StaticBlock(container) ||
99 is.SwitchCase(container) ||
100 is.TSModuleBlock(container)) &&
101 (binding.scope === scope ||
102 (scope.kind === 'functionBody' && binding.scope === scope.parent))
103 )
104}
105β
106interface DeclarationIndex extends Pick<
107 ModuleDeclarationGraph,
108 'declarations' | 'declarationSymbols'
109> {
110 /**
111 * Destructuring elements that can be dropped on their own, with the bindings
112 * each declares: array pattern elements, and properties of object patterns
113 * without a rest element (dropping one would change what the rest collects).
114 */
115 patternElements: Map<Node, Set<Binding>>
116}
117β
118function addOwner(
119 owners: Map<Node, Set<Binding>>,
120 node: Node,
121 binding: Binding,
122) {
123 const bindings = owners.get(node) ?? new Set<Binding>()
124 bindings.add(binding)
125 owners.set(node, bindings)
126}
127β
128function declarationIndex(
129 module: Module,
130 bindings: Array<Binding>,
131): DeclarationIndex {
132 const declarations = new Map<Binding, Node>()
133 const declarationSymbols = new Map<Node, Set<Binding>>()
134 const patternElements = new Map<Node, Set<Binding>>()
135 for (const binding of bindings) {
136 // Parameters belong to their function or signature, never to a statement,
137 // even when a signature sits in a declaration's type arguments
138 if (binding.flags & (BindingFlags.Parameter | BindingFlags.TypeParameter)) {
139 continue
140 }
141 for (const identifier of binding.declarations) {
142 const declaration = declarationOf(module, identifier)
143 if (!declaration) {
144 continue
145 }
146 const previous = declarations.get(binding)
147 if (
148 declaresInOwnScope(module, binding, declaration) &&
149 (!previous ||
150 (is.TSDeclareFunction(previous) &&
151 !is.TSDeclareFunction(declaration)))
152 ) {
153 declarations.set(binding, declaration)
154 }
155 addOwner(declarationSymbols, declaration, binding)
156 if (is.VariableDeclarator(declaration)) {
157 let element: Node = identifier
158 while (element !== declaration.id) {
159 const pattern = module.parentOf(element)!
160 if (
161 is.ArrayPattern(pattern) ||
162 (is.ObjectPattern(pattern) &&
163 !pattern.properties.some((property) => is.RestElement(property)))
164 ) {
165 addOwner(patternElements, element, binding)
166 }
167 element = pattern
168 }
169 }
170 }
171 }
172 return { declarations, declarationSymbols, patternElements }
173}
174β
175/** Bindings sharing a declarator are one initialization unit. */
176export function moduleDeclarationGraph(module: Module): ModuleDeclarationGraph {
177 const { declarations, declarationSymbols } = declarationIndex(
178 module,
179 module.rootScope.bindings,
180 )
181 const dependencies = new Map<Binding, Set<Binding>>()
182 for (const [declaration, owners] of declarationSymbols) {
183 const references = collectModuleReferences(module, declaration)
184 for (const binding of owners) {
185 const combined = dependencies.get(binding) ?? new Set<Binding>()
186 for (const reference of references) {
187 if (reference !== binding) {
188 combined.add(reference)
189 }
190 }
191 dependencies.set(binding, combined)
192 }
193 }
194 return { declarations, declarationSymbols, dependencies }
195}
196β
197export function expandTransitively<T>(
198 roots: Set<T>,
199 dependencies: Map<T, Set<T>>,
200): Set<T> {
201 const expanded = new Set(roots)
202 for (const item of expanded) {
203 for (const dependency of dependencies.get(item) ?? []) {
204 expanded.add(dependency)
205 }
206 }
207 return expanded
208}
209β
210/** Erase imports/exports that exist only in TypeScript's type space. */
211export function stripTypeExports(program: Program): void {
212 program.body = program.body.filter((statement) => {
213 if (is.ImportDeclaration(statement)) {
214 if (statement.importKind === 'type') {
215 return false
216 }
217 const hadSpecifiers = statement.specifiers.length > 0
218 statement.specifiers = statement.specifiers.filter(
219 (specifier) =>
220 !is.ImportSpecifier(specifier) || specifier.importKind !== 'type',
221 )
222 return !hadSpecifiers || statement.specifiers.length > 0
223 }
224 if (is.ExportAllDeclaration(statement)) {
225 return statement.exportKind !== 'type'
226 }
227 if (is.ExportNamedDeclaration(statement)) {
228 if (
229 statement.exportKind === 'type' ||
230 is.TSInterfaceDeclaration(statement.declaration) ||
231 is.TSTypeAliasDeclaration(statement.declaration)
232 ) {
233 return false
234 }
235 const hadSpecifiers = statement.specifiers.length > 0
236 statement.specifiers = statement.specifiers.filter(
237 (specifier) => specifier.exportKind !== 'type',
238 )
239 return (
240 !!statement.declaration ||
241 !hadSpecifiers ||
242 statement.specifiers.length > 0
243 )
244 }
245 return true
246 })
247}
248β
249export interface RemoveUnusedBindingsOptions {
250 roots?: Iterable<Binding | string>
251}
252β
253interface BindingUses {
254 /** Declarations present in the traced program. */
255 present: Set<Binding>
256 /** Bindings used outside of any declaration, including exports. */
257 roots: Set<Binding>
258 /** Bindings used by each declaration's own code. */
259 uses: Map<Binding, Set<Binding>>
260 /** Declarations that execute only when their enclosing declaration does. */
261 parents: Map<Binding, Set<Binding>>
262 /**
263 * The owners (null outside of any declaration) of each import's erased
264 * references: references from types, and for an import named `React`, the
265 * JSX that a classic JSX runtime compiles to `React.createElement` calls.
266 */
267 erasedReferences: Map<Binding, Set<Set<Binding> | null>>
268}
269β
270interface JsxFactoryNames {
271 /** Names JSX elements compile to calls of. */
272 element: Array<string>
273 /** Names fragments also compile to references of. */
274 fragment: Array<string>
275}
276β
277const jsxFactoryNamesCache = new WeakMap<Module, JsxFactoryNames>()
278β
279/**
280 * The names a classic JSX runtime compiles JSX to references of, as the
281 * file's `@jsx` and `@jsxFrag` pragmas name them (`React.createElement` β
282 * `React`). `@jsxRuntime automatic` makes them ignored. The default `React`
283 * factory is an erased reference instead (see `BindingUses`).
284 */
285function jsxFactoryNames(module: Module): JsxFactoryNames {
286 let names = jsxFactoryNamesCache.get(module)
287 if (!names) {
288 names = { element: [], fragment: [] }
289 if (
290 !module.comments.some((comment) =>
291 /@jsxRuntime\s+automatic\b/.test(comment.value),
292 )
293 ) {
294 for (const comment of module.comments) {
295 for (const [, pragma, name] of comment.value.matchAll(
296 /@(jsx|jsxFrag)\s+([\p{L}\p{N}_$]+)/gu,
297 )) {
298 names[pragma === 'jsx' ? 'element' : 'fragment'].push(name!)
299 }
300 }
301 }
302 jsxFactoryNamesCache.set(module, names)
303 }
304 return names
305}
306β
307function jsxFactoriesOf(names: JsxFactoryNames, node: Node): Array<string> {
308 return is.JSXFragment(node)
309 ? [...names.element, ...names.fragment]
310 : names.element
311}
312β
313function addEdge(
314 edges: Map<Binding, Set<Binding>>,
315 from: Binding,
316 to: Binding,
317) {
318 const targets = edges.get(from) ?? new Set<Binding>()
319 targets.add(to)
320 edges.set(from, targets)
321}
322β
323/**
324 * Runtime uses only: TypeScript erases types, so they neither use a declaration
325 * nor keep it alive; erased references to imports are recorded apart.
326 * `originOf` maps a traced node to its source node, if any.
327 */
328function collectBindingUses(
329 module: Module,
330 program: Program,
331 index: DeclarationIndex,
332 originOf: (node: Node) => Node | undefined,
333): BindingUses {
334 const byName = new Map(
335 module.rootScope.bindings.map((binding) => [binding.name, binding]),
336 )
337 const result: BindingUses = {
338 present: new Set(),
339 roots: new Set(),
340 uses: new Map(),
341 parents: new Map(),
342 erasedReferences: new Map(),
343 }
344 const reactImport = byName.get('React')
345 const factories = jsxFactoryNames(module)
346 const erasedReference = (owner: Set<Binding> | null, binding: Binding) => {
347 if (binding.has(BindingFlags.Import)) {
348 const owners = result.erasedReferences.get(binding) ?? new Set()
349 owners.add(owner)
350 result.erasedReferences.set(binding, owners)
351 }
352 }
353 const ownerStack: Array<Set<Binding> | null> = []
354 const scopeStack: Array<Scope> = []
355 const use = (owner: Set<Binding> | null, binding: Binding) => {
356 if (!owner) {
357 result.roots.add(binding)
358 return
359 }
360 for (const source of owner) {
361 addEdge(result.uses, source, binding)
362 }
363 }
364 walk(program, {
365 enter(node) {
366 const original = originOf(node)
367 const own = original ? index.declarationSymbols.get(original) : undefined
368 const parentOwner = ownerStack.at(-1) ?? null
369 // A destructuring element's default value and computed key evaluate for
370 // its own bindings; the initializer evaluates for all of them.
371 const owner =
372 own ??
373 (original ? index.patternElements.get(original) : undefined) ??
374 parentOwner
375 ownerStack.push(owner)
376 const scope = original
377 ? module.scopeOf(original)
378 : (scopeStack.at(-1) ?? module.rootScope)
379 scopeStack.push(scope)
380 for (const binding of own ?? []) {
381 result.present.add(binding)
382 for (const parent of parentOwner ?? []) {
383 addEdge(result.parents, binding, parent)
384 }
385 }
386 // Export records are uses even when there are no lexical references. A
387 // transform that removes an export may also remove its declaration graph.
388 const markExport = (identifier: Node) => {
389 const originalIdentifier = originOf(identifier)
390 const binding = originalIdentifier
391 ? module.bindingOf(originalIdentifier)
392 : byName.get(nameOf(identifier) ?? '')
393 if (binding) {
394 use(owner, binding)
395 }
396 }
397 if (is.ExportNamedDeclaration(node) && node.declaration) {
398 const declaration = node.declaration
399 if (is.VariableDeclaration(declaration)) {
400 for (const item of declaration.declarations) {
401 for (const identifier of bindingIdentifiers(item.id)) {
402 markExport(identifier)
403 }
404 }
405 } else if ('id' in declaration && declaration.id) {
406 markExport(declaration.id)
407 }
408 }
409 if (
410 is.ExportDefaultDeclaration(node) &&
411 (is.FunctionDeclaration(node.declaration) ||
412 is.ClassDeclaration(node.declaration)) &&
413 node.declaration.id
414 ) {
415 markExport(node.declaration.id)
416 }
417 if (is.ExportSpecifier(node)) {
418 markExport(node.local)
419 }
420 const reference = original ? module.referenceOf(original) : null
421 if (reference?.inTypePosition && reference.binding) {
422 erasedReference(owner, reference.binding)
423 }
424 if (is.JSXElement(node) || is.JSXFragment(node)) {
425 if (reactImport) {
426 erasedReference(owner, reactImport)
427 }
428 for (const name of jsxFactoriesOf(factories, node)) {
429 const factory = module.lookup(name, { from: scope })
430 if (factory) {
431 use(owner, factory)
432 }
433 }
434 }
435 let binding =
436 reference && !reference.inTypePosition ? reference.binding : null
437 const generated = generatedReferenceOf(node)
438 if (!original && generated) {
439 binding =
440 typeof generated === 'string'
441 ? module.lookup(generated, { from: scope })
442 : generated
443 }
444 if (binding) {
445 use(owner, binding)
446 }
447 },
448 leave() {
449 ownerStack.pop()
450 scopeStack.pop()
451 },
452 })
453 return result
454}
455β
456/**
457 * Declarations that nothing outside their own reference cycle uses at runtime,
458 * such as `const stop = subscribe(() => stop())`. They exist for their side
459 * effects, or for the TypeScript transform to erase, as imports only used in
460 * types (except a classic JSX runtime's `React`, which JSX needs).
461 */
462function findInitiallyUnused({ present, roots, uses }: BindingUses) {
463 // Tarjan's strongly connected components, iterative to bound stack depth
464 const order = new Map<Binding, number>()
465 const lowLink = new Map<Binding, number>()
466 const component = new Map<Binding, Array<Binding>>()
467 const stack: Array<Binding> = []
468 for (const start of present) {
469 if (order.has(start)) {
470 continue
471 }
472 const work: Array<[Binding, Iterator<Binding>]> = []
473 const visit = (binding: Binding) => {
474 lowLink.set(binding, order.size)
475 order.set(binding, order.size)
476 stack.push(binding)
477 work.push([binding, (uses.get(binding) ?? new Set()).values()])
478 }
479 visit(start)
480 while (work.length) {
481 const [binding, targets] = work.at(-1)!
482 const next = targets.next()
483 if (!next.done) {
484 if (!order.has(next.value)) {
485 visit(next.value)
486 } else if (!component.has(next.value)) {
487 lowLink.set(
488 binding,
489 Math.min(lowLink.get(binding)!, order.get(next.value)!),
490 )
491 }
492 continue
493 }
494 work.pop()
495 const caller = work.at(-1)?.[0]
496 if (caller) {
497 lowLink.set(
498 caller,
499 Math.min(lowLink.get(caller)!, lowLink.get(binding)!),
500 )
501 }
502 if (lowLink.get(binding) === order.get(binding)) {
503 const members: Array<Binding> = []
504 let member: Binding
505 do {
506 member = stack.pop()!
507 members.push(member)
508 component.set(member, members)
509 } while (member !== binding)
510 }
511 }
512 }
513 const used = new Set<Array<Binding>>()
514 for (const root of roots) {
515 const members = component.get(root)
516 if (members) {
517 used.add(members)
518 }
519 }
520 for (const [from, targets] of uses) {
521 for (const to of targets) {
522 const members = component.get(to)
523 if (members && members !== component.get(from)) {
524 used.add(members)
525 }
526 }
527 }
528 return new Set(
529 [...present].filter((binding) => !used.has(component.get(binding)!)),
530 )
531}
532β
533interface InitiallyUnused {
534 /** Survive wherever their enclosing code does. */
535 preserved: Set<Binding>
536 /**
537 * Imports only types reference, which survive wherever such a reference (or
538 * the JSX a classic runtime compiles with them) does.
539 */
540 erased: Set<Binding>
541}
542β
543const initiallyUnusedBindings = new WeakMap<Module, InitiallyUnused>()
544β
545function initiallyUnused(module: Module, index: DeclarationIndex) {
546 let unused = initiallyUnusedBindings.get(module)
547 if (!unused) {
548 const uses = collectBindingUses(module, module.ast, index, (node) => node)
549 const all = findInitiallyUnused(uses)
550 const erased = new Set(
551 [...all].filter(
552 (binding) =>
553 binding.has(BindingFlags.Import) &&
554 binding.references.some((reference) => reference.inTypePosition),
555 ),
556 )
557 unused = {
558 preserved: new Set([...all].filter((binding) => !erased.has(binding))),
559 erased,
560 }
561 initiallyUnusedBindings.set(module, unused)
562 }
563 return unused
564}
565β
566/**
567 * Rebuild liveness from surviving nodes, using original binding identity. This
568 * removes dependencies of erased route options without reparsing generated code.
569 * Only declarations the source used, and whose uses the transform erased, are
570 * removed: initially unused ones survive wherever their enclosing code does,
571 * except imports only types reference, which survive with those references.
572 * Callers decide output ownership before invoking this lexical binding cleanup.
573 */
574export function removeUnusedBindings(
575 module: Module,
576 program: Program,
577 originalNodes: WeakMap<Node, Node>,
578 { roots = [] }: RemoveUnusedBindingsOptions = {},
579): void {
580 stripTypeExports(program)
581 const index = declarationIndex(module, module.bindings)
582 const { preserved, erased } = initiallyUnused(module, index)
583 const output = collectBindingUses(module, program, index, (node) =>
584 originalNodes.get(node),
585 )
586 const byName = new Map(
587 module.rootScope.bindings.map((binding) => [binding.name, binding]),
588 )
589 const live = new Set(output.roots)
590 for (const root of roots) {
591 const binding = typeof root === 'string' ? byName.get(root) : root
592 if (binding) {
593 live.add(binding)
594 }
595 }
596 const dependencies = new Map<Binding, Set<Binding>>()
597 for (const [from, targets] of output.uses) {
598 for (const to of targets) {
599 addEdge(dependencies, from, to)
600 }
601 }
602 for (const [binding, parents] of output.parents) {
603 for (const parent of parents) {
604 // A live nested declaration needs its enclosing code to exist
605 addEdge(dependencies, binding, parent)
606 // and a preserved one survives wherever its enclosing code does
607 if (preserved.has(binding)) {
608 addEdge(dependencies, parent, binding)
609 }
610 }
611 }
612 for (const binding of output.present) {
613 if (preserved.has(binding) && !output.parents.has(binding)) {
614 live.add(binding)
615 }
616 }
617 for (const [binding, owners] of output.erasedReferences) {
618 if (!erased.has(binding)) {
619 continue
620 }
621 for (const owner of owners) {
622 if (!owner) {
623 live.add(binding)
624 continue
625 }
626 for (const from of owner) {
627 addEdge(dependencies, from, binding)
628 }
629 }
630 }
631 const retained = expandTransitively(live, dependencies)
632 const removable = new Set(
633 [...output.present].filter((binding) => !retained.has(binding)),
634 )
635 const isRemovable = (node: Node | null) => {
636 const original = node && originalNodes.get(node)
637 const owners =
638 original &&
639 (index.declarationSymbols.get(original) ??
640 index.patternElements.get(original))
641 return !!owners && [...owners].every((binding) => removable.has(binding))
642 }
643 walk(program, {
644 enter(node, context) {
645 if (isRemovable(node)) {
646 context.remove()
647 } else if (is.ObjectPattern(node)) {
648 node.properties = node.properties.filter(
649 (property) => !isRemovable(property),
650 )
651 } else if (is.ArrayPattern(node)) {
652 // Holes keep the positions of the remaining elements
653 node.elements = node.elements.map((element) =>
654 isRemovable(element) ? null : element,
655 )
656 }
657 },
658 leave(node, context) {
659 if (is.VariableDeclaration(node) && node.declarations.length === 0) {
660 // A statement slot, as in `if (x) var y = z`, cannot be left empty;
661 // a statement list, a loop head and an `export` can.
662 if (
663 context.index === null &&
664 context.key !== 'init' &&
665 context.key !== 'declaration'
666 ) {
667 context.replace(b.BlockStatement({ body: [] }))
668 } else {
669 context.remove()
670 }
671 } else if (is.ImportDeclaration(node) && node.specifiers.length === 0) {
672 const original = originalNodes.get(node)
673 if (
674 original &&
675 is.ImportDeclaration(original) &&
676 original.specifiers.length > 0
677 ) {
678 context.remove()
679 }
680 } else if (
681 is.ExportNamedDeclaration(node) &&
682 !node.declaration &&
683 node.specifiers.length === 0 &&
684 !node.source
685 ) {
686 context.remove()
687 }
688 },
689 })
690β
691 const referencedNames = new Set<string>()
692 const factories = jsxFactoryNames(module)
693 walk(program, {
694 enter(node) {
695 if (is.JSXElement(node) || is.JSXFragment(node)) {
696 for (const name of jsxFactoriesOf(factories, node)) {
697 referencedNames.add(name)
698 }
699 }
700 const original = originalNodes.get(node)
701 if (original) {
702 const reference = module.referenceOf(original)
703 if (reference && !reference.inTypePosition) {
704 referencedNames.add(reference.name)
705 }
706 } else {
707 const generated = generatedReferenceOf(node)
708 if (generated) {
709 referencedNames.add(
710 typeof generated === 'string' ? generated : generated.name,
711 )
712 }
713 }
714 },
715 })
716 program.body = program.body.filter((statement) => {
717 if (
718 !is.ImportDeclaration(statement) ||
719 originalNodes.has(statement) ||
720 statement.specifiers.length === 0
721 ) {
722 return true
723 }
724 statement.specifiers = statement.specifiers.filter((specifier) =>
725 referencedNames.has(specifier.local.name),
726 )
727 return statement.specifiers.length > 0
728 })
729}
730β
731export type ModuleInfoBinding =
732 | { type: 'import'; source: string; importedName: string }
733 | { type: 'var'; init: Expression | null }
734β
735export interface ExtractedModuleInfo {
736 bindings: Map<string, ModuleInfoBinding>
737 exports: Map<string, string>
738 reExportAllSources: Array<string>
739}
740β
741/** The bundler owns cross-module resolution; Yuku provides local module records. */
742export function extractModuleInfo(sourceModule: Module): ExtractedModuleInfo {
743 const bindings = new Map<string, ModuleInfoBinding>()
744 const exportBindings = new Map<string, string>()
745 const reExportAllSources: Array<string> = []
746 const graph = declarationIndex(sourceModule, sourceModule.rootScope.bindings)
747 for (const [binding, declaration] of graph.declarations) {
748 bindings.set(binding.name, {
749 type: 'var',
750 init: is.VariableDeclarator(declaration) ? declaration.init : null,
751 })
752 }
753 for (const record of sourceModule.imports) {
754 if (record.local && record.specifier && !record.typeOnly) {
755 bindings.set(record.local.name, {
756 type: 'import',
757 source: record.specifier,
758 importedName: record.isNamespace ? '*' : (record.name ?? 'default'),
759 })
760 }
761 }
762 let syntheticIndex = 0
763 const syntheticName = () => {
764 let name: string
765 do {
766 name = `__module_export_${syntheticIndex++}__`
767 } while (bindings.has(name))
768 return name
769 }
770 for (const record of sourceModule.exports) {
771 if (record.typeOnly) {
772 continue
773 }
774 if (record.kind === 'star' && record.specifier) {
775 reExportAllSources.push(record.specifier)
776 } else if (record.name) {
777 if (record.local) {
778 exportBindings.set(record.name, record.local.name)
779 } else if (record.specifier) {
780 const name = syntheticName()
781 bindings.set(name, {
782 type: 'import',
783 source: record.specifier,
784 importedName:
785 record.kind === 'namespace'
786 ? '*'
787 : (record.fromName ?? record.name),
788 })
789 exportBindings.set(record.name, name)
790 } else if (record.name === 'default') {
791 const statement = sourceModule.ast.body.find(
792 is.ExportDefaultDeclaration,
793 )
794 if (statement) {
795 const declaration = statement.declaration
796 const name = syntheticName()
797 bindings.set(name, {
798 type: 'var',
799 init: is.Expression(declaration) ? declaration : null,
800 })
801 exportBindings.set('default', name)
802 }
803 }
804 }
805 }
806 return { bindings, exports: exportBindings, reExportAllSources }
807}
808β
809export { unwrap as unwrapExpression } from 'yuku-ast'