@lwc/babel-plugin-component 2.42.0 → 2.44.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.
Files changed (45) hide show
  1. package/README.md +37 -0
  2. package/dist/index.cjs.js +1146 -0
  3. package/dist/index.cjs.js.map +1 -0
  4. package/dist/index.js +1144 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +26 -9
  7. package/types/compiler-version-number.d.ts +3 -0
  8. package/types/component.d.ts +3 -0
  9. package/types/constants.d.ts +26 -0
  10. package/types/decorators/api/index.d.ts +8 -0
  11. package/types/decorators/api/shared.d.ts +3 -0
  12. package/types/decorators/api/transform.d.ts +6 -0
  13. package/types/decorators/api/validate.d.ts +2 -0
  14. package/types/decorators/index.d.ts +21 -0
  15. package/types/decorators/track/index.d.ts +10 -0
  16. package/types/decorators/types.d.ts +20 -0
  17. package/types/decorators/wire/index.d.ts +8 -0
  18. package/types/decorators/wire/shared.d.ts +3 -0
  19. package/types/decorators/wire/transform.d.ts +4 -0
  20. package/types/decorators/wire/validate.d.ts +2 -0
  21. package/types/dedupe-imports.d.ts +4 -0
  22. package/types/dynamic-imports.d.ts +3 -0
  23. package/types/index.d.ts +9 -0
  24. package/types/scope-css-imports.d.ts +3 -0
  25. package/types/types.d.ts +18 -0
  26. package/types/utils.d.ts +21 -0
  27. package/src/compiler-version-number.js +0 -33
  28. package/src/component.js +0 -89
  29. package/src/constants.js +0 -67
  30. package/src/decorators/api/index.js +0 -18
  31. package/src/decorators/api/shared.js +0 -17
  32. package/src/decorators/api/transform.js +0 -95
  33. package/src/decorators/api/validate.js +0 -160
  34. package/src/decorators/index.js +0 -271
  35. package/src/decorators/track/index.js +0 -49
  36. package/src/decorators/wire/index.js +0 -18
  37. package/src/decorators/wire/shared.js +0 -17
  38. package/src/decorators/wire/transform.js +0 -261
  39. package/src/decorators/wire/validate.js +0 -100
  40. package/src/dedupe-imports.js +0 -56
  41. package/src/dynamic-imports.js +0 -70
  42. package/src/index.d.ts +0 -10
  43. package/src/index.js +0 -77
  44. package/src/scope-css-imports.js +0 -23
  45. package/src/utils.js +0 -116
