@ethlete/cdk 5.0.0-next.24 → 5.0.0-next.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,279 @@
1
+ import { LEGACY_SPINNER_COLOR_VARIABLE, LEGACY_SPINNER_TAG, lineOfIndex, PICTURE_TAG, SPINNER_TAG, } from './templates.js';
2
+ export const DOCS_BASE_URL = 'https://ethlete-sdk-docs.web.app';
3
+ export const createEmptyReport = () => ({
4
+ picturesWithoutAlt: [],
5
+ pictureClassInputs: [],
6
+ themedSpinners: [],
7
+ spinnerModeBindings: [],
8
+ judgmentSymbols: new Map(),
9
+ gatedSymbols: new Map(),
10
+ });
11
+ export const isReportEmpty = (report) => report.picturesWithoutAlt.length === 0 &&
12
+ report.pictureClassInputs.length === 0 &&
13
+ report.themedSpinners.length === 0 &&
14
+ report.spinnerModeBindings.length === 0 &&
15
+ report.judgmentSymbols.size === 0 &&
16
+ report.gatedSymbols.size === 0;
17
+ const PICTURE_CLASS_INPUTS = ['imgClass', 'figureClass', 'pictureClass', 'figcaptionClass'];
18
+ const VARIANT_PREFIX = /^([\w-]+:)+/;
19
+ const INDEFINITE_SIZES = new Set(['auto', 'min', 'max', 'fit']);
20
+ export const classifyImgClass = (value) => {
21
+ if (!value)
22
+ return 'unclassified';
23
+ const tokens = value.split(/\s+/).filter(Boolean);
24
+ let definiteWidth = false;
25
+ let definiteHeight = false;
26
+ let hasAspect = false;
27
+ let hasConstraint = false;
28
+ let hasIndefiniteAxis = false;
29
+ let hasResponsiveSizing = false;
30
+ for (const rawToken of tokens) {
31
+ const hasVariant = VARIANT_PREFIX.test(rawToken);
32
+ const token = rawToken.replace(VARIANT_PREFIX, '');
33
+ const axis = /^(w|h|size)-(.+)$/.exec(token);
34
+ const constraint = /^(?:max|min)-(?:w|h)-(.+)$/.exec(token);
35
+ const aspect = /^aspect-(.+)$/.exec(token);
36
+ if (!axis && !constraint && !aspect)
37
+ continue;
38
+ // A sizing class behind a breakpoint or a state is a judgment call, not a mode.
39
+ if (hasVariant) {
40
+ hasResponsiveSizing = true;
41
+ continue;
42
+ }
43
+ if (constraint) {
44
+ hasConstraint = true;
45
+ continue;
46
+ }
47
+ if (aspect) {
48
+ hasAspect ||= aspect[1] !== 'auto';
49
+ continue;
50
+ }
51
+ const [, prefix, size] = axis;
52
+ if (INDEFINITE_SIZES.has(size)) {
53
+ hasIndefiniteAxis = true;
54
+ continue;
55
+ }
56
+ definiteWidth ||= prefix === 'w' || prefix === 'size';
57
+ definiteHeight ||= prefix === 'h' || prefix === 'size';
58
+ }
59
+ if (hasResponsiveSizing)
60
+ return 'unclassified';
61
+ if ((definiteWidth && definiteHeight) || ((definiteWidth || definiteHeight) && hasAspect))
62
+ return 'fit';
63
+ if (definiteWidth || definiteHeight || hasConstraint || hasIndefiniteAxis)
64
+ return 'element-classes';
65
+ return 'unclassified';
66
+ };
67
+ const forEachOpeningTag = (template, tagName, visit) => {
68
+ const pattern = new RegExp(`<${tagName}(?=[\\s/>])[^>]*>`, 'g');
69
+ let match = pattern.exec(template);
70
+ while (match) {
71
+ visit(match[0], match.index);
72
+ match = pattern.exec(template);
73
+ }
74
+ };
75
+ /** The class list an attribute spells out, or `null` when only an expression knows it. */
76
+ const classListOf = (quotedValue, isBound) => {
77
+ const inner = quotedValue.slice(1, -1);
78
+ if (!isBound)
79
+ return inner;
80
+ const literal = /^'([^']*)'$/.exec(inner.trim());
81
+ return literal ? literal[1] : null;
82
+ };
83
+ export const scanTemplate = (report, template, { file, startLine }) => {
84
+ const lineAt = (index) => startLine + lineOfIndex(template, index) - 1;
85
+ forEachOpeningTag(template, PICTURE_TAG, (tag, index) => {
86
+ if (!/(^|\s)\[?alt\]?\s*=/.test(tag)) {
87
+ report.picturesWithoutAlt.push({ file, line: lineAt(index) });
88
+ }
89
+ const attributePattern = new RegExp(`\\s\\[?(${PICTURE_CLASS_INPUTS.join('|')})\\]?\\s*=\\s*("[^"]*"|'[^']*')`, 'g');
90
+ let match = attributePattern.exec(tag);
91
+ while (match) {
92
+ const input = match[1];
93
+ const value = classListOf(match[2], match[0].includes('['));
94
+ report.pictureClassInputs.push({
95
+ file,
96
+ line: lineAt(index),
97
+ input,
98
+ value,
99
+ mode: input === 'imgClass' ? classifyImgClass(value) : 'unclassified',
100
+ });
101
+ match = attributePattern.exec(tag);
102
+ }
103
+ });
104
+ for (const tagName of [SPINNER_TAG, LEGACY_SPINNER_TAG]) {
105
+ forEachOpeningTag(template, tagName, (tag, index) => {
106
+ if (/\s\[mode\]\s*=/.test(tag) && !/\s\[mode\]\s*=\s*(["'])'(in)?determinate'\1/.test(tag)) {
107
+ report.spinnerModeBindings.push({ file, line: lineAt(index) });
108
+ }
109
+ });
110
+ }
111
+ };
112
+ export const scanStyleSheet = (report, styles, { file, startLine }) => {
113
+ const lineAt = (index) => startLine + lineOfIndex(styles, index) - 1;
114
+ const variablePattern = new RegExp(`${LEGACY_SPINNER_COLOR_VARIABLE}(-\\d+)?`, 'g');
115
+ let variableMatch = variablePattern.exec(styles);
116
+ while (variableMatch) {
117
+ report.themedSpinners.push({
118
+ file,
119
+ line: lineAt(variableMatch.index),
120
+ detail: variableMatch[1]
121
+ ? `\`${variableMatch[0]}\` belonged to \`multiColor\`, which has no successor - drop it.`
122
+ : `\`${variableMatch[0]}\` was rewritten to \`--et-spinner-color\`.`,
123
+ });
124
+ variableMatch = variablePattern.exec(styles);
125
+ }
126
+ const blockPattern = /([^{}]+)\{([^{}]*)\}/g;
127
+ let blockMatch = blockPattern.exec(styles);
128
+ while (blockMatch) {
129
+ if (blockMatch[1].includes('.et-legacy') && /(^|[\s;])(--)?[\w-]*color\s*:/.test(blockMatch[2])) {
130
+ const selectorOffset = blockMatch[1].length - blockMatch[1].trimStart().length;
131
+ report.themedSpinners.push({
132
+ file,
133
+ line: lineAt(blockMatch.index + selectorOffset),
134
+ detail: `\`${blockMatch[1].trim().replace(/\s+/g, ' ')}\` colours a legacy-themed element.`,
135
+ });
136
+ }
137
+ blockMatch = blockPattern.exec(styles);
138
+ }
139
+ };
140
+ export const addSymbolSite = (target, symbol, entry, site) => {
141
+ const existing = target.get(symbol);
142
+ if (existing) {
143
+ existing.sites.push(site);
144
+ return;
145
+ }
146
+ target.set(symbol, { entry, sites: [site] });
147
+ };
148
+ const renderSites = (sites) => sites.map((site) => `- \`${site.file}:${site.line}\`${site.detail ? ` - ${site.detail}` : ''}`);
149
+ const renderDocsLink = (entry) => (entry.docs ? ` See ${DOCS_BASE_URL}${entry.docs}.` : '');
150
+ const renderSymbolSection = (symbols, describe) => [...symbols.entries()].flatMap(([symbol, { entry, sites }]) => [
151
+ `### \`${symbol}\``,
152
+ '',
153
+ describe(entry),
154
+ ...(entry.note ? ['', entry.note] : []),
155
+ '',
156
+ ...renderSites(sites),
157
+ '',
158
+ ]);
159
+ const renderPictureClassGroup = (sites, heading, guidance) => {
160
+ if (sites.length === 0)
161
+ return [];
162
+ return [
163
+ `### ${heading}`,
164
+ '',
165
+ ...guidance,
166
+ '',
167
+ ...sites.map((site) => `- \`${site.file}:${site.line}\` - \`${site.input}\`${site.value === null ? ' (bound expression)' : `="${site.value}"`}`),
168
+ '',
169
+ ];
170
+ };
171
+ export const renderReport = (report, context) => {
172
+ const pictureClassSites = report.pictureClassInputs;
173
+ const fitSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'fit');
174
+ const elementClassSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'element-classes');
175
+ const unclassifiedSites = pictureClassSites.filter((site) => site.input === 'imgClass' && site.mode === 'unclassified');
176
+ const wrapperClassSites = pictureClassSites.filter((site) => site.input !== 'imgClass');
177
+ const versionLines = Object.entries(context.installedVersions).map(([packageName, version]) => `- \`${packageName}\`: ${version ?? 'not declared in `package.json` - version-gated rewrites were applied unverified'}`);
178
+ return [
179
+ '# Migrating off @ethlete/cdk: what is left to do',
180
+ '',
181
+ `The generator rewrote the mechanical parts (${context.rewrittenFiles} file(s)). Everything below needs a decision`,
182
+ 'it cannot make. Symbols whose contract changed keep importing from `@ethlete/cdk` on purpose - switch the',
183
+ 'import once the call site matches the successor API.',
184
+ '',
185
+ 'Installed versions the version gate compared against:',
186
+ '',
187
+ ...versionLines,
188
+ '',
189
+ ...(report.picturesWithoutAlt.length > 0
190
+ ? [
191
+ '## `<et-picture>` without `alt`',
192
+ '',
193
+ '`alt` is required on the components picture. Passing `""` is allowed and means the image is decorative -',
194
+ 'a deliberate statement that it carries no information, not a placeholder for text nobody wrote yet. Which',
195
+ 'of the two a site needs is a product decision.',
196
+ '',
197
+ ...renderSites(report.picturesWithoutAlt),
198
+ '',
199
+ ]
200
+ : []),
201
+ ...(report.themedSpinners.length > 0
202
+ ? [
203
+ '## Themed spinners',
204
+ '',
205
+ 'The cdk spinner defaulted to a themed `#1e88e5`; the components spinner defaults to `currentColor`. A',
206
+ 'spinner that should carry a theme colour needs the `color` input (`<et-spinner color="brand" />`); one',
207
+ `inside a button or a link is usually better off inheriting. See ${DOCS_BASE_URL}/components/loader.`,
208
+ '',
209
+ ...renderSites(report.themedSpinners),
210
+ '',
211
+ ]
212
+ : []),
213
+ ...(report.spinnerModeBindings.length > 0
214
+ ? [
215
+ '## Spinner `[mode]` bindings',
216
+ '',
217
+ 'A bound `mode` cannot be rewritten mechanically. `mode` split into the `determinate` boolean, so',
218
+ '`[mode]="expr"` becomes `[determinate]="expr === \'determinate\'"` (or whatever the expression meant).',
219
+ '',
220
+ ...renderSites(report.spinnerModeBindings),
221
+ '',
222
+ ]
223
+ : []),
224
+ ...(pictureClassSites.length > 0
225
+ ? [
226
+ '## Picture class inputs',
227
+ '',
228
+ '`imgClass` / `pictureClass` / `figureClass` / `figcaptionClass` are gone. There are two replacements and',
229
+ 'they are not interchangeable: `fit` needs a definite box in both axes, so using it where the image sizes',
230
+ 'its own box collapses the layout. Each site below is grouped by what its classes actually express.',
231
+ '',
232
+ ...renderPictureClassGroup(fitSites, 'Definite in both axes - use `fit`', [
233
+ 'Move the box classes to the host (`<et-picture class="size-8" fit="cover">`) and let `fit` decide what the',
234
+ 'image does inside that box.',
235
+ ]),
236
+ ...renderPictureClassGroup(elementClassSites, 'Image sizes its own box - style `.et-picture-img`', [
237
+ 'These constrain one axis (`max-h-*`, `w-auto`, a single axis) and let the image resolve the other. `fit`',
238
+ 'cannot express that. Style the element class directly - `[&_.et-picture-img]:max-h-41` - which is',
239
+ 'documented, stable API.',
240
+ ]),
241
+ ...renderPictureClassGroup(unclassifiedSites, 'Unclassified - decide per site', [
242
+ 'The value is a bound expression, responsive, or says nothing about sizing. Either move the classes to the',
243
+ `host and add \`fit\`, or style \`.et-picture-img\` directly. See ${DOCS_BASE_URL}/components/picture.`,
244
+ ]),
245
+ ...renderPictureClassGroup(wrapperClassSites, 'Wrapper classes', [
246
+ 'The `<figure>`, `<picture>` and `<figcaption>` passthroughs have no successor input. Put layout classes on',
247
+ 'the host, or target `.et-picture-figure` / `.et-picture-picture` / `.et-picture-figcaption`.',
248
+ ]),
249
+ ]
250
+ : []),
251
+ ...(report.gatedSymbols.size > 0
252
+ ? [
253
+ '## Successors that need a newer package',
254
+ '',
255
+ 'These imports were left untouched: the successor does not exist in the version this workspace has',
256
+ 'installed. Upgrade, then re-run the generator.',
257
+ '',
258
+ ...renderSymbolSection(report.gatedSymbols, (entry) => {
259
+ const installed = context.installedVersions[entry.package ?? ''] ?? 'unknown';
260
+ return `\`${entry.to}\` requires \`${entry.package}\` ≥ ${entry.since} (installed: ${installed}).${renderDocsLink(entry)}`;
261
+ }),
262
+ ]
263
+ : []),
264
+ ...(report.judgmentSymbols.size > 0
265
+ ? [
266
+ '## Symbols whose contract changed',
267
+ '',
268
+ 'Renaming the import is not enough for these - the successor behaves differently, or several symbols',
269
+ 'replace one.',
270
+ '',
271
+ ...renderSymbolSection(report.judgmentSymbols, (entry) => {
272
+ const successor = entry.kind === 'reshape' ? `stays \`${entry.to}\`` : `becomes \`${entry.to}\``;
273
+ return `${entry.kind}: ${successor} in \`${entry.package}\`.${renderDocsLink(entry)}`;
274
+ }),
275
+ ]
276
+ : []),
277
+ ].join('\n');
278
+ };
279
+ //# sourceMappingURL=report.js.map
@@ -0,0 +1,30 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "migrate-from-cdk",
4
+ "title": "Migrate from @ethlete/cdk to @ethlete/components",
5
+ "type": "object",
6
+ "properties": {
7
+ "projects": {
8
+ "type": "array",
9
+ "items": { "type": "string" },
10
+ "description": "Nx projects to migrate. Defaults to every project in the workspace.",
11
+ "alias": "project"
12
+ },
13
+ "include": {
14
+ "type": "array",
15
+ "items": { "type": "string" },
16
+ "description": "Path prefixes to migrate, relative to the workspace root (e.g. 'apps/shop'). Unioned with `projects`.",
17
+ "alias": "includePath"
18
+ },
19
+ "mapPath": {
20
+ "type": "string",
21
+ "description": "Path to migration-map.json. Defaults to the copy shipped with the installed @ethlete/cdk."
22
+ },
23
+ "skipFormat": {
24
+ "type": "boolean",
25
+ "description": "Skip formatting files after migration",
26
+ "default": false
27
+ }
28
+ },
29
+ "required": []
30
+ }
@@ -0,0 +1,71 @@
1
+ import * as ts from 'typescript';
2
+ import { applyReplacements, createSourceFile } from './imports.js';
3
+ export const lineOfIndex = (content, index) => content.slice(0, index).split('\n').length;
4
+ const stringLikeSpans = (node, sourceFile, spans) => {
5
+ if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {
6
+ const start = node.getStart(sourceFile) + 1;
7
+ const end = node.getEnd() - 1;
8
+ spans.push({ start, end, text: sourceFile.text.slice(start, end) });
9
+ return;
10
+ }
11
+ ts.forEachChild(node, (child) => stringLikeSpans(child, sourceFile, spans));
12
+ };
13
+ const inlineSpansFor = (content, filePath, propertyName) => {
14
+ const sourceFile = createSourceFile(content, filePath);
15
+ const spans = [];
16
+ const visit = (node) => {
17
+ if (ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && node.name.text === propertyName) {
18
+ stringLikeSpans(node.initializer, sourceFile, spans);
19
+ }
20
+ ts.forEachChild(node, visit);
21
+ };
22
+ visit(sourceFile);
23
+ return spans;
24
+ };
25
+ export const findInlineTemplateSpans = (content, filePath) => inlineSpansFor(content, filePath, 'template');
26
+ export const findInlineStyleSpans = (content, filePath) => inlineSpansFor(content, filePath, 'styles');
27
+ export const transformInlineSpans = (content, spans, transform) => {
28
+ const replacements = [];
29
+ for (const span of spans) {
30
+ const next = transform(span.text);
31
+ if (next !== span.text) {
32
+ replacements.push({ start: span.start, end: span.end, replacement: next });
33
+ }
34
+ }
35
+ return applyReplacements(content, replacements);
36
+ };
37
+ /** Every opening tag of `tagName`, passed through `transform`. */
38
+ export const mapOpeningTags = (template, tagName, transform) => template.replace(new RegExp(`<${tagName}(?=[\\s/>])[^>]*>`, 'g'), transform);
39
+ export const PICTURE_TAG = 'et-picture';
40
+ export const SPINNER_TAG = 'et-spinner';
41
+ export const LEGACY_SPINNER_TAG = 'et-progress-spinner';
42
+ export const SKELETON_ITEM_TAG = 'et-skeleton-item';
43
+ const HAS_SHAPE = /(^|\s)\[?shape\]?\s*=/;
44
+ /** `shape` defaults to `text` in components, so the cdk's block behaviour has to be spelled out. */
45
+ const rewriteSkeletonItems = (template) => mapOpeningTags(template, SKELETON_ITEM_TAG, (tag) => HAS_SHAPE.test(tag) ? tag : tag.replace(`<${SKELETON_ITEM_TAG}`, `<${SKELETON_ITEM_TAG} shape="rect"`));
46
+ const rewriteSpinnerTags = (template) => template
47
+ .replace(new RegExp(`<${LEGACY_SPINNER_TAG}(?=[\\s/>])`, 'g'), `<${SPINNER_TAG}`)
48
+ .replace(new RegExp(`</${LEGACY_SPINNER_TAG}\\s*>`, 'g'), `</${SPINNER_TAG}>`);
49
+ const rewriteSpinnerAttributes = (template) => mapOpeningTags(template, SPINNER_TAG, (tag) => tag
50
+ .replace(/\smode\s*=\s*(["'])indeterminate\1/g, '')
51
+ .replace(/\s\[mode\]\s*=\s*(["'])'indeterminate'\1/g, '')
52
+ .replace(/\smode\s*=\s*(["'])determinate\1/g, ' [determinate]="true"')
53
+ .replace(/\s\[mode\]\s*=\s*(["'])'determinate'\1/g, ' [determinate]="true"')
54
+ .replace(/(\s)\[renderBackground\]/g, '$1[track]')
55
+ .replace(/(\s)renderBackground(?=[\s=/>])/g, '$1track')
56
+ .replace(/\s\[?multiColor\]?\s*=\s*("[^"]*"|'[^']*')/g, '')
57
+ .replace(/\smultiColor(?=[\s/>])/g, ''));
58
+ const rewritePictureAttributes = (template) => mapOpeningTags(template, PICTURE_TAG, (tag) => tag
59
+ .replace(/(\s)\[hasPriority\]/g, '$1[priority]')
60
+ .replace(/(\s)hasPriority(?=[\s=/>])/g, '$1priority')
61
+ .replace(/(\s)\(imgLoaded\)/g, '$1(imgLoad)'));
62
+ const rewriteTooltipAttributes = (template) => template
63
+ .replace(/(\s)\[tooltipAriaDescription\]/g, '$1[etTooltipAriaDescription]')
64
+ .replace(/(\s)tooltipAriaDescription(?=[\s=/>])/g, '$1etTooltipAriaDescription');
65
+ export const rewriteTemplate = (template) => {
66
+ const withSpinnerTags = rewriteSpinnerTags(template);
67
+ return rewriteTooltipAttributes(rewritePictureAttributes(rewriteSpinnerAttributes(rewriteSkeletonItems(withSpinnerTags))));
68
+ };
69
+ export const LEGACY_SPINNER_COLOR_VARIABLE = '--et-progress-spinner-color';
70
+ export const rewriteStyleSheet = (styles) => styles.replace(new RegExp(`${LEGACY_SPINNER_COLOR_VARIABLE}(?![\\w-])`, 'g'), '--et-spinner-color');
71
+ //# sourceMappingURL=templates.js.map