@embroider/macros 1.20.6 → 1.21.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.
package/README.md CHANGED
@@ -159,6 +159,35 @@ let foo = importSync('foo');
159
159
  let foo = require('foo');
160
160
  ```
161
161
 
162
+ #### dynamic paths
163
+
164
+ `importSync` also accepts a template literal with interpolations, as long as the
165
+ directory part of the path is a relative path that's known at build time:
166
+
167
+ ```js
168
+ import { importSync } from '@embroider/macros';
169
+
170
+ let mod = importSync(`./results/${type}-result`);
171
+ ```
172
+
173
+ The macro reads that directory at build time and expands the call into a lookup
174
+ over its contents, so the above compiles to something like:
175
+
176
+ ```js
177
+ let mod = {
178
+ 'fact-result': esc(_factResult),
179
+ 'task-result': esc(_taskResult),
180
+ }[`${type}-result`];
181
+ ```
182
+
183
+ Only the entries that the pattern could actually select are included. A file
184
+ extension on the pattern is optional and ignored — `./results/${type}-result.js`
185
+ behaves identically to `./results/${type}-result`.
186
+
187
+ The interpolations must stay within a single path segment. A pattern like
188
+ `./results/${dir}/${type}` is a build error, because the directory to read isn't
189
+ known until runtime.
190
+
162
191
  #### hint
163
192
 
164
193
  When using `importSync` on non ember-addon packages both the package being imported from *and* `ember-auto-import` *must* be in the `dependencies` of your addons `package.json`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embroider/macros",
3
- "version": "1.20.6",
3
+ "version": "1.21.0",
4
4
  "private": false,
5
5
  "description": "Standardized build-time macros for ember apps.",
6
6
  "keywords": [
@@ -33,7 +33,7 @@
33
33
  "lodash": "^4.17.21",
34
34
  "resolve": "^1.20.0",
35
35
  "semver": "^7.3.2",
36
- "@embroider/shared-internals": "3.1.1"
36
+ "@embroider/shared-internals": "3.2.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@babel/core": "^7.14.5",
@@ -54,8 +54,8 @@
54
54
  "scenario-tester": "^3.0.1",
55
55
  "typescript": "^5.4.5",
56
56
  "vitest": "^3.2.4",
57
- "@embroider/test-support": "0.36.0",
58
- "@embroider/core": "4.6.3"
57
+ "@embroider/core": "4.6.6",
58
+ "@embroider/test-support": "0.36.0"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@glint/template": "^1.0.0"
@@ -69,6 +69,8 @@
69
69
  "node": "12.* || 14.* || >= 16"
70
70
  },
71
71
  "ember-addon": {
72
+ "version": 2,
73
+ "type": "addon",
72
74
  "main": "src/ember-addon-main.js"
73
75
  },
74
76
  "scripts": {
@@ -0,0 +1,22 @@
1
+ import type * as Babel from '@babel/core';
2
+ import type { types as t } from '@babel/core';
3
+ type Types = typeof Babel.types;
4
+ export type PatternPart = {
5
+ type: 'static';
6
+ value: string;
7
+ } | {
8
+ type: 'dynamic';
9
+ value: t.Expression;
10
+ };
11
+ export interface ParsedSpecifier {
12
+ dir: string;
13
+ pattern: PatternPart[];
14
+ }
15
+ export declare function patternParts(types: Types, specifier: t.Node): PatternPart[] | undefined;
16
+ export declare function parseSpecifier(parts: PatternPart[]): ParsedSpecifier | undefined;
17
+ export declare function entryKey(entry: string): string;
18
+ export declare function patternMatcher(pattern: PatternPart[]): (key: string) => boolean;
19
+ export declare function lookupExpression(types: Types, pattern: PatternPart[]): t.Expression;
20
+ export declare function relativeSpecifier(path: string): string;
21
+ export {};
22
+ //# sourceMappingURL=import-sync-pattern.d.ts.map
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.patternParts = patternParts;
4
+ exports.parseSpecifier = parseSpecifier;
5
+ exports.entryKey = entryKey;
6
+ exports.patternMatcher = patternMatcher;
7
+ exports.lookupExpression = lookupExpression;
8
+ exports.relativeSpecifier = relativeSpecifier;
9
+ // Turns a specifier expression into a flat list of static and dynamic parts.
10
+ // Returns undefined if this isn't a shape we understand.
11
+ function patternParts(types, specifier) {
12
+ if (specifier.type === 'TemplateLiteral') {
13
+ let parts = [];
14
+ for (let [index, quasi] of specifier.quasis.entries()) {
15
+ parts.push({ type: 'static', value: quasi.value.cooked });
16
+ let expression = specifier.expressions[index];
17
+ if (expression) {
18
+ if (!types.isExpression(expression)) {
19
+ return undefined;
20
+ }
21
+ parts.push({ type: 'dynamic', value: expression });
22
+ }
23
+ }
24
+ return normalize(parts);
25
+ }
26
+ // babel might transform the template form `../my-path/${id}` into
27
+ // '../my-path/'.concat(id)
28
+ if (specifier.type === 'CallExpression' &&
29
+ specifier.callee.type === 'MemberExpression' &&
30
+ specifier.callee.property.type === 'Identifier' &&
31
+ specifier.callee.property.name === 'concat' &&
32
+ specifier.callee.object.type === 'StringLiteral') {
33
+ let parts = [{ type: 'static', value: specifier.callee.object.value }];
34
+ for (let arg of specifier.arguments) {
35
+ if (arg.type === 'StringLiteral') {
36
+ parts.push({ type: 'static', value: arg.value });
37
+ }
38
+ else if (types.isExpression(arg)) {
39
+ parts.push({ type: 'dynamic', value: arg });
40
+ }
41
+ else {
42
+ return undefined;
43
+ }
44
+ }
45
+ return normalize(parts);
46
+ }
47
+ return undefined;
48
+ }
49
+ // merges adjacent static parts and drops empty ones, so that the rest of the
50
+ // code can assume statics are maximal and non-empty
51
+ function normalize(parts) {
52
+ let output = [];
53
+ for (let part of parts) {
54
+ if (part.type === 'static') {
55
+ if (part.value === '') {
56
+ continue;
57
+ }
58
+ let previous = output[output.length - 1];
59
+ if ((previous === null || previous === void 0 ? void 0 : previous.type) === 'static') {
60
+ output[output.length - 1] = { type: 'static', value: previous.value + part.value };
61
+ continue;
62
+ }
63
+ }
64
+ output.push(part);
65
+ }
66
+ return output;
67
+ }
68
+ // Splits the parts into the directory we're going to read and the pattern that
69
+ // entries in it need to match. Returns undefined when the parts don't describe
70
+ // a relative path with a statically-known directory.
71
+ function parseSpecifier(parts) {
72
+ let first = parts[0];
73
+ if ((first === null || first === void 0 ? void 0 : first.type) !== 'static' || !first.value.startsWith('.')) {
74
+ return undefined;
75
+ }
76
+ let slash = first.value.lastIndexOf('/');
77
+ if (slash === -1) {
78
+ return undefined;
79
+ }
80
+ let dir = first.value.slice(0, slash + 1);
81
+ let head = first.value.slice(slash + 1);
82
+ let pattern = normalize([{ type: 'static', value: head }, ...parts.slice(1)]);
83
+ // The directory we read is only one level deep, so a "/" anywhere later in
84
+ // the pattern could never match one of its entries.
85
+ if (pattern.some(part => part.type === 'static' && part.value.includes('/'))) {
86
+ return undefined;
87
+ }
88
+ return { dir, pattern: withoutExtension(pattern) };
89
+ }
90
+ // The lookup table is keyed by extension-less filenames, because that's what we
91
+ // hand to the resolver. So if the author wrote the extension (which is what
92
+ // Vite's own dynamic import rules ask for) we drop it from the pattern too.
93
+ function withoutExtension(pattern) {
94
+ let last = pattern[pattern.length - 1];
95
+ if ((last === null || last === void 0 ? void 0 : last.type) !== 'static') {
96
+ return pattern;
97
+ }
98
+ let stripped = last.value.replace(/\.\w+$/, '');
99
+ if (stripped === last.value) {
100
+ return pattern;
101
+ }
102
+ return normalize([...pattern.slice(0, -1), { type: 'static', value: stripped }]);
103
+ }
104
+ // The key we use for a directory entry: its name minus the file extension.
105
+ function entryKey(entry) {
106
+ let dot = entry.lastIndexOf('.');
107
+ return dot === -1 ? entry : entry.slice(0, dot);
108
+ }
109
+ // Which keys could this pattern actually select? Everything else in the
110
+ // directory would be dead weight in the bundle.
111
+ function patternMatcher(pattern) {
112
+ let source = '^' + pattern.map(part => (part.type === 'static' ? escapeRegExp(part.value) : '[\\s\\S]*')).join('') + '$';
113
+ let regex = new RegExp(source);
114
+ return key => regex.test(key);
115
+ }
116
+ function escapeRegExp(str) {
117
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
118
+ }
119
+ // Builds the expression we use to index into the lookup table. When the pattern
120
+ // is a single interpolation (the only shape that used to work) this is just that
121
+ // expression, so existing call sites compile to byte-identical output.
122
+ function lookupExpression(types, pattern) {
123
+ if (pattern.length === 1 && pattern[0].type === 'dynamic') {
124
+ return pattern[0].value;
125
+ }
126
+ let quasis = [];
127
+ let expressions = [];
128
+ let pending = '';
129
+ for (let part of pattern) {
130
+ if (part.type === 'static') {
131
+ pending += part.value;
132
+ }
133
+ else {
134
+ quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }));
135
+ pending = '';
136
+ expressions.push(part.value);
137
+ }
138
+ }
139
+ quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }, true));
140
+ return types.templateLiteral(quasis, expressions);
141
+ }
142
+ function escapeTemplate(str) {
143
+ return str.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
144
+ }
145
+ // path.join() will strip a leading "./", which would turn our relative path
146
+ // into a bare package specifier.
147
+ function relativeSpecifier(path) {
148
+ let normalized = path.replace(/\\/g, '/');
149
+ return normalized.startsWith('.') ? normalized : './' + normalized;
150
+ }
151
+ //# sourceMappingURL=import-sync-pattern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import-sync-pattern.js","sourceRoot":"","sources":["import-sync-pattern.ts"],"names":[],"mappings":";;AA8BA,oCAuCC;AAyBD,wCAoBC;AAkBD,4BAGC;AAID,wCAKC;AASD,4CAkBC;AAQD,8CAGC;AA1JD,6EAA6E;AAC7E,yDAAyD;AACzD,SAAgB,YAAY,CAAC,KAAY,EAAE,SAAiB;IAC1D,IAAI,SAAS,CAAC,IAAI,KAAK,iBAAiB,EAAE,CAAC;QACzC,IAAI,KAAK,GAAkB,EAAE,CAAC;QAC9B,KAAK,IAAI,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;YACtD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,CAAC,MAAO,EAAE,CAAC,CAAC;YAC3D,IAAI,UAAU,GAAG,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YAC9C,IAAI,UAAU,EAAE,CAAC;gBACf,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,UAAU,CAAC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t } from '@babel/core';\n\ntype Types = typeof Babel.types;\n\n/*\n Support for `importSync` with a dynamic path, like:\n\n importSync(`../components/results/${type}-result`)\n\n In eager mode we can't do a truly dynamic import, so we expand the call into a\n lookup table over the real contents of the directory. To do that correctly we\n need to understand the *whole* pattern, not just the part before the first\n interpolation.\n*/\n\nexport type PatternPart = { type: 'static'; value: string } | { type: 'dynamic'; value: t.Expression };\n\n// A parsed `importSync` specifier: the statically-known directory that we will\n// read, plus the pattern that filenames within it must match.\nexport interface ParsedSpecifier {\n // always ends in \"/\", always starts with \".\" (we only support relative paths)\n dir: string;\n // the filename pattern, with the file extension (if any) already removed, so\n // it lines up with the extension-less keys we put in the lookup table\n pattern: PatternPart[];\n}\n\n// Turns a specifier expression into a flat list of static and dynamic parts.\n// Returns undefined if this isn't a shape we understand.\nexport function patternParts(types: Types, specifier: t.Node): PatternPart[] | undefined {\n if (specifier.type === 'TemplateLiteral') {\n let parts: PatternPart[] = [];\n for (let [index, quasi] of specifier.quasis.entries()) {\n parts.push({ type: 'static', value: quasi.value.cooked! });\n let expression = specifier.expressions[index];\n if (expression) {\n if (!types.isExpression(expression)) {\n return undefined;\n }\n parts.push({ type: 'dynamic', value: expression });\n }\n }\n return normalize(parts);\n }\n\n // babel might transform the template form `../my-path/${id}` into\n // '../my-path/'.concat(id)\n if (\n specifier.type === 'CallExpression' &&\n specifier.callee.type === 'MemberExpression' &&\n specifier.callee.property.type === 'Identifier' &&\n specifier.callee.property.name === 'concat' &&\n specifier.callee.object.type === 'StringLiteral'\n ) {\n let parts: PatternPart[] = [{ type: 'static', value: specifier.callee.object.value }];\n for (let arg of specifier.arguments) {\n if (arg.type === 'StringLiteral') {\n parts.push({ type: 'static', value: arg.value });\n } else if (types.isExpression(arg)) {\n parts.push({ type: 'dynamic', value: arg });\n } else {\n return undefined;\n }\n }\n return normalize(parts);\n }\n\n return undefined;\n}\n\n// merges adjacent static parts and drops empty ones, so that the rest of the\n// code can assume statics are maximal and non-empty\nfunction normalize(parts: PatternPart[]): PatternPart[] {\n let output: PatternPart[] = [];\n for (let part of parts) {\n if (part.type === 'static') {\n if (part.value === '') {\n continue;\n }\n let previous = output[output.length - 1];\n if (previous?.type === 'static') {\n output[output.length - 1] = { type: 'static', value: previous.value + part.value };\n continue;\n }\n }\n output.push(part);\n }\n return output;\n}\n\n// Splits the parts into the directory we're going to read and the pattern that\n// entries in it need to match. Returns undefined when the parts don't describe\n// a relative path with a statically-known directory.\nexport function parseSpecifier(parts: PatternPart[]): ParsedSpecifier | undefined {\n let first = parts[0];\n if (first?.type !== 'static' || !first.value.startsWith('.')) {\n return undefined;\n }\n let slash = first.value.lastIndexOf('/');\n if (slash === -1) {\n return undefined;\n }\n let dir = first.value.slice(0, slash + 1);\n let head = first.value.slice(slash + 1);\n let pattern = normalize([{ type: 'static', value: head }, ...parts.slice(1)]);\n\n // The directory we read is only one level deep, so a \"/\" anywhere later in\n // the pattern could never match one of its entries.\n if (pattern.some(part => part.type === 'static' && part.value.includes('/'))) {\n return undefined;\n }\n\n return { dir, pattern: withoutExtension(pattern) };\n}\n\n// The lookup table is keyed by extension-less filenames, because that's what we\n// hand to the resolver. So if the author wrote the extension (which is what\n// Vite's own dynamic import rules ask for) we drop it from the pattern too.\nfunction withoutExtension(pattern: PatternPart[]): PatternPart[] {\n let last = pattern[pattern.length - 1];\n if (last?.type !== 'static') {\n return pattern;\n }\n let stripped = last.value.replace(/\\.\\w+$/, '');\n if (stripped === last.value) {\n return pattern;\n }\n return normalize([...pattern.slice(0, -1), { type: 'static', value: stripped }]);\n}\n\n// The key we use for a directory entry: its name minus the file extension.\nexport function entryKey(entry: string): string {\n let dot = entry.lastIndexOf('.');\n return dot === -1 ? entry : entry.slice(0, dot);\n}\n\n// Which keys could this pattern actually select? Everything else in the\n// directory would be dead weight in the bundle.\nexport function patternMatcher(pattern: PatternPart[]): (key: string) => boolean {\n let source =\n '^' + pattern.map(part => (part.type === 'static' ? escapeRegExp(part.value) : '[\\\\s\\\\S]*')).join('') + '$';\n let regex = new RegExp(source);\n return key => regex.test(key);\n}\n\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// Builds the expression we use to index into the lookup table. When the pattern\n// is a single interpolation (the only shape that used to work) this is just that\n// expression, so existing call sites compile to byte-identical output.\nexport function lookupExpression(types: Types, pattern: PatternPart[]): t.Expression {\n if (pattern.length === 1 && pattern[0].type === 'dynamic') {\n return pattern[0].value;\n }\n let quasis: t.TemplateElement[] = [];\n let expressions: t.Expression[] = [];\n let pending = '';\n for (let part of pattern) {\n if (part.type === 'static') {\n pending += part.value;\n } else {\n quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }));\n pending = '';\n expressions.push(part.value);\n }\n }\n quasis.push(types.templateElement({ raw: escapeTemplate(pending), cooked: pending }, true));\n return types.templateLiteral(quasis, expressions);\n}\n\nfunction escapeTemplate(str: string): string {\n return str.replace(/\\\\/g, '\\\\\\\\').replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${');\n}\n\n// path.join() will strip a leading \"./\", which would turn our relative path\n// into a bare package specifier.\nexport function relativeSpecifier(path: string): string {\n let normalized = path.replace(/\\\\/g, '/');\n return normalized.startsWith('.') ? normalized : './' + normalized;\n}\n"]}
@@ -45,6 +45,7 @@ const error_1 = __importDefault(require("./error"));
45
45
  const fail_build_1 = __importDefault(require("./fail-build"));
46
46
  const evaluate_json_1 = require("./evaluate-json");
47
47
  const fs_1 = require("fs");
48
+ const import_sync_pattern_1 = require("./import-sync-pattern");
48
49
  const path_1 = require("path");
49
50
  function main(context) {
50
51
  let t = context.types;
@@ -181,48 +182,51 @@ function main(context) {
181
182
  if (callee.referencesImport('@embroider/macros', 'importSync')) {
182
183
  if (state.opts.importSyncImplementation === 'eager') {
183
184
  let specifier = path.node.arguments[0];
184
- if ((specifier === null || specifier === void 0 ? void 0 : specifier.type) !== 'StringLiteral') {
185
- let relativePath = '';
186
- let property;
187
- if (specifier.type === 'TemplateLiteral') {
188
- relativePath = specifier.quasis[0].value.cooked;
189
- property = specifier.expressions[0];
190
- }
191
- // babel might transform template form `../my-path/${id}` to '../my-path/'.concat(id)
192
- if (specifier.type === 'CallExpression' &&
193
- specifier.callee.type === 'MemberExpression' &&
194
- specifier.callee.property.type === 'Identifier' &&
195
- specifier.callee.property.name === 'concat' &&
196
- specifier.callee.object.type === 'StringLiteral') {
197
- relativePath = specifier.callee.object.value;
198
- property = specifier.arguments[0];
185
+ let target;
186
+ if ((specifier === null || specifier === void 0 ? void 0 : specifier.type) === 'StringLiteral') {
187
+ target = specifier.value;
188
+ }
189
+ else {
190
+ let parts = specifier ? (0, import_sync_pattern_1.patternParts)(t, specifier) : undefined;
191
+ if (parts && parts.length > 0 && parts.every(part => part.type === 'static')) {
192
+ // a template literal that has no interpolations at all is just
193
+ // a string, so treat it like one
194
+ target = parts.map(part => (part.type === 'static' ? part.value : '')).join('');
199
195
  }
200
- if (property && relativePath && relativePath.startsWith('.')) {
201
- const resolvedPath = (0, path_1.resolve)((0, path_1.dirname)(state.filename), relativePath);
196
+ else {
197
+ let parsed = parts ? (0, import_sync_pattern_1.parseSpecifier)(parts) : undefined;
198
+ if (!parsed) {
199
+ throw new Error(`importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier === null || specifier === void 0 ? void 0 : specifier.type}`);
200
+ }
201
+ const { dir, pattern } = parsed;
202
+ const resolvedPath = (0, path_1.resolve)((0, path_1.dirname)(state.filename), dir);
202
203
  let entries = [];
203
204
  if ((0, fs_1.existsSync)(resolvedPath)) {
204
205
  entries = (0, fs_1.readdirSync)(resolvedPath).filter(e => !e.startsWith('.'));
205
206
  }
206
- const obj = t.objectExpression(entries.map(e => {
207
- let key = e.split('.')[0];
208
- const rest = e.split('.').slice(1, -1);
209
- if (rest.length) {
210
- key += `.${rest}`;
207
+ const matches = (0, import_sync_pattern_1.patternMatcher)(pattern);
208
+ const seen = new Set();
209
+ const properties = [];
210
+ for (const entry of entries) {
211
+ const key = (0, import_sync_pattern_1.entryKey)(entry);
212
+ // entries that the pattern could never select would just bloat
213
+ // the bundle, and files that differ only by extension collapse
214
+ // to the same key (and the same extension-less import)
215
+ if (!matches(key) || seen.has(key)) {
216
+ continue;
211
217
  }
212
- const id = t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [state.importUtil.import(path, (0, path_1.join)(relativePath, key).replace(/\\/g, '/'), '*')]);
213
- return t.objectProperty(t.stringLiteral(key), id);
214
- }));
215
- const memberExpr = t.memberExpression(obj, property, true);
218
+ seen.add(key);
219
+ const id = t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [state.importUtil.import(path, (0, import_sync_pattern_1.relativeSpecifier)((0, path_1.join)(dir, key)), '*')]);
220
+ properties.push(t.objectProperty(t.stringLiteral(key), id));
221
+ }
222
+ const memberExpr = t.memberExpression(t.objectExpression(properties), (0, import_sync_pattern_1.lookupExpression)(t, pattern), true);
216
223
  path.replaceWith(memberExpr);
217
224
  state.calledIdentifiers.add(callee.node);
218
225
  return;
219
226
  }
220
- else {
221
- throw new Error(`importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier.type}`);
222
- }
223
227
  }
224
228
  path.replaceWith(t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [
225
- state.importUtil.import(path, specifier.value, '*'),
229
+ state.importUtil.import(path, target, '*'),
226
230
  ]));
227
231
  state.calledIdentifiers.add(callee.node);
228
232
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"macros-babel-plugin.js","sourceRoot":"","sources":["macros-babel-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBA,uBA4SC;AAzTD,mCAAoC;AAEpC,6CAAiE;AACjE,qEAA+E;AAC/E,iCAAgD;AAEhD,oDAA4B;AAC5B,8DAAqC;AACrC,mDAA2D;AAE3D,2BAA6C;AAC7C,+B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CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;oBACrD,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;wBACrB,IAAI,CAAC,WAAW,CAAC,IAAA,6BAAa,EAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;oBACzD,CAAC;gBACH,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,CAAC;AACrB,CAAC","sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport type { types as t } from '@babel/core';\nimport type State from './state';\nimport { initState } from './state';\nimport type { Mode as GetConfigMode } from './get-config';\nimport { inlineRuntimeConfig, insertConfig } from './get-config';\nimport macroCondition, { identifyMacroConditionPath } from './macro-condition';\nimport { isEachPath, insertEach } from './each';\n\nimport error from './error';\nimport failBuild from './fail-build';\nimport { Evaluator, buildLiterals } from './evaluate-json';\nimport type * as Babel from '@babel/core';\nimport { existsSync, readdirSync } from 'fs';\nimport { resolve, dirname, join } from 'path';\n\nexport default function main(context: typeof Babel): unknown {\n let t = context.types;\n let visitor = {\n Program: {\n enter(path: NodePath<t.Program>, state: State) {\n initState(context, path, state);\n },\n exit(_: NodePath<t.Program>, state: State) {\n // @embroider/macros itself has no runtime behaviors and should always be removed\n state.importUtil.removeAllImports('@embroider/macros');\n for (let handler of state.jobs) {\n handler();\n }\n },\n },\n 'IfStatement|ConditionalExpression|LogicalExpression': {\n enter(path: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>, state: State) {\n let found = identifyMacroConditionPath(path);\n if (found) {\n state.calledIdentifiers.add(found.callExpression.get('callee').node);\n macroCondition(found, state, context);\n }\n },\n },\n ForOfStatement: {\n enter(path: NodePath<t.ForOfStatement>, state: State) {\n if (isEachPath(path)) {\n state.calledIdentifiers.add(path.get('right').get('callee').node);\n insertEach(path, state, context);\n }\n },\n },\n FunctionDeclaration: {\n enter(path: NodePath<t.FunctionDeclaration>, state: State) {\n let id = path.get('id');\n if (id.isIdentifier() && id.node.name === 'initializeRuntimeMacrosConfig' && state.opts.mode === 'run-time') {\n let pkg = state.owningPackage();\n if (pkg && pkg.name === '@embroider/macros') {\n inlineRuntimeConfig(path, state, context);\n }\n }\n },\n },\n CallExpression: {\n enter(path: NodePath<t.CallExpression>, state: State) {\n let callee = path.get('callee');\n if (!callee.isIdentifier()) {\n return;\n }\n\n // failBuild is implemented for side-effect, not value, so it's not\n // handled by evaluateMacroCall.\n if (callee.referencesImport('@embroider/macros', 'failBuild')) {\n state.calledIdentifiers.add(callee.node);\n failBuild(path, state);\n return;\n }\n\n if (callee.referencesImport('@embroider/macros', 'importSync')) {\n // we handle importSync in the exit hook\n return;\n }\n\n // getOwnConfig/getGlobalConfig/getConfig needs special handling, so\n // even though it also emits values via evaluateMacroCall when they're\n // needed recursively by other macros, it has its own insertion-handling\n // code that we invoke here.\n //\n // The things that are special include:\n // - automatic collapsing of chained properties, etc\n // - these macros have runtime implementations sometimes, which changes\n // how we rewrite them\n let mode: GetConfigMode | false = callee.referencesImport('@embroider/macros', 'getOwnConfig')\n ? 'own'\n : callee.referencesImport('@embroider/macros', 'getGlobalConfig')\n ? 'getGlobalConfig'\n : callee.referencesImport('@embroider/macros', 'getConfig')\n ? 'package'\n : false;\n if (mode) {\n state.calledIdentifiers.add(callee.node);\n insertConfig(path, state, mode, context);\n return;\n }\n\n // isTesting can have a runtime implementation. At compile time it\n // instead falls through to evaluateMacroCall.\n if (callee.referencesImport('@embroider/macros', 'isTesting') && state.opts.mode === 'run-time') {\n state.calledIdentifiers.add(callee.node);\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'isTesting'));\n return;\n }\n\n if (callee.referencesImport('@embroider/macros', 'setTesting')) {\n state.calledIdentifiers.add(callee.node);\n\n if (state.opts.mode === 'run-time') {\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'setTesting'));\n } else {\n let args = path.get('arguments');\n if (args.length === 0) {\n throw error(path, `setTesting() requires a boolean argument`);\n }\n\n let arg = args[0];\n let evaluator = new Evaluator({ state });\n let result = evaluator.evaluate(arg);\n\n if (!result.confident) {\n throw error(\n arg,\n `setTesting() can only be called with a statically analyzable value in compile-time mode. The argument must be a literal boolean or other macro that can resolves to a boolean at compile-time.`\n );\n }\n\n let macrosConfig = (state.opts.globalConfig['@embroider/macros'] as any) || {};\n let currentIsTesting = Boolean(macrosConfig.isTesting);\n let newIsTesting = Boolean(result.value);\n\n if (currentIsTesting !== newIsTesting) {\n throw error(\n path,\n `setTesting(${newIsTesting}) cannot change the testing state in compile-time mode. The current global config has isTesting=${currentIsTesting}. ` +\n `setTesting() calls are compiled away at build time, so they cannot change the testing state. ` +\n `If you need to change the testing state at runtime, use runtime mode instead.`\n );\n }\n\n path.remove();\n }\n return;\n }\n\n let result = new Evaluator({ state }).evaluateMacroCall(path);\n if (result.confident) {\n state.calledIdentifiers.add(callee.node);\n path.replaceWith(buildLiterals(result.value, context));\n }\n },\n exit(path: NodePath<t.CallExpression>, state: State) {\n let callee = path.get('callee');\n if (!callee.isIdentifier()) {\n return;\n }\n // importSync doesn't evaluate to a static value, so it's implemented\n // directly here, not in evaluateMacroCall.\n // We intentionally do this on exit here, to allow other transforms to handle importSync before we do\n // For example ember-auto-import needs to do some custom transforms to enable use of dynamic template strings,\n // so its babel plugin needs to see and handle the importSync call first!\n if (callee.referencesImport('@embroider/macros', 'importSync')) {\n if (state.opts.importSyncImplementation === 'eager') {\n let specifier = path.node.arguments[0];\n if (specifier?.type !== 'StringLiteral') {\n let relativePath = '';\n let property;\n if (specifier.type === 'TemplateLiteral') {\n relativePath = specifier.quasis[0].value.cooked!;\n property = specifier.expressions[0] as t.Expression;\n }\n // babel might transform template form `../my-path/${id}` to '../my-path/'.concat(id)\n if (\n specifier.type === 'CallExpression' &&\n specifier.callee.type === 'MemberExpression' &&\n specifier.callee.property.type === 'Identifier' &&\n specifier.callee.property.name === 'concat' &&\n specifier.callee.object.type === 'StringLiteral'\n ) {\n relativePath = specifier.callee.object.value;\n property = specifier.arguments[0] as t.Expression;\n }\n if (property && relativePath && relativePath.startsWith('.')) {\n const resolvedPath = resolve(dirname((state as any).filename), relativePath);\n let entries: string[] = [];\n if (existsSync(resolvedPath)) {\n entries = readdirSync(resolvedPath).filter(e => !e.startsWith('.'));\n }\n const obj = t.objectExpression(\n entries.map(e => {\n let key = e.split('.')[0];\n const rest = e.split('.').slice(1, -1);\n if (rest.length) {\n key += `.${rest}`;\n }\n const id = t.callExpression(\n state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'),\n [state.importUtil.import(path, join(relativePath, key).replace(/\\\\/g, '/'), '*')]\n );\n return t.objectProperty(t.stringLiteral(key), id);\n })\n );\n const memberExpr = t.memberExpression(obj, property, true);\n path.replaceWith(memberExpr);\n state.calledIdentifiers.add(callee.node);\n return;\n } else {\n throw new Error(\n `importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier.type}`\n );\n }\n }\n path.replaceWith(\n t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [\n state.importUtil.import(path, specifier.value, '*'),\n ])\n );\n state.calledIdentifiers.add(callee.node);\n return;\n } else {\n if (path.scope.hasBinding('require')) {\n path.scope.rename('require');\n }\n let r = t.identifier('require');\n state.generatedRequires.add(r);\n path.replaceWith(\n t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [\n t.callExpression(r, path.node.arguments),\n ])\n );\n }\n }\n },\n },\n ReferencedIdentifier(path: NodePath<t.Identifier>, state: State) {\n for (let candidate of [\n 'dependencySatisfies',\n 'appEmberSatisfies',\n 'moduleExists',\n 'getConfig',\n 'getOwnConfig',\n 'failBuild',\n // we cannot check importSync, as the babel transform runs on exit, so *after* this check\n // 'importSync',\n 'isDevelopingApp',\n 'isDevelopingThisPackage',\n 'isTesting',\n 'setTesting',\n ]) {\n if (path.referencesImport('@embroider/macros', candidate) && !state.calledIdentifiers.has(path.node)) {\n throw error(path, `You can only use ${candidate} as a function call`);\n }\n }\n\n if (path.referencesImport('@embroider/macros', 'macroCondition') && !state.calledIdentifiers.has(path.node)) {\n throw error(\n path,\n `macroCondition can only be used as the predicate of an if statement, ternary expression, or && / || logical expression`\n );\n }\n\n if (path.referencesImport('@embroider/macros', 'each') && !state.calledIdentifiers.has(path.node)) {\n throw error(\n path,\n `the each() macro can only be used within a for ... of statement, like: for (let x of each(thing)){}`\n );\n }\n\n if (state.opts.owningPackageRoot) {\n // there is only an owningPackageRoot when we are running inside a\n // classic ember-cli build. In the embroider stage3 build, there is no\n // owning package root because we're compiling *all* packages\n // simultaneously.\n //\n // given that we're inside classic ember-cli, stop here without trying\n // to rewrite bare `require`. It's not needed, because both our\n // `importSync` and any user-written bare `require` can both mean the\n // same thing: runtime AMD `require`.\n return;\n }\n\n if (\n path.node.name === 'require' &&\n !state.generatedRequires.has(path.node) &&\n !path.scope.hasBinding('require') &&\n state.owningPackage().isEmberAddon()\n ) {\n // Our importSync macro has been compiled to `require`. But we want to\n // distinguish that from any pre-existing, user-written `require` in an\n // Ember addon, which should retain its *runtime* meaning.\n path.replaceWith(t.memberExpression(t.identifier('window'), path.node));\n }\n },\n };\n\n if ((context as any).types.OptionalMemberExpression) {\n // our getConfig and getOwnConfig macros are supposed to be able to absorb\n // optional chaining. To make that work we need to see the optional chaining\n // before preset-env compiles them away.\n (visitor as any).OptionalMemberExpression = {\n enter(path: NodePath<t.OptionalMemberExpression>, state: State) {\n if (state.opts.mode === 'compile-time') {\n let result = new Evaluator({ state }).evaluate(path);\n if (result.confident) {\n path.replaceWith(buildLiterals(result.value, context));\n }\n }\n },\n };\n }\n\n return { visitor };\n}\n"]}
1
+ {"version":3,"file":"macros-babel-plugin.js","sourceRoot":"","sources":["macros-babel-plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,uBA8SC;AAnUD,mCAAoC;AAEpC,6CAAiE;AACjE,qEAA+E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AAe,CAAC,KAAK,CAAC,wBAAwB,EAAE,CAAC;QACpD,0EAA0E;QAC1E,4EAA4E;QAC5E,wCAAwC;QACvC,OAAe,CAAC,wBAAwB,GAAG;YAC1C,KAAK,CAAC,IAA0C,EAAE,KAAY;gBAC5D,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;oBACvC,IAAI,MAAM,GAAG,IAAI,yBAAS,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;oBACrD,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;wBACrB,IAAI,CAAC,WAAW,CAAC,IAAA,6BAAa,EAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;oBACzD,CAAC;gBACH,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,CAAC;AACrB,CAAC","sourcesContent":["import type { NodePath } from '@babel/traverse';\nimport type { types as t } from '@babel/core';\nimport type State from './state';\nimport { initState } from './state';\nimport type { Mode as GetConfigMode } from './get-config';\nimport { inlineRuntimeConfig, insertConfig } from './get-config';\nimport macroCondition, { identifyMacroConditionPath } from './macro-condition';\nimport { isEachPath, insertEach } from './each';\n\nimport error from './error';\nimport failBuild from './fail-build';\nimport { Evaluator, buildLiterals } from './evaluate-json';\nimport type * as Babel from '@babel/core';\nimport { existsSync, readdirSync } from 'fs';\nimport {\n entryKey,\n lookupExpression,\n parseSpecifier,\n patternMatcher,\n patternParts,\n relativeSpecifier,\n} from './import-sync-pattern';\nimport { resolve, dirname, join } from 'path';\n\nexport default function main(context: typeof Babel): unknown {\n let t = context.types;\n let visitor = {\n Program: {\n enter(path: NodePath<t.Program>, state: State) {\n initState(context, path, state);\n },\n exit(_: NodePath<t.Program>, state: State) {\n // @embroider/macros itself has no runtime behaviors and should always be removed\n state.importUtil.removeAllImports('@embroider/macros');\n for (let handler of state.jobs) {\n handler();\n }\n },\n },\n 'IfStatement|ConditionalExpression|LogicalExpression': {\n enter(path: NodePath<t.IfStatement | t.ConditionalExpression | t.LogicalExpression>, state: State) {\n let found = identifyMacroConditionPath(path);\n if (found) {\n state.calledIdentifiers.add(found.callExpression.get('callee').node);\n macroCondition(found, state, context);\n }\n },\n },\n ForOfStatement: {\n enter(path: NodePath<t.ForOfStatement>, state: State) {\n if (isEachPath(path)) {\n state.calledIdentifiers.add(path.get('right').get('callee').node);\n insertEach(path, state, context);\n }\n },\n },\n FunctionDeclaration: {\n enter(path: NodePath<t.FunctionDeclaration>, state: State) {\n let id = path.get('id');\n if (id.isIdentifier() && id.node.name === 'initializeRuntimeMacrosConfig' && state.opts.mode === 'run-time') {\n let pkg = state.owningPackage();\n if (pkg && pkg.name === '@embroider/macros') {\n inlineRuntimeConfig(path, state, context);\n }\n }\n },\n },\n CallExpression: {\n enter(path: NodePath<t.CallExpression>, state: State) {\n let callee = path.get('callee');\n if (!callee.isIdentifier()) {\n return;\n }\n\n // failBuild is implemented for side-effect, not value, so it's not\n // handled by evaluateMacroCall.\n if (callee.referencesImport('@embroider/macros', 'failBuild')) {\n state.calledIdentifiers.add(callee.node);\n failBuild(path, state);\n return;\n }\n\n if (callee.referencesImport('@embroider/macros', 'importSync')) {\n // we handle importSync in the exit hook\n return;\n }\n\n // getOwnConfig/getGlobalConfig/getConfig needs special handling, so\n // even though it also emits values via evaluateMacroCall when they're\n // needed recursively by other macros, it has its own insertion-handling\n // code that we invoke here.\n //\n // The things that are special include:\n // - automatic collapsing of chained properties, etc\n // - these macros have runtime implementations sometimes, which changes\n // how we rewrite them\n let mode: GetConfigMode | false = callee.referencesImport('@embroider/macros', 'getOwnConfig')\n ? 'own'\n : callee.referencesImport('@embroider/macros', 'getGlobalConfig')\n ? 'getGlobalConfig'\n : callee.referencesImport('@embroider/macros', 'getConfig')\n ? 'package'\n : false;\n if (mode) {\n state.calledIdentifiers.add(callee.node);\n insertConfig(path, state, mode, context);\n return;\n }\n\n // isTesting can have a runtime implementation. At compile time it\n // instead falls through to evaluateMacroCall.\n if (callee.referencesImport('@embroider/macros', 'isTesting') && state.opts.mode === 'run-time') {\n state.calledIdentifiers.add(callee.node);\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'isTesting'));\n return;\n }\n\n if (callee.referencesImport('@embroider/macros', 'setTesting')) {\n state.calledIdentifiers.add(callee.node);\n\n if (state.opts.mode === 'run-time') {\n callee.replaceWith(state.importUtil.import(callee, state.pathToOurAddon('runtime'), 'setTesting'));\n } else {\n let args = path.get('arguments');\n if (args.length === 0) {\n throw error(path, `setTesting() requires a boolean argument`);\n }\n\n let arg = args[0];\n let evaluator = new Evaluator({ state });\n let result = evaluator.evaluate(arg);\n\n if (!result.confident) {\n throw error(\n arg,\n `setTesting() can only be called with a statically analyzable value in compile-time mode. The argument must be a literal boolean or other macro that can resolves to a boolean at compile-time.`\n );\n }\n\n let macrosConfig = (state.opts.globalConfig['@embroider/macros'] as any) || {};\n let currentIsTesting = Boolean(macrosConfig.isTesting);\n let newIsTesting = Boolean(result.value);\n\n if (currentIsTesting !== newIsTesting) {\n throw error(\n path,\n `setTesting(${newIsTesting}) cannot change the testing state in compile-time mode. The current global config has isTesting=${currentIsTesting}. ` +\n `setTesting() calls are compiled away at build time, so they cannot change the testing state. ` +\n `If you need to change the testing state at runtime, use runtime mode instead.`\n );\n }\n\n path.remove();\n }\n return;\n }\n\n let result = new Evaluator({ state }).evaluateMacroCall(path);\n if (result.confident) {\n state.calledIdentifiers.add(callee.node);\n path.replaceWith(buildLiterals(result.value, context));\n }\n },\n exit(path: NodePath<t.CallExpression>, state: State) {\n let callee = path.get('callee');\n if (!callee.isIdentifier()) {\n return;\n }\n // importSync doesn't evaluate to a static value, so it's implemented\n // directly here, not in evaluateMacroCall.\n // We intentionally do this on exit here, to allow other transforms to handle importSync before we do\n // For example ember-auto-import needs to do some custom transforms to enable use of dynamic template strings,\n // so its babel plugin needs to see and handle the importSync call first!\n if (callee.referencesImport('@embroider/macros', 'importSync')) {\n if (state.opts.importSyncImplementation === 'eager') {\n let specifier = path.node.arguments[0];\n let target: string | undefined;\n if (specifier?.type === 'StringLiteral') {\n target = specifier.value;\n } else {\n let parts = specifier ? patternParts(t, specifier) : undefined;\n if (parts && parts.length > 0 && parts.every(part => part.type === 'static')) {\n // a template literal that has no interpolations at all is just\n // a string, so treat it like one\n target = parts.map(part => (part.type === 'static' ? part.value : '')).join('');\n } else {\n let parsed = parts ? parseSpecifier(parts) : undefined;\n if (!parsed) {\n throw new Error(\n `importSync eager mode only supports dynamic paths which are relative, must start with a '.', had ${specifier?.type}`\n );\n }\n const { dir, pattern } = parsed;\n const resolvedPath = resolve(dirname((state as any).filename), dir);\n let entries: string[] = [];\n if (existsSync(resolvedPath)) {\n entries = readdirSync(resolvedPath).filter(e => !e.startsWith('.'));\n }\n const matches = patternMatcher(pattern);\n const seen = new Set<string>();\n const properties: t.ObjectProperty[] = [];\n for (const entry of entries) {\n const key = entryKey(entry);\n // entries that the pattern could never select would just bloat\n // the bundle, and files that differ only by extension collapse\n // to the same key (and the same extension-less import)\n if (!matches(key) || seen.has(key)) {\n continue;\n }\n seen.add(key);\n const id = t.callExpression(\n state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'),\n [state.importUtil.import(path, relativeSpecifier(join(dir, key)), '*')]\n );\n properties.push(t.objectProperty(t.stringLiteral(key), id));\n }\n const memberExpr = t.memberExpression(\n t.objectExpression(properties),\n lookupExpression(t, pattern),\n true\n );\n path.replaceWith(memberExpr);\n state.calledIdentifiers.add(callee.node);\n return;\n }\n }\n path.replaceWith(\n t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [\n state.importUtil.import(path, target, '*'),\n ])\n );\n state.calledIdentifiers.add(callee.node);\n return;\n } else {\n if (path.scope.hasBinding('require')) {\n path.scope.rename('require');\n }\n let r = t.identifier('require');\n state.generatedRequires.add(r);\n path.replaceWith(\n t.callExpression(state.importUtil.import(path, state.pathToOurAddon('es-compat2'), 'default', 'esc'), [\n t.callExpression(r, path.node.arguments),\n ])\n );\n }\n }\n },\n },\n ReferencedIdentifier(path: NodePath<t.Identifier>, state: State) {\n for (let candidate of [\n 'dependencySatisfies',\n 'appEmberSatisfies',\n 'moduleExists',\n 'getConfig',\n 'getOwnConfig',\n 'failBuild',\n // we cannot check importSync, as the babel transform runs on exit, so *after* this check\n // 'importSync',\n 'isDevelopingApp',\n 'isDevelopingThisPackage',\n 'isTesting',\n 'setTesting',\n ]) {\n if (path.referencesImport('@embroider/macros', candidate) && !state.calledIdentifiers.has(path.node)) {\n throw error(path, `You can only use ${candidate} as a function call`);\n }\n }\n\n if (path.referencesImport('@embroider/macros', 'macroCondition') && !state.calledIdentifiers.has(path.node)) {\n throw error(\n path,\n `macroCondition can only be used as the predicate of an if statement, ternary expression, or && / || logical expression`\n );\n }\n\n if (path.referencesImport('@embroider/macros', 'each') && !state.calledIdentifiers.has(path.node)) {\n throw error(\n path,\n `the each() macro can only be used within a for ... of statement, like: for (let x of each(thing)){}`\n );\n }\n\n if (state.opts.owningPackageRoot) {\n // there is only an owningPackageRoot when we are running inside a\n // classic ember-cli build. In the embroider stage3 build, there is no\n // owning package root because we're compiling *all* packages\n // simultaneously.\n //\n // given that we're inside classic ember-cli, stop here without trying\n // to rewrite bare `require`. It's not needed, because both our\n // `importSync` and any user-written bare `require` can both mean the\n // same thing: runtime AMD `require`.\n return;\n }\n\n if (\n path.node.name === 'require' &&\n !state.generatedRequires.has(path.node) &&\n !path.scope.hasBinding('require') &&\n state.owningPackage().isEmberAddon()\n ) {\n // Our importSync macro has been compiled to `require`. But we want to\n // distinguish that from any pre-existing, user-written `require` in an\n // Ember addon, which should retain its *runtime* meaning.\n path.replaceWith(t.memberExpression(t.identifier('window'), path.node));\n }\n },\n };\n\n if ((context as any).types.OptionalMemberExpression) {\n // our getConfig and getOwnConfig macros are supposed to be able to absorb\n // optional chaining. To make that work we need to see the optional chaining\n // before preset-env compiles them away.\n (visitor as any).OptionalMemberExpression = {\n enter(path: NodePath<t.OptionalMemberExpression>, state: State) {\n if (state.opts.mode === 'compile-time') {\n let result = new Evaluator({ state }).evaluate(path);\n if (result.confident) {\n path.replaceWith(buildLiterals(result.value, context));\n }\n }\n },\n };\n }\n\n return { visitor };\n}\n"]}