@ethlete/core 5.0.0-next.7 → 5.0.0-next.71

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 (54) hide show
  1. package/CHANGELOG.md +849 -0
  2. package/README.md +28 -4
  3. package/design/interactive-styles.ts +5 -0
  4. package/design/theme-css.js +392 -0
  5. package/design/theme-css.ts +547 -0
  6. package/fesm2022/ethlete-core.mjs +9357 -5667
  7. package/fesm2022/ethlete-core.mjs.map +1 -1
  8. package/generators/devtools-about/generator.js +122 -0
  9. package/generators/devtools-about/schema.json +25 -0
  10. package/generators/generators.json +41 -5
  11. package/generators/migrate-color-theme-variants/color-theme-variants.js +136 -0
  12. package/generators/migrate-color-theme-variants/migration.js +46 -0
  13. package/generators/migrate-color-theme-variants/schema.json +26 -0
  14. package/generators/migrate-create-destroy/create-destroy.js +317 -0
  15. package/generators/migrate-create-destroy/migration.js +46 -0
  16. package/generators/migrate-create-destroy/schema.json +26 -0
  17. package/generators/migrate-legacy-color-themes/legacy-color-themes.js +123 -0
  18. package/generators/migrate-legacy-color-themes/migration.js +93 -0
  19. package/generators/migrate-legacy-color-themes/schema.json +26 -0
  20. package/generators/migrate-provider-shape/migration-scope.js +35 -0
  21. package/generators/migrate-provider-shape/migration.js +50 -0
  22. package/generators/migrate-provider-shape/provider-shape.js +284 -0
  23. package/generators/migrate-provider-shape/schema.json +26 -0
  24. package/generators/migrate-surface-interaction-swatch/interaction-swatch.js +63 -0
  25. package/generators/migrate-surface-interaction-swatch/migration.js +36 -0
  26. package/generators/migrate-surface-interaction-swatch/schema.json +26 -0
  27. package/generators/migrate-to-v5/apply-replacements.js +14 -0
  28. package/generators/migrate-to-v5/color-naming.js +124 -0
  29. package/generators/migrate-to-v5/create-provider.js +67 -55
  30. package/generators/migrate-to-v5/migration-files.js +13 -0
  31. package/generators/migrate-to-v5/migration.js +33 -19
  32. package/generators/migrate-to-v5/removed-exports.js +161 -0
  33. package/generators/migrate-to-v5/router-state-service.js +125 -330
  34. package/generators/migrate-to-v5/schema.json +22 -0
  35. package/generators/migrate-to-v5/service-classes.js +108 -0
  36. package/generators/migrate-to-v5/sync-observable-consumers.js +80 -0
  37. package/generators/migrate-to-v5/viewport-service.js +226 -491
  38. package/generators/tailwind-4-color-theme/generator.js +411 -0
  39. package/generators/tailwind-4-color-theme/schema.json +44 -0
  40. package/generators/tailwind-4-surface-theme/generator.js +379 -0
  41. package/generators/tailwind-4-surface-theme/schema.json +48 -0
  42. package/migrations/legacy-color-themes.md +38 -0
  43. package/migrations/seo-directive-removed.md +81 -0
  44. package/migrations/surface-theme-regenerate.md +20 -0
  45. package/migrations.json +59 -0
  46. package/package.json +38 -21
  47. package/src/lib/animations/easing-tokens-styles.component.css +155 -0
  48. package/src/lib/providers/visually-hidden-styles.component.css +13 -0
  49. package/src/lib/resize-handles/resize-handles.component.css +137 -0
  50. package/src/lib/theming/color-interactive-styles.component.css +147 -0
  51. package/src/lib/theming/surface-interactive-styles.component.css +42 -0
  52. package/types/ethlete-core.d.ts +3842 -2205
  53. package/generators/tailwind-4-theme/generator.js +0 -514
  54. package/generators/tailwind-4-theme/schema.json +0 -32
