@knighted/module 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/ast.d.ts +1 -0
  2. package/dist/async.d.ts +4 -0
  3. package/dist/buildEsmPrelude.d.ts +14 -0
  4. package/dist/cjs/ast.d.cts +1 -0
  5. package/dist/cjs/async.d.cts +4 -0
  6. package/dist/cjs/buildEsmPrelude.d.cts +14 -0
  7. package/dist/cjs/exportBagToEsm.d.cts +13 -0
  8. package/dist/cjs/format.cjs +78 -852
  9. package/dist/cjs/formatVisitor.d.cts +42 -0
  10. package/dist/cjs/helpers/async.cjs +57 -0
  11. package/dist/cjs/idiomaticPlan.d.cts +28 -0
  12. package/dist/cjs/interopHelpers.d.cts +5 -0
  13. package/dist/cjs/lowerCjsRequireToImports.d.cts +17 -0
  14. package/dist/cjs/lowerEsmToCjs.d.cts +22 -0
  15. package/dist/cjs/pipeline/buildEsmPrelude.cjs +65 -0
  16. package/dist/cjs/pipeline/exportBagToEsm.cjs +81 -0
  17. package/dist/cjs/pipeline/formatVisitor.cjs +171 -0
  18. package/dist/cjs/pipeline/idiomaticPlan.cjs +224 -0
  19. package/dist/cjs/pipeline/interopHelpers.cjs +10 -0
  20. package/dist/cjs/pipeline/lowerCjsRequireToImports.cjs +110 -0
  21. package/dist/cjs/pipeline/lowerEsmToCjs.cjs +204 -0
  22. package/dist/exportBagToEsm.d.ts +13 -0
  23. package/dist/format.js +74 -848
  24. package/dist/formatVisitor.d.ts +42 -0
  25. package/dist/helpers/ast.d.ts +1 -0
  26. package/dist/helpers/async.d.ts +4 -0
  27. package/dist/helpers/async.js +50 -0
  28. package/dist/idiomaticPlan.d.ts +28 -0
  29. package/dist/interopHelpers.d.ts +5 -0
  30. package/dist/lowerCjsRequireToImports.d.ts +17 -0
  31. package/dist/lowerEsmToCjs.d.ts +22 -0
  32. package/dist/pipeline/buildEsmPrelude.d.ts +14 -0
  33. package/dist/pipeline/buildEsmPrelude.js +59 -0
  34. package/dist/pipeline/exportBagToEsm.d.ts +13 -0
  35. package/dist/pipeline/exportBagToEsm.js +75 -0
  36. package/dist/pipeline/formatVisitor.d.ts +42 -0
  37. package/dist/pipeline/formatVisitor.js +166 -0
  38. package/dist/pipeline/idiomaticPlan.d.ts +28 -0
  39. package/dist/pipeline/idiomaticPlan.js +218 -0
  40. package/dist/pipeline/interopHelpers.d.ts +5 -0
  41. package/dist/pipeline/interopHelpers.js +5 -0
  42. package/dist/pipeline/lowerCjsRequireToImports.d.ts +17 -0
  43. package/dist/pipeline/lowerCjsRequireToImports.js +102 -0
  44. package/dist/pipeline/lowerEsmToCjs.d.ts +22 -0
  45. package/dist/pipeline/lowerEsmToCjs.js +197 -0
  46. package/package.json +1 -1
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.buildIdiomaticPlan = void 0;
7
+ var _ast = require("../helpers/ast.cjs");
8
+ const reservedExports = new Set(['await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield']);
9
+ const isValidExportName = name => /^[$A-Z_a-z][$\w]*$/.test(name) && !reservedExports.has(name);
10
+ const isAllowedRhs = node => node.type === 'Identifier' || node.type === 'Literal' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' || node.type === 'ClassExpression';
11
+ const expressionHasRequireCall = (node, shadowed) => {
12
+ let found = false;
13
+ const walkNode = n => {
14
+ if (!(0, _ast.isAstNode)(n) || found) return;
15
+ if ((0, _ast.isCallExpressionNode)(n) && (0, _ast.isIdentifierNode)(n.callee) && n.callee.name === 'require' && !shadowed.has('require')) {
16
+ found = true;
17
+ return;
18
+ }
19
+ if ((0, _ast.isCallExpressionNode)(n) && (0, _ast.isMemberExpressionNode)(n.callee) && (0, _ast.isIdentifierNode)(n.callee.object) && n.callee.object.name === 'require' && !shadowed.has('require')) {
20
+ found = true;
21
+ return;
22
+ }
23
+ const record = n;
24
+ const keys = Object.keys(record);
25
+ for (const key of keys) {
26
+ const value = record[key];
27
+ if (!value) continue;
28
+ if (Array.isArray(value)) {
29
+ for (const item of value) {
30
+ if (item && typeof item === 'object') walkNode(item);
31
+ if (found) return;
32
+ }
33
+ } else if (value && typeof value === 'object') {
34
+ walkNode(value);
35
+ if (found) return;
36
+ }
37
+ }
38
+ };
39
+ walkNode(node);
40
+ return found;
41
+ };
42
+ const rhsSourceFor = (code, node) => code.slice(node.start, node.end).replace(/\b__dirname\b/g, 'import.meta.dirname').replace(/\b__filename\b/g, 'import.meta.filename');
43
+ const tryObjectLiteralExport = (rhs, code, requireShadowed, baseIsModuleExports, propName) => {
44
+ if (!baseIsModuleExports || propName !== 'exports') return null;
45
+ if (rhs.type !== 'ObjectExpression') return null;
46
+ const exportsOut = [];
47
+ const seenKeys = new Set();
48
+ for (const prop of rhs.properties) {
49
+ if (prop.type !== 'Property') return null;
50
+ if (prop.kind !== 'init') return null;
51
+ if (prop.computed || prop.method) return null;
52
+ if (prop.key.type !== 'Identifier') return null;
53
+ const key = prop.key.name;
54
+ if (key === '__proto__' || key === 'prototype') return null;
55
+ if (!isValidExportName(key)) return null;
56
+ if (seenKeys.has(key)) return null;
57
+ const value = prop.value.type === 'Identifier' && prop.shorthand ? prop.key : prop.value;
58
+ if (!isAllowedRhs(value)) return null;
59
+ if (expressionHasRequireCall(value, requireShadowed)) return null;
60
+ const rhsSrc = rhsSourceFor(code, value);
61
+ if (value.type === 'Identifier' && value.name === key) {
62
+ exportsOut.push(`export { ${key} };`);
63
+ } else if (value.type === 'Identifier') {
64
+ exportsOut.push(`export { ${rhsSrc} as ${key} };`);
65
+ } else {
66
+ exportsOut.push(`export const ${key} = ${rhsSrc};`);
67
+ }
68
+ seenKeys.add(key);
69
+ }
70
+ exportsOut.push(`export default ${rhsSourceFor(code, rhs)};`);
71
+ return {
72
+ exportsOut,
73
+ seenKeys
74
+ };
75
+ };
76
+ const buildIdiomaticPlan = ({
77
+ src,
78
+ code,
79
+ exportTable,
80
+ shadowedBindings,
81
+ idiomaticMode
82
+ }) => {
83
+ if (idiomaticMode === 'off') return {
84
+ ok: false,
85
+ reason: 'disabled'
86
+ };
87
+ const entries = [...exportTable.values()];
88
+ if (!entries.length) return {
89
+ ok: false,
90
+ reason: 'no-exports'
91
+ };
92
+ if (exportTable.hasUnsupportedExportWrite) {
93
+ return {
94
+ ok: false,
95
+ reason: 'unsupported-left'
96
+ };
97
+ }
98
+ const viaSet = new Set();
99
+ for (const entry of entries) {
100
+ entry.via.forEach(v => viaSet.add(v));
101
+ if (entry.hasGetter) return {
102
+ ok: false,
103
+ reason: 'getter-present'
104
+ };
105
+ if (entry.reassignments.length) return {
106
+ ok: false,
107
+ reason: 'reassignment'
108
+ };
109
+ if (entry.hasNonTopLevelWrite) return {
110
+ ok: false,
111
+ reason: 'non-top-level'
112
+ };
113
+ if (entry.writes.length !== 1) return {
114
+ ok: false,
115
+ reason: 'multiple-writes'
116
+ };
117
+ if (entry.key !== 'default' && !isValidExportName(entry.key)) return {
118
+ ok: false,
119
+ reason: 'non-identifier-key'
120
+ };
121
+ }
122
+ if (viaSet.size > 1) return {
123
+ ok: false,
124
+ reason: 'mixed-exports'
125
+ };
126
+ const replacements = [];
127
+ const exportsOut = [];
128
+ const seen = new Set();
129
+ const requireShadowed = shadowedBindings;
130
+ for (const entry of entries) {
131
+ const write = entry.writes[0];
132
+ if (write.type !== 'AssignmentExpression') {
133
+ return {
134
+ ok: false,
135
+ reason: 'unsupported-write-kind'
136
+ };
137
+ }
138
+ const left = write.left;
139
+ if (left.type !== 'MemberExpression' || left.computed || left.property.type !== 'Identifier') {
140
+ return {
141
+ ok: false,
142
+ reason: 'unsupported-left'
143
+ };
144
+ }
145
+ const base = left.object;
146
+ const propName = left.property.name;
147
+ const baseIsExports = base.type === 'Identifier' && base.name === 'exports';
148
+ const baseIsModuleExports = base.type === 'Identifier' && base.name === 'module' && propName === 'exports' || base.type === 'MemberExpression' && base.object.type === 'Identifier' && base.object.name === 'module' && base.property.type === 'Identifier' && base.property.name === 'exports';
149
+ if (!baseIsExports && !baseIsModuleExports) {
150
+ return {
151
+ ok: false,
152
+ reason: 'unsupported-base'
153
+ };
154
+ }
155
+ const rhs = write.right;
156
+ const objectLiteralPlan = tryObjectLiteralExport(rhs, code, requireShadowed, baseIsModuleExports, propName);
157
+ if (!objectLiteralPlan) {
158
+ if (!isAllowedRhs(rhs)) return {
159
+ ok: false,
160
+ reason: 'unsupported-rhs'
161
+ };
162
+ if (expressionHasRequireCall(rhs, requireShadowed)) {
163
+ return {
164
+ ok: false,
165
+ reason: 'rhs-require'
166
+ };
167
+ }
168
+ }
169
+ const rhsSrc = rhsSourceFor(code, rhs);
170
+ if (propName === 'exports' && baseIsModuleExports) {
171
+ if (objectLiteralPlan) {
172
+ for (const line of objectLiteralPlan.exportsOut) {
173
+ exportsOut.push(line);
174
+ }
175
+ objectLiteralPlan.seenKeys.forEach(k => seen.add(k));
176
+ } else {
177
+ if (seen.has('default')) return {
178
+ ok: false,
179
+ reason: 'duplicate-default'
180
+ };
181
+ seen.add('default');
182
+ exportsOut.push(`export default ${rhsSrc};`);
183
+ }
184
+ } else {
185
+ if (seen.has(propName)) return {
186
+ ok: false,
187
+ reason: 'duplicate-key'
188
+ };
189
+ seen.add(propName);
190
+ if (rhs.type === 'Identifier') {
191
+ const rhsId = rhsSourceFor(code, rhs);
192
+ const rhsName = rhs.name;
193
+ if (rhsId === rhsName && rhsName === propName) {
194
+ exportsOut.push(`export { ${propName} };`);
195
+ } else if (rhsId === rhsName) {
196
+ exportsOut.push(`export { ${rhsId} as ${propName} };`);
197
+ } else {
198
+ exportsOut.push(`export const ${propName} = ${rhsId};`);
199
+ }
200
+ } else {
201
+ exportsOut.push(`export const ${propName} = ${rhsSrc};`);
202
+ }
203
+ }
204
+ let end = write.end;
205
+ while (end < src.length && (src[end] === ' ' || src[end] === '\t')) end++;
206
+ if (end < src.length && src[end] === ';') end++;
207
+ replacements.push({
208
+ start: write.start,
209
+ end
210
+ });
211
+ }
212
+ if (!seen.size) return {
213
+ ok: false,
214
+ reason: 'no-seen'
215
+ };
216
+ return {
217
+ ok: true,
218
+ plan: {
219
+ replacements,
220
+ exports: exportsOut
221
+ }
222
+ };
223
+ };
224
+ exports.buildIdiomaticPlan = buildIdiomaticPlan;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.requireInteropName = exports.requireInteropHelper = exports.interopHelper = exports.defaultInteropName = void 0;
7
+ const defaultInteropName = exports.defaultInteropName = '__interopDefault';
8
+ const interopHelper = exports.interopHelper = `const ${defaultInteropName} = mod => (mod && mod.__esModule ? mod.default : mod);\n`;
9
+ const requireInteropName = exports.requireInteropName = '__requireDefault';
10
+ const requireInteropHelper = exports.requireInteropHelper = `const ${requireInteropName} = mod => (mod && typeof mod === 'object' && 'default' in mod ? mod.default : mod);\n`;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.lowerCjsRequireToImports = exports.isStaticRequire = exports.isRequireCall = void 0;
7
+ var _ast = require("../helpers/ast.cjs");
8
+ var _interopHelpers = require("./interopHelpers.cjs");
9
+ const isRequireCallee = (callee, shadowed) => {
10
+ if (callee.type === 'Identifier' && callee.name === 'require' && !shadowed.has('require')) {
11
+ return true;
12
+ }
13
+ if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'module' && !shadowed.has('module') && callee.property.type === 'Identifier' && callee.property.name === 'require') {
14
+ return true;
15
+ }
16
+ return false;
17
+ };
18
+ const isStaticRequire = (node, shadowed) => node.type === 'CallExpression' && isRequireCallee(node.callee, shadowed) && node.arguments.length === 1 && node.arguments[0].type === 'Literal' && typeof node.arguments[0].value === 'string';
19
+ exports.isStaticRequire = isStaticRequire;
20
+ const isRequireCall = (node, shadowed) => node.type === 'CallExpression' && isRequireCallee(node.callee, shadowed);
21
+ exports.isRequireCall = isRequireCall;
22
+ const lowerCjsRequireToImports = (program, code, shadowed) => {
23
+ const transforms = [];
24
+ const imports = [];
25
+ const hoisted = [];
26
+ let nsIndex = 0;
27
+ let needsCreateRequire = false;
28
+ let needsInteropHelper = false;
29
+ const isJsonSpecifier = value => {
30
+ const base = value.split(/[?#]/)[0] ?? value;
31
+ return base.endsWith('.json');
32
+ };
33
+ for (const stmt of program.body) {
34
+ if (stmt.type === 'VariableDeclaration') {
35
+ const decls = stmt.declarations;
36
+ const allStatic = decls.length > 0 && decls.every(decl => decl.init && isStaticRequire(decl.init, shadowed));
37
+ if (allStatic) {
38
+ for (const decl of decls) {
39
+ const init = decl.init;
40
+ if (!init || !(0, _ast.isCallExpressionNode)(init)) {
41
+ needsCreateRequire = true;
42
+ continue;
43
+ }
44
+ const arg = init.arguments[0];
45
+ const source = code.slice(arg.start, arg.end);
46
+ const value = arg.value;
47
+ const isJson = typeof value === 'string' && isJsonSpecifier(value);
48
+ const ns = `__cjsImport${nsIndex++}`;
49
+ const jsonImport = isJson ? `${source} with { type: "json" }` : source;
50
+ if (decl.id.type === 'Identifier') {
51
+ imports.push(isJson ? `import ${ns} from ${jsonImport};\n` : `import * as ${ns} from ${jsonImport};\n`);
52
+ hoisted.push(isJson ? `const ${decl.id.name} = ${ns};\n` : `const ${decl.id.name} = ${_interopHelpers.requireInteropName}(${ns});\n`);
53
+ needsInteropHelper ||= !isJson;
54
+ } else if (decl.id.type === 'ObjectPattern' || decl.id.type === 'ArrayPattern') {
55
+ const pattern = code.slice(decl.id.start, decl.id.end);
56
+ imports.push(isJson ? `import ${ns} from ${jsonImport};\n` : `import * as ${ns} from ${jsonImport};\n`);
57
+ hoisted.push(isJson ? `const ${pattern} = ${ns};\n` : `const ${pattern} = ${_interopHelpers.requireInteropName}(${ns});\n`);
58
+ needsInteropHelper ||= !isJson;
59
+ } else {
60
+ needsCreateRequire = true;
61
+ }
62
+ }
63
+ transforms.push({
64
+ start: stmt.start,
65
+ end: stmt.end,
66
+ code: ';\n'
67
+ });
68
+ continue;
69
+ }
70
+ for (const decl of decls) {
71
+ const init = decl.init;
72
+ if (init && isRequireCall(init, shadowed)) {
73
+ needsCreateRequire = true;
74
+ }
75
+ }
76
+ }
77
+ if (stmt.type === 'ExpressionStatement') {
78
+ const expr = stmt.expression;
79
+ if (expr && isStaticRequire(expr, shadowed)) {
80
+ if (!(0, _ast.isCallExpressionNode)(expr)) {
81
+ needsCreateRequire = true;
82
+ continue;
83
+ }
84
+ const arg = expr.arguments[0];
85
+ const source = code.slice(arg.start, arg.end);
86
+ const value = arg.value;
87
+ const isJson = typeof value === 'string' && isJsonSpecifier(value);
88
+ const jsonImport = isJson ? `${source} with { type: "json" }` : source;
89
+ imports.push(`import ${jsonImport};\n`);
90
+ transforms.push({
91
+ start: stmt.start,
92
+ end: stmt.end,
93
+ code: ';\n'
94
+ });
95
+ continue;
96
+ }
97
+ if (expr && isRequireCall(expr, shadowed)) {
98
+ needsCreateRequire = true;
99
+ }
100
+ }
101
+ }
102
+ return {
103
+ transforms,
104
+ imports,
105
+ hoisted,
106
+ needsCreateRequire,
107
+ needsInteropHelper
108
+ };
109
+ };
110
+ exports.lowerCjsRequireToImports = lowerCjsRequireToImports;
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.lowerEsmToCjs = exports.exportAssignment = void 0;
7
+ var _ast = require("../helpers/ast.cjs");
8
+ var _interopHelpers = require("./interopHelpers.cjs");
9
+ const isValidIdent = name => /^[$A-Z_a-z][$\w]*$/.test(name);
10
+ const exportAssignment = (name, expr, live) => {
11
+ const prop = isValidIdent(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
12
+ if (live === 'strict') {
13
+ const key = JSON.stringify(name);
14
+ return `Object.defineProperty(exports, ${key}, { enumerable: true, get: () => ${expr} });`;
15
+ }
16
+ return `exports${prop} = ${expr};`;
17
+ };
18
+ exports.exportAssignment = exportAssignment;
19
+ const lowerEsmToCjs = (program, code, opts, containsTopLevelAwait) => {
20
+ const live = opts.liveBindings ?? 'strict';
21
+ const importTransforms = [];
22
+ const exportTransforms = [];
23
+ let needsInterop = false;
24
+ let importIndex = 0;
25
+ for (const node of program.body) {
26
+ if (node.type === 'ImportDeclaration') {
27
+ const srcLiteral = code.slice(node.source.start, node.source.end);
28
+ const specifiers = node.specifiers ?? [];
29
+ const defaultSpec = specifiers.find(s => s.type === 'ImportDefaultSpecifier');
30
+ const namespaceSpec = specifiers.find(s => s.type === 'ImportNamespaceSpecifier');
31
+ const namedSpecs = specifiers.filter(s => s.type === 'ImportSpecifier');
32
+ if (!specifiers.length) {
33
+ importTransforms.push({
34
+ start: node.start,
35
+ end: node.end,
36
+ code: `require(${srcLiteral});\n`,
37
+ needsInterop: false
38
+ });
39
+ continue;
40
+ }
41
+ const modIdent = `__mod${importIndex++}`;
42
+ const lines = [];
43
+ lines.push(`const ${modIdent} = require(${srcLiteral});`);
44
+ if (namespaceSpec) {
45
+ lines.push(`const ${namespaceSpec.local.name} = ${modIdent};`);
46
+ }
47
+ if (defaultSpec) {
48
+ let init = modIdent;
49
+ switch (opts.cjsDefault) {
50
+ case 'module-exports':
51
+ init = modIdent;
52
+ break;
53
+ case 'none':
54
+ init = `${modIdent}.default`;
55
+ break;
56
+ case 'auto':
57
+ default:
58
+ init = `${_interopHelpers.defaultInteropName}(${modIdent})`;
59
+ needsInterop = true;
60
+ break;
61
+ }
62
+ lines.push(`const ${defaultSpec.local.name} = ${init};`);
63
+ }
64
+ if (namedSpecs.length) {
65
+ const pairs = namedSpecs.map(s => {
66
+ const imported = (0, _ast.getModuleExportName)(s.imported);
67
+ if (!imported) return s.local.name;
68
+ const local = s.local.name;
69
+ return imported === local ? imported : `${imported}: ${local}`;
70
+ });
71
+ lines.push(`const { ${pairs.join(', ')} } = ${modIdent};`);
72
+ }
73
+ importTransforms.push({
74
+ start: node.start,
75
+ end: node.end,
76
+ code: `${lines.join('\n')}\n`,
77
+ needsInterop
78
+ });
79
+ }
80
+ if (node.type === 'ExportNamedDeclaration') {
81
+ if (node.declaration) {
82
+ const decl = node.declaration;
83
+ const declSrc = code.slice(decl.start, decl.end);
84
+ const exportedNames = [];
85
+ if (decl.type === 'VariableDeclaration') {
86
+ for (const d of decl.declarations) {
87
+ if (d.id.type === 'Identifier') {
88
+ exportedNames.push(d.id.name);
89
+ }
90
+ }
91
+ } else if ('id' in decl && decl.id?.type === 'Identifier') {
92
+ exportedNames.push(decl.id.name);
93
+ }
94
+ const exportLines = exportedNames.map(name => exportAssignment(name, name, live));
95
+ exportTransforms.push({
96
+ start: node.start,
97
+ end: node.end,
98
+ code: `${declSrc}\n${exportLines.join('\n')}\n`
99
+ });
100
+ continue;
101
+ }
102
+ if (node.specifiers?.length) {
103
+ if (node.source) {
104
+ const srcLiteral = code.slice(node.source.start, node.source.end);
105
+ const modIdent = `__mod${importIndex++}`;
106
+ const lines = [`const ${modIdent} = require(${srcLiteral});`];
107
+ for (const spec of node.specifiers) {
108
+ if (spec.type !== 'ExportSpecifier') continue;
109
+ const exported = (0, _ast.getModuleExportName)(spec.exported);
110
+ const imported = (0, _ast.getModuleExportName)(spec.local);
111
+ if (!exported || !imported) continue;
112
+ let rhs = `${modIdent}.${imported}`;
113
+ if (imported === 'default') {
114
+ rhs = `${_interopHelpers.defaultInteropName}(${modIdent})`;
115
+ needsInterop = true;
116
+ }
117
+ lines.push(exportAssignment(exported, rhs, live));
118
+ }
119
+ exportTransforms.push({
120
+ start: node.start,
121
+ end: node.end,
122
+ code: `${lines.join('\n')}\n`,
123
+ needsInterop
124
+ });
125
+ } else {
126
+ const lines = [];
127
+ for (const spec of node.specifiers) {
128
+ if (spec.type !== 'ExportSpecifier') continue;
129
+ const exported = (0, _ast.getModuleExportName)(spec.exported);
130
+ const local = (0, _ast.getModuleExportName)(spec.local);
131
+ if (!exported || !local) continue;
132
+ lines.push(exportAssignment(exported, local, live));
133
+ }
134
+ exportTransforms.push({
135
+ start: node.start,
136
+ end: node.end,
137
+ code: `${lines.join('\n')}\n`
138
+ });
139
+ }
140
+ }
141
+ }
142
+ if (node.type === 'ExportDefaultDeclaration') {
143
+ const decl = node.declaration;
144
+ const useExportsObject = containsTopLevelAwait && opts.topLevelAwait !== 'error';
145
+ if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
146
+ if (decl.id?.name) {
147
+ const declSrc = code.slice(decl.start, decl.end);
148
+ const assign = useExportsObject ? `exports.default = ${decl.id.name};` : `module.exports = ${decl.id.name};`;
149
+ exportTransforms.push({
150
+ start: node.start,
151
+ end: node.end,
152
+ code: `${declSrc}\n${assign}\n`
153
+ });
154
+ } else {
155
+ const declSrc = code.slice(decl.start, decl.end);
156
+ const assign = useExportsObject ? `exports.default = ${declSrc};` : `module.exports = ${declSrc};`;
157
+ exportTransforms.push({
158
+ start: node.start,
159
+ end: node.end,
160
+ code: `${assign}\n`
161
+ });
162
+ }
163
+ } else {
164
+ const exprSrc = code.slice(decl.start, decl.end);
165
+ const assign = useExportsObject ? `exports.default = ${exprSrc};` : `module.exports = ${exprSrc};`;
166
+ exportTransforms.push({
167
+ start: node.start,
168
+ end: node.end,
169
+ code: `${assign}\n`
170
+ });
171
+ }
172
+ }
173
+ if (node.type === 'ExportAllDeclaration') {
174
+ const srcLiteral = code.slice(node.source.start, node.source.end);
175
+ if ('exported' in node && node.exported) {
176
+ const exported = (0, _ast.getModuleExportName)(node.exported);
177
+ if (!exported) continue;
178
+ const modIdent = `__mod${importIndex++}`;
179
+ const lines = [`const ${modIdent} = require(${srcLiteral});`, exportAssignment(exported, modIdent, live)];
180
+ exportTransforms.push({
181
+ start: node.start,
182
+ end: node.end,
183
+ code: `${lines.join('\n')}\n`
184
+ });
185
+ } else {
186
+ const modIdent = `__mod${importIndex++}`;
187
+ const lines = [`const ${modIdent} = require(${srcLiteral});`];
188
+ const loop = `for (const k in ${modIdent}) {\n if (k === 'default') continue;\n if (!Object.prototype.hasOwnProperty.call(${modIdent}, k)) continue;\n Object.defineProperty(exports, k, { enumerable: true, get: () => ${modIdent}[k] });\n}`;
189
+ lines.push(loop);
190
+ exportTransforms.push({
191
+ start: node.start,
192
+ end: node.end,
193
+ code: `${lines.join('\n')}\n`
194
+ });
195
+ }
196
+ }
197
+ }
198
+ return {
199
+ importTransforms,
200
+ exportTransforms,
201
+ needsInterop
202
+ };
203
+ };
204
+ exports.lowerEsmToCjs = lowerEsmToCjs;
@@ -0,0 +1,13 @@
1
+ import MagicString from 'magic-string';
2
+ import type { ExportsMap } from '../helpers/ast.js';
3
+ type WarnOnce = (codeId: string, message: string, loc?: {
4
+ start: number;
5
+ end: number;
6
+ }) => void;
7
+ declare const exportBagToEsm: (params: {
8
+ code: MagicString;
9
+ exportTable: ExportsMap;
10
+ warnOnce: WarnOnce;
11
+ importMetaRef: boolean;
12
+ }) => boolean;
13
+ export { exportBagToEsm, type WarnOnce };