@buxlabs/es6-to-amd 1.2.0 → 2.0.0

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.
@@ -0,0 +1,7 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(npm view *)"
5
+ ]
6
+ }
7
+ }
package/CHANGELOG.md CHANGED
@@ -1,3 +1,24 @@
1
+ ## 2.0.0
2
+
3
+ - breaking: require node >= 24.12.0
4
+ - breaking: renamed imports (`import { a as b }`) resolve to the imported member instead of the whole module
5
+ - update: abstract-syntax-tree to 3.0.0
6
+ - remove: pure-utilities, ava, nyc, standard
7
+ - edit: tests run on node:test with 100% coverage
8
+ - add: support `export * from`, `export * as ns from` and `export { a } from`
9
+ - add: support default export combined with named exports
10
+ - add: support destructured exports
11
+ - fix: generated params no longer collide with identifiers used in the file
12
+ - fix: property names, labels and shadowing variables are no longer rewritten as imports
13
+ - fix: code after `export default` is executed
14
+ - fix: `export { a as b }` uses the exported name
15
+ - fix: a dependency imported multiple times is listed once
16
+
17
+ ## 1.2.1
18
+
19
+ - update: all dependencies
20
+ - remove: underscore
21
+
1
22
  ## 1.0.1
2
23
 
3
24
  - update: all dependencies
package/package.json CHANGED
@@ -1,13 +1,11 @@
1
1
  {
2
2
  "name": "@buxlabs/es6-to-amd",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "es6 to amd converter",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "ava test/spec/*.js",
8
- "lint": "standard",
9
- "watch:test": "npm t -- --watch",
10
- "coverage": "nyc npm t"
7
+ "test": "node --test test/spec/*.js",
8
+ "coverage": "node --test --experimental-test-coverage --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 test/spec/*.js"
11
9
  },
12
10
  "repository": {
13
11
  "type": "git",
@@ -24,19 +22,10 @@
24
22
  "url": "https://github.com/buxlabs/es6-to-amd/issues"
25
23
  },
26
24
  "homepage": "https://github.com/buxlabs/es6-to-amd#readme",
27
- "devDependencies": {
28
- "ava": "^3.15.0",
29
- "nyc": "^15.1.0",
30
- "standard": "^16.0.3"
31
- },
32
25
  "dependencies": {
33
- "abstract-syntax-tree": "^2.20.0",
34
- "pure-utilities": "^1.2.3",
35
- "underscore": "^1.13.1"
26
+ "abstract-syntax-tree": "^3.0.0"
36
27
  },
37
- "standard": {
38
- "ignore": [
39
- "test/fixture/*"
40
- ]
28
+ "engines": {
29
+ "node": ">=24.12.0"
41
30
  }
42
31
  }
@@ -1,9 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const { unique } = require('underscore')
4
3
  const AbstractSyntaxTree = require('abstract-syntax-tree')
5
- const { identifier } = require('pure-utilities/array')
6
- const { flatten } = require('pure-utilities/collection')
7
4
 
