-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
741 lines (666 loc) · 22.6 KB
/
format.ts
File metadata and controls
741 lines (666 loc) · 22.6 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
import { dirname, join, resolve as pathResolve } from 'node:path'
import { readFile as fsReadFile, stat as fsStat } from 'node:fs/promises'
import type { Node, ParseResult } from 'oxc-parser'
import MagicString from 'magic-string'
import type { ExportsMap } from './helpers/ast.js'
import { hasTopLevelAwait, isAsyncContext } from './helpers/async.js'
import { isIdentifierName } from './helpers/identifier.js'
import { assignmentExpression } from './formatters/assignmentExpression.js'
import { identifier } from './formatters/identifier.js'
import { memberExpression } from './formatters/memberExpression.js'
import { metaProperty } from './formatters/metaProperty.js'
import { buildIdiomaticPlan } from './pipeline/idiomaticPlan.js'
import { buildEsmPrelude } from './pipeline/buildEsmPrelude.js'
import { exportBagToEsm, type WarnOnce } from './pipeline/exportBagToEsm.js'
import {
isRequireCall,
isStaticRequire,
lowerCjsRequireToImports,
type RequireTransform,
} from './pipeline/lowerCjsRequireToImports.js'
import {
lowerEsmToCjs,
type ExportTransform,
type ImportTransform,
} from './pipeline/lowerEsmToCjs.js'
import { buildFormatVisitor, type FormatWalkState } from './pipeline/formatVisitor.js'
import { interopHelper } from './pipeline/interopHelpers.js'
import type { Diagnostic, ExportsMeta, FormatterOptions } from './types.js'
import { collectCjsExports } from './utils/exports.js'
import { collectModuleIdentifiers } from './utils/identifiers.js'
import { isValidUrl } from './utils/url.js'
import { builtinSpecifiers } from './utils/builtinSpecifiers.js'
import { ancestorWalk } from './walk.js'
const isRequireMainMember = (node: Node, shadowed: Set<string>) =>
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'require' &&
!shadowed.has('require') &&
node.property.type === 'Identifier' &&
node.property.name === 'main'
const stripQuery = (value: string) =>
value.includes('?') || value.includes('#') ? (value.split(/[?#]/)[0] ?? value) : value
const packageFromSpecifier = (spec: string) => {
const cleaned = stripQuery(spec)
if (!cleaned) return null
if (cleaned.startsWith('node:')) return null
if (/^(?:\.?\.?\/|\/)/.test(cleaned)) return null
if (/^[a-zA-Z][a-zA-Z+.-]*:/.test(cleaned)) return null
const parts = cleaned.split('/')
if (cleaned.startsWith('@')) {
if (parts.length < 2) return null
const pkg = `${parts[0]}/${parts[1]}`
if (builtinSpecifiers.has(pkg) || builtinSpecifiers.has(parts[1] ?? '')) return null
const subpath = parts.slice(2).join('/')
return { pkg, subpath }
}
const pkg = parts[0] ?? ''
if (!pkg || builtinSpecifiers.has(pkg)) return null
const subpath = parts.slice(1).join('/')
return { pkg, subpath }
}
const fileExists = async (filename: string) => {
try {
const stats = await fsStat(filename)
return stats.isFile()
} catch {
return false
}
}
const findPackageManifest = async (
pkg: string,
filePath: string | undefined,
cwd: string | undefined,
) => {
const startDir = filePath
? dirname(pathResolve(filePath))
: pathResolve(cwd ?? process.cwd())
const seen = new Set<string>()
let dir = startDir
while (!seen.has(dir)) {
seen.add(dir)
const candidate = join(dir, 'node_modules', pkg, 'package.json')
if (await fileExists(candidate)) return candidate
const parent = dirname(dir)
if (parent === dir) break
dir = parent
}
return null
}
const readPackageManifest = async (
pkg: string,
filePath: string | undefined,
cwd: string | undefined,
cache: Map<string, any | null>,
) => {
const start = pathResolve(filePath ? dirname(filePath) : (cwd ?? process.cwd()))
const cacheKey = `${pkg}@${start}`
if (cache.has(cacheKey)) return cache.get(cacheKey)
const manifestPath = await findPackageManifest(pkg, filePath, cwd)
if (!manifestPath) {
cache.set(cacheKey, null)
return null
}
try {
const raw = await fsReadFile(manifestPath, 'utf8')
const json = JSON.parse(raw)
cache.set(cacheKey, json)
return json
} catch {
cache.set(cacheKey, null)
return null
}
}
const analyzeExportsTargets = (exportsField: unknown) => {
const root =
exportsField && typeof exportsField === 'object' && !Array.isArray(exportsField)
? // @ts-expect-error -- loose lookup of root export condition
(exportsField['.'] ?? exportsField)
: exportsField
if (typeof root === 'string') {
return { importTarget: root, requireTarget: root }
}
if (root && typeof root === 'object') {
const record = root as Record<string, unknown>
const importTarget = typeof record.import === 'string' ? record.import : undefined
const requireTarget = typeof record.require === 'string' ? record.require : undefined
const defaultTarget = typeof record.default === 'string' ? record.default : undefined
return {
importTarget: importTarget ?? defaultTarget,
requireTarget: requireTarget ?? defaultTarget,
}
}
return { importTarget: undefined, requireTarget: undefined }
}
const describeDualPackage = (pkgJson: any) => {
const { importTarget, requireTarget } = analyzeExportsTargets(pkgJson?.exports)
const moduleField = typeof pkgJson?.module === 'string' ? pkgJson.module : undefined
const mainField = typeof pkgJson?.main === 'string' ? pkgJson.main : undefined
const typeField = typeof pkgJson?.type === 'string' ? pkgJson.type : undefined
const divergentExports = importTarget && requireTarget && importTarget !== requireTarget
const divergentModuleMain = moduleField && mainField && moduleField !== mainField
const typeModuleMainCjs =
typeField === 'module' && typeof mainField === 'string' && mainField.endsWith('.cjs')
const hasHazardSignals = divergentExports || divergentModuleMain || typeModuleMainCjs
const details: string[] = []
if (divergentExports) {
details.push(`exports import -> ${importTarget}, require -> ${requireTarget}`)
}
if (divergentModuleMain) {
details.push(`module -> ${moduleField}, main -> ${mainField}`)
}
if (typeModuleMainCjs) {
details.push(`type: module with CommonJS main (${mainField})`)
}
return { hasHazardSignals, details, importTarget, requireTarget }
}
const normalizeAllowlist = (allowlist?: Iterable<string>) => {
return new Set(
[...(allowlist ?? [])].map(item => item.trim()).filter(item => item.length > 0),
)
}
type HazardLevel = 'warning' | 'error'
export type PackageUse = {
spec: string
subpath: string
loc?: { start: number; end: number }
filePath?: string
}
export type PackageUsage = {
imports: PackageUse[]
requires: PackageUse[]
}
const recordUsage = (
usages: Map<string, PackageUsage>,
pkg: string,
kind: 'import' | 'require',
spec: string,
subpath: string,
loc?: { start: number; end: number },
filePath?: string,
) => {
const existing = usages.get(pkg) ?? { imports: [], requires: [] }
const bucket = kind === 'import' ? existing.imports : existing.requires
bucket.push({ spec, subpath, loc, filePath })
usages.set(pkg, existing)
}
const collectDualPackageUsage = async (
program: Node,
shadowedBindings: Set<string>,
filePath?: string,
) => {
const usages = new Map<string, PackageUsage>()
await ancestorWalk(program, {
enter(node) {
if (
node.type === 'ImportDeclaration' &&
node.source.type === 'Literal' &&
typeof node.source.value === 'string'
) {
const pkg = packageFromSpecifier(node.source.value)
if (pkg)
recordUsage(
usages,
pkg.pkg,
'import',
node.source.value,
pkg.subpath,
{ start: node.source.start, end: node.source.end },
filePath,
)
}
if (
node.type === 'ExportNamedDeclaration' &&
node.source &&
node.source.type === 'Literal' &&
typeof node.source.value === 'string'
) {
const pkg = packageFromSpecifier(node.source.value)
if (pkg)
recordUsage(
usages,
pkg.pkg,
'import',
node.source.value,
pkg.subpath,
{ start: node.source.start, end: node.source.end },
filePath,
)
}
if (
node.type === 'ExportAllDeclaration' &&
node.source.type === 'Literal' &&
typeof node.source.value === 'string'
) {
const pkg = packageFromSpecifier(node.source.value)
if (pkg)
recordUsage(
usages,
pkg.pkg,
'import',
node.source.value,
pkg.subpath,
{ start: node.source.start, end: node.source.end },
filePath,
)
}
if (
node.type === 'ImportExpression' &&
node.source.type === 'Literal' &&
typeof node.source.value === 'string'
) {
const pkg = packageFromSpecifier(node.source.value)
if (pkg)
recordUsage(
usages,
pkg.pkg,
'import',
node.source.value,
pkg.subpath,
{ start: node.source.start, end: node.source.end },
filePath,
)
}
if (node.type === 'CallExpression' && isStaticRequire(node, shadowedBindings)) {
const arg = node.arguments[0]
if (arg?.type === 'Literal' && typeof arg.value === 'string') {
const pkg = packageFromSpecifier(arg.value)
if (pkg)
recordUsage(
usages,
pkg.pkg,
'require',
arg.value,
pkg.subpath,
{
start: arg.start,
end: arg.end,
},
filePath,
)
}
}
},
})
return usages
}
const dualPackageHazardDiagnostics = async (params: {
usages: Map<string, PackageUsage>
hazardLevel: HazardLevel
filePath?: string
cwd?: string
manifestCache?: Map<string, any | null>
hazardAllowlist?: Iterable<string>
}) => {
const { usages, hazardLevel, filePath, cwd } = params
const manifestCache = params.manifestCache ?? new Map<string, any | null>()
const allowlist = normalizeAllowlist(params.hazardAllowlist)
const diags: Diagnostic[] = []
for (const [pkg, usage] of usages) {
if (allowlist.has(pkg)) continue
const hasImport = usage.imports.length > 0
const hasRequire = usage.requires.length > 0
const combined = [...usage.imports, ...usage.requires]
const hasRoot = combined.some(entry => !entry.subpath)
const hasSubpath = combined.some(entry => Boolean(entry.subpath))
const origin = usage.imports[0] ?? usage.requires[0]
const diagFile = origin?.filePath ?? filePath
if (hasImport && hasRequire) {
const uniq = <T>(items: T[]) => [...new Set(items)]
const importSpecs = uniq(
usage.imports.map(u => (u.subpath ? `${pkg}/${u.subpath}` : pkg)),
)
const requireSpecs = uniq(
usage.requires.map(u => (u.subpath ? `${pkg}/${u.subpath}` : pkg)),
)
diags.push({
level: hazardLevel,
code: 'dual-package-mixed-specifiers',
message: `Package '${pkg}' is loaded via import (${importSpecs.join(', ')}) and require (${requireSpecs.join(', ')}); conditional exports can instantiate it twice.`,
filePath: diagFile,
loc: origin?.loc,
})
}
if (hasRoot && hasSubpath) {
const subpaths = combined
.filter(entry => entry.subpath)
.map(entry => `${pkg}/${entry.subpath}`)
const originSubpath = combined.find(entry => entry.subpath) ?? combined[0]
diags.push({
level: hazardLevel,
code: 'dual-package-subpath',
message: `Package '${pkg}' is referenced via root specifier '${pkg}' and subpath(s) ${subpaths.join(', ')}; mixing them loads separate module instances.`,
filePath: originSubpath?.filePath ?? filePath,
loc: originSubpath?.loc,
})
}
if (hasImport && hasRequire) {
const manifest = await readPackageManifest(pkg, diagFile, cwd, manifestCache)
if (manifest) {
const meta = describeDualPackage(manifest)
if (meta.hasHazardSignals) {
const detail = meta.details.length ? ` (${meta.details.join('; ')})` : ''
diags.push({
level: hazardLevel,
code: 'dual-package-conditional-exports',
message: `Package '${pkg}' exposes different entry points for import vs require${detail}. Mixed usage can produce distinct instances.`,
filePath: diagFile,
loc: origin?.loc,
})
}
}
}
}
return diags
}
const detectDualPackageHazards = async (params: {
program: Node
shadowedBindings: Set<string>
hazardLevel: HazardLevel
filePath?: string
cwd?: string
diagOnce: (
level: HazardLevel,
codeId: string,
message: string,
loc?: { start: number; end: number },
) => void
hazardAllowlist?: Iterable<string>
}) => {
const { program, shadowedBindings, hazardLevel, filePath, cwd, diagOnce } = params
const manifestCache = new Map<string, any | null>()
const usages = await collectDualPackageUsage(program, shadowedBindings, filePath)
const diags = await dualPackageHazardDiagnostics({
usages,
hazardLevel,
filePath,
cwd,
manifestCache,
hazardAllowlist: params.hazardAllowlist,
})
for (const diag of diags) {
diagOnce(diag.level, diag.code, diag.message, diag.loc)
}
}
function format(
src: string,
ast: ParseResult,
opts: FormatterOptions & { sourceMap: true },
): Promise<MagicString>
function format(src: string, ast: ParseResult, opts: FormatterOptions): Promise<string>
async function format(src: string, ast: ParseResult, opts: FormatterOptions) {
const code = new MagicString(src)
const exportsMeta = {
hasExportsBeenReassigned: false,
defaultExportValue: undefined,
hasDefaultExportBeenReassigned: false,
hasDefaultExportBeenAssigned: false,
} satisfies ExportsMeta
const warned = new Set<string>()
const emitDiagnostic = (diag: Diagnostic) => {
if (opts.diagnostics) {
opts.diagnostics(diag)
return
}
if (diag.level === 'warning') {
// eslint-disable-next-line no-console -- used for opt-in diagnostics
console.warn(diag.message)
return
}
// eslint-disable-next-line no-console -- used for opt-in diagnostics
console.error(diag.message)
}
const diagOnce = (
level: Diagnostic['level'],
codeId: string,
message: string,
loc?: { start: number; end: number },
) => {
const key = `${level}:${codeId}:${loc?.start ?? ''}`
if (warned.has(key)) return
warned.add(key)
emitDiagnostic({ level, code: codeId, message, filePath: opts.filePath, loc })
}
const warnOnce: WarnOnce = (
codeId: string,
message: string,
loc?: { start: number; end: number },
) => diagOnce('warning', codeId, message, loc)
const transformMode = opts.transformSyntax
const fullTransform = transformMode === true
const moduleIdentifiers = await collectModuleIdentifiers(ast.program)
const shadowedBindings = new Set(
[...moduleIdentifiers.entries()]
.filter(([, meta]) => meta.declare.length > 0)
.map(([name]) => name),
)
const hazardMode = opts.detectDualPackageHazard ?? 'warn'
if (hazardMode !== 'off') {
const hazardLevel: HazardLevel = hazardMode === 'error' ? 'error' : 'warning'
await detectDualPackageHazards({
program: ast.program,
shadowedBindings,
hazardLevel,
filePath: opts.filePath,
cwd: opts.cwd,
diagOnce,
hazardAllowlist: opts.dualPackageHazardAllowlist,
})
}
if (opts.target === 'module' && fullTransform) {
if (shadowedBindings.has('module') || shadowedBindings.has('exports')) {
throw new Error(
'Cannot transform to ESM: module or exports is shadowed in module scope.',
)
}
}
const exportTable: ExportsMap | null =
opts.target === 'module' ? await collectCjsExports(ast.program) : null
const idiomaticMode =
opts.target === 'module' && fullTransform ? (opts.idiomaticExports ?? 'safe') : 'off'
let useExportsBag = fullTransform
let idiomaticPlan: {
replacements: Array<{ start: number; end: number }>
exports: string[]
} | null = null
let idiomaticFallbackReason: string | undefined
if (opts.target === 'module' && exportTable) {
const hasExportsVia = [...exportTable.values()].some(entry =>
entry.via.has('exports'),
)
const hasModuleExportsVia = [...exportTable.values()].some(entry =>
entry.via.has('module.exports'),
)
if (hasExportsVia && hasModuleExportsVia) {
const firstExports = [...exportTable.values()].find(entry =>
entry.via.has('exports'),
)?.writes[0]
const firstModule = [...exportTable.values()].find(entry =>
entry.via.has('module.exports'),
)?.writes[0]
warnOnce(
'cjs-mixed-exports',
'Both module.exports and exports are assigned in this module; CommonJS shadowing may not match synthesized ESM exports.',
{ start: firstModule?.start ?? 0, end: firstExports?.end ?? 0 },
)
}
if (idiomaticMode !== 'off') {
const res = buildIdiomaticPlan({
src,
code,
exportTable,
shadowedBindings,
idiomaticMode,
})
if (res.ok) {
useExportsBag = false
idiomaticPlan = res.plan
} else {
idiomaticFallbackReason = res.reason
}
}
}
const shouldCheckTopLevelAwait = opts.target === 'commonjs' && fullTransform
const containsTopLevelAwait = shouldCheckTopLevelAwait
? hasTopLevelAwait(ast.program)
: false
if (idiomaticFallbackReason && idiomaticMode !== 'off') {
warnOnce(
'idiomatic-exports-fallback',
`Idiomatic exports disabled for this file: ${idiomaticFallbackReason}. Falling back to helper exports.`,
)
}
const requireMainStrategy = opts.requireMainStrategy ?? 'import-meta-main'
let requireMainNeedsRealpath = false
let needsRequireResolveHelper = false
const nestedRequireStrategy = opts.nestedRequireStrategy ?? 'create-require'
const importMetaPreludeMode = opts.importMetaPrelude ?? 'auto'
let importMetaRef = false
const shouldLowerCjs = opts.target === 'commonjs' && fullTransform
const shouldRaiseEsm = opts.target === 'module' && fullTransform
let hoistedImports: string[] = []
let hoistedStatements: string[] = []
let pendingRequireTransforms: RequireTransform[] = []
let needsCreateRequire = false
let needsImportInterop = false
let pendingCjsTransforms: {
transforms: Array<ImportTransform | ExportTransform>
needsInterop: boolean
} | null = null
if (shouldLowerCjs && opts.topLevelAwait === 'error' && containsTopLevelAwait) {
throw new Error(
'Top-level await is not supported when targeting CommonJS (set topLevelAwait to "wrap" or "preserve" to override).',
)
}
if (shouldRaiseEsm) {
const {
transforms,
imports,
hoisted,
needsCreateRequire: reqCreate,
needsInteropHelper: reqInteropHelper,
} = lowerCjsRequireToImports(ast.program, code, shadowedBindings)
pendingRequireTransforms = transforms
hoistedImports = imports
hoistedStatements = hoisted
needsCreateRequire = reqCreate
needsImportInterop = reqInteropHelper
}
const walkState: FormatWalkState = {
importMetaRef,
requireMainNeedsRealpath,
needsCreateRequire,
needsRequireResolveHelper,
}
await ancestorWalk(ast.program, {
enter: buildFormatVisitor(
{
code,
opts,
warnOnce,
shadowedBindings,
requireMainStrategy,
nestedRequireStrategy,
shouldRaiseEsm,
fullTransform,
useExportsBag,
exportsMeta,
isRequireMainMember,
isRequireCall,
isStaticRequire,
isAsyncContext,
isValidUrl,
isIdentifierName,
assignmentExpression,
metaProperty,
memberExpression,
identifier,
},
walkState,
),
})
;({
importMetaRef,
requireMainNeedsRealpath,
needsCreateRequire,
needsRequireResolveHelper,
} = walkState)
if (pendingRequireTransforms.length) {
for (const t of pendingRequireTransforms) {
code.overwrite(t.start, t.end, t.code)
}
}
if (!useExportsBag && idiomaticPlan) {
if (idiomaticPlan.exports.length === idiomaticPlan.replacements.length) {
idiomaticPlan.replacements.forEach((rep, idx) => {
code.overwrite(rep.start, rep.end, idiomaticPlan!.exports[idx])
})
} else {
const [first, ...rest] = idiomaticPlan.replacements
if (first) {
code.overwrite(first.start, first.end, idiomaticPlan.exports.join('\n'))
}
for (const rep of rest) {
const original = code.slice(rep.start, rep.end)
const hasSemicolon = original.trimEnd().endsWith(';')
code.overwrite(rep.start, rep.end, hasSemicolon ? ';' : '')
}
}
}
if (shouldLowerCjs) {
const { importTransforms, exportTransforms, needsInterop } = lowerEsmToCjs(
ast.program,
code,
opts,
containsTopLevelAwait,
)
pendingCjsTransforms = {
transforms: [...importTransforms, ...exportTransforms].sort(
(a, b) => a.start - b.start,
),
needsInterop,
}
}
if (pendingCjsTransforms) {
for (const t of pendingCjsTransforms.transforms) {
code.overwrite(t.start, t.end, t.code)
}
if (pendingCjsTransforms.needsInterop) {
code.prepend(`${interopHelper}exports.__esModule = true;\n`)
}
}
if (useExportsBag && opts.target === 'module' && fullTransform && exportTable) {
importMetaRef = exportBagToEsm({ code, exportTable, warnOnce, importMetaRef })
}
if (shouldRaiseEsm && fullTransform) {
const prelude = buildEsmPrelude({
needsCreateRequire,
needsRequireResolveHelper,
requireMainNeedsRealpath,
hoistedImports,
hoistedStatements,
needsImportInterop,
importMetaPreludeMode,
importMetaRef,
useExportsBag,
})
code.prepend(prelude)
}
if (opts.target === 'commonjs' && fullTransform && containsTopLevelAwait) {
if (opts.topLevelAwait === 'wrap') {
code.prepend('const __tla = (async () => {\n')
code.append('\nreturn module.exports;\n})();\n')
code.append(
'const __setTla = target => {\n if (!target) return;\n const type = typeof target;\n if (type !== "object" && type !== "function") return;\n target.__tla = __tla;\n};\n',
)
code.append(
'__setTla(module.exports);\n__tla.then(resolved => __setTla(resolved), err => { throw err; });\n',
)
} else {
code.prepend(';(async () => {\n')
code.append('\n})();\n')
}
}
return opts.sourceMap ? code : code.toString()
}
export { format, collectDualPackageUsage, dualPackageHazardDiagnostics }