package/dist/index.js ADDED
@@ -0,0 +1,1144 @@
1
+ /**
2
+ * Copyright (C) 2023 salesforce.com, inc.
3
+ */
4
+ import { extname, basename } from 'path';
5
+ import { addNamed, addDefault } from '@babel/helper-module-imports';
6
+ import { generateErrorMessage, DecoratorErrors, LWCClassErrors } from '@lwc/errors';
7
+ import lineColumn from 'line-column';
8
+ import { LWC_VERSION_COMMENT } from '@lwc/shared';
9
+
10
+ /*
11
+ * Copyright (c) 2023, salesforce.com, inc.
12
+ * All rights reserved.
13
+ * SPDX-License-Identifier: MIT
14
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
15
+ */
16
+ // This set is for attributes that have a camel cased property name
17
+ // For example, div.tabIndex.
18
+ // We do not want users to define @api properties with these names
19
+ // Because the template will never call them. It'll always call the camel
20
+ // cased version.
21
+ const AMBIGUOUS_PROP_SET = new Map([
22
+ ['bgcolor', 'bgColor'],
23
+ ['accesskey', 'accessKey'],
24
+ ['contenteditable', 'contentEditable'],
25
+ ['contextmenu', 'contextMenu'],
26
+ ['tabindex', 'tabIndex'],
27
+ ['maxlength', 'maxLength'],
28
+ ['maxvalue', 'maxValue'],
29
+ ]);
30
+ // This set is for attributes that can never be defined
31
+ // by users on their components.
32
+ // We throw for these.
33
+ const DISALLOWED_PROP_SET = new Set(['is', 'class', 'slot', 'style']);
34
+ const LWC_PACKAGE_ALIAS = 'lwc';
35
+ const LWC_PACKAGE_EXPORTS = {
36
+ BASE_COMPONENT: 'LightningElement',
37
+ API_DECORATOR: 'api',
38
+ TRACK_DECORATOR: 'track',
39
+ WIRE_DECORATOR: 'wire',
40
+ };
41
+ const LWC_COMPONENT_PROPERTIES = {
42
+ PUBLIC_PROPS: 'publicProps',
43
+ PUBLIC_METHODS: 'publicMethods',
44
+ WIRE: 'wire',
45
+ TRACK: 'track',
46
+ };
47
+ const DECORATOR_TYPES = {
48
+ PROPERTY: 'property',
49
+ GETTER: 'getter',
50
+ SETTER: 'setter',
51
+ METHOD: 'method',
52
+ };
53
+ const REGISTER_COMPONENT_ID = 'registerComponent';
54
+ const REGISTER_DECORATORS_ID = 'registerDecorators';
55
+ const TEMPLATE_KEY = 'tmpl';
56
+ const COMPONENT_NAME_KEY = 'sel';
57
+
58
+ /*
59
+ * Copyright (c) 2023, salesforce.com, inc.
60
+ * All rights reserved.
61
+ * SPDX-License-Identifier: MIT
62
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
63
+ */
64
+ function getBaseName(classPath) {
65
+ const ext = extname(classPath);
66
+ return basename(classPath, ext);
67
+ }
68
+ function importDefaultTemplate(path, state) {
69
+ const { filename } = state.file.opts;
70
+ const componentName = getBaseName(filename);
71
+ return addDefault(path, `./${componentName}.html`, {
72
+ nameHint: TEMPLATE_KEY,
73
+ });
74
+ }
75
+ function needsComponentRegistration(path) {
76
+ return ((path.isIdentifier() && path.node.name !== 'undefined' && path.node.name !== 'null') ||
77
+ path.isCallExpression() ||
78
+ path.isClassDeclaration() ||
79
+ path.isConditionalExpression());
80
+ }
81
+ function getComponentRegisteredName(t, state) {
82
+ const { namespace, name } = state.opts;
83
+ const kebabCasedName = name === null || name === void 0 ? void 0 : name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
84
+ const componentName = namespace && kebabCasedName ? `${namespace}-${kebabCasedName}` : '';
85
+ return t.stringLiteral(componentName);
86
+ }
87
+ function component ({ types: t }) {
88
+ function createRegisterComponent(declarationPath, state) {
89
+ const registerComponentId = addNamed(declarationPath, REGISTER_COMPONENT_ID, LWC_PACKAGE_ALIAS);
90
+ const templateIdentifier = importDefaultTemplate(declarationPath, state);
91
+ const statementPath = declarationPath.getStatementParent();
92
+ const componentRegisteredName = getComponentRegisteredName(t, state);
93
+ let node = declarationPath.node;
94
+ if (declarationPath.isClassDeclaration()) {
95
+ const hasIdentifier = t.isIdentifier(node.id);
96
+ if (hasIdentifier) {
97
+ statementPath.insertBefore(node);
98
+ node = node.id;
99
+ }
100
+ else {
101
+ // if it does not have an id, we can treat it as a ClassExpression
102
+ t.toExpression(node);
103
+ }
104
+ }
105
+ return t.callExpression(registerComponentId, [
106
+ node,
107
+ t.objectExpression([
108
+ t.objectProperty(t.identifier(TEMPLATE_KEY), templateIdentifier),
109
+ t.objectProperty(t.identifier(COMPONENT_NAME_KEY), componentRegisteredName),
110
+ ]),
111
+ ]);
112
+ }
113
+ return {
114
+ ExportDefaultDeclaration(path, state) {
115
+ const implicitResolution = !state.opts.isExplicitImport;
116
+ if (implicitResolution) {
117
+ const declaration = path.get('declaration');
118
+ if (needsComponentRegistration(declaration)) {
119
+ declaration.replaceWith(createRegisterComponent(declaration, state));
120
+ }
121
+ }
122
+ },
123
+ };
124
+ }
125
+
126
+ /*
127
+ * Copyright (c) 2023, salesforce.com, inc.
128
+ * All rights reserved.
129
+ * SPDX-License-Identifier: MIT
130
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
131
+ */
132
+ function isClassMethod(classMethod, properties = {}) {
133
+ const { kind = 'method', name } = properties;
134
+ return (classMethod.isClassMethod({ kind }) &&
135
+ (!name || classMethod.get('key').isIdentifier({ name })) &&
136
+ (properties.static === undefined || classMethod.node.static === properties.static));
137
+ }
138
+ function isGetterClassMethod(classMethod, properties = {}) {
139
+ return isClassMethod(classMethod, {
140
+ kind: 'get',
141
+ name: properties.name,
142
+ static: properties.static,
143
+ });
144
+ }
145
+ function isSetterClassMethod(classMethod, properties = {}) {
146
+ return isClassMethod(classMethod, {
147
+ kind: 'set',
148
+ name: properties.name,
149
+ static: properties.static,
150
+ });
151
+ }
152
+ function getEngineImportsStatements(path) {
153
+ const programPath = path.isProgram()
154
+ ? path
155
+ : path.findParent((node) => node.isProgram());
156
+ return programPath.get('body').filter((node) => {
157
+ const source = node.get('source');
158
+ return node.isImportDeclaration() && source.isStringLiteral({ value: LWC_PACKAGE_ALIAS });
159
+ });
160
+ }
161
+ function getEngineImportSpecifiers(path) {
162
+ const imports = getEngineImportsStatements(path);
163
+ return (imports
164
+ // Flat-map the specifier list for each import statement
165
+ .flatMap((importStatement) => importStatement.get('specifiers'))
166
+ // Skip ImportDefaultSpecifier and ImportNamespaceSpecifier
167
+ .filter((specifier) => specifier.type === 'ImportSpecifier')
168
+ // Get the list of specifiers with their name
169
+ .map((specifier) => {
170
+ const imported = specifier.get('imported').node
171
+ .name;
172
+ return { name: imported, path: specifier };
173
+ }));
174
+ }
175
+ function normalizeFilename(source) {
176
+ return (
177
+ // TODO [#3444]: use `this.filename` to get the filename
178
+ (source.hub &&
179
+ source.hub.file &&
180
+ source.hub.file.opts &&
181
+ source.hub.file.opts.filename) ||
182
+ null);
183
+ }
184
+ function normalizeLocation(source) {
185
+ const location = (source.node && (source.node.loc || source.node._loc)) || null;
186
+ if (!location) {
187
+ return null;
188
+ }
189
+ const code = source.hub.getCode();
190
+ if (!code) {
191
+ return {
192
+ line: location.start.line,
193
+ column: location.start.column,
194
+ };
195
+ }
196
+ const lineFinder = lineColumn(code);
197
+ const startOffset = lineFinder.toIndex(location.start.line, location.start.column + 1);
198
+ const endOffset = lineFinder.toIndex(location.end.line, location.end.column) + 1;
199
+ const length = endOffset - startOffset;
200
+ return {
201
+ line: location.start.line,
202
+ column: location.start.column,
203
+ start: startOffset,
204
+ length,
205
+ };
206
+ }
207
+ function generateError(source, { errorInfo, messageArgs }) {
208
+ const message = generateErrorMessage(errorInfo, messageArgs);
209
+ const error = source.buildCodeFrameError(message);
210
+ error.filename = normalizeFilename(source);
211
+ error.loc = normalizeLocation(source);
212
+ error.lwcCode = errorInfo && errorInfo.code;
213
+ return error;
214
+ }
215
+
216
+ /*
217
+ * Copyright (c) 2023, salesforce.com, inc.
218
+ * All rights reserved.
219
+ * SPDX-License-Identifier: MIT
220
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
221
+ */
222
+ const { API_DECORATOR: API_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
223
+ function isApiDecorator(decorator) {
224
+ return decorator.name === API_DECORATOR$2;
225
+ }
226
+
227
+ /*
228
+ * Copyright (c) 2023, salesforce.com, inc.
229
+ * All rights reserved.
230
+ * SPDX-License-Identifier: MIT
231
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
232
+ */
233
+ const { TRACK_DECORATOR: TRACK_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
234
+ function validateConflict(path, decorators) {
235
+ const isPublicFieldTracked = decorators.some((decorator) => decorator.name === TRACK_DECORATOR$2 &&
236
+ decorator.path.parentPath.node === path.parentPath.node);
237
+ if (isPublicFieldTracked) {
238
+ throw generateError(path, {
239
+ errorInfo: DecoratorErrors.API_AND_TRACK_DECORATOR_CONFLICT,
240
+ });
241
+ }
242
+ }
243
+ function isBooleanPropDefaultTrue(property) {
244
+ const propertyValue = property.node.value;
245
+ return propertyValue && propertyValue.type === 'BooleanLiteral' && propertyValue.value;
246
+ }
247
+ function validatePropertyValue(property) {
248
+ if (isBooleanPropDefaultTrue(property)) {
249
+ throw generateError(property, {
250
+ errorInfo: DecoratorErrors.INVALID_BOOLEAN_PUBLIC_PROPERTY,
251
+ });
252
+ }
253
+ }
254
+ function validatePropertyName(property) {
255
+ if (property.node.computed) {
256
+ throw generateError(property, {
257
+ errorInfo: DecoratorErrors.PROPERTY_CANNOT_BE_COMPUTED,
258
+ });
259
+ }
260
+ const propertyName = property.get('key.name').node;
261
+ if (propertyName === 'part') {
262
+ throw generateError(property, {
263
+ errorInfo: DecoratorErrors.PROPERTY_NAME_PART_IS_RESERVED,
264
+ messageArgs: [propertyName],
265
+ });
266
+ }
267
+ else if (propertyName.startsWith('on')) {
268
+ throw generateError(property, {
269
+ errorInfo: DecoratorErrors.PROPERTY_NAME_CANNOT_START_WITH_ON,
270
+ messageArgs: [propertyName],
271
+ });
272
+ }
273
+ else if (propertyName.startsWith('data') && propertyName.length > 4) {
274
+ throw generateError(property, {
275
+ errorInfo: DecoratorErrors.PROPERTY_NAME_CANNOT_START_WITH_DATA,
276
+ messageArgs: [propertyName],
277
+ });
278
+ }
279
+ else if (DISALLOWED_PROP_SET.has(propertyName)) {
280
+ throw generateError(property, {
281
+ errorInfo: DecoratorErrors.PROPERTY_NAME_IS_RESERVED,
282
+ messageArgs: [propertyName],
283
+ });
284
+ }
285
+ else if (AMBIGUOUS_PROP_SET.has(propertyName)) {
286
+ const camelCased = AMBIGUOUS_PROP_SET.get(propertyName);
287
+ throw generateError(property, {
288
+ errorInfo: DecoratorErrors.PROPERTY_NAME_IS_AMBIGUOUS,
289
+ messageArgs: [propertyName, camelCased],
290
+ });
291
+ }
292
+ }
293
+ function validateSingleApiDecoratorOnSetterGetterPair(decorators) {
294
+ // keep track of visited class methods
295
+ const visitedMethods = new Set();
296
+ decorators.forEach((decorator) => {
297
+ const { path, decoratedNodeType } = decorator;
298
+ // since we are validating get/set we only look at @api methods
299
+ if (isApiDecorator(decorator) &&
300
+ (decoratedNodeType === DECORATOR_TYPES.GETTER ||
301
+ decoratedNodeType === DECORATOR_TYPES.SETTER)) {
302
+ const methodPath = path.parentPath;
303
+ const methodName = methodPath.get('key.name').node;
304
+ if (visitedMethods.has(methodName)) {
305
+ throw generateError(methodPath, {
306
+ errorInfo: DecoratorErrors.SINGLE_DECORATOR_ON_SETTER_GETTER_PAIR,
307
+ messageArgs: [methodName],
308
+ });
309
+ }
310
+ visitedMethods.add(methodName);
311
+ }
312
+ });
313
+ }
314
+ function validateUniqueness(decorators) {
315
+ const apiDecorators = decorators.filter(isApiDecorator);
316
+ for (let i = 0; i < apiDecorators.length; i++) {
317
+ const { path: currentPath, type: currentType } = apiDecorators[i];
318
+ const currentPropertyName = currentPath.parentPath.get('key.name').node;
319
+ for (let j = 0; j < apiDecorators.length; j++) {
320
+ const { path: comparePath, type: compareType } = apiDecorators[j];
321
+ const comparePropertyName = comparePath.parentPath.get('key.name')
322
+ .node;
323
+ // We will throw if the considered properties have the same name, and when their
324
+ // are not part of a pair of getter/setter.
325
+ const haveSameName = currentPropertyName === comparePropertyName;
326
+ const isDifferentProperty = currentPath !== comparePath;
327
+ const isGetterSetterPair = (currentType === DECORATOR_TYPES.GETTER &&
328
+ compareType === DECORATOR_TYPES.SETTER) ||
329
+ (currentType === DECORATOR_TYPES.SETTER && compareType === DECORATOR_TYPES.GETTER);
330
+ if (haveSameName && isDifferentProperty && !isGetterSetterPair) {
331
+ throw generateError(comparePath, {
332
+ errorInfo: DecoratorErrors.DUPLICATE_API_PROPERTY,
333
+ messageArgs: [currentPropertyName],
334
+ });
335
+ }
336
+ }
337
+ }
338
+ }
339
+ function validate$3(decorators) {
340
+ const apiDecorators = decorators.filter(isApiDecorator);
341
+ if (apiDecorators.length === 0) {
342
+ return;
343
+ }
344
+ apiDecorators.forEach(({ path, decoratedNodeType }) => {
345
+ validateConflict(path, decorators);
346
+ if (decoratedNodeType !== DECORATOR_TYPES.METHOD) {
347
+ const property = path.parentPath;
348
+ validatePropertyName(property);
349
+ validatePropertyValue(property);
350
+ }
351
+ });
352
+ validateSingleApiDecoratorOnSetterGetterPair(decorators);
353
+ validateUniqueness(decorators);
354
+ }
355
+
356
+ const { PUBLIC_PROPS, PUBLIC_METHODS } = LWC_COMPONENT_PROPERTIES;
357
+ const PUBLIC_PROP_BIT_MASK = {
358
+ PROPERTY: 0,
359
+ GETTER: 1,
360
+ SETTER: 2,
361
+ };
362
+ function getPropertyBitmask(type) {
363
+ switch (type) {
364
+ case DECORATOR_TYPES.GETTER:
365
+ return PUBLIC_PROP_BIT_MASK.GETTER;
366
+ case DECORATOR_TYPES.SETTER:
367
+ return PUBLIC_PROP_BIT_MASK.SETTER;
368
+ default:
369
+ return PUBLIC_PROP_BIT_MASK.PROPERTY;
370
+ }
371
+ }
372
+ function getSiblingGetSetPairType(propertyName, type, classBodyItems) {
373
+ const siblingKind = type === DECORATOR_TYPES.GETTER ? 'set' : 'get';
374
+ const siblingNode = classBodyItems.find((classBodyItem) => {
375
+ const isClassMethod = classBodyItem.isClassMethod({ kind: siblingKind });
376
+ const isSamePropertyName = classBodyItem.node.key.name ===
377
+ propertyName;
378
+ return isClassMethod && isSamePropertyName;
379
+ });
380
+ if (siblingNode) {
381
+ return siblingKind === 'get' ? DECORATOR_TYPES.GETTER : DECORATOR_TYPES.SETTER;
382
+ }
383
+ }
384
+ function computePublicPropsConfig(publicPropertyMetas, classBodyItems) {
385
+ return publicPropertyMetas.reduce((acc, { propertyName, decoratedNodeType }) => {
386
+ if (!(propertyName in acc)) {
387
+ acc[propertyName] = {};
388
+ }
389
+ acc[propertyName].config |= getPropertyBitmask(decoratedNodeType);
390
+ if (decoratedNodeType === DECORATOR_TYPES.GETTER ||
391
+ decoratedNodeType === DECORATOR_TYPES.SETTER) {
392
+ // With the latest decorator spec, only one of the getter/setter pair needs a decorator.
393
+ // We need to add the proper bitmask for the sibling getter/setter if it exists.
394
+ const pairType = getSiblingGetSetPairType(propertyName, decoratedNodeType, classBodyItems);
395
+ if (pairType) {
396
+ acc[propertyName].config |= getPropertyBitmask(pairType);
397
+ }
398
+ }
399
+ return acc;
400
+ }, {});
401
+ }
402
+ function transform$2(t, decoratorMetas, classBodyItems) {
403
+ const objectProperties = [];
404
+ const apiDecoratorMetas = decoratorMetas.filter(isApiDecorator);
405
+ const publicPropertyMetas = apiDecoratorMetas.filter(({ decoratedNodeType }) => decoratedNodeType !== DECORATOR_TYPES.METHOD);
406
+ if (publicPropertyMetas.length) {
407
+ const propsConfig = computePublicPropsConfig(publicPropertyMetas, classBodyItems);
408
+ objectProperties.push(t.objectProperty(t.identifier(PUBLIC_PROPS), t.valueToNode(propsConfig)));
409
+ }
410
+ const publicMethodMetas = apiDecoratorMetas.filter(({ decoratedNodeType }) => decoratedNodeType === DECORATOR_TYPES.METHOD);
411
+ if (publicMethodMetas.length) {
412
+ const methodNames = publicMethodMetas.map(({ propertyName }) => propertyName);
413
+ objectProperties.push(t.objectProperty(t.identifier(PUBLIC_METHODS), t.valueToNode(methodNames)));
414
+ }
415
+ return objectProperties;
416
+ }
417
+
418
+ /*
419
+ * Copyright (c) 2023, salesforce.com, inc.
420
+ * All rights reserved.
421
+ * SPDX-License-Identifier: MIT
422
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
423
+ */
424
+ const { API_DECORATOR: API_DECORATOR$1 } = LWC_PACKAGE_EXPORTS;
425
+ var api = {
426
+ name: API_DECORATOR$1,
427
+ validate: validate$3,
428
+ transform: transform$2,
429
+ };
430
+
431
+ /*
432
+ * Copyright (c) 2023, salesforce.com, inc.
433
+ * All rights reserved.
434
+ * SPDX-License-Identifier: MIT
435
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
436
+ */
437
+ const { WIRE_DECORATOR: WIRE_DECORATOR$2 } = LWC_PACKAGE_EXPORTS;
438
+ function isWireDecorator(decorator) {
439
+ return decorator.name === WIRE_DECORATOR$2;
440
+ }
441
+
442
+ const { TRACK_DECORATOR: TRACK_DECORATOR$1, WIRE_DECORATOR: WIRE_DECORATOR$1, API_DECORATOR } = LWC_PACKAGE_EXPORTS;
443
+ function validateWireParameters(path) {
444
+ const [id, config] = path.get('expression.arguments');
445
+ if (!id) {
446
+ throw generateError(path, {
447
+ errorInfo: DecoratorErrors.ADAPTER_SHOULD_BE_FIRST_PARAMETER,
448
+ });
449
+ }
450
+ const isIdentifier = id.isIdentifier();
451
+ const isMemberExpression = id.isMemberExpression();
452
+ if (!isIdentifier && !isMemberExpression) {
453
+ throw generateError(id, {
454
+ errorInfo: DecoratorErrors.FUNCTION_IDENTIFIER_SHOULD_BE_FIRST_PARAMETER,
455
+ });
456
+ }
457
+ if (id.isMemberExpression({ computed: true })) {
458
+ throw generateError(id, {
459
+ errorInfo: DecoratorErrors.FUNCTION_IDENTIFIER_CANNOT_HAVE_COMPUTED_PROPS,
460
+ });
461
+ }
462
+ // TODO [#3444]: improve member expression computed typechecking
463
+ // @ts-ignore
464
+ if (isMemberExpression && !id.get('object').isIdentifier()) {
465
+ throw generateError(id, {
466
+ errorInfo: DecoratorErrors.FUNCTION_IDENTIFIER_CANNOT_HAVE_NESTED_MEMBER_EXRESSIONS,
467
+ });
468
+ }
469
+ // TODO [#3444]: improve member expression computed typechecking
470
+ // Ensure wire adapter is imported (check for member expression or identifier)
471
+ // @ts-ignore
472
+ const wireBinding = isMemberExpression ? id.node.object.name : id.node.name;
473
+ if (!path.scope.getBinding(wireBinding)) {
474
+ throw generateError(id, {
475
+ errorInfo: DecoratorErrors.WIRE_ADAPTER_SHOULD_BE_IMPORTED,
476
+ messageArgs: [id.node.name],
477
+ });
478
+ }
479
+ // ensure wire adapter is a first parameter
480
+ if (wireBinding &&
481
+ !path.scope.getBinding(wireBinding).path.isImportSpecifier() &&
482
+ !path.scope.getBinding(wireBinding).path.isImportDefaultSpecifier()) {
483
+ throw generateError(id, {
484
+ errorInfo: DecoratorErrors.IMPORTED_FUNCTION_IDENTIFIER_SHOULD_BE_FIRST_PARAMETER,
485
+ });
486
+ }
487
+ if (config && !config.isObjectExpression()) {
488
+ throw generateError(config, {
489
+ errorInfo: DecoratorErrors.CONFIG_OBJECT_SHOULD_BE_SECOND_PARAMETER,
490
+ });
491
+ }
492
+ }
493
+ function validateUsageWithOtherDecorators(path, decorators) {
494
+ decorators.forEach((decorator) => {
495
+ if (path !== decorator.path &&
496
+ decorator.name === WIRE_DECORATOR$1 &&
497
+ decorator.path.parentPath.node === path.parentPath.node) {
498
+ throw generateError(path, {
499
+ errorInfo: DecoratorErrors.ONE_WIRE_DECORATOR_ALLOWED,
500
+ });
501
+ }
502
+ if ((decorator.name === API_DECORATOR || decorator.name === TRACK_DECORATOR$1) &&
503
+ decorator.path.parentPath.node === path.parentPath.node) {
504
+ throw generateError(path, {
505
+ errorInfo: DecoratorErrors.CONFLICT_WITH_ANOTHER_DECORATOR,
506
+ messageArgs: [decorator.name],
507
+ });
508
+ }
509
+ });
510
+ }
511
+ function validate$2(decorators) {
512
+ decorators.filter(isWireDecorator).forEach(({ path }) => {
513
+ validateUsageWithOtherDecorators(path, decorators);
514
+ validateWireParameters(path);
515
+ });
516
+ }
517
+
518
+ const WIRE_PARAM_PREFIX = '$';
519
+ const WIRE_CONFIG_ARG_NAME = '$cmp';
520
+ function isObservedProperty(configProperty) {
521
+ const propertyValue = configProperty.get('value');
522
+ return (propertyValue.isStringLiteral() && propertyValue.node.value.startsWith(WIRE_PARAM_PREFIX));
523
+ }
524
+ function getWiredStatic(wireConfig) {
525
+ return wireConfig
526
+ .get('properties')
527
+ .filter((property) => !isObservedProperty(property))
528
+ .map((path) => path.node);
529
+ }
530
+ function getWiredParams(t, wireConfig) {
531
+ return wireConfig
532
+ .get('properties')
533
+ .filter((property) => isObservedProperty(property))
534
+ .map((path) => {
535
+ // Need to clone deep the observed property to remove the param prefix
536
+ const clonedProperty = t.cloneDeep(path.node);
537
+ clonedProperty.value.value = clonedProperty.value.value.slice(1);
538
+ return clonedProperty;
539
+ });
540
+ }
541
+ function getGeneratedConfig(t, wiredValue) {
542
+ let counter = 0;
543
+ const configBlockBody = [];
544
+ const configProps = [];
545
+ const generateParameterConfigValue = (memberExprPaths) => {
546
+ // Note: When memberExprPaths ($foo.bar) has an invalid identifier (eg: foo..bar, foo.bar[3])
547
+ // it should (ideally) resolve in a compilation error during validation phase.
548
+ // This is not possible due that platform components may have a param definition which is invalid
549
+ // but passes compilation, and throwing at compile time would break such components.
550
+ // In such cases where the param does not have proper notation, the config generated will use the bracket
551
+ // notation to match the current behavior (that most likely end up resolving that param as undefined).
552
+ const isInvalidMemberExpr = memberExprPaths.some((maybeIdentifier) => !(t.isValidES3Identifier(maybeIdentifier) && maybeIdentifier.length > 0));
553
+ const memberExprPropertyGen = !isInvalidMemberExpr
554
+ ? t.identifier
555
+ : t.StringLiteral;
556
+ if (memberExprPaths.length === 1) {
557
+ return {
558
+ configValueExpression: t.memberExpression(t.identifier(WIRE_CONFIG_ARG_NAME), memberExprPropertyGen(memberExprPaths[0])),
559
+ };
560
+ }
561
+ const varName = 'v' + ++counter;
562
+ const varDeclaration = t.variableDeclaration('let', [
563
+ t.variableDeclarator(t.identifier(varName), t.memberExpression(t.identifier(WIRE_CONFIG_ARG_NAME), memberExprPropertyGen(memberExprPaths[0]), isInvalidMemberExpr)),
564
+ ]);
565
+ // Results in: v != null && ... (v = v.i) != null && ... (v = v.(n-1)) != null
566
+ let conditionTest = t.binaryExpression('!=', t.identifier(varName), t.nullLiteral());
567
+ for (let i = 1, n = memberExprPaths.length; i < n - 1; i++) {
568
+ const nextPropValue = t.assignmentExpression('=', t.identifier(varName), t.memberExpression(t.identifier(varName), memberExprPropertyGen(memberExprPaths[i]), isInvalidMemberExpr));
569
+ conditionTest = t.logicalExpression('&&', conditionTest, t.binaryExpression('!=', nextPropValue, t.nullLiteral()));
570
+ }
571
+ // conditionTest ? v.n : undefined
572
+ const configValueExpression = t.conditionalExpression(conditionTest, t.memberExpression(t.identifier(varName), memberExprPropertyGen(memberExprPaths[memberExprPaths.length - 1]), isInvalidMemberExpr), t.identifier('undefined'));
573
+ return {
574
+ varDeclaration,
575
+ configValueExpression,
576
+ };
577
+ };
578
+ if (wiredValue.static) {
579
+ Array.prototype.push.apply(configProps, wiredValue.static);
580
+ }
581
+ if (wiredValue.params) {
582
+ wiredValue.params.forEach((param) => {
583
+ const memberExprPaths = param.value.value.split('.');
584
+ const paramConfigValue = generateParameterConfigValue(memberExprPaths);
585
+ configProps.push(t.objectProperty(param.key, paramConfigValue.configValueExpression));
586
+ if (paramConfigValue.varDeclaration) {
587
+ configBlockBody.push(paramConfigValue.varDeclaration);
588
+ }
589
+ });
590
+ }
591
+ configBlockBody.push(t.returnStatement(t.objectExpression(configProps)));
592
+ const fnExpression = t.functionExpression(null, [t.identifier(WIRE_CONFIG_ARG_NAME)], t.blockStatement(configBlockBody));
593
+ return t.objectProperty(t.identifier('config'), fnExpression);
594
+ }
595
+ function buildWireConfigValue(t, wiredValues) {
596
+ return t.objectExpression(wiredValues.map((wiredValue) => {
597
+ const wireConfig = [];
598
+ if (wiredValue.adapter) {
599
+ wireConfig.push(t.objectProperty(t.identifier('adapter'), wiredValue.adapter.expression));
600
+ }
601
+ if (wiredValue.params) {
602
+ const dynamicParamNames = wiredValue.params.map((p) => {
603
+ return t.stringLiteral(t.isIdentifier(p.key) ? p.key.name : p.key.value);
604
+ });
605
+ wireConfig.push(t.objectProperty(t.identifier('dynamic'), t.arrayExpression(dynamicParamNames)));
606
+ }
607
+ if (wiredValue.isClassMethod) {
608
+ wireConfig.push(t.objectProperty(t.identifier('method'), t.numericLiteral(1)));
609
+ }
610
+ wireConfig.push(getGeneratedConfig(t, wiredValue));
611
+ return t.objectProperty(t.identifier(wiredValue.propertyName), t.objectExpression(wireConfig));
612
+ }));
613
+ }
614
+ const SUPPORTED_VALUE_TO_TYPE_MAP = {
615
+ StringLiteral: 'string',
616
+ NumericLiteral: 'number',
617
+ BooleanLiteral: 'boolean',
618
+ };
619
+ const scopedReferenceLookup = (scope) => (name) => {
620
+ const binding = scope.getBinding(name);
621
+ let type;
622
+ let value;
623
+ if (binding) {
624
+ if (binding.kind === 'module') {
625
+ // Resolves module import to the name of the module imported
626
+ // e.g. import { foo } from 'bar' gives value 'bar' for `name == 'foo'
627
+ const parentPathNode = binding.path.parentPath.node;
628
+ if (parentPathNode && parentPathNode.source) {
629
+ type = 'module';
630
+ value = parentPathNode.source.value;
631
+ }
632
+ }
633
+ else if (binding.kind === 'const') {
634
+ // Resolves `const foo = 'text';` references to value 'text', where `name == 'foo'`
635
+ const init = binding.path.node.init;
636
+ if (init &&
637
+ SUPPORTED_VALUE_TO_TYPE_MAP[init.type]) {
638
+ type =
639
+ SUPPORTED_VALUE_TO_TYPE_MAP[init.type];
640
+ value = init
641
+ .value;
642
+ }
643
+ }
644
+ }
645
+ return {
646
+ type,
647
+ value,
648
+ };
649
+ };
650
+ function transform$1(t, decoratorMetas) {
651
+ const objectProperties = [];
652
+ const wiredValues = decoratorMetas.filter(isWireDecorator).map(({ path }) => {
653
+ const [id, config] = path.get('expression.arguments');
654
+ const propertyName = path.parentPath.get('key.name').node;
655
+ const isClassMethod = path.parentPath.isClassMethod({
656
+ kind: 'method',
657
+ });
658
+ const wiredValue = {
659
+ propertyName,
660
+ isClassMethod,
661
+ };
662
+ if (config) {
663
+ wiredValue.static = getWiredStatic(config);
664
+ wiredValue.params = getWiredParams(t, config);
665
+ }
666
+ const referenceLookup = scopedReferenceLookup(path.scope);
667
+ const isMemberExpression = id.isMemberExpression();
668
+ const isIdentifier = id.isIdentifier();
669
+ if (isIdentifier || isMemberExpression) {
670
+ const referenceName = isMemberExpression ? id.node.object.name : id.node.name;
671
+ const reference = referenceLookup(referenceName);
672
+ wiredValue.adapter = {
673
+ name: referenceName,
674
+ expression: t.cloneDeep(id.node),
675
+ reference: reference.type === 'module' ? reference.value : undefined,
676
+ };
677
+ }
678
+ return wiredValue;
679
+ });
680
+ if (wiredValues.length) {
681
+ objectProperties.push(t.objectProperty(t.identifier(LWC_COMPONENT_PROPERTIES.WIRE), buildWireConfigValue(t, wiredValues)));
682
+ }
683
+ return objectProperties;
684
+ }
685
+
686
+ /*
687
+ * Copyright (c) 2023, salesforce.com, inc.
688
+ * All rights reserved.
689
+ * SPDX-License-Identifier: MIT
690
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
691
+ */
692
+ const { WIRE_DECORATOR } = LWC_PACKAGE_EXPORTS;
693
+ var wire = {
694
+ name: WIRE_DECORATOR,
695
+ validate: validate$2,
696
+ transform: transform$1,
697
+ };
698
+
699
+ /*
700
+ * Copyright (c) 2023, salesforce.com, inc.
701
+ * All rights reserved.
702
+ * SPDX-License-Identifier: MIT
703
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
704
+ */
705
+ const { TRACK_DECORATOR } = LWC_PACKAGE_EXPORTS;
706
+ const TRACK_PROPERTY_VALUE = 1;
707
+ function isTrackDecorator(decorator) {
708
+ return decorator.name === TRACK_DECORATOR;
709
+ }
710
+ function validate$1(decorators) {
711
+ decorators.filter(isTrackDecorator).forEach(({ path }) => {
712
+ if (!path.parentPath.isClassProperty()) {
713
+ throw generateError(path, {
714
+ errorInfo: DecoratorErrors.TRACK_ONLY_ALLOWED_ON_CLASS_PROPERTIES,
715
+ });
716
+ }
717
+ });
718
+ }
719
+ function transform(t, decoratorMetas) {
720
+ const objectProperties = [];
721
+ const trackDecoratorMetas = decoratorMetas.filter(isTrackDecorator);
722
+ if (trackDecoratorMetas.length) {
723
+ const config = trackDecoratorMetas.reduce((acc, meta) => {
724
+ acc[meta.propertyName] = TRACK_PROPERTY_VALUE;
725
+ return acc;
726
+ }, {});
727
+ objectProperties.push(t.objectProperty(t.identifier(LWC_COMPONENT_PROPERTIES.TRACK), t.valueToNode(config)));
728
+ }
729
+ return objectProperties;
730
+ }
731
+ var track = {
732
+ name: TRACK_DECORATOR,
733
+ transform,
734
+ validate: validate$1,
735
+ };
736
+
737
+ const DECORATOR_TRANSFORMS = [api, wire, track];
738
+ const AVAILABLE_DECORATORS = DECORATOR_TRANSFORMS.map((transform) => transform.name).join(', ');
739
+ function isLwcDecoratorName(name) {
740
+ return DECORATOR_TRANSFORMS.some((transform) => transform.name === name);
741
+ }
742
+ /** Returns a list of all the references to an identifier */
743
+ function getReferences(identifier) {
744
+ return identifier.scope.getBinding(identifier.node.name).referencePaths;
745
+ }
746
+ /** Returns the type of decorator depdending on the property or method if get applied to */
747
+ function getDecoratedNodeType(decoratorPath) {
748
+ const propertyOrMethod = decoratorPath.parentPath;
749
+ if (isClassMethod(propertyOrMethod)) {
750
+ return DECORATOR_TYPES.METHOD;
751
+ }
752
+ else if (isGetterClassMethod(propertyOrMethod)) {
753
+ return DECORATOR_TYPES.GETTER;
754
+ }
755
+ else if (isSetterClassMethod(propertyOrMethod)) {
756
+ return DECORATOR_TYPES.SETTER;
757
+ }
758
+ else if (propertyOrMethod.isClassProperty()) {
759
+ return DECORATOR_TYPES.PROPERTY;
760
+ }
761
+ else {
762
+ throw generateError(propertyOrMethod, {
763
+ errorInfo: DecoratorErrors.INVALID_DECORATOR_TYPE,
764
+ });
765
+ }
766
+ }
767
+ function validateImportedLwcDecoratorUsage(engineImportSpecifiers) {
768
+ engineImportSpecifiers
769
+ .filter(({ name }) => isLwcDecoratorName(name))
770
+ .reduce((acc, { name, path }) => {
771
+ // Get a list of all the local references
772
+ const local = path.get('imported');
773
+ const references = getReferences(local).map((reference) => ({
774
+ name,
775
+ reference,
776
+ }));
777
+ return [...acc, ...references];
778
+ }, [])
779
+ .forEach(({ name, reference }) => {
780
+ // Get the decorator from the identifier
781
+ // If the the decorator is:
782
+ // - an identifier @track : the decorator is the parent of the identifier
783
+ // - a call expression @wire("foo") : the decorator is the grand-parent of the identifier
784
+ const decorator = reference.parentPath.isDecorator()
785
+ ? reference.parentPath
786
+ : reference.parentPath.parentPath;
787
+ if (!decorator.isDecorator()) {
788
+ throw generateError(decorator, {
789
+ errorInfo: DecoratorErrors.IS_NOT_DECORATOR,
790
+ messageArgs: [name],
791
+ });
792
+ }
793
+ const propertyOrMethod = decorator.parentPath;
794
+ if (!propertyOrMethod.isClassProperty() && !propertyOrMethod.isClassMethod()) {
795
+ throw generateError(propertyOrMethod, {
796
+ errorInfo: DecoratorErrors.IS_NOT_CLASS_PROPERTY_OR_CLASS_METHOD,
797
+ messageArgs: [name],
798
+ });
799
+ }
800
+ });
801
+ }
802
+ function isImportedFromLwcSource(decoratorBinding) {
803
+ const bindingPath = decoratorBinding.path;
804
+ return (bindingPath.isImportSpecifier() &&
805
+ bindingPath.parent.source.value === 'lwc');
806
+ }
807
+ /** Validate the usage of decorator by calling each validation function */
808
+ function validate(decorators) {
809
+ for (const { name, path } of decorators) {
810
+ const binding = path.scope.getBinding(name);
811
+ if (binding === undefined || !isImportedFromLwcSource(binding)) {
812
+ throw generateInvalidDecoratorError(path);
813
+ }
814
+ }
815
+ DECORATOR_TRANSFORMS.forEach(({ validate }) => validate(decorators));
816
+ }
817
+ /** Remove import specifiers. It also removes the import statement if the specifier list becomes empty */
818
+ function removeImportedDecoratorSpecifiers(engineImportSpecifiers) {
819
+ engineImportSpecifiers
820
+ .filter(({ name }) => isLwcDecoratorName(name))
821
+ .forEach(({ path }) => {
822
+ const importStatement = path.parentPath;
823
+ path.remove();
824
+ if (importStatement.get('specifiers').length === 0) {
825
+ importStatement.remove();
826
+ }
827
+ });
828
+ }
829
+ function generateInvalidDecoratorError(path) {
830
+ const expressionPath = path.get('expression');
831
+ const { node } = path;
832
+ const { expression } = node;
833
+ let name;
834
+ if (expressionPath.isIdentifier()) {
835
+ name = expression.name;
836
+ }
837
+ else if (expressionPath.isCallExpression()) {
838
+ name = expression.callee.name;
839
+ }
840
+ if (name) {
841
+ return generateError(path.parentPath, {
842
+ errorInfo: DecoratorErrors.INVALID_DECORATOR_WITH_NAME,
843
+ messageArgs: [name, AVAILABLE_DECORATORS, LWC_PACKAGE_ALIAS],
844
+ });
845
+ }
846
+ else {
847
+ return generateError(path.parentPath, {
848
+ errorInfo: DecoratorErrors.INVALID_DECORATOR,
849
+ messageArgs: [AVAILABLE_DECORATORS, LWC_PACKAGE_ALIAS],
850
+ });
851
+ }
852
+ }
853
+ function collectDecoratorPaths(bodyItems) {
854
+ return bodyItems.reduce((acc, bodyItem) => {
855
+ const decorators = bodyItem.get('decorators');
856
+ if (decorators && decorators.length) {
857
+ acc.push(...decorators);
858
+ }
859
+ return acc;
860
+ }, []);
861
+ }
862
+ function getDecoratorMetadata(decoratorPath) {
863
+ const expressionPath = decoratorPath.get('expression');
864
+ let name;
865
+ if (expressionPath.isIdentifier()) {
866
+ name = expressionPath.node.name;
867
+ }
868
+ else if (expressionPath.isCallExpression()) {
869
+ name = expressionPath.node.callee.name;
870
+ }
871
+ else {
872
+ throw generateInvalidDecoratorError(decoratorPath);
873
+ }
874
+ const propertyName = decoratorPath.parent.key.name;
875
+ const decoratedNodeType = getDecoratedNodeType(decoratorPath);
876
+ return {
877
+ name,
878
+ propertyName,
879
+ path: decoratorPath,
880
+ decoratedNodeType,
881
+ };
882
+ }
883
+ function getMetadataObjectPropertyList(t, decoratorMetas, classBodyItems) {
884
+ const list = [
885
+ ...api.transform(t, decoratorMetas, classBodyItems),
886
+ ...track.transform(t, decoratorMetas),
887
+ ...wire.transform(t, decoratorMetas),
888
+ ];
889
+ const fieldNames = classBodyItems
890
+ .filter((field) => field.isClassProperty({ computed: false, static: false }))
891
+ .filter((field) => !field.node.decorators)
892
+ .map((field) => field.node.key.name);
893
+ if (fieldNames.length) {
894
+ list.push(t.objectProperty(t.identifier('fields'), t.valueToNode(fieldNames)));
895
+ }
896
+ return list;
897
+ }
898
+ function decorators({ types: t }) {
899
+ function createRegisterDecoratorsCallExpression(path, classExpression, props) {
900
+ const id = addNamed(path, REGISTER_DECORATORS_ID, LWC_PACKAGE_ALIAS);
901
+ return t.callExpression(id, [classExpression, t.objectExpression(props)]);
902
+ }
903
+ // Babel reinvokes visitors for node reinsertion so we use this to avoid an infinite loop.
904
+ const visitedClasses = new WeakSet();
905
+ return {
906
+ Class(path) {
907
+ const { node } = path;
908
+ if (visitedClasses.has(node)) {
909
+ return;
910
+ }
911
+ visitedClasses.add(node);
912
+ const classBodyItems = path.get('body.body');
913
+ if (classBodyItems.length === 0) {
914
+ return;
915
+ }
916
+ const decoratorPaths = collectDecoratorPaths(classBodyItems);
917
+ const decoratorMetas = decoratorPaths.map(getDecoratorMetadata);
918
+ validate(decoratorMetas);
919
+ const metaPropertyList = getMetadataObjectPropertyList(t, decoratorMetas, classBodyItems);
920
+ if (metaPropertyList.length === 0) {
921
+ return;
922
+ }
923
+ decoratorPaths.forEach((path) => path.remove());
924
+ const isAnonymousClassDeclaration = path.isClassDeclaration() && !path.get('id').isIdentifier();
925
+ const shouldTransformAsClassExpression = path.isClassExpression() || isAnonymousClassDeclaration;
926
+ if (shouldTransformAsClassExpression) {
927
+ // Example:
928
+ // export default class extends LightningElement {}
929
+ // Output:
930
+ // export default registerDecorators(class extends LightningElement {});
931
+ // if it does not have an id, we can treat it as a ClassExpression
932
+ const classExpression = t.toExpression(node);
933
+ path.replaceWith(createRegisterDecoratorsCallExpression(path, classExpression, metaPropertyList));
934
+ }
935
+ else {
936
+ // Example: export default class NamedClass extends LightningElement {}
937
+ // Output:
938
+ // export default class NamedClass extends LightningElement {}
939
+ // registerDecorators(NamedClass);
940
+ // Note: This will be further transformed
941
+ const statementPath = path.getStatementParent();
942
+ statementPath.insertAfter(t.expressionStatement(createRegisterDecoratorsCallExpression(path, node.id, metaPropertyList)));
943
+ }
944
+ },
945
+ };
946
+ }
947
+
948
+ /*
949
+ * Copyright (c) 2023, salesforce.com, inc.
950
+ * All rights reserved.
951
+ * SPDX-License-Identifier: MIT
952
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
953
+ */
954
+ function defaultImport(t, specifiers) {
955
+ const defaultImport = specifiers.find((s) => t.isImportDefaultSpecifier(s));
956
+ return defaultImport && defaultImport.local.name;
957
+ }
958
+ function dedupeImports ({ types: t }) {
959
+ return function (path) {
960
+ const body = path.get('body');
961
+ const importStatements = body.filter((s) => s.isImportDeclaration());
962
+ const visited = new Map();
963
+ importStatements.forEach((importPath) => {
964
+ const sourceLiteral = importPath.node.source;
965
+ // If the import is of the type import * as X, just ignore it since we can't dedupe
966
+ if (importPath.node.specifiers.some((_) => t.isImportNamespaceSpecifier(_))) {
967
+ return;
968
+ }
969
+ // If we have seen the same source, we will try to dedupe it
970
+ if (visited.has(sourceLiteral.value)) {
971
+ const visitedImport = visited.get(sourceLiteral.value);
972
+ const visitedSpecifiers = visitedImport.node.specifiers;
973
+ const visitedDefaultImport = defaultImport(t, visitedSpecifiers);
974
+ // We merge all the named imports unless is a default with the same name
975
+ let canImportBeRemoved = true;
976
+ importPath.node.specifiers.forEach((s) => {
977
+ if (visitedDefaultImport && t.isImportDefaultSpecifier(s)) {
978
+ if (visitedDefaultImport !== s.local.name) {
979
+ canImportBeRemoved = false;
980
+ }
981
+ }
982
+ else {
983
+ visitedSpecifiers.push(s);
984
+ }
985
+ });
986
+ if (canImportBeRemoved) {
987
+ importPath.remove();
988
+ }
989
+ // We need to sort the imports due to a bug in babel where default must be first
990
+ visitedSpecifiers.sort((a) => (t.isImportDefaultSpecifier(a) ? -1 : 1));
991
+ }
992
+ else {
993
+ visited.set(sourceLiteral.value, importPath);
994
+ }
995
+ });
996
+ };
997
+ }
998
+
999
+ function getImportSource(path) {
1000
+ return path.parentPath.get('arguments.0');
1001
+ }
1002
+ function validateImport(sourcePath) {
1003
+ if (!sourcePath.isStringLiteral()) {
1004
+ throw generateError(sourcePath, {
1005
+ errorInfo: LWCClassErrors.INVALID_DYNAMIC_IMPORT_SOURCE_STRICT,
1006
+ messageArgs: [String(sourcePath)],
1007
+ });
1008
+ }
1009
+ }
1010
+ /*
1011
+ * Expected API for this plugin:
1012
+ * { dynamicImports: { loader: string, strictSpecifier: boolean } }
1013
+ */
1014
+ function dynamicImports () {
1015
+ function getLoaderRef(path, loaderName, state) {
1016
+ if (!state.loaderRef) {
1017
+ state.loaderRef = addNamed(path, 'load', loaderName);
1018
+ }
1019
+ return state.loaderRef;
1020
+ }
1021
+ function addDynamicImportDependency(dependency, state) {
1022
+ // TODO [#3444]: state.dynamicImports seems unused and can probably be deleted
1023
+ if (!state.dynamicImports) {
1024
+ state.dynamicImports = [];
1025
+ }
1026
+ if (!state.dynamicImports.includes(dependency)) {
1027
+ state.dynamicImports.push(dependency);
1028
+ }
1029
+ }
1030
+ return {
1031
+ Import(path, state) {
1032
+ const { dynamicImports } = state.opts;
1033
+ if (!dynamicImports) {
1034
+ return;
1035
+ }
1036
+ const { loader, strictSpecifier } = dynamicImports;
1037
+ const sourcePath = getImportSource(path);
1038
+ if (strictSpecifier) {
1039
+ validateImport(sourcePath);
1040
+ }
1041
+ if (loader) {
1042
+ const loaderId = getLoaderRef(path, loader, state);
1043
+ path.replaceWith(loaderId);
1044
+ }
1045
+ if (sourcePath.isStringLiteral()) {
1046
+ addDynamicImportDependency(sourcePath.node.value, state);
1047
+ }
1048
+ },
1049
+ };
1050
+ }
1051
+
1052
+ /*
1053
+ * Copyright (c) 2023, salesforce.com, inc.
1054
+ * All rights reserved.
1055
+ * SPDX-License-Identifier: MIT
1056
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
1057
+ */
1058
+ function scopeCssImports ({ types: t }, path) {
1059
+ const programPath = path.isProgram() ? path : path.findParent((node) => node.isProgram());
1060
+ programPath.get('body').forEach((node) => {
1061
+ if (node.isImportDeclaration()) {
1062
+ const source = node.get('source');
1063
+ if (source.type === 'StringLiteral' && source.node.value.endsWith('.scoped.css')) {
1064
+ source.replaceWith(t.stringLiteral(source.node.value + '?scoped=true'));
1065
+ }
1066
+ }
1067
+ });
1068
+ }
1069
+
1070
+ function compilerVersionNumber({ types: t }) {
1071
+ return {
1072
+ ClassBody(path) {
1073
+ if (path.parent.superClass === null) {
1074
+ // Components *must* extend from either LightningElement or some other superclass (e.g. a mixin).
1075
+ // We can skip classes without a superclass to avoid adding unnecessary comments.
1076
+ return;
1077
+ }
1078
+ // If the class body is empty, we want an inner comment. Otherwise we want it after the last child
1079
+ // of the class body. In either case, we want it right before the `}` at the end of the function body.
1080
+ if (path.node.body.length > 0) {
1081
+ // E.g. `class Foo extends Lightning Element { /*LWC compiler v1.2.3*/ }`
1082
+ t.addComment(path.node.body[path.node.body.length - 1], 'trailing', LWC_VERSION_COMMENT,
1083
+ /* line */ false);
1084
+ }
1085
+ else {
1086
+ // E.g. `class Foo extends Lightning Element { bar = 'baz'; /*LWC compiler v1.2.3*/ }`
1087
+ t.addComment(path.node, 'inner', LWC_VERSION_COMMENT, /* line */ false);
1088
+ }
1089
+ },
1090
+ };
1091
+ }
1092
+
1093
+ /*
1094
+ * Copyright (c) 2023, salesforce.com, inc.
1095
+ * All rights reserved.
1096
+ * SPDX-License-Identifier: MIT
1097
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
1098
+ */
1099
+ /**
1100
+ * The transform is done in 2 passes:
1101
+ * - First, apply in a single AST traversal the decorators and the component transformation.
1102
+ * - Then, in a second path transform class properties using the official babel plugin "babel-plugin-transform-class-properties".
1103
+ */
1104
+ function LwcClassTransform(api) {
1105
+ const { ExportDefaultDeclaration: transformCreateRegisterComponent } = component(api);
1106
+ const { Class: transformDecorators } = decorators(api);
1107
+ const { Import: transformDynamicImports } = dynamicImports();
1108
+ const { ClassBody: addCompilerVersionNumber } = compilerVersionNumber(api);
1109
+ return {
1110
+ manipulateOptions(opts, parserOpts) {
1111
+ parserOpts.plugins.push('classProperties', [
1112
+ 'decorators',
1113
+ { decoratorsBeforeExport: true },
1114
+ ]);
1115
+ },
1116
+ visitor: {
1117
+ // The LWC babel plugin is incompatible with other plugins. To get around this, we run the LWC babel plugin
1118
+ // first by running all its traversals from this Program visitor.
1119
+ Program: {
1120
+ enter(path) {
1121
+ const engineImportSpecifiers = getEngineImportSpecifiers(path);
1122
+ // Validate the usage of LWC decorators.
1123
+ validateImportedLwcDecoratorUsage(engineImportSpecifiers);
1124
+ // Add ?scoped=true to *.scoped.css imports
1125
+ scopeCssImports(api, path);
1126
+ },
1127
+ exit(path) {
1128
+ const engineImportSpecifiers = getEngineImportSpecifiers(path);
1129
+ removeImportedDecoratorSpecifiers(engineImportSpecifiers);
1130
+ // Will eventually be removed to eliminate unnecessary complexity. Rollup already does this for us.
1131
+ dedupeImports(api)(path);
1132
+ },
1133
+ },
1134
+ Import: transformDynamicImports,
1135
+ Class: transformDecorators,
1136
+ ClassBody: addCompilerVersionNumber,
1137
+ ExportDefaultDeclaration: transformCreateRegisterComponent,
1138
+ },
1139
+ };
1140
+ }
1141
+
1142
+ export { LwcClassTransform as default };
1143
+ /** version: 2.44.0 */
1144
+ //# sourceMappingURL=index.js.map