@@ -0,0 +1,50 @@
1
+ import { formatFiles } from '@nx/devkit';
2
+ import { createMigrationScope } from './migration-scope.js';
3
+ import { migrateProviderShapeInFile } from './provider-shape.js';
4
+ export const PROVIDER_SHAPE_REPORT_PATH = 'provider-shape-migration-tasks.md';
5
+ const renderReport = (tasks) => [
6
+ '# Provider-shape migration tasks',
7
+ '',
8
+ 'The codemod rewrote every destructured provider declaration into a definition plus one extractor per',
9
+ 'binding. The sites below are **not** plain module-scope declarations, so they were left alone - each',
10
+ 'needs a decision a codemod cannot make.',
11
+ '',
12
+ 'Recipes:',
13
+ '',
14
+ '- A factory of your own that returned a `[provide, inject, token]` tuple: return the definition from',
15
+ ' `define*Provider(…)` directly, and let its callers use the extractors.',
16
+ '- A call inside a function: read `.provide` / `.inject` / `.token` off the definition.',
17
+ '',
18
+ ...tasks.map((task) => [`## \`${task.id}\``, '', `- ${task.file}:${task.line}`, `- ${task.message}`, ''].join('\n')),
19
+ ].join('\n');
20
+ export default async function migrateProviderShape(tree, schema) {
21
+ console.log('\nšŸ”„ Migrating provider tuples to the definition shape...');
22
+ const scope = createMigrationScope(tree, schema);
23
+ console.log(` Scope: ${scope.describe()}`);
24
+ const tasks = [];
25
+ let filesChanged = 0;
26
+ scope.visit(tree, (filePath) => {
27
+ if (!filePath.endsWith('.ts') || filePath.endsWith('.d.ts'))
28
+ return;
29
+ const before = tree.read(filePath, 'utf-8');
30
+ if (!before)
31
+ return;
32
+ const result = migrateProviderShapeInFile(filePath, before);
33
+ tasks.push(...result.tasks);
34
+ if (result.changed) {
35
+ tree.write(filePath, result.content);
36
+ filesChanged++;
37
+ console.log(` āœ“ ${filePath}`);
38
+ }
39
+ });
40
+ if (tasks.length > 0) {
41
+ tree.write(PROVIDER_SHAPE_REPORT_PATH, renderReport(tasks));
42
+ }
43
+ if (!schema.skipFormat) {
44
+ await formatFiles(tree);
45
+ }
46
+ console.log(`\nāœ… Rewrote ${filesChanged} file(s).`);
47
+ if (tasks.length > 0) {
48
+ console.log(`āš ļø ${tasks.length} site(s) need a manual decision - see ${PROVIDER_SHAPE_REPORT_PATH}.`);
49
+ }
50
+ }
@@ -0,0 +1,284 @@
1
+ import * as ts from 'typescript';
2
+ /**
3
+ * `export const [provideX, injectX] = createRootProvider(…)` is undroppable by construction: array
4
+ * destructuring invokes the iterator protocol, so no bundler will remove the statement, and everything
5
+ * the factory's closure names is retained with it. The definition shape is droppable per binding.
6
+ *
7
+ * Two families need rewriting. The `create*Provider` / `createLabels` helpers were replaced by
8
+ * `define*`, and their declarations take a pure annotation because they sit in library source. The
9
+ * runtime factories below kept their names - only their return shape changed from tuple to definition -
10
+ * and their call sites are application code, where an annotation would be noise.
11
+ */
12
+ const FACTORY_TO_DEFINE = {
13
+ createProvider: 'defineProvider',
14
+ createRootProvider: 'defineRootProvider',
15
+ createStaticProvider: 'defineStaticProvider',
16
+ createStaticRootProvider: 'defineStaticRootProvider',
17
+ createLabels: 'defineLabels',
18
+ };
19
+ const REF_FACTORIES = new Set([
20
+ 'createQueryClient',
21
+ 'createBearerAuthProvider',
22
+ 'createWebSocketClient',
23
+ 'createQueryContext',
24
+ ]);
25
+ const isKnownFactory = (name) => FACTORY_TO_DEFINE[name] !== undefined || REF_FACTORIES.has(name);
26
+ /** Which extractor names the three tuple positions become. */
27
+ const POSITION_TO_EXTRACTOR = ['toProvideFn', 'toInjectFn', 'toToken'];
28
+ const PURE = '/* @__PURE__ */';
29
+ /** `injectFooBar` / `provideFooBar` / `FOO_BAR_TOKEN` → `FOO_BAR`. */
30
+ const toDefinitionBaseName = (bindingName) => {
31
+ const withoutPrefix = bindingName
32
+ .replace(/^ɵ/, '')
33
+ .replace(/^(provide|inject)/i, '')
34
+ .replace(/_TOKEN$/, '');
35
+ const screaming = withoutPrefix
36
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
37
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
38
+ .toUpperCase();
39
+ return screaming.replace(/^_+|_+$/g, '') || 'PROVIDER';
40
+ };
41
+ const uniqueDefinitionName = (bindingNames, taken) => {
42
+ const base = `${toDefinitionBaseName(bindingNames[1] ?? bindingNames[0] ?? bindingNames[2] ?? 'provider')}_DEF`;
43
+ let candidate = base;
44
+ let suffix = 2;
45
+ while (taken.has(candidate)) {
46
+ candidate = `${base}_${suffix++}`;
47
+ }
48
+ taken.add(candidate);
49
+ return candidate;
50
+ };
51
+ const collectImportedFactories = (sourceFile) => {
52
+ const importedFactories = new Map();
53
+ for (const statement of sourceFile.statements) {
54
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
55
+ continue;
56
+ if (!statement.moduleSpecifier.text.startsWith('@ethlete/'))
57
+ continue;
58
+ const bindings = statement.importClause?.namedBindings;
59
+ if (!bindings || !ts.isNamedImports(bindings))
60
+ continue;
61
+ for (const element of bindings.elements) {
62
+ const importedName = element.propertyName?.text ?? element.name.text;
63
+ if (isKnownFactory(importedName))
64
+ importedFactories.set(element.name.text, importedName);
65
+ }
66
+ }
67
+ return importedFactories;
68
+ };
69
+ const findTupleSites = (sourceFile) => {
70
+ const sites = [];
71
+ const importedFactories = collectImportedFactories(sourceFile);
72
+ for (const statement of sourceFile.statements) {
73
+ if (!ts.isVariableStatement(statement) || statement.declarationList.declarations.length !== 1)
74
+ continue;
75
+ const declaration = statement.declarationList.declarations[0];
76
+ if (!declaration || !ts.isArrayBindingPattern(declaration.name))
77
+ continue;
78
+ const call = declaration.initializer;
79
+ if (!call || !ts.isCallExpression(call) || !ts.isIdentifier(call.expression))
80
+ continue;
81
+ const factory = importedFactories.get(call.expression.text);
82
+ if (!factory)
83
+ continue;
84
+ const bindings = declaration.name.elements.map((element) => {
85
+ if (ts.isOmittedExpression(element) || !ts.isIdentifier(element.name))
86
+ return null;
87
+ return element.name.text;
88
+ });
89
+ if (bindings.length > POSITION_TO_EXTRACTOR.length)
90
+ continue;
91
+ sites.push({
92
+ statement,
93
+ call,
94
+ factory,
95
+ bindings,
96
+ isExported: !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword),
97
+ });
98
+ }
99
+ return sites;
100
+ };
101
+ /** The offset the replacement starts at: before the declaration's own JSDoc, if it has one. */
102
+ const declarationStart = (content, statement, sourceFile) => {
103
+ const start = statement.getStart(sourceFile);
104
+ const comments = ts.getLeadingCommentRanges(content, statement.getFullStart());
105
+ const first = comments?.[0];
106
+ // Only treat comments as the declaration's own when nothing but whitespace separates them from it.
107
+ if (!first || /\S/.test(content.slice(comments[comments.length - 1].end, start)))
108
+ return start;
109
+ return first.pos;
110
+ };
111
+ const rewriteSite = (content, sourceFile, site, definitionName) => {
112
+ const start = declarationStart(content, site.statement, sourceFile);
113
+ const statementStart = site.statement.getStart(sourceFile);
114
+ const doc = content.slice(start, statementStart);
115
+ const replacement = FACTORY_TO_DEFINE[site.factory];
116
+ const annotation = replacement ? `${PURE} ` : '';
117
+ const callTail = content.slice(site.call.expression.getEnd(), site.call.getEnd());
118
+ const definition = `const ${definitionName} = ${annotation}${replacement ?? site.factory}${callTail};`;
119
+ const exportKeyword = site.isExported ? 'export ' : '';
120
+ const extractions = site.bindings
121
+ .map((binding, index) => binding === null
122
+ ? null
123
+ : `${exportKeyword}const ${binding} = ${annotation}${POSITION_TO_EXTRACTOR[index]}(${definitionName});`)
124
+ .filter((line) => line !== null);
125
+ // The JSDoc documented the pair, so it belongs on the first binding a consumer can reach.
126
+ const documented = extractions.length > 0 ? [definition, '', doc + extractions[0], ...extractions.slice(1)] : [doc + definition];
127
+ return { start, end: site.statement.getEnd(), text: documented.join('\n') };
128
+ };
129
+ const rewriteImports = (sourceFile, factoriesUsed, extractorsUsed) => {
130
+ const rewrites = [];
131
+ const imports = sourceFile.statements.filter(ts.isImportDeclaration);
132
+ const replacementsUsed = new Set([...factoriesUsed].flatMap((factory) => (FACTORY_TO_DEFINE[factory] ? [FACTORY_TO_DEFINE[factory]] : [])));
133
+ const extractorHost = imports.find((statement) => namedImportsOf(statement, sourceFile)?.some((name) => extractorsUsed.has(name))) ??
134
+ imports.find(isCoreImport);
135
+ for (const statement of imports) {
136
+ const bindings = statement.importClause?.namedBindings;
137
+ if (!bindings || !ts.isNamedImports(bindings))
138
+ continue;
139
+ const elements = bindings.elements.map((element) => ({
140
+ text: element.getText(sourceFile),
141
+ importedName: element.propertyName?.text ?? element.name.text,
142
+ }));
143
+ const replaced = elements.filter((element) => factoriesUsed.has(element.importedName) && FACTORY_TO_DEFINE[element.importedName] !== undefined);
144
+ const additions = statement === extractorHost ? [...replacementsUsed, ...extractorsUsed] : [];
145
+ if (replaced.length === 0 && additions.length === 0)
146
+ continue;
147
+ const kept = elements.filter((element) => !replaced.includes(element)).map((element) => element.text);
148
+ const merged = [...new Set([...kept, ...additions])].sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()));
149
+ rewrites.push({
150
+ start: bindings.getStart(sourceFile),
151
+ end: bindings.getEnd(),
152
+ text: `{ ${merged.join(', ')} }`,
153
+ });
154
+ }
155
+ if (extractorHost)
156
+ return rewrites;
157
+ // Nothing to join - the file only imported a ref factory from another package, so add a core import.
158
+ const anchor = imports[imports.length - 1];
159
+ const position = anchor ? anchor.getEnd() : 0;
160
+ const statement = `import { ${[...replacementsUsed, ...extractorsUsed].sort().join(', ')} } from '@ethlete/core';`;
161
+ rewrites.push({ start: position, end: position, text: anchor ? `\n${statement}` : `${statement}\n` });
162
+ return rewrites;
163
+ };
164
+ const namedImportsOf = (statement, sourceFile) => {
165
+ const bindings = statement.importClause?.namedBindings;
166
+ if (!bindings || !ts.isNamedImports(bindings))
167
+ return undefined;
168
+ return bindings.elements.map((element) => element.getText(sourceFile));
169
+ };
170
+ const isCoreImport = (statement) => ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text === '@ethlete/core';
171
+ /**
172
+ * Rewrites every top-level destructured provider tuple in one file into a descriptor plus one pure
173
+ * extractor per exported binding. Returns the file unchanged when there is nothing to do.
174
+ */
175
+ export const migrateProviderShapeInFile = (filePath, content) => {
176
+ if (![...Object.keys(FACTORY_TO_DEFINE), ...REF_FACTORIES].some((factory) => content.includes(factory))) {
177
+ return { content, changed: false, tasks: [] };
178
+ }
179
+ const sourceFile = ts.createSourceFile(filePath, content, ts.ScriptTarget.Latest, true);
180
+ const sites = findTupleSites(sourceFile);
181
+ const tasks = collectTasks(filePath, sourceFile, sites);
182
+ if (sites.length === 0)
183
+ return { content, changed: false, tasks };
184
+ const taken = collectTopLevelNames(sourceFile);
185
+ const factoriesUsed = new Set(sites.map((site) => site.factory));
186
+ const extractorsUsed = new Set(sites.flatMap((site) => site.bindings.flatMap((binding, index) => (binding === null ? [] : [POSITION_TO_EXTRACTOR[index]]))));
187
+ const edits = [
188
+ ...sites.map((site) => rewriteSite(content, sourceFile, site, uniqueDefinitionName(site.bindings.filter((b) => b !== null), taken))),
189
+ ...rewriteImports(sourceFile, factoriesUsed, extractorsUsed),
190
+ ].sort((a, b) => b.start - a.start);
191
+ let updated = content;
192
+ for (const edit of edits) {
193
+ updated = updated.slice(0, edit.start) + edit.text + updated.slice(edit.end);
194
+ }
195
+ return { content: updated, changed: updated !== content, tasks };
196
+ };
197
+ /** Call sites the codemod cannot safely rewrite - a factory result that is not a plain tuple binding. */
198
+ const collectTasks = (filePath, sourceFile, sites) => {
199
+ const rewritten = new Set(sites.map((site) => site.statement));
200
+ const tasks = [];
201
+ const importedFactories = collectImportedFactories(sourceFile);
202
+ for (const statement of sourceFile.statements) {
203
+ if (!ts.isExportDeclaration(statement))
204
+ continue;
205
+ if (!statement.moduleSpecifier || !ts.isStringLiteral(statement.moduleSpecifier))
206
+ continue;
207
+ if (!statement.moduleSpecifier.text.startsWith('@ethlete/') || !statement.exportClause)
208
+ continue;
209
+ if (!ts.isNamedExports(statement.exportClause))
210
+ continue;
211
+ for (const element of statement.exportClause.elements) {
212
+ const exportedName = element.propertyName?.text ?? element.name.text;
213
+ if (!isKnownFactory(exportedName))
214
+ continue;
215
+ const { line } = sourceFile.getLineAndCharacterOfPosition(element.getStart(sourceFile));
216
+ tasks.push({
217
+ id: `provider-shape:${filePath}:${line + 1}`,
218
+ file: filePath,
219
+ line: line + 1,
220
+ message: `The \`${exportedName}\` re-export must be migrated manually because the replacement API returns a provider definition.`,
221
+ });
222
+ }
223
+ }
224
+ const visit = (node) => {
225
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
226
+ const importedFactory = importedFactories.get(node.expression.text);
227
+ if (!importedFactory || FACTORY_TO_DEFINE[importedFactory] === undefined) {
228
+ ts.forEachChild(node, visit);
229
+ return;
230
+ }
231
+ const statement = enclosingStatement(node);
232
+ if (!statement || !rewritten.has(statement)) {
233
+ const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile));
234
+ const factory = importedFactory;
235
+ const replacement = FACTORY_TO_DEFINE[factory];
236
+ tasks.push({
237
+ id: `provider-shape:${filePath}:${line + 1}`,
238
+ file: filePath,
239
+ line: line + 1,
240
+ message: replacement
241
+ ? `\`${factory}\` is gone. Replace it with \`${replacement}\` and read the halves with \`toProvideFn\` / \`toInjectFn\` / \`toToken\`.`
242
+ : `\`${factory}\` returns a provider definition now, not a \`[provide, inject, token]\` tuple. Read the halves with \`toProvideFn\` / \`toInjectFn\` / \`toToken\`, or \`.provide\` / \`.inject\` / \`.token\` inside a function.`,
243
+ });
244
+ }
245
+ }
246
+ ts.forEachChild(node, visit);
247
+ };
248
+ visit(sourceFile);
249
+ return tasks;
250
+ };
251
+ const collectTopLevelNames = (sourceFile) => {
252
+ const names = new Set();
253
+ for (const statement of sourceFile.statements) {
254
+ if (ts.isImportDeclaration(statement)) {
255
+ const clause = statement.importClause;
256
+ if (clause?.name)
257
+ names.add(clause.name.text);
258
+ const bindings = clause?.namedBindings;
259
+ if (bindings && ts.isNamedImports(bindings))
260
+ bindings.elements.forEach((element) => names.add(element.name.text));
261
+ if (bindings && ts.isNamespaceImport(bindings))
262
+ names.add(bindings.name.text);
263
+ }
264
+ else if (ts.isVariableStatement(statement)) {
265
+ for (const declaration of statement.declarationList.declarations) {
266
+ if (ts.isIdentifier(declaration.name))
267
+ names.add(declaration.name.text);
268
+ }
269
+ }
270
+ else if ((ts.isClassDeclaration(statement) || ts.isFunctionDeclaration(statement)) && statement.name) {
271
+ names.add(statement.name.text);
272
+ }
273
+ }
274
+ return names;
275
+ };
276
+ const enclosingStatement = (node) => {
277
+ let current = node;
278
+ while (current && !ts.isSourceFile(current)) {
279
+ if (ts.isVariableStatement(current))
280
+ return current;
281
+ current = current.parent;
282
+ }
283
+ return undefined;
284
+ };
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "migrate-provider-shape",
4
+ "title": "Migrate provider tuples to the definition shape",
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. Every declaration is rewritten independently, so any scope is safe - use this to keep the diff reviewable.",
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. 'libs/ui'). Unioned with `projects`. Defaults to the whole workspace.",
17
+ "alias": "includePath"
18
+ },
19
+ "skipFormat": {
20
+ "type": "boolean",
21
+ "description": "Skip formatting files after migration",
22
+ "default": false
23
+ }
24
+ },
25
+ "required": []
26
+ }
@@ -0,0 +1,63 @@
1
+ import { Project, SyntaxKind } from 'ts-morph';
2
+ const INTERACTION_KEYS = ['default', 'hover', 'focus', 'active', 'disabled'];
3
+ const createProject = () => new Project({
4
+ useInMemoryFileSystem: true,
5
+ compilerOptions: {
6
+ target: 99,
7
+ module: 99,
8
+ },
9
+ });
10
+ const isFlatInteractionColor = (initializer) => initializer
11
+ .getProperties()
12
+ .some((property) => property.isKind(SyntaxKind.PropertyAssignment) && INTERACTION_KEYS.includes(property.getName()));
13
+ const findFlatInteractionColor = (sourceFile) => {
14
+ for (const property of sourceFile.getDescendantsOfKind(SyntaxKind.PropertyAssignment)) {
15
+ if (property.getName() !== 'interactionColor')
16
+ continue;
17
+ const initializer = property.getInitializer();
18
+ if (initializer?.isKind(SyntaxKind.ObjectLiteralExpression) && isFlatInteractionColor(initializer)) {
19
+ return initializer;
20
+ }
21
+ if (initializer?.isKind(SyntaxKind.Identifier)) {
22
+ const declaration = sourceFile
23
+ .getVariableDeclarations()
24
+ .find((candidate) => candidate.getName() === initializer.getText());
25
+ const referencedInitializer = declaration?.getInitializer();
26
+ if (referencedInitializer?.isKind(SyntaxKind.ObjectLiteralExpression) &&
27
+ isFlatInteractionColor(referencedInitializer)) {
28
+ return referencedInitializer;
29
+ }
30
+ }
31
+ }
32
+ return null;
33
+ };
34
+ /**
35
+ * Rewrites `interactionColor: { default, hover, … }` into `interactionColor: { color: { default, … } }`,
36
+ * the swatch shape that also carries the optional `onColor` and `inkColor` maps.
37
+ */
38
+ export const migrateInteractionSwatchInFile = (filePath, content) => {
39
+ if (!content.includes('interactionColor')) {
40
+ return { changed: false, content };
41
+ }
42
+ const sourceFile = createProject().createSourceFile(filePath, content);
43
+ let changed = false;
44
+ // Re-queried after every rewrite: manipulating the AST forgets the nodes a single up-front
45
+ // collection would have handed us.
46
+ for (let initializer = findFlatInteractionColor(sourceFile); initializer;) {
47
+ initializer.replaceWithText(`{ color: ${initializer.getText()} }`);
48
+ changed = true;
49
+ initializer = findFlatInteractionColor(sourceFile);
50
+ }
51
+ const unresolved = sourceFile
52
+ .getDescendantsOfKind(SyntaxKind.PropertyAssignment)
53
+ .filter((property) => property.getName() === 'interactionColor')
54
+ .flatMap((property) => {
55
+ const initializer = property.getInitializer();
56
+ return initializer && !initializer.isKind(SyntaxKind.ObjectLiteralExpression) ? [initializer.getText()] : [];
57
+ });
58
+ return {
59
+ changed,
60
+ content: changed ? sourceFile.getFullText() : content,
61
+ ...(unresolved.length > 0 ? { unresolved } : {}),
62
+ };
63
+ };
@@ -0,0 +1,36 @@
1
+ import { formatFiles } from '@nx/devkit';
2
+ import { createMigrationScope } from '../migrate-provider-shape/migration-scope.js';
3
+ import { migrateInteractionSwatchInFile } from './interaction-swatch.js';
4
+ export default async function migrateSurfaceInteractionSwatch(tree, schema) {
5
+ console.log('\nšŸ”„ Migrating surface interactionColor to the swatch shape...');
6
+ const scope = createMigrationScope(tree, schema);
7
+ console.log(` Scope: ${scope.describe()}`);
8
+ let filesChanged = 0;
9
+ let unresolvedCount = 0;
10
+ scope.visit(tree, (filePath) => {
11
+ if (!filePath.endsWith('.ts') || filePath.endsWith('.d.ts'))
12
+ return;
13
+ const before = tree.read(filePath, 'utf-8');
14
+ if (!before)
15
+ return;
16
+ const result = migrateInteractionSwatchInFile(filePath, before);
17
+ for (const expression of result.unresolved ?? []) {
18
+ unresolvedCount++;
19
+ console.warn(` ⚠ ${filePath}: could not resolve interactionColor value ${expression}`);
20
+ }
21
+ if (!result.changed)
22
+ return;
23
+ tree.write(filePath, result.content);
24
+ filesChanged++;
25
+ console.log(` āœ“ ${filePath}`);
26
+ });
27
+ console.log(filesChanged === 0
28
+ ? ' Nothing to migrate.\n'
29
+ : `\nāœ… Migrated ${filesChanged} file(s). Regenerate your surface CSS with \`nx g @ethlete/core:tailwind-4-surface-theme\`.\n`);
30
+ if (unresolvedCount > 0) {
31
+ console.warn(` Review ${unresolvedCount} unresolved interactionColor value(s) manually.\n`);
32
+ }
33
+ if (!schema.skipFormat) {
34
+ await formatFiles(tree);
35
+ }
36
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "migrate-surface-interaction-swatch",
4
+ "title": "Migrate surface interactionColor to the swatch shape",
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/web'). Unioned with `projects`. Defaults to the whole workspace.",
17
+ "alias": "includePath"
18
+ },
19
+ "skipFormat": {
20
+ "type": "boolean",
21
+ "description": "Skip formatting files after migration",
22
+ "default": false
23
+ }
24
+ },
25
+ "required": []
26
+ }
@@ -0,0 +1,14 @@
1
+ const IDENTIFIER_CHAR = /[\w$]/;
2
+ export function applyReplacements(content, replacements) {
3
+ return [...replacements]
4
+ .sort(([a], [b]) => b.length - a.length)
5
+ .reduce((result, [original, replacement]) => result.replace(snippetPattern(original), () => replacement), content);
6
+ }
7
+ function snippetPattern(snippet) {
8
+ const start = IDENTIFIER_CHAR.test(snippet.charAt(0)) ? '(?<![\\w$])' : '';
9
+ const end = IDENTIFIER_CHAR.test(snippet.charAt(snippet.length - 1)) ? '(?![\\w$])' : '';
10
+ return new RegExp(`${start}${escapeRegExp(snippet)}${end}`, 'g');
11
+ }
12
+ function escapeRegExp(value) {
13
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
14
+ }
@@ -0,0 +1,124 @@
1
+ import { collectFiles } from './migration-files.js';
2
+ /**
3
+ * Symbol renames in TypeScript files (imports + usage).
4
+ */
5
+ const TS_SYMBOL_RENAMES = {
6
+ ProvideThemeDirective: 'ProvideColorDirective',
7
+ THEME_PROVIDER: 'COLOR_PROVIDER',
8
+ ColorThemedDirective: 'ColorInteractiveDirective',
9
+ ColorThemedStylesComponent: 'ColorInteractiveStylesComponent',
10
+ SurfaceThemedDirective: 'SurfaceInteractiveDirective',
11
+ SurfaceThemedStylesComponent: 'SurfaceInteractiveStylesComponent',
12
+ injectThemesPrefix: 'injectColorThemesPrefix',
13
+ createCssThemeName: 'createCssColorThemeName',
14
+ };
15
+ /**
16
+ * String replacements applied to HTML templates and inline templates.
17
+ */
18
+ const TEMPLATE_REPLACEMENTS = [
19
+ ['[etProvideTheme]', '[etProvideColor]'],
20
+ ['etProvideTheme', 'etProvideColor'],
21
+ ['[etColorThemed]', '[etColorInteractive]'],
22
+ ['etColorThemed', 'etColorInteractive'],
23
+ ['[etSurfaceThemed]', '[etSurfaceInteractive]'],
24
+ ['etSurfaceThemed', 'etSurfaceInteractive'],
25
+ ['et-theme-alt--', 'et-color-alt--'],
26
+ ['et-theme--', 'et-color--'],
27
+ ];
28
+ /**
29
+ * CSS class name replacements.
30
+ */
31
+ const CSS_REPLACEMENTS = [
32
+ ['.et-color-themed', '.et-color-interactive'],
33
+ ['.et-surface-themed', '.et-surface-interactive'],
34
+ ['.et-theme--', '.et-color--'],
35
+ ['.et-theme-alt--', '.et-color-alt--'],
36
+ ];
37
+ /**
38
+ * Host directive input alias replacements in TypeScript files.
39
+ */
40
+ const HOST_DIRECTIVE_REPLACEMENTS = [
41
+ ["'etProvideTheme:theme'", "'etProvideColor:color'"],
42
+ ["'etProvideTheme:color'", "'etProvideColor:color'"],
43
+ ['"etProvideTheme:theme"', '"etProvideColor:color"'],
44
+ ['"etProvideTheme"', '"etProvideColor"'],
45
+ ["'etProvideTheme: theme'", "'etProvideColor: color'"],
46
+ ['"etProvideTheme: theme"', '"etProvideColor: color"'],
47
+ ];
48
+ export default async function migrateColorNaming(tree, scope) {
49
+ let filesModified = 0;
50
+ for (const filePath of collectFiles(tree, scope, ['.ts', '.html', '.css', '.scss'])) {
51
+ const wasModified = filePath.endsWith('.ts')
52
+ ? migrateTypeScriptFile(tree, filePath)
53
+ : filePath.endsWith('.html')
54
+ ? migrateTemplateFile(tree, filePath)
55
+ : migrateCssFile(tree, filePath);
56
+ if (wasModified)
57
+ filesModified++;
58
+ }
59
+ return { filesChanged: filesModified, review: [] };
60
+ }
61
+ function migrateTypeScriptFile(tree, filePath) {
62
+ let content = tree.read(filePath, 'utf-8');
63
+ if (!content)
64
+ return false;
65
+ const original = content;
66
+ if (!/from\s+['"]@ethlete\/(?:core|cdk|theming)['"]/.test(content))
67
+ return false;
68
+ // Rename symbols
69
+ for (const [oldName, newName] of Object.entries(TS_SYMBOL_RENAMES)) {
70
+ content = replaceWholeWord(content, oldName, newName);
71
+ }
72
+ // Rename host directive input aliases
73
+ for (const [oldStr, newStr] of HOST_DIRECTIVE_REPLACEMENTS) {
74
+ content = content.replaceAll(oldStr, newStr);
75
+ }
76
+ // Handle inline templates in TypeScript files
77
+ for (const [oldStr, newStr] of TEMPLATE_REPLACEMENTS) {
78
+ content = content.replaceAll(oldStr, newStr);
79
+ }
80
+ // Handle CSS in TypeScript files
81
+ for (const [oldStr, newStr] of CSS_REPLACEMENTS) {
82
+ content = content.replaceAll(oldStr, newStr);
83
+ }
84
+ if (content !== original) {
85
+ tree.write(filePath, content);
86
+ return true;
87
+ }
88
+ return false;
89
+ }
90
+ function migrateTemplateFile(tree, filePath) {
91
+ let content = tree.read(filePath, 'utf-8');
92
+ if (!content)
93
+ return false;
94
+ const original = content;
95
+ for (const [oldStr, newStr] of TEMPLATE_REPLACEMENTS) {
96
+ content = content.replaceAll(oldStr, newStr);
97
+ }
98
+ if (content !== original) {
99
+ tree.write(filePath, content);
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+ function migrateCssFile(tree, filePath) {
105
+ let content = tree.read(filePath, 'utf-8');
106
+ if (!content)
107
+ return false;
108
+ const original = content;
109
+ for (const [oldStr, newStr] of CSS_REPLACEMENTS) {
110
+ content = content.replaceAll(oldStr, newStr);
111
+ }
112
+ if (content !== original) {
113
+ tree.write(filePath, content);
114
+ return true;
115
+ }
116
+ return false;
117
+ }
118
+ function replaceWholeWord(content, oldWord, newWord) {
119
+ const regex = new RegExp(`\\b${escapeRegex(oldWord)}\\b`, 'g');
120
+ return content.replace(regex, newWord);
121
+ }
122
+ function escapeRegex(str) {
123
+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
124
+ }