-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathcustom-elements-manifest.config.js
More file actions
297 lines (262 loc) · 10.9 KB
/
custom-elements-manifest.config.js
File metadata and controls
297 lines (262 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { isStaticMember } from '@custom-elements-manifest/analyzer/src/utils/ast-helpers.js';
import { extractMixinNodes } from '@custom-elements-manifest/analyzer/src/utils/mixins.js';
const inheritanceDenyList = ['PolylitMixin', 'DirMixin'];
// Attribute types that can't be set via HTML attributes
const ignoredAttributeTypes = ['object', 'unknown', 'Array'];
// Members incorrectly picked up by CEM from assignments to sub-object properties
// (e.g., `this._controller.slotName = 'sr-label'` misinterpreted as a class field)
const ignoredMembers = ['slotName', 'id'];
// Events incorrectly picked up by CEM from dynamic dispatchEvent calls
// (e.g., `new CustomEvent(eventName, ...)` where eventName is a variable)
const ignoredEvents = ['eventName'];
const ignoredStaticMembers = [
'is',
'cvdlName',
'properties',
'observers',
'addCheckedInitializer',
'createProperty',
'getOrCreateMap',
'getPropertyDescriptor',
'enabledWarnings',
'shadowRootOptions',
'polylitConfig',
'constraints',
'delegateAttrs',
'delegateProps',
'lumoInjector',
'experimental',
];
/**
* Convert camelCase to dash-case.
* @param {string} str - e.g. "clearButtonVisible"
* @returns {string} - e.g. "clear-button-visible"
*/
function camelToDash(str) {
return str.replace(/([a-z])([A-Z])/gu, '$1-$2').toLowerCase();
}
/**
* @param {{name: string}} a
* @param {{name: string}} b
* @returns
*/
function sortName(a, b) {
const nameA = a.name?.toUpperCase(); // ignore upper and lowercase
const nameB = b.name?.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
}
/**
* Extracts @mixes JSDoc tag names from a node's JSDoc comments.
* @param {object} node - A TypeScript AST node
* @param {object} ts - The TypeScript module
* @returns {string[]} - Array of mixin names
*/
function getJsDocMixesTags(node, ts) {
return (node.jsDoc || [])
.flatMap((doc) => doc.tags || [])
.filter((tag) => ts.isJSDocUnknownTag(tag) && tag.tagName.text === 'mixes')
.map((tag) => tag.comment?.trim())
.filter(Boolean);
}
/**
* Resolves a mixin name to a package reference by checking the module's imports.
* @param {object} sourceFile - The TypeScript source file AST
* @param {string} mixinName - The mixin name (e.g., "InputControlMixin")
* @param {object} ts - The TypeScript module
* @returns {{ name: string, package?: string, module?: string } | null}
*/
function resolveMixinRef(sourceFile, mixinName, ts) {
for (const statement of sourceFile.statements) {
if (!ts.isImportDeclaration(statement)) continue;
const moduleSpecifier = statement.moduleSpecifier.text;
const importClause = statement.importClause;
if (!importClause) continue;
// Check named imports
const namedBindings = importClause.namedBindings;
if (!namedBindings || !ts.isNamedImports(namedBindings)) continue;
const match = namedBindings.elements.find((el) => el.name.text === mixinName);
if (!match) continue;
if (moduleSpecifier.startsWith('.')) {
// Same-package import
return { name: mixinName, module: moduleSpecifier.replace(/^\.\//u, '') };
}
// Cross-package import
return { name: mixinName, package: moduleSpecifier };
}
return null;
}
/**
* CEM plugin that augments mixin declarations with @mixes JSDoc tag references
* that the analyzer couldn't capture from static analysis (e.g., when
* I18nMixin wraps other mixins as: I18nMixin(defaultI18n, Chain(superClass))).
*/
function mixesPlugin() {
return {
analyzePhase({ ts, node, moduleDoc }) {
// Only process mixin export declarations (const Mixin = (superClass) => class ...)
if (!ts.isVariableStatement(node)) return;
for (const decl of node.declarationList.declarations) {
const mixesNames = getJsDocMixesTags(node, ts);
if (mixesNames.length === 0) continue;
const mixinName = decl.name.text;
const mixinDecl = moduleDoc.declarations?.find((d) => d.name === mixinName && d.kind === 'mixin');
if (!mixinDecl) continue;
const existingMixinNames = new Set((mixinDecl.mixins || []).map((m) => m.name));
const sourceFile = node.getSourceFile();
for (const mixName of mixesNames) {
if (existingMixinNames.has(mixName)) continue;
const ref = resolveMixinRef(sourceFile, mixName, ts);
if (ref) {
mixinDecl.mixins ||= [];
mixinDecl.mixins.push(ref);
}
}
}
},
};
}
/**
* CEM plugin that marks `readOnly: true` properties as `readonly` in custom-elements.json
* to filter them out of Lit property bindings when generating web-types-lit.json files.
*/
function readonlyPlugin() {
return {
analyzePhase({ ts, node, moduleDoc }) {
const mixinNodes = extractMixinNodes(node);
const classNode = mixinNodes ? mixinNodes.mixinClass : ts.isClassDeclaration(node) ? node : undefined;
if (!classNode) return;
// Find `static get properties()` method
for (const member of classNode.members || []) {
if (!ts.isGetAccessorDeclaration(member) || !isStaticMember(member) || member.name?.text !== 'properties') {
continue;
}
// Find the return statement's object literal
const returnStmt = member.body?.statements?.find(ts.isReturnStatement);
const returnObj = returnStmt?.expression;
if (!returnObj || !ts.isObjectLiteralExpression(returnObj)) continue;
for (const prop of returnObj.properties) {
if (!ts.isPropertyAssignment(prop)) continue;
const propName = prop.name?.text;
if (!propName) continue;
// Check if the property config object has `readOnly: true`
const configObj = prop.initializer;
if (!ts.isObjectLiteralExpression(configObj)) continue;
const hasReadOnly = configObj.properties.some(
(p) =>
ts.isPropertyAssignment(p) &&
p.name?.text === 'readOnly' &&
p.initializer?.kind === ts.SyntaxKind.TrueKeyword,
);
if (!hasReadOnly) continue;
// Find the matching member in moduleDoc declarations and mark it readonly
for (const declaration of moduleDoc.declarations || []) {
const cemMember = declaration.members?.find((m) => m.name === propName);
if (cemMember) {
cemMember.readonly = true;
}
}
}
}
},
};
}
/**
* CEM plugin that marks class declarations with `@private` or `@protected` JSDoc tags
* so they can be filtered out during the packageLinkPhase.
*/
function classPrivacyPlugin() {
return {
analyzePhase({ ts, node, moduleDoc }) {
if (!ts.isClassDeclaration(node) || !node.name) return;
const tag = (node.jsDoc || [])
.flatMap((doc) => doc.tags || [])
.find((t) => t.tagName?.text === 'private' || t.tagName?.text === 'protected');
if (!tag) return;
const decl = moduleDoc.declarations?.find((d) => d.name === node.name.text);
if (decl) {
decl.privacy = tag.tagName.text;
}
},
};
}
export default {
globs: ['packages/**/src/(vaadin-*.js|*-mixin.js)'],
packagejson: false,
litelement: true,
plugins: [
classPrivacyPlugin(),
mixesPlugin(),
readonlyPlugin(),
{
packageLinkPhase({ customElementsManifest }) {
for (const definition of customElementsManifest.modules) {
// Filter out class declarations marked as @private or @protected
const privateClassNames = new Set(
(definition.declarations || [])
.filter((d) => d.privacy === 'private' || d.privacy === 'protected')
.map((d) => d.name),
);
if (privateClassNames.size > 0) {
definition.declarations = definition.declarations.filter((d) => !privateClassNames.has(d.name));
definition.exports = (definition.exports || []).filter((e) => !privateClassNames.has(e.declaration?.name));
}
for (const declaration of definition.declarations) {
// Filter out private and protected API and internal static getters.
// Transform field members' attribute property from camelCase to dash-case.
if (declaration?.members?.length) {
declaration.members = declaration.members
.filter((member) => member.privacy !== 'private' && member.privacy !== 'protected')
.filter((member) => !member.name.startsWith('_'))
.filter((member) => !ignoredMembers.includes(member.name))
.filter((member) => !(member.static && ignoredStaticMembers.includes(member.name)))
.map((member) => {
if (member.kind === 'field' && member.attribute) {
return { ...member, attribute: camelToDash(member.attribute) };
}
return member;
})
.sort(sortName);
}
// Transform attributes:
// - Filter out attributes whose corresponding field member is not public.
// - Filter out starting with underscore e.g. `_lastTabIndex`
// - Filter out `dir` attribute inherited from DirMixin.
// - Filter out attributes with non-primitive types (can't be set via HTML attributes).
// - Transform camelCase attribute names to dash-case.
if (declaration?.attributes?.length) {
const publicMemberNames = new Set((declaration.members || []).map((m) => m.name));
declaration.attributes = declaration.attributes
.filter((attr) => !attr.fieldName || publicMemberNames.has(attr.fieldName))
.filter((member) => !inheritanceDenyList.includes(member.inheritedFrom?.name))
.filter((member) => !member.name.startsWith('_') && member.name !== 'dir')
.filter((member) => !ignoredAttributeTypes.some((type) => member.type?.text?.includes(type)))
.map((attr) => ({ ...attr, name: camelToDash(attr.name) }))
.sort(sortName);
}
// Filter out events:
// - inherited from PolylitMixin
// - with type "CustomEvent" but no name (invalid/inherited events)
if (declaration?.events?.length) {
declaration.events = declaration.events
.filter((member) => !inheritanceDenyList.includes(member.inheritedFrom?.name))
.filter((member) => !(member.type?.text === 'CustomEvent' && !member.name))
.filter((member) => !ignoredEvents.includes(member.name))
.sort(sortName);
}
}
}
// Remove modules with empty declarations and exports
customElementsManifest.modules = customElementsManifest.modules.filter(
(mod) => mod.declarations?.length || mod.exports?.length,
);
},
},
],
};