8
5
  const {
9
6
  BlockStatement,
@@ -16,32 +13,68 @@ const {
16
13
  ReturnStatement
17
14
  } = AbstractSyntaxTree
18
15
 
19
- class Module extends AbstractSyntaxTree {
20
- convert () {
21
- if (this.has('ImportDeclaration') || this.has('ImportExpression')) {
22
- this.convertCodeWithImportDeclarations()
23
- } else if (this.has('ExportDefaultDeclaration')) {
24
- this.convertExportDefaultDeclarationToDefine()
25
- } else if (this.has('ExportNamedDeclaration')) {
26
- this.convertExportNamedDeclarationToDefine()
16
+ const MODULE_DECLARATIONS = [
17
+ 'ImportDeclaration',
18
+ 'ExportAllDeclaration',
19
+ 'ExportDefaultDeclaration',
20
+ 'ExportNamedDeclaration'
21
+ ]
22
+
23
+ function getFreeIdentifier (identifiers) {
24
+ let alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
25
+ let index = 0
26
+ while (identifiers.includes(alphabet[index])) {
27
+ index += 1
28
+ if (index === alphabet.length) {
29
+ index = 0
30
+ alphabet = alphabet.map(character => '_' + character)
27
31
  }
28
32
  }
33
+ return alphabet[index]
34
+ }
29
35
 
30
- convertCodeWithImportDeclarations () {
31
- const pairs = this.getDependencyPairs()
32
- if (this.has('ImportExpression')) {
33
- pairs.unshift({ element: 'require', param: 'require' })
34
- this.convertImportExpressions()
36
+ function uniqueBy (array, iteratee) {
37
+ const seen = new Set()
38
+ return array.filter(item => {
39
+ const key = iteratee(item)
40
+ if (seen.has(key)) { return false }
41
+ seen.add(key)
42
+ return true
43
+ })
44
+ }
45
+
46
+ function isModuleDeclaration (node) {
47
+ return MODULE_DECLARATIONS.includes(node.type)
48
+ }
49
+
50
+ // import and export names are either identifiers or string literals
51
+ function getName (node) {
52
+ return node.type === 'Identifier' ? node.name : node.value
53
+ }
54
+
55
+ function getIdentifier (name) {
56
+ return { type: 'Identifier', name }
57
+ }
58
+
59
+ class Module extends AbstractSyntaxTree {
60
+ convert () {
61
+ const dynamic = this.has('ImportExpression')
62
+ if (!dynamic && !this.body.some(isModuleDeclaration)) {
63
+ return
35
64
  }
36
- this.remove({ type: 'ImportDeclaration' })
37
- this.normalizePairs(pairs)
38
- if (this.has('ExportDefaultDeclaration')) {
39
- this.convertExportDefaultDeclarationToReturn()
40
- } else if (this.has('ExportNamedDeclaration')) {
41
- this.convertExportNamedDeclarations()
65
+ this.names = this.find('Identifier').map(node => node.name)
66
+ this.params = new Map()
67
+ this.scope = AbstractSyntaxTree.scope(this._tree)
68
+ this.exports = { properties: [], spreads: [], default: null }
69
+ const dependencies = this.getDependencies()
70
+ if (dynamic) {
71
+ dependencies.unshift({ element: 'require', param: 'require' })
72
+ this.convertImportExpressions()
42
73
  }
74
+ this.convertModuleDeclarations()
75
+ this.appendReturnStatement()
43
76
  this.prependUseStrictLiteral()
44
- this.wrapWithDefineWithArrayExpression(pairs)
77
+ this.wrapWithDefine(dependencies)
45
78
  }
46
79
 
47
80
  prependUseStrictLiteral () {
@@ -50,55 +83,72 @@ class Module extends AbstractSyntaxTree {
50
83
  }))
51
84
  }
52
85
 
53
- isSideEffectImportDeclaration (node) {
54
- return node.source && node.source.type === 'Literal' && node.specifiers.length === 0
86
+ getFreeName (name) {
87
+ while (this.names.includes(name)) {
88
+ name = '_' + name
89
+ }
90
+ this.names.push(name)
91
+ return name
92
+ }
93
+
94
+ // every dependency gets one param: the local name of its default or
95
+ // namespace import when there is one, a generated identifier otherwise
96
+ getParam (element) {
97
+ if (!this.params.has(element)) {
98
+ const param = getFreeIdentifier(this.names)
99
+ this.names.push(param)
100
+ this.params.set(element, param)
101
+ }
102
+ return this.params.get(element)
55
103
  }
56
104
 
57
- getDependencyPairs () {
58
- const dependencyToIdentifierMap = {}
59
- const imports = this.find('ImportDeclaration')
60
- const ids = unique(imports.map(item => item.name))
61
- const result = flatten(imports.map(node => {
62
- if (this.isSideEffectImportDeclaration(node)) {
63
- return {
64
- element: node.source.value
105
+ getDependencies () {
106
+ const imports = this.body.filter(node => node.type === 'ImportDeclaration')
107
+ for (const node of imports) {
108
+ for (const specifier of node.specifiers) {
109
+ if (specifier.type !== 'ImportSpecifier' && !this.params.has(node.source.value)) {
110
+ this.params.set(node.source.value, specifier.local.name)
65
111
  }
66
112
  }
67
- return node.specifiers.map(function (specifier) {
68
- if (specifier.type === 'ImportDefaultSpecifier' || specifier.type === 'ImportNamespaceSpecifier') {
69
- return this.getLocalSpecifier(node, specifier)
70
- }
71
- if (specifier.type === 'ImportSpecifier') {
72
- let param
73
- const value = node.source.value
74
- if (specifier.imported.name !== specifier.local.name) {
75
- return this.getLocalSpecifier(node, specifier)
76
- } else if (Object.prototype.hasOwnProperty.call(dependencyToIdentifierMap, value)) {
77
- param = dependencyToIdentifierMap[value]
78
- } else {
79
- const identifiers = unique(flatten(ids)).concat(Object.values(dependencyToIdentifierMap))
80
- param = identifier(identifiers)
81
- dependencyToIdentifierMap[value] = param
82
- }
83
- return {
84
- param,
85
- element: node.source.value,
86
- name: specifier.local.name
87
- }
88
- }
89
- }.bind(this))
90
- }))
91
- return result.sort((a, b) => {
92
- if (a.param && !b.param) { return -1 }
93
- if (!a.param && b.param) { return 1 }
94
- return 0
113
+ }
114
+ const dependencies = this.body.flatMap(node => {
115
+ if (node.type === 'ImportDeclaration') {
116
+ return this.getImportDependencies(node)
117
+ }
118
+ // export ... from
119
+ return node.source ? { element: node.source.value, param: this.getParam(node.source.value) } : []
95
120
  })
121
+ const elements = new Set(dependencies.filter(pair => pair.param).map(pair => pair.element))
122
+ const pairs = dependencies.filter(pair => pair.param || !elements.has(pair.element))
123
+ return uniqueBy(pairs, pair => pair.element + '\n' + pair.param)
124
+ .sort((a, b) => Boolean(b.param) - Boolean(a.param))
96
125
  }
97
126
 
98
- getLocalSpecifier (node, specifier) {
99
- return {
100
- element: node.source.value,
101
- param: specifier.local.name
127
+ getImportDependencies (node) {
128
+ const element = node.source.value
129
+ if (node.specifiers.length === 0) {
130
+ return { element }
131
+ }
132
+ return node.specifiers.map(specifier => {
133
+ if (specifier.type !== 'ImportSpecifier') {
134
+ return { element, param: specifier.local.name }
135
+ }
136
+ const param = this.getParam(element)
137
+ this.convertReferences(specifier.local.name, param, specifier.imported)
138
+ return { element, param }
139
+ })
140
+ }
141
+
142
+ // scope analysis gives the identifiers that really refer to the import,
143
+ // so property keys, labels and shadowing variables are left untouched
144
+ convertReferences (name, param, imported) {
145
+ const binding = this.scope.getBinding(name)
146
+ for (const { identifier, parent } of binding.references) {
147
+ if (parent.type === 'Property' && parent.shorthand) {
148
+ parent.shorthand = false
149
+ }
150
+ delete identifier.name
151
+ Object.assign(identifier, this.getMemberExpression(param, imported))
102
152
  }
103
153
  }
104
154
 
@@ -126,7 +176,7 @@ class Module extends AbstractSyntaxTree {
126
176
  this.getBinaryExpression(new Literal({ value: 'default' }), 'in', module)
127
177
  ),
128
178
  this.getObjectExpression([this.getProperty(defaultIdentifier, module)]),
129
- this.getCallExpression(this.getMemberExpression('Object', 'defineProperty'), [
179
+ this.getCallExpression(this.getMemberExpression('Object', getIdentifier('defineProperty')), [
130
180
  module,
131
181
  new Literal({ value: 'default' }),
132
182
  this.getObjectExpression([
@@ -144,47 +194,113 @@ class Module extends AbstractSyntaxTree {
144
194
  })
145
195
  }
146
196
 
147
- convertExportNamedDeclarations () {
148
- const declarations = this.find('ExportNamedDeclaration')
149
- this.convertExportNamedDeclarationToDeclaration()
150
- this.remove({ type: 'ExportNamedDeclaration' })
151
- this.append(new ReturnStatement({
152
- argument: this.getObjectExpressionForDeclarations(declarations)
153
- }))
197
+ convertModuleDeclarations () {
198
+ const last = this.body.at(-1)
199
+ const single = this.body.filter(node => node.type.startsWith('Export')).length === 1
200
+ this.body = this.body.flatMap(node => {
201
+ if (node.type === 'ImportDeclaration') {
202
+ return []
203
+ }
204
+ if (node.type === 'ExportAllDeclaration') {
205
+ return this.convertExportAllDeclaration(node)
206
+ }
207
+ if (node.type === 'ExportNamedDeclaration') {
208
+ return this.convertExportNamedDeclaration(node)
209
+ }
210
+ if (node.type === 'ExportDefaultDeclaration') {
211
+ return this.convertExportDefaultDeclaration(node, node === last && single)
212
+ }
213
+ return node
214
+ })
154
215
  }
155
216
 
156
- convertExportNamedDeclarationToDeclaration () {
157
- this.replace({
158
- enter: function (node) {
159
- if (node.type === 'ExportNamedDeclaration' && node.declaration) {
160
- return node.declaration
217
+ addExport (exported, value, shorthand = false) {
218
+ if (getName(exported) === 'default') {
219
+ this.exports.default = value
220
+ } else {
221
+ this.exports.properties.push(this.getProperty(exported, value, shorthand))
222
+ }
223
+ }
224
+
225
+ convertExportAllDeclaration (node) {
226
+ const param = getIdentifier(this.getParam(node.source.value))
227
+ if (node.exported) {
228
+ this.addExport(node.exported, param)
229
+ } else {
230
+ this.exports.spreads.push(param)
231
+ }
232
+ return []
233
+ }
234
+
235
+ convertExportNamedDeclaration (node) {
236
+ if (node.declaration) {
237
+ const identifiers = new Set(AbstractSyntaxTree.find(node.declaration, 'Identifier'))
238
+ for (const binding of this.scope.bindings) {
239
+ if (binding.declarations.some(identifier => identifiers.has(identifier))) {
240
+ this.addExport(getIdentifier(binding.name), getIdentifier(binding.name))
161
241
  }
162
242
  }
163
- })
243
+ return node.declaration
244
+ }
245
+ for (const { local, exported } of node.specifiers) {
246
+ if (!node.source) {
247
+ this.addExport(exported, local, local.type === 'Identifier' && local.name === exported.name)
248
+ } else if (getName(local) === 'default') {
249
+ this.addExport(exported, getIdentifier(this.getParam(node.source.value)))
250
+ } else {
251
+ this.addExport(exported, this.getMemberExpression(this.getParam(node.source.value), local))
252
+ }
253
+ }
254
+ return []
164
255
  }
165
256
 
166
- convertExportDefaultDeclarationToDefine () {
167
- this.prependUseStrictLiteral()
168
- this.convertExportDefaultDeclarationToReturn()
169
- this.wrap(body => {
170
- return [this.getDefineWithFunctionExpression(body)]
171
- })
257
+ convertExportDefaultDeclaration (node, returnable) {
258
+ const { declaration } = node
259
+ if (returnable) {
260
+ return new ReturnStatement({ argument: this.getExpression(declaration) })
261
+ }
262
+ if (declaration.type.endsWith('Declaration') && declaration.id) {
263
+ this.exports.default = getIdentifier(declaration.id.name)
264
+ return declaration
265
+ }
266
+ const name = this.getFreeName('_default')
267
+ this.exports.default = getIdentifier(name)
268
+ return {
269
+ type: 'VariableDeclaration',
270
+ kind: 'const',
271
+ declarations: [{
272
+ type: 'VariableDeclarator',
273
+ id: getIdentifier(name),
274
+ init: this.getExpression(declaration)
275
+ }]
276
+ }
172
277
  }
173
278
 
174
- getDefineWithFunctionExpression (body) {
175
- return this.getDefine([this.getFunctionExpression([], body)])
279
+ // default exported functions and classes are declarations
280
+ getExpression (node) {
281
+ node.type = node.type.replace('Declaration', 'Expression')
282
+ return node
176
283
  }
177
284
 
178
- convertExportDefaultDeclarationToReturn () {
179
- this.replace({
180
- enter: node => {
181
- if (node.type === 'ExportDefaultDeclaration') {
182
- node.type = 'ReturnStatement'
183
- node.argument = node.declaration
184
- return node
185
- }
285
+ appendReturnStatement () {
286
+ const { properties, spreads } = this.exports
287
+ let argument = this.exports.default
288
+ if (properties.length > 0 || spreads.length > 0) {
289
+ if (argument) {
290
+ properties.push(this.getProperty(getIdentifier('default'), argument))
186
291
  }
187
- })
292
+ argument = this.getObjectExpression(properties)
293
+ if (spreads.length > 0) {
294
+ const sources = properties.length > 0 ? [...spreads, argument] : spreads
295
+ argument = this.getCallExpression(
296
+ this.getMemberExpression('Object', getIdentifier('assign')),
297
+ [this.getObjectExpression([]), ...sources]
298
+ )
299
+ }
300
+ }
301
+ if (argument) {
302
+ this.append(new ReturnStatement({ argument }))
303
+ }
188
304
  }
189
305
 
190
306
  getDefine (nodes) {
@@ -196,17 +312,9 @@ class Module extends AbstractSyntaxTree {
196
312
  })
197
313
  }
198
314
 
199
- convertExportNamedDeclarationToDefine () {
200
- this.prependUseStrictLiteral()
201
- this.convertExportNamedDeclarations()
202
- this.wrap(body => {
203
- return [this.getDefineWithFunctionExpression(body)]
204
- })
205
- }
206
-
207
315
  getFunctionExpression (params, body) {
208
316
  return new FunctionExpression({
209
- params: params,
317
+ params,
210
318
  body: new BlockStatement({ body })
211
319
  })
212
320
  }
@@ -225,145 +333,50 @@ class Module extends AbstractSyntaxTree {
225
333
  })
226
334
  }
227
335
 
228
- getMemberExpression (object, member) {
336
+ getMemberExpression (object, property) {
337
+ const computed = property.type !== 'Identifier'
229
338
  return {
230
339
  type: 'MemberExpression',
231
- object: {
232
- type: 'Identifier',
233
- name: object
234
- },
235
- property: {
236
- type: 'Identifier',
237
- name: member
238
- }
340
+ object: getIdentifier(object),
341
+ property: computed ? { type: 'Literal', value: property.value } : getIdentifier(property.name),
342
+ computed
239
343
  }
240
344
  }
241
345
 
242
346
  getConditionalExpression (test, consequent, alternate) {
243
- return {
244
- type: 'ConditionalExpression',
245
- test: test,
246
- consequent: consequent,
247
- alternate: alternate
248
- }
347
+ return { type: 'ConditionalExpression', test, consequent, alternate }
249
348
  }
250
349
 
251
350
  getLogicalExpression (left, operator, right) {
252
- return {
253
- type: 'LogicalExpression',
254
- left: left,
255
- operator: operator,
256
- right: right
257
- }
351
+ return { type: 'LogicalExpression', left, operator, right }
258
352
  }
259
353
 
260
354
  getBinaryExpression (left, operator, right) {
261
- return {
262
- type: 'BinaryExpression',
263
- left: left,
264
- operator: operator,
265
- right: right
266
- }
355
+ return { type: 'BinaryExpression', left, operator, right }
267
356
  }
268
357
 
269
358
  getTypeof (argument) {
270
- return {
271
- type: 'UnaryExpression',
272
- prefix: true,
273
- operator: 'typeof',
274
- argument: argument
275
- }
359
+ return { type: 'UnaryExpression', prefix: true, operator: 'typeof', argument }
276
360
  }
277
361
 
278
- getProperty (nodeOrKey, shorthandOrValue) {
279
- return {
280
- type: 'Property',
281
- key: nodeOrKey,
282
- value: typeof shorthandOrValue === 'boolean' || typeof shorthandOrValue === 'undefined' ? nodeOrKey : shorthandOrValue,
283
- shorthand: shorthandOrValue === true,
284
- kind: 'init'
285
- }
362
+ getProperty (key, value, shorthand = false) {
363
+ return { type: 'Property', key, value, shorthand, kind: 'init' }
286
364
  }
287
365
 
288
366
  getObjectExpression (properties) {
289
- return {
290
- type: 'ObjectExpression',
291
- properties: properties
292
- }
293
- }
294
-
295
- getObjectExpressionForDeclarations (declarations) {
296
- return this.getObjectExpression(this.mapDeclarationsToProperties(declarations))
297
- }
298
-
299
- mapDeclarationsToProperties (declarations) {
300
- return flatten(declarations.map(this.mapDeclarationToProperty.bind(this)))
301
- }
302
-
303
- mapDeclarationToProperty (declaration) {
304
- if (!declaration.declaration && declaration.specifiers) {
305
- return declaration.specifiers.map(node => {
306
- return this.getProperty(node.local, true)
307
- })
308
- }
309
- if (declaration.declaration.type === 'VariableDeclaration') {
310
- return declaration.declaration.declarations.map(node => {
311
- return this.getProperty(node.id)
312
- })
313
- }
314
- return this.getProperty(declaration.declaration.id)
315
- }
316
-
317
- normalizePairs (pairs) {
318
- const nodes = pairs.filter(pair => !!pair.name)
319
- const names = nodes.map(node => node.name)
320
- this.replace({
321
- leave: (current, parent) => {
322
- if (current.type === 'Identifier') {
323
- const index = names.indexOf(current.name)
324
- if (index !== -1) {
325
- const pair = nodes[index]
326
- return this.convertIdentifierToMemberExpression(pair)
327
- }
328
- }
329
- return current
330
- }
331
- })
332
- }
333
-
334
- convertIdentifierToMemberExpression (pair, current) {
335
- return {
336
- type: 'MemberExpression',
337
- object: {
338
- type: 'Identifier',
339
- name: pair.param
340
- },
341
- property: {
342
- type: 'Identifier',
343
- name: pair.name
344
- }
345
- }
367
+ return { type: 'ObjectExpression', properties }
346
368
  }
347
369
 
348
370
  getArrayExpression (elements) {
349
- return { type: 'ArrayExpression', elements: elements }
371
+ return { type: 'ArrayExpression', elements }
350
372
  }
351
373
 
352
- wrapWithDefineWithArrayExpression (pairs) {
353
- pairs = unique(pairs, item => item.element + item.param)
354
- const elements = pairs.map(pair => pair.element)
355
- .map(function (element) {
356
- return { type: 'Literal', value: element }
357
- })
358
- const params = pairs.filter(pair => pair.param).map(pair => pair.param)
359
- .map(function (param) {
360
- return { type: 'Identifier', name: param }
361
- })
374
+ wrapWithDefine (dependencies) {
375
+ const elements = dependencies.map(pair => ({ type: 'Literal', value: pair.element }))
376
+ const params = dependencies.filter(pair => pair.param).map(pair => getIdentifier(pair.param))
362
377
  this.wrap(body => {
363
- return [this.getDefine([
364
- this.getArrayExpression(elements),
365
- this.getFunctionExpression(params, body)
366
- ])]
378
+ const callback = this.getFunctionExpression(params, body)
379
+ return [this.getDefine(elements.length > 0 ? [this.getArrayExpression(elements), callback] : [callback])]
367
380
  })
368
381
  }
369
382
  }