@atlaspack/optimizer-inline-requires 2.12.1-dev.3567 → 2.13.1-canary.3630

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # @atlaspack/optimizer-inline-requires
2
+
3
+ ## 2.13.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#335](https://github.com/atlassian-labs/atlaspack/pull/335) [`b4dbd4d`](https://github.com/atlassian-labs/atlaspack/commit/b4dbd4d5b23d1b7aa3fcdf59cc7bc8bedd3a59cf) Thanks [@yamadapc](https://github.com/yamadapc)! - Initial changeset release
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [[`b4dbd4d`](https://github.com/atlassian-labs/atlaspack/commit/b4dbd4d5b23d1b7aa3fcdf59cc7bc8bedd3a59cf)]:
12
+ - @atlaspack/feature-flags@2.13.0
13
+ - @atlaspack/plugin@2.13.0
14
+ - @atlaspack/rust@2.13.0
15
+ - @atlaspack/types@2.13.0
@@ -7,13 +7,6 @@ function _plugin() {
7
7
  };
8
8
  return data;
9
9
  }
10
- function _featureFlags() {
11
- const data = require("@atlaspack/feature-flags");
12
- _featureFlags = function () {
13
- return data;
14
- };
15
- return data;
16
- }
17
10
  function _rust() {
18
11
  const data = require("@atlaspack/rust");
19
12
  _rust = function () {
@@ -21,14 +14,6 @@ function _rust() {
21
14
  };
22
15
  return data;
23
16
  }
24
- function _core() {
25
- const data = require("@swc/core");
26
- _core = function () {
27
- return data;
28
- };
29
- return data;
30
- }
31
- var _RequireInliningVisitor = require("./RequireInliningVisitor");
32
17
  function _nullthrows() {
33
18
  const data = _interopRequireDefault(require("nullthrows"));
34
19
  _nullthrows = function () {
@@ -76,11 +61,10 @@ module.exports = new (_plugin().Optimizer)({
76
61
  assetPublicIdsWithSideEffects
77
62
  };
78
63
  },
79
- async optimize({
64
+ optimize({
80
65
  bundle,
81
66
  contents,
82
67
  map: originalMap,
83
- tracer,
84
68
  logger,
85
69
  bundleConfig,
86
70
  options
@@ -92,58 +76,24 @@ module.exports = new (_plugin().Optimizer)({
92
76
  };
93
77
  }
94
78
  try {
95
- if ((0, _featureFlags().getFeatureFlag)('fastOptimizeInlineRequires')) {
96
- let sourceMap = null;
97
- const result = (0, _rust().runInlineRequiresOptimizer)({
98
- code: contents.toString(),
99
- sourceMaps: !!bundle.env.sourceMap,
100
- ignoreModuleIds: Array.from(bundleConfig.assetPublicIdsWithSideEffects)
101
- });
102
- const sourceMapResult = result.sourceMap;
103
- if (sourceMapResult != null) {
104
- sourceMap = new (_sourceMap().default)(options.projectRoot);
105
- sourceMap.addVLQMap(JSON.parse(sourceMapResult));
106
- if (originalMap) {
107
- sourceMap.extends(originalMap);
108
- }
109
- }
110
- return {
111
- contents: result.code,
112
- map: originalMap
113
- };
114
- }
115
- let measurement = tracer.createMeasurement('@atlaspack/optimizer-inline-requires', 'parse', bundle.name);
116
- const ast = await (0, _core().parse)(contents.toString());
117
- measurement && measurement.end();
118
- const visitor = new _RequireInliningVisitor.RequireInliningVisitor({
119
- bundle,
120
- logger,
121
- assetPublicIdsWithSideEffects: bundleConfig.assetPublicIdsWithSideEffects
79
+ let sourceMap = null;
80
+ const result = (0, _rust().runInlineRequiresOptimizer)({
81
+ code: contents.toString(),
82
+ sourceMaps: !!bundle.env.sourceMap,
83
+ ignoreModuleIds: Array.from(bundleConfig.assetPublicIdsWithSideEffects)
122
84
  });
123
- measurement = tracer.createMeasurement('@atlaspack/optimizer-inline-requires', 'visit', bundle.name);
124
- visitor.visitProgram(ast);
125
- measurement && measurement.end();
126
- if (visitor.dirty) {
127
- const measurement = tracer.createMeasurement('@atlaspack/optimizer-inline-requires', 'print', bundle.name);
128
- const result = await (0, _core().print)(ast, {
129
- sourceMaps: !!bundle.env.sourceMap
130
- });
131
- measurement && measurement.end();
132
- let sourceMap = null;
133
- let resultMap = result.map;
134
- let contents = (0, _nullthrows().default)(result.code);
135
- if (resultMap != null) {
136
- sourceMap = new (_sourceMap().default)(options.projectRoot);
137
- sourceMap.addVLQMap(JSON.parse(resultMap));
138
- if (originalMap) {
139
- sourceMap.extends(originalMap);
140
- }
85
+ const sourceMapResult = result.sourceMap;
86
+ if (sourceMapResult != null) {
87
+ sourceMap = new (_sourceMap().default)(options.projectRoot);
88
+ sourceMap.addVLQMap(JSON.parse(sourceMapResult));
89
+ if (originalMap) {
90
+ sourceMap.extends(originalMap);
141
91
  }
142
- return {
143
- contents,
144
- map: sourceMap
145
- };
146
92
  }
93
+ return {
94
+ contents: result.code,
95
+ map: sourceMap
96
+ };
147
97
  } catch (err) {
148
98
  logger.warn({
149
99
  origin: 'atlaspack-optimizer-experimental-inline-requires',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/optimizer-inline-requires",
3
- "version": "2.12.1-dev.3567+c06f4487e",
3
+ "version": "2.13.1-canary.3630+10a6f37ef",
4
4
  "license": "(MIT OR Apache-2.0)",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -12,17 +12,17 @@
12
12
  "main": "lib/InlineRequires.js",
13
13
  "source": "src/InlineRequires.js",
14
14
  "engines": {
15
- "atlaspack": "^2.12.1-dev.3567+c06f4487e",
15
+ "atlaspack": "2.13.1-canary.3630+10a6f37ef",
16
16
  "node": ">= 14.0.0"
17
17
  },
18
18
  "dependencies": {
19
- "@atlaspack/feature-flags": "2.12.1-dev.3567+c06f4487e",
20
- "@atlaspack/plugin": "2.12.1-dev.3567+c06f4487e",
21
- "@atlaspack/rust": "2.12.1-dev.3567+c06f4487e",
22
- "@atlaspack/types": "2.12.1-dev.3567+c06f4487e",
19
+ "@atlaspack/feature-flags": "2.13.1-canary.3630+10a6f37ef",
20
+ "@atlaspack/plugin": "2.13.1-canary.3630+10a6f37ef",
21
+ "@atlaspack/rust": "2.13.1-canary.3630+10a6f37ef",
22
+ "@atlaspack/types": "2.13.1-canary.3630+10a6f37ef",
23
23
  "@parcel/source-map": "^2.1.1",
24
- "@swc/core": "^1.7.26",
24
+ "@swc/core": "^1.10.0",
25
25
  "nullthrows": "^1.1.1"
26
26
  },
27
- "gitHead": "c06f4487ebddc632957147c8b585a97e149062a1"
27
+ "gitHead": "10a6f37ef063d0227ebb26310383e899dbd9b1e6"
28
28
  }
@@ -1,9 +1,6 @@
1
1
  // @flow strict-local
2
2
  import {Optimizer} from '@atlaspack/plugin';
3
- import {getFeatureFlag} from '@atlaspack/feature-flags';
4
3
  import {runInlineRequiresOptimizer} from '@atlaspack/rust';
5
- import {parse, print} from '@swc/core';
6
- import {RequireInliningVisitor} from './RequireInliningVisitor';
7
4
  import nullthrows from 'nullthrows';
8
5
  import SourceMap from '@parcel/source-map';
9
6
 
@@ -45,11 +42,10 @@ module.exports = new Optimizer<empty, BundleConfig>({
45
42
  return {assetPublicIdsWithSideEffects};
46
43
  },
47
44
 
48
- async optimize({
45
+ optimize({
49
46
  bundle,
50
47
  contents,
51
48
  map: originalMap,
52
- tracer,
53
49
  logger,
54
50
  bundleConfig,
55
51
  options,
@@ -59,72 +55,21 @@ module.exports = new Optimizer<empty, BundleConfig>({
59
55
  }
60
56
 
61
57
  try {
62
- if (getFeatureFlag('fastOptimizeInlineRequires')) {
63
- let sourceMap = null;
64
- const result = runInlineRequiresOptimizer({
65
- code: contents.toString(),
66
- sourceMaps: !!bundle.env.sourceMap,
67
- ignoreModuleIds: Array.from(
68
- bundleConfig.assetPublicIdsWithSideEffects,
69
- ),
70
- });
71
- const sourceMapResult = result.sourceMap;
72
- if (sourceMapResult != null) {
73
- sourceMap = new SourceMap(options.projectRoot);
74
- sourceMap.addVLQMap(JSON.parse(sourceMapResult));
75
- if (originalMap) {
76
- sourceMap.extends(originalMap);
77
- }
78
- }
79
- return {contents: result.code, map: originalMap};
80
- }
81
-
82
- let measurement = tracer.createMeasurement(
83
- '@atlaspack/optimizer-inline-requires',
84
- 'parse',
85
- bundle.name,
86
- );
87
- const ast = await parse(contents.toString());
88
- measurement && measurement.end();
89
-
90
- const visitor = new RequireInliningVisitor({
91
- bundle,
92
- logger,
93
- assetPublicIdsWithSideEffects:
94
- bundleConfig.assetPublicIdsWithSideEffects,
58
+ let sourceMap = null;
59
+ const result = runInlineRequiresOptimizer({
60
+ code: contents.toString(),
61
+ sourceMaps: !!bundle.env.sourceMap,
62
+ ignoreModuleIds: Array.from(bundleConfig.assetPublicIdsWithSideEffects),
95
63
  });
96
-
97
- measurement = tracer.createMeasurement(
98
- '@atlaspack/optimizer-inline-requires',
99
- 'visit',
100
- bundle.name,
101
- );
102
- visitor.visitProgram(ast);
103
- measurement && measurement.end();
104
-
105
- if (visitor.dirty) {
106
- const measurement = tracer.createMeasurement(
107
- '@atlaspack/optimizer-inline-requires',
108
- 'print',
109
- bundle.name,
110
- );
111
- const result = await print(ast, {sourceMaps: !!bundle.env.sourceMap});
112
- measurement && measurement.end();
113
-
114
- let sourceMap = null;
115
- let resultMap = result.map;
116
- let contents: string = nullthrows(result.code);
117
-
118
- if (resultMap != null) {
119
- sourceMap = new SourceMap(options.projectRoot);
120
- sourceMap.addVLQMap(JSON.parse(resultMap));
121
- if (originalMap) {
122
- sourceMap.extends(originalMap);
123
- }
64
+ const sourceMapResult = result.sourceMap;
65
+ if (sourceMapResult != null) {
66
+ sourceMap = new SourceMap(options.projectRoot);
67
+ sourceMap.addVLQMap(JSON.parse(sourceMapResult));
68
+ if (originalMap) {
69
+ sourceMap.extends(originalMap);
124
70
  }
125
-
126
- return {contents, map: sourceMap};
127
71
  }
72
+ return {contents: result.code, map: sourceMap};
128
73
  } catch (err) {
129
74
  logger.warn({
130
75
  origin: 'atlaspack-optimizer-experimental-inline-requires',
@@ -1,194 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.RequireInliningVisitor = void 0;
7
- function _Visitor() {
8
- const data = require("@swc/core/Visitor");
9
- _Visitor = function () {
10
- return data;
11
- };
12
- return data;
13
- }
14
- function _nullthrows() {
15
- const data = _interopRequireDefault(require("nullthrows"));
16
- _nullthrows = function () {
17
- return data;
18
- };
19
- return data;
20
- }
21
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
- class RequireInliningVisitor extends _Visitor().Visitor {
23
- constructor({
24
- bundle,
25
- logger,
26
- assetPublicIdsWithSideEffects
27
- }) {
28
- super();
29
- this.currentModuleNode = null;
30
- this.moduleVariables = new Set();
31
- this.moduleVariableMap = new Map();
32
- this.dirty = false;
33
- this.logger = logger;
34
- this.bundle = bundle;
35
- this.assetPublicIdsWithSideEffects = assetPublicIdsWithSideEffects;
36
- }
37
- visitFunctionExpression(n) {
38
- // This visitor tries to find module definition functions, these are of the form:
39
- //
40
- // parcelRequire.register("moduleId", function (require, module, exports) { ... });
41
- //
42
- // We do this to set the vistior variable `inModuleDefinition` for subsequent visits,
43
- // and also reset the module variable tracking data structures.
44
- //
45
- // (TODO: Support arrow functions if we modify the runtime to output arrow functions)
46
- if (n.params.length === 3 && n.params[0].pat.type === 'Identifier' && n.params[0].pat.value === 'require' && n.params[1].pat.type === 'Identifier' && n.params[1].pat.value === 'module' && n.params[2].pat.type === 'Identifier' && n.params[2].pat.value === 'exports') {
47
- // `inModuleDefinition` is either null, or the module definition node
48
- this.currentModuleNode = n;
49
- this.moduleVariables = new Set();
50
- this.moduleVariableMap = new Map();
51
- }
52
-
53
- // Make sure we visit the function itself
54
- let result = super.visitFunctionExpression(n);
55
-
56
- // only "exit" module definition if we're exiting the module definition node
57
- if (n === this.currentModuleNode) {
58
- this.currentModuleNode = null;
59
- }
60
- return result;
61
- }
62
- visitVariableDeclaration(n) {
63
- // We're looking for variable declarations that look like this:
64
- //
65
- // `var $acw62 = require("acw62");`
66
- let needsReplacement = false;
67
- for (let i = 0; i < n.declarations.length; i++) {
68
- let decl = n.declarations[i];
69
- const init = decl.init;
70
- if (!init || init.type !== 'CallExpression') {
71
- continue;
72
- }
73
- if ((init.callee.type === 'Identifier' && init.callee.value === 'require' || init.callee.value === 'parcelRequire') && decl.id.value !== 'parcelHelpers' &&
74
- // ignore var parcelHelpers = require("@atlaspack/transformer-js/src/esmodule-helpers.js");
75
- init.arguments[0].expression.type === 'StringLiteral' && typeof decl.id.value === 'string' && decl.id.value.startsWith('$')) {
76
- const variable = decl.id.value;
77
- const assetPublicId = variable.substring(1);
78
-
79
- // We need to determine whether the asset we're require'ing has sideEffects - if it does, we
80
- // shouldn't optimise it to an inline require as the side effects need to run immediately
81
- //
82
- // We need to use the public id of the asset (which is the variable name used for requiring it) in
83
- // order to find the asset in the bundle graph, and check whether `asset.sideEffects` is true - in
84
- // which case we skip optimising this asset.
85
- //
86
- // This won't work in dev mode, because the id used to require the asset isn't the public id
87
- if (this.assetPublicIdsWithSideEffects && this.assetPublicIdsWithSideEffects.has(assetPublicId)) {
88
- continue;
89
- }
90
-
91
- // The moduleVariableMap contains a mapping from (e.g. $acw62 -> the AST node `require("acw62")`)
92
- this.moduleVariableMap.set(variable, init);
93
- // The moduleVariables set is just the used set of modules (e.g. `$acw62`)
94
- this.moduleVariables.add(variable);
95
-
96
- // Replace this with a null declarator, we'll use the `init` where it's declared.
97
- //
98
- // This mutates `var $acw62 = require("acw62")` -> `var $acw62 = null`
99
- //
100
- // The variable will be unused and removed by optimisation
101
- decl.init = undefined;
102
- needsReplacement = true;
103
- } else if (decl.id.type === 'Identifier' && typeof decl.id.value === 'string' && decl.id.value.endsWith('Default') && decl.id.value.startsWith('$')) {
104
- // Handle modules with default values, these look like this in the source:
105
- // ```
106
- // var _app = require("./App");
107
- // var _appDefault = parcelHelpers.interopDefault(_app);
108
- // ```
109
- //
110
- // In this case we want to also put `_appDefault` into the `moduleVariableMap` with the initializer node,
111
- // but we want to replace `_app` in there with `require("./App")`.. to summarise, this code will end up looking like:
112
- //
113
- // ```
114
- // var _app = null;
115
- // var _appDefault = null;
116
- // ```
117
- //
118
- // .. and where `_appDefault` is used we replace that with `parcelHelpers.interopDefault(require('./App'))`
119
- const variable = decl.id.value;
120
- const baseId = variable.substring(0, decl.id.value.length - 'Default'.length);
121
- if (!this.moduleVariables.has(baseId)) {
122
- continue;
123
- }
124
- init.arguments[0] = {
125
- spread: undefined,
126
- expression: (0, _nullthrows().default)(this.moduleVariableMap.get(baseId))
127
- };
128
- this.moduleVariableMap.set(variable, init);
129
- this.moduleVariables.add(variable);
130
- decl.init = undefined;
131
- needsReplacement = true;
132
- }
133
- }
134
- if (!needsReplacement) {
135
- return super.visitVariableDeclaration(n);
136
- } else {
137
- this.dirty = true;
138
- return n;
139
- }
140
- }
141
- visitIdentifier(n) {
142
- // This does the actual replacement - for any identifier within this factory function
143
- // that is in the `moduleVariables` list, replace the identifier with the original expression
144
- // that was going to be used to initialise the identifier.
145
- //
146
- // The replacement expression uses the `(0, require(...))` pattern to allow for safe replacement
147
- // in any use cases (since we're replacing a variable access with a function call) - the minifier
148
- // will take care of optimising this away where possible.
149
- //
150
- // e.g.
151
- // var $abc = require("abc");
152
- // console.log($abc.foo());
153
- //
154
- // becomes
155
- //
156
- // var $abc;
157
- // console.log((0, require("abc")).foo);
158
- //
159
- if (this.moduleVariables.has(n.value)) {
160
- // $FlowFixMe the types don't allow for swapping out the node type here, might need a different approach
161
- return this.getReplacementExpression(n.value);
162
- }
163
- return super.visitIdentifier(n);
164
- }
165
-
166
- // Helper function to wrap an existing node in a sequence expression, that is, it
167
- // will take a node `n` and return the AST for `(0, n)`
168
- //
169
- // This ensures that the require call can be correctly used in any context - where
170
- // the sequence is redundant, the minifier will optimise it away.
171
- getReplacementExpression(id) {
172
- return {
173
- type: 'ParenthesisExpression',
174
- span: RequireInliningVisitor.getEmptySpan(),
175
- expression: {
176
- type: 'SequenceExpression',
177
- span: RequireInliningVisitor.getEmptySpan(),
178
- expressions: [{
179
- type: 'NumericLiteral',
180
- span: RequireInliningVisitor.getEmptySpan(),
181
- value: 0
182
- }, (0, _nullthrows().default)(this.moduleVariableMap.get(id))]
183
- }
184
- };
185
- }
186
- static getEmptySpan() {
187
- return {
188
- start: 0,
189
- end: 0,
190
- ctxt: 0
191
- };
192
- }
193
- }
194
- exports.RequireInliningVisitor = RequireInliningVisitor;
@@ -1,226 +0,0 @@
1
- // @flow strict-local
2
- import type {NamedBundle, PluginLogger} from '@atlaspack/types';
3
-
4
- import type {
5
- CallExpression,
6
- VariableDeclaration,
7
- FunctionExpression,
8
- ParenthesisExpression,
9
- Span,
10
- Identifier,
11
- } from '@swc/core';
12
- import {Visitor} from '@swc/core/Visitor';
13
- import nullthrows from 'nullthrows';
14
-
15
- type VisitorOpts = {|
16
- bundle: NamedBundle,
17
- logger: PluginLogger,
18
- assetPublicIdsWithSideEffects: Set<string>,
19
- |};
20
-
21
- export class RequireInliningVisitor extends Visitor {
22
- currentModuleNode: null | FunctionExpression;
23
- moduleVariables: Set<string>;
24
- moduleVariableMap: Map<string, CallExpression>;
25
- dirty: boolean;
26
- logger: PluginLogger;
27
- bundle: NamedBundle;
28
- assetPublicIdsWithSideEffects: Set<string>;
29
-
30
- constructor({bundle, logger, assetPublicIdsWithSideEffects}: VisitorOpts) {
31
- super();
32
- this.currentModuleNode = null;
33
- this.moduleVariables = new Set();
34
- this.moduleVariableMap = new Map();
35
- this.dirty = false;
36
- this.logger = logger;
37
- this.bundle = bundle;
38
- this.assetPublicIdsWithSideEffects = assetPublicIdsWithSideEffects;
39
- }
40
-
41
- visitFunctionExpression(n: FunctionExpression): FunctionExpression {
42
- // This visitor tries to find module definition functions, these are of the form:
43
- //
44
- // parcelRequire.register("moduleId", function (require, module, exports) { ... });
45
- //
46
- // We do this to set the vistior variable `inModuleDefinition` for subsequent visits,
47
- // and also reset the module variable tracking data structures.
48
- //
49
- // (TODO: Support arrow functions if we modify the runtime to output arrow functions)
50
- if (
51
- n.params.length === 3 &&
52
- n.params[0].pat.type === 'Identifier' &&
53
- n.params[0].pat.value === 'require' &&
54
- n.params[1].pat.type === 'Identifier' &&
55
- n.params[1].pat.value === 'module' &&
56
- n.params[2].pat.type === 'Identifier' &&
57
- n.params[2].pat.value === 'exports'
58
- ) {
59
- // `inModuleDefinition` is either null, or the module definition node
60
- this.currentModuleNode = n;
61
- this.moduleVariables = new Set();
62
- this.moduleVariableMap = new Map();
63
- }
64
-
65
- // Make sure we visit the function itself
66
- let result = super.visitFunctionExpression(n);
67
-
68
- // only "exit" module definition if we're exiting the module definition node
69
- if (n === this.currentModuleNode) {
70
- this.currentModuleNode = null;
71
- }
72
- return result;
73
- }
74
-
75
- visitVariableDeclaration(n: VariableDeclaration): VariableDeclaration {
76
- // We're looking for variable declarations that look like this:
77
- //
78
- // `var $acw62 = require("acw62");`
79
- let needsReplacement = false;
80
- for (let i = 0; i < n.declarations.length; i++) {
81
- let decl = n.declarations[i];
82
- const init = decl.init;
83
- if (!init || init.type !== 'CallExpression') {
84
- continue;
85
- }
86
-
87
- if (
88
- ((init.callee.type === 'Identifier' &&
89
- init.callee.value === 'require') ||
90
- init.callee.value === 'parcelRequire') &&
91
- decl.id.value !== 'parcelHelpers' && // ignore var parcelHelpers = require("@atlaspack/transformer-js/src/esmodule-helpers.js");
92
- init.arguments[0].expression.type === 'StringLiteral' &&
93
- typeof decl.id.value === 'string' &&
94
- decl.id.value.startsWith('$')
95
- ) {
96
- const variable = decl.id.value;
97
- const assetPublicId = variable.substring(1);
98
-
99
- // We need to determine whether the asset we're require'ing has sideEffects - if it does, we
100
- // shouldn't optimise it to an inline require as the side effects need to run immediately
101
- //
102
- // We need to use the public id of the asset (which is the variable name used for requiring it) in
103
- // order to find the asset in the bundle graph, and check whether `asset.sideEffects` is true - in
104
- // which case we skip optimising this asset.
105
- //
106
- // This won't work in dev mode, because the id used to require the asset isn't the public id
107
- if (
108
- this.assetPublicIdsWithSideEffects &&
109
- this.assetPublicIdsWithSideEffects.has(assetPublicId)
110
- ) {
111
- continue;
112
- }
113
-
114
- // The moduleVariableMap contains a mapping from (e.g. $acw62 -> the AST node `require("acw62")`)
115
- this.moduleVariableMap.set(variable, init);
116
- // The moduleVariables set is just the used set of modules (e.g. `$acw62`)
117
- this.moduleVariables.add(variable);
118
-
119
- // Replace this with a null declarator, we'll use the `init` where it's declared.
120
- //
121
- // This mutates `var $acw62 = require("acw62")` -> `var $acw62 = null`
122
- //
123
- // The variable will be unused and removed by optimisation
124
- decl.init = undefined;
125
- needsReplacement = true;
126
- } else if (
127
- decl.id.type === 'Identifier' &&
128
- typeof decl.id.value === 'string' &&
129
- decl.id.value.endsWith('Default') &&
130
- decl.id.value.startsWith('$')
131
- ) {
132
- // Handle modules with default values, these look like this in the source:
133
- // ```
134
- // var _app = require("./App");
135
- // var _appDefault = parcelHelpers.interopDefault(_app);
136
- // ```
137
- //
138
- // In this case we want to also put `_appDefault` into the `moduleVariableMap` with the initializer node,
139
- // but we want to replace `_app` in there with `require("./App")`.. to summarise, this code will end up looking like:
140
- //
141
- // ```
142
- // var _app = null;
143
- // var _appDefault = null;
144
- // ```
145
- //
146
- // .. and where `_appDefault` is used we replace that with `parcelHelpers.interopDefault(require('./App'))`
147
- const variable = decl.id.value;
148
- const baseId = variable.substring(
149
- 0,
150
- decl.id.value.length - 'Default'.length,
151
- );
152
- if (!this.moduleVariables.has(baseId)) {
153
- continue;
154
- }
155
- init.arguments[0] = {
156
- spread: undefined,
157
- expression: nullthrows(this.moduleVariableMap.get(baseId)),
158
- };
159
- this.moduleVariableMap.set(variable, init);
160
- this.moduleVariables.add(variable);
161
-
162
- decl.init = undefined;
163
- needsReplacement = true;
164
- }
165
- }
166
- if (!needsReplacement) {
167
- return super.visitVariableDeclaration(n);
168
- } else {
169
- this.dirty = true;
170
- return n;
171
- }
172
- }
173
-
174
- visitIdentifier(n: Identifier): Identifier {
175
- // This does the actual replacement - for any identifier within this factory function
176
- // that is in the `moduleVariables` list, replace the identifier with the original expression
177
- // that was going to be used to initialise the identifier.
178
- //
179
- // The replacement expression uses the `(0, require(...))` pattern to allow for safe replacement
180
- // in any use cases (since we're replacing a variable access with a function call) - the minifier
181
- // will take care of optimising this away where possible.
182
- //
183
- // e.g.
184
- // var $abc = require("abc");
185
- // console.log($abc.foo());
186
- //
187
- // becomes
188
- //
189
- // var $abc;
190
- // console.log((0, require("abc")).foo);
191
- //
192
- if (this.moduleVariables.has(n.value)) {
193
- // $FlowFixMe the types don't allow for swapping out the node type here, might need a different approach
194
- return this.getReplacementExpression(n.value);
195
- }
196
- return super.visitIdentifier(n);
197
- }
198
-
199
- // Helper function to wrap an existing node in a sequence expression, that is, it
200
- // will take a node `n` and return the AST for `(0, n)`
201
- //
202
- // This ensures that the require call can be correctly used in any context - where
203
- // the sequence is redundant, the minifier will optimise it away.
204
- getReplacementExpression(id: string): ParenthesisExpression {
205
- return {
206
- type: 'ParenthesisExpression',
207
- span: RequireInliningVisitor.getEmptySpan(),
208
- expression: {
209
- type: 'SequenceExpression',
210
- span: RequireInliningVisitor.getEmptySpan(),
211
- expressions: [
212
- {
213
- type: 'NumericLiteral',
214
- span: RequireInliningVisitor.getEmptySpan(),
215
- value: 0,
216
- },
217
- nullthrows(this.moduleVariableMap.get(id)),
218
- ],
219
- },
220
- };
221
- }
222
-
223
- static getEmptySpan(): Span {
224
- return {start: 0, end: 0, ctxt: 0};
225
- }
226
- }
@@ -1,81 +0,0 @@
1
- import {parse, print} from '@swc/core';
2
- import {RequireInliningVisitor} from '../src/RequireInliningVisitor';
3
- import assert from 'assert';
4
- import logger from '@atlaspack/logger';
5
-
6
- async function testRequireInliningVisitor(src, sideEffects) {
7
- const ast = await parse(src, {});
8
- const assetPublicIdsWithSideEffects = new Set(sideEffects);
9
-
10
- const visitor = new RequireInliningVisitor({
11
- bundle: {
12
- name: 'test-bundle',
13
- },
14
- assetPublicIdsWithSideEffects,
15
- logger,
16
- });
17
- visitor.visitProgram(ast);
18
- return (await print(ast)).code;
19
- }
20
-
21
- function getModule(body) {
22
- return `
23
- n.register('def456', function(require, module, exports) {
24
- ${body}
25
- });
26
- `;
27
- }
28
-
29
- function normaliseCode(code) {
30
- return code
31
- .split('\n')
32
- .map((line) => line.trim())
33
- .join('\n')
34
- .trim();
35
- }
36
-
37
- function assertEqualCode(left, right) {
38
- assert.equal(normaliseCode(left), normaliseCode(right));
39
- }
40
-
41
- describe('InliningVisitor', () => {
42
- it('performs basic inlining', async () => {
43
- const src = getModule(`
44
- var $abc123 = require('abc123');
45
- console.log($abc123);`);
46
- const result = await testRequireInliningVisitor(src, []);
47
- assertEqualCode(
48
- result,
49
- getModule(`var $abc123;
50
- console.log((0, require('abc123')));`),
51
- );
52
- });
53
-
54
- it('performs module default inlining', async () => {
55
- const src = getModule(
56
- `var $abc123 = require('abc123');
57
- var $abc123Default = parcelHelpers.interopDefault($abc123);
58
- console.log($abc123Default.foo());`,
59
- );
60
- const expected = getModule(
61
- `var $abc123;
62
- var $abc123Default;
63
- console.log((0, parcelHelpers.interopDefault(require('abc123'))).foo());`,
64
- );
65
- const result = await testRequireInliningVisitor(src, []);
66
- assertEqualCode(result, expected);
67
- });
68
-
69
- it('ignores assets with sideEffects', async () => {
70
- const src = getModule(`var $abc123 = require('abc123');
71
- var $abc456 = require('abc456');
72
- console.log($abc123);
73
- console.log($abc456);`);
74
- const expected = getModule(`var $abc123 = require('abc123');
75
- var $abc456;
76
- console.log($abc123);
77
- console.log((0, require('abc456')));`);
78
- const result = await testRequireInliningVisitor(src, ['abc123']);
79
- assertEqualCode(result, expected);
80
- });
81
- });