@entur/typography 3.0.7 → 3.1.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 (69) hide show
  1. package/README.md +9 -38
  2. package/dist/beta/cjs/components/Heading.cjs +39 -29
  3. package/dist/beta/cjs/components/Heading.cjs.map +1 -1
  4. package/dist/beta/cjs/components/Label.cjs +22 -0
  5. package/dist/beta/cjs/components/Label.cjs.map +1 -0
  6. package/dist/beta/cjs/components/Link.cjs +18 -33
  7. package/dist/beta/cjs/components/Link.cjs.map +1 -1
  8. package/dist/beta/cjs/components/ListItem.cjs +29 -25
  9. package/dist/beta/cjs/components/ListItem.cjs.map +1 -1
  10. package/dist/beta/cjs/components/NumberedList.cjs +34 -24
  11. package/dist/beta/cjs/components/NumberedList.cjs.map +1 -1
  12. package/dist/beta/cjs/components/Text.cjs +40 -28
  13. package/dist/beta/cjs/components/Text.cjs.map +1 -1
  14. package/dist/beta/cjs/components/TextContainer.cjs +26 -0
  15. package/dist/beta/cjs/components/TextContainer.cjs.map +1 -0
  16. package/dist/beta/cjs/components/UnorderedList.cjs +19 -21
  17. package/dist/beta/cjs/components/UnorderedList.cjs.map +1 -1
  18. package/dist/beta/cjs/index.cjs +8 -3
  19. package/dist/beta/cjs/index.cjs.map +1 -1
  20. package/dist/beta/cjs/utils/utils.cjs +73 -41
  21. package/dist/beta/cjs/utils/utils.cjs.map +1 -1
  22. package/dist/beta/cjs/utils/warnAboutGlobalStyles.cjs +113 -0
  23. package/dist/beta/cjs/utils/warnAboutGlobalStyles.cjs.map +1 -0
  24. package/dist/beta/esm/components/Heading.mjs +40 -30
  25. package/dist/beta/esm/components/Heading.mjs.map +1 -1
  26. package/dist/beta/esm/components/Label.mjs +22 -0
  27. package/dist/beta/esm/components/Label.mjs.map +1 -0
  28. package/dist/beta/esm/components/Link.mjs +20 -35
  29. package/dist/beta/esm/components/Link.mjs.map +1 -1
  30. package/dist/beta/esm/components/ListItem.mjs +30 -26
  31. package/dist/beta/esm/components/ListItem.mjs.map +1 -1
  32. package/dist/beta/esm/components/NumberedList.mjs +35 -25
  33. package/dist/beta/esm/components/NumberedList.mjs.map +1 -1
  34. package/dist/beta/esm/components/Text.mjs +41 -29
  35. package/dist/beta/esm/components/Text.mjs.map +1 -1
  36. package/dist/beta/esm/components/TextContainer.mjs +26 -0
  37. package/dist/beta/esm/components/TextContainer.mjs.map +1 -0
  38. package/dist/beta/esm/components/UnorderedList.mjs +20 -22
  39. package/dist/beta/esm/components/UnorderedList.mjs.map +1 -1
  40. package/dist/beta/esm/index.mjs +8 -3
  41. package/dist/beta/esm/index.mjs.map +1 -1
  42. package/dist/beta/esm/utils/utils.mjs +73 -41
  43. package/dist/beta/esm/utils/utils.mjs.map +1 -1
  44. package/dist/beta/esm/utils/warnAboutGlobalStyles.mjs +113 -0
  45. package/dist/beta/esm/utils/warnAboutGlobalStyles.mjs.map +1 -0
  46. package/dist/beta/styles/index.css +878 -609
  47. package/dist/beta/types/components/Heading.d.ts +27 -11
  48. package/dist/beta/types/components/Label.d.ts +22 -0
  49. package/dist/beta/types/components/Link.d.ts +11 -9
  50. package/dist/beta/types/components/ListItem.d.ts +11 -7
  51. package/dist/beta/types/components/NumberedList.d.ts +15 -7
  52. package/dist/beta/types/components/Text.d.ts +33 -13
  53. package/dist/beta/types/components/TextContainer.d.ts +25 -0
  54. package/dist/beta/types/components/UnorderedList.d.ts +11 -7
  55. package/dist/beta/types/index.d.ts +11 -2
  56. package/dist/beta/types/tests/styles.test.d.ts +1 -0
  57. package/dist/beta/types/tests/warnAboutGlobalStyles.test.d.ts +1 -0
  58. package/dist/beta/types/types.d.ts +16 -5
  59. package/dist/beta/types/utils/utils.d.ts +15 -4
  60. package/dist/beta/types/utils/warnAboutGlobalStyles.d.ts +4 -0
  61. package/dist/styles.css +13 -5
  62. package/dist/styles.no-base-tokens.css +822 -0
  63. package/package.json +8 -12
  64. package/dist/beta/cjs/components/Blockquote.cjs +0 -29
  65. package/dist/beta/cjs/components/Blockquote.cjs.map +0 -1
  66. package/dist/beta/esm/components/Blockquote.mjs +0 -29
  67. package/dist/beta/esm/components/Blockquote.mjs.map +0 -1
  68. package/dist/beta/types/components/Blockquote.d.ts +0 -12
  69. package/scripts/migrate-typography.mjs +0 -1462
@@ -1,1462 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * NOTICE: This script is generated using AI with human guidance.
5
- * Typography Migration Script
6
- *
7
- * This script helps you migrate from old typography components to new beta typography.
8
- *
9
- * MIGRATION MODES:
10
- *
11
- * šŸš€ Complete Mode (default):
12
- * - Updates import paths AND component usage
13
- * - Replaces old components with beta components
14
- * - CONSEQUENCES:
15
- * * <Heading1-6> becomes <Heading as="h1-6" variant="title-1|title-2|subtitle-1|subtitle-2|section-1|section-2">
16
- * * <Paragraph> becomes <Text variant="paragraph">
17
- * * <LeadParagraph> becomes <Text variant="leading">
18
- * * <SmallText> becomes <Text variant="subparagraph">
19
- * * <StrongText> becomes <Text as="strong" weight="bold">
20
- * * <SubLabel> becomes <Text variant="sublabel">
21
- * * <SubParagraph> becomes <Text variant="subparagraph">
22
- * * <Label> becomes <Text variant="label"> (or <Text as="label" variant="label"> if htmlFor prop exists)
23
- * * <EmphasizedText> becomes <Text variant="emphasized">
24
- * * <CodeText> becomes <Text variant="code-text">
25
- * * <PreformattedText> becomes <Text variant="preformatted-text">
26
- * * <Link> becomes <Link> (from @entur/typography/beta)
27
- * * <Blockquote> becomes <Blockquote> (from @entur/typography/beta)
28
- * * <BlockquoteFooter> becomes <BlockquoteFooter> (from @entur/typography/beta)
29
- * * <UnorderedList> becomes <UnorderedList> (from @entur/typography/beta)
30
- * * <NumberedList> becomes <NumberedList> (from @entur/typography/beta)
31
- * * <ListItem> becomes <ListItem> (from @entur/typography/beta)
32
- * * Import paths change from @entur/typography to @entur/typography/beta
33
- * * Props may need updates (e.g., margin becomes spacing)
34
- * * Styling classes may change
35
- * * Test thoroughly after migration!
36
- *
37
-
38
- *
39
- * Usage:
40
- * 1. Run this script in your project root
41
- * 2. Choose your migration mode (complete)
42
- * 3. Update your styles as needed
43
- * 4. Test your application thoroughly
44
- *
45
- * Options:
46
- * --dry-run Show what would be changed without modifying files
47
- *
48
- * Environment Variables:
49
- * TYPOGRAPHY_MIGRATION_DIRS Comma-separated list of directories to scan
50
- * Example: "src/**,app/**"
51
- *
52
- * Security Features:
53
- * - Only scans allowed directories (src/**, app/**, etc.)
54
- * - Never scans node_modules, dist, build, .git, etc.
55
- * - Dry-run mode for safe testing
56
- * - Path validation prevents directory traversal attacks
57
- *
58
- */
59
-
60
- import fs from 'fs';
61
- import path from 'path';
62
- import { fileURLToPath } from 'url';
63
-
64
- // Get __dirname equivalent for ES modules
65
- const __filename = fileURLToPath(import.meta.url);
66
- const __dirname = path.dirname(__filename);
67
-
68
- // Try to use glob if available, fallback to Node.js built-ins
69
- let glob;
70
- let useGlob = false;
71
-
72
- // Initialize glob detection
73
- async function initializeGlob() {
74
- try {
75
- const globModule = await import('glob');
76
- glob = globModule.default || globModule;
77
- useGlob = true;
78
- console.log('šŸ“¦ Using glob package for pattern matching');
79
- } catch {
80
- console.log('šŸ“ Using Node.js built-ins for file discovery');
81
- console.log(
82
- ' (Install glob for better pattern matching: npm install glob or yarn add glob)',
83
- );
84
- }
85
- }
86
-
87
- // Configuration
88
- const BETA_IMPORT = '@entur/typography/beta';
89
-
90
- // Enhanced warning detection patterns - only truly problematic patterns
91
- const PROBLEMATIC_PATTERNS = {
92
- // Style conflicts that will cause issues
93
- styleMarginConflict: /style=.*margin=/g,
94
- styleSpacingConflict: /style=.*spacing=/g,
95
-
96
- // Invalid HTML structure
97
- nestedTypography: /<Text[^>]*>.*<Text[^>]*>/g,
98
-
99
- // Accessibility issues
100
- missingAsProps: /<Heading[^>]*>(?!.*\bas=)/g,
101
-
102
- // Semantic HTML mismatches
103
- semanticMismatch: /<Heading[^>]*as="([^"]*)"[^>]*variant="([^"]*)"/g,
104
- };
105
-
106
-
107
- // =============================================================================
108
- // šŸŽÆ MIGRATION FOLDERS CONFIGURATION
109
- // =============================================================================
110
- //
111
- // EDIT THIS SECTION TO CONTROL WHICH FOLDERS ARE SCANNED
112
- //
113
- // ADD FOLDERS: Add new patterns to scan additional directories
114
- // REMOVE FOLDERS: Delete patterns you don't want to scan
115
- // CLEAR ALL: Remove all patterns to scan only what you add
116
- //
117
- // Examples:
118
- // 'src/**' - Scan src folder and all subdirectories
119
- // 'app/**' - Scan app folder and all subdirectories
120
- // 'packages/my-app/**' - Scan specific package
121
- // 'frontend/**' - Scan frontend directory
122
- // 'shared/**' - Scan shared components
123
- // 'components/**' - Scan components folder
124
- //
125
- // =============================================================================
126
-
127
- const MIGRATION_FOLDERS = [
128
- // šŸ‘‡ ADD YOUR FOLDERS HERE šŸ‘‡
129
- 'src/**',
130
- 'app/**',
131
- 'apps/**',
132
- 'components/**',
133
- 'packages/**',
134
- 'pages/**',
135
- 'lib/**',
136
- 'utils/**',
137
- 'styles/**',
138
- 'css/**',
139
- 'scss/**',
140
- // šŸ‘† ADD YOUR FOLDERS ABOVE šŸ‘†
141
- ];
142
-
143
- // =============================================================================
144
-
145
- // Validate and sanitize directory input for security
146
- function validateDirectoryPath(dir) {
147
- return !path.isAbsolute(dir) && !dir.includes('..') && !dir.includes('~');
148
- }
149
-
150
- // Enhanced file analysis for better warning detection - only truly problematic patterns
151
- function analyzeFile(filePath, content) {
152
- const analysis = {
153
- hasStyleConflicts: false,
154
- hasNestedTypography: false,
155
- hasAccessibilityIssues: false,
156
- hasSemanticMismatches: false,
157
- lineNumbers: {},
158
- suggestions: [],
159
- warnings: [],
160
- };
161
-
162
- // Line-by-line analysis for better context
163
- content.split('\n').forEach((line, index) => {
164
- const lineNum = index + 1;
165
-
166
- // Check for style conflicts (style + margin/spacing)
167
- if (
168
- line.match(PROBLEMATIC_PATTERNS.styleMarginConflict) ||
169
- line.match(PROBLEMATIC_PATTERNS.styleSpacingConflict)
170
- ) {
171
- analysis.hasStyleConflicts = true;
172
- analysis.lineNumbers.styleConflicts = (
173
- analysis.lineNumbers.styleConflicts || []
174
- ).concat(lineNum);
175
-
176
- // Generate warning message
177
- analysis.warnings.push(
178
- `Line ${lineNum}: Style conflicts detected - component has both style and margin/spacing props`,
179
- );
180
- }
181
-
182
- // Check for nested typography components (invalid HTML)
183
- if (line.match(PROBLEMATIC_PATTERNS.nestedTypography)) {
184
- analysis.hasNestedTypography = true;
185
- analysis.lineNumbers.nestedTypography = (
186
- analysis.lineNumbers.nestedTypography || []
187
- ).concat(lineNum);
188
-
189
- // Generate warning message
190
- analysis.warnings.push(
191
- `Line ${lineNum}: Nested typography components detected - invalid HTML structure`,
192
- );
193
- }
194
-
195
- // Check for missing as props (accessibility issue)
196
- if (line.match(PROBLEMATIC_PATTERNS.missingAsProps)) {
197
- analysis.hasAccessibilityIssues = true;
198
- analysis.lineNumbers.missingAsProps = (
199
- analysis.lineNumbers.missingAsProps || []
200
- ).concat(lineNum);
201
-
202
- // Generate warning message
203
- analysis.warnings.push(
204
- `Line ${lineNum}: Missing 'as' prop - accessibility issue for Heading component`,
205
- );
206
- }
207
-
208
- // Check for semantic mismatches (e.g., h1 with subtitle variant)
209
- if (line.match(PROBLEMATIC_PATTERNS.semanticMismatch)) {
210
- analysis.hasSemanticMismatches = true;
211
- analysis.lineNumbers.semanticMismatches = (
212
- analysis.lineNumbers.semanticMismatches || []
213
- ).concat(lineNum);
214
-
215
- // Generate warning message
216
- analysis.warnings.push(
217
- `Line ${lineNum}: Semantic mismatch detected - heading level and variant combination may be incorrect`,
218
- );
219
- }
220
- });
221
-
222
- return analysis;
223
- }
224
-
225
-
226
- let ALLOWED_DIRECTORIES = process.env.TYPOGRAPHY_MIGRATION_DIRS
227
- ? process.env.TYPOGRAPHY_MIGRATION_DIRS.split(',')
228
- : MIGRATION_FOLDERS;
229
-
230
- // Filter out potentially dangerous paths
231
- ALLOWED_DIRECTORIES = ALLOWED_DIRECTORIES.filter(validateDirectoryPath);
232
-
233
- if (ALLOWED_DIRECTORIES.length === 0) {
234
- console.error(
235
- 'āŒ Error: No valid migration directories found after security validation.',
236
- );
237
- console.error(
238
- 'All directory paths must be relative and not contain ".." or "~".',
239
- );
240
- console.error('');
241
- console.error('Valid examples:');
242
- console.error(' src/**');
243
- console.error(' app/**');
244
- console.error(' components/**');
245
- console.error('');
246
- console.error('Invalid examples:');
247
- console.error(' /absolute/path');
248
- console.error(' ../parent/directory');
249
- console.error(' ~/home/directory');
250
- process.exit(1);
251
- }
252
-
253
- // Security: Block-list of directories to never scan
254
- const BLOCKED_DIRECTORIES = [
255
- '**/node_modules/**',
256
- '**/dist/**',
257
- '**/build/**',
258
- '**/.git/**',
259
- '**/coverage/**',
260
- '**/.next/**',
261
- '**/.nuxt/**',
262
- '**/public/**',
263
- '**/static/**',
264
- '**/assets/**',
265
- '**/images/**',
266
- '**/fonts/**',
267
- '**/vendor/**',
268
- '**/temp/**',
269
- '**/tmp/**',
270
- ];
271
-
272
- // Component mapping for complete migration
273
- const COMPONENT_MAPPING = {
274
- Heading1: { component: 'Heading', as: 'h1', variant: 'title-1' },
275
- Heading2: { component: 'Heading', as: 'h2', variant: 'title-2' },
276
- Heading3: { component: 'Heading', as: 'h3', variant: 'subtitle-1' },
277
- Heading4: { component: 'Heading', as: 'h4', variant: 'subtitle-2' },
278
- Heading5: { component: 'Heading', as: 'h5', variant: 'section-1' },
279
- Heading6: { component: 'Heading', as: 'h6', variant: 'section-2' },
280
- Paragraph: { component: 'Text', variant: 'paragraph' },
281
- LeadParagraph: { component: 'Text', variant: 'leading' },
282
- SmallText: { component: 'Text', variant: 'subparagraph' },
283
- StrongText: { component: 'Text', as: 'strong', weight: 'bold' },
284
- SubLabel: { component: 'Text', variant: 'sublabel' },
285
- SubParagraph: { component: 'Text', variant: 'subparagraph' },
286
- Label: { component: 'Text', variant: 'label' },
287
- EmphasizedText: { component: 'Text', variant: 'emphasized' },
288
- CodeText: { component: 'Text', variant: 'code-text' },
289
- PreformattedText: { component: 'Text', variant: 'preformatted-text' },
290
- Link: { component: 'Link' }, // Convert Link to beta Link
291
- Blockquote: { component: 'Blockquote' }, // Convert Blockquote to beta Blockquote
292
- BlockquoteFooter: { component: 'BlockquoteFooter' }, // Convert BlockquoteFooter to beta BlockquoteFooter
293
- UnorderedList: { component: 'UnorderedList' },
294
- NumberedList: { component: 'NumberedList' },
295
- ListItem: { component: 'ListItem' },
296
- };
297
-
298
- // Props mapping for migration
299
- const PROPS_MAPPING = {
300
- margin: 'spacing',
301
- };
302
-
303
- // Spacing value mapping from old margin to new spacing
304
- // Based on the actual CSS classes in src/beta/styles.scss
305
- // and the old margin prop values: "top" | "bottom" | "both" | "none"
306
- const SPACING_MAPPING = {
307
- // Old margin values mapped to new spacing values
308
- none: 'none', // No spacing
309
- top: 'md-top', // Top margin only (medium size)
310
- bottom: 'md-bottom', // Bottom margin only (medium size)
311
- both: 'md', // Both top and bottom margins (medium size)
312
-
313
- // Additional spacing values for more granular control
314
- // These weren't in the old margin prop but are available in new spacing
315
- left: 'md-left', // Left margin (medium size)
316
- right: 'md-right', // Right margin (medium size)
317
-
318
- // Size-based spacing (applies to both top and bottom)
319
- xs: 'xs',
320
- sm: 'sm',
321
- md: 'md',
322
- lg: 'lg',
323
- xl: 'xl',
324
-
325
- // Specific directional spacing with sizes
326
- 'xs-top': 'xs-top',
327
- 'xs-bottom': 'xs-bottom',
328
- 'sm-top': 'sm-top',
329
- 'sm-bottom': 'sm-bottom',
330
- 'md-top': 'md-top',
331
- 'md-bottom': 'md-bottom',
332
- 'lg-top': 'lg-top',
333
- 'lg-bottom': 'lg-bottom',
334
- 'xl-top': 'xl-top',
335
- 'xl-bottom': 'xl-bottom',
336
-
337
- // Extra small variants
338
- xs2: 'xs2',
339
- 'xs2-top': 'xs2-top',
340
- 'xs2-bottom': 'xs2-bottom',
341
- };
342
-
343
-
344
- // Parse JSX props more robustly
345
- function parseJSXProps(propsString) {
346
- if (!propsString || !propsString.trim()) {
347
- return { props: {}, warnings: [], spreadProps: [] };
348
- }
349
-
350
- const props = {};
351
- const warnings = [];
352
- const spreadProps = []; // Track spread props separately
353
- const originalSyntax = {}; // Track original JSX syntax for each prop
354
-
355
- try {
356
- // Parse props manually to handle complex cases
357
- let remaining = propsString.trim();
358
-
359
- // First, extract all spread props
360
- const spreadRegex = /\.\.\.\{?(\w+)\}?/g;
361
- let spreadMatch;
362
- while ((spreadMatch = spreadRegex.exec(remaining)) !== null) {
363
- spreadProps.push(spreadMatch[1]);
364
- }
365
-
366
- // Remove spread props from the string to parse regular props
367
- remaining = remaining.replace(/\.\.\.\{?(\w+)\}?/g, '');
368
-
369
- // Now parse regular props
370
- while (remaining.trim().length > 0) {
371
- // Skip whitespace
372
- remaining = remaining.replace(/^\s+/, '');
373
-
374
- // Match prop name
375
- const nameMatch = remaining.match(/^(\w+)=/);
376
- if (!nameMatch) break;
377
-
378
- const propName = nameMatch[1];
379
- const matchLength = nameMatch[0].length;
380
- remaining = remaining.substring(matchLength);
381
-
382
- // Match prop value
383
- if (remaining.startsWith('"') || remaining.startsWith("'")) {
384
- // String value
385
- const quote = remaining[0];
386
- const endQuoteIndex = remaining.indexOf(quote, 1);
387
- if (endQuoteIndex === -1) {
388
- warnings.push(`Unterminated string in prop ${propName}`);
389
- break;
390
- }
391
-
392
- const propValue = remaining.substring(1, endQuoteIndex);
393
- props[propName] = propValue;
394
- originalSyntax[propName] = 'string'; // Mark as string literal
395
- remaining = remaining.substring(endQuoteIndex + 1);
396
- } else if (remaining.startsWith('{')) {
397
- // Object value - find matching closing brace
398
- let braceCount = 0;
399
- let endIndex = -1;
400
-
401
- for (let i = 0; i < remaining.length; i++) {
402
- if (remaining[i] === '{') braceCount++;
403
- if (remaining[i] === '}') {
404
- braceCount--;
405
- if (braceCount === 0) {
406
- endIndex = i;
407
- break;
408
- }
409
- }
410
- }
411
-
412
- if (endIndex === -1) {
413
- warnings.push(`Unterminated object in prop ${propName}`);
414
- break;
415
- }
416
-
417
- const propValue = remaining.substring(1, endIndex);
418
- props[propName] = propValue;
419
- originalSyntax[propName] = 'jsx'; // Mark as JSX expression
420
- remaining = remaining.substring(endIndex + 1);
421
- } else {
422
- // Boolean prop
423
- props[propName] = true;
424
- originalSyntax[propName] = 'boolean'; // Mark as boolean
425
- break;
426
- }
427
-
428
- // Skip whitespace
429
- remaining = remaining.replace(/^\s+/, '');
430
- }
431
- } catch (error) {
432
- warnings.push(`Failed to parse props: ${error.message}`);
433
- }
434
-
435
- return { props, warnings, spreadProps, originalSyntax };
436
- }
437
-
438
- // Migrate props from old to new format
439
- function migrateProps(props, oldComponent) {
440
- const migratedProps = { ...props };
441
- const warnings = [];
442
-
443
- // Handle margin prop migration
444
- if (props.margin) {
445
- const newSpacing = SPACING_MAPPING[props.margin];
446
- if (newSpacing) {
447
- migratedProps.spacing = newSpacing;
448
- delete migratedProps.margin;
449
- warnings.push(
450
- `Migrated 'margin="${props.margin}"' to 'spacing="${newSpacing}"'`,
451
- );
452
- } else {
453
- // Unknown margin value - suggest alternatives
454
- const suggestions = getSpacingSuggestions(props.margin);
455
- migratedProps.spacing = props.margin; // Keep original value for now
456
- delete migratedProps.margin;
457
- warnings.push(
458
- `Migrated 'margin="${props.margin}"' to 'spacing="${props.margin}"' (unknown value). ${suggestions}`,
459
- );
460
- }
461
- }
462
-
463
- // Handle Heading components with existing 'as' prop
464
- if (oldComponent.startsWith('Heading') && props.as) {
465
- const headingNumber = oldComponent.replace('Heading', '');
466
- const expectedAs = `h${headingNumber}`;
467
-
468
- if (props.as !== expectedAs) {
469
- warnings.push(
470
- `Heading component has 'as="${props.as}"' but expected 'as="${expectedAs}"' - review semantic HTML structure`,
471
- );
472
- }
473
- }
474
-
475
- // Handle style prop conflicts
476
- if (props.style && props.margin) {
477
- warnings.push(
478
- `Component has both 'style' and 'margin' props - check for conflicts`,
479
- );
480
- }
481
-
482
- return { props: migratedProps, warnings };
483
- }
484
-
485
- // Helper function to suggest spacing alternatives for unknown margin values
486
- function getSpacingSuggestions(unknownMargin) {
487
- const suggestions = [];
488
-
489
- // Check if it might be one of the old margin values
490
- if (['top', 'bottom', 'both', 'none'].includes(unknownMargin)) {
491
- suggestions.push(
492
- `"${unknownMargin}" is a valid old margin value and will be migrated correctly.`,
493
- );
494
- return suggestions.join(' ');
495
- }
496
-
497
- // Check if it might be a directional value
498
- if (
499
- unknownMargin.includes('top') ||
500
- unknownMargin.includes('bottom') ||
501
- unknownMargin.includes('left') ||
502
- unknownMargin.includes('right')
503
- ) {
504
- suggestions.push(
505
- 'Consider using directional spacing like "md-top", "sm-bottom", etc.',
506
- );
507
- }
508
-
509
- // Check if it might be a size value
510
- if (['xs', 'sm', 'md', 'lg', 'xl'].includes(unknownMargin)) {
511
- suggestions.push(
512
- 'Consider using size-based spacing like "xs", "sm", "md", "lg", "xl".',
513
- );
514
- }
515
-
516
- // Check if it might be a specific variant
517
- if (unknownMargin.includes('xs2')) {
518
- suggestions.push(
519
- 'Consider using "xs2", "xs2-top", or "xs2-bottom" for extra small spacing.',
520
- );
521
- }
522
-
523
- if (suggestions.length === 0) {
524
- suggestions.push(
525
- 'Old margin values: "none", "top", "bottom", "both". New spacing values: "xs", "sm", "md", "lg", "xl", and directional variants.',
526
- );
527
- }
528
-
529
- return suggestions.join(' ');
530
- }
531
-
532
- // Convert props object back to JSX string
533
- function propsToString(props, originalSyntax = {}) {
534
- if (!props || Object.keys(props).length === 0) {
535
- return '';
536
- }
537
-
538
- return (
539
- ' ' +
540
- Object.entries(props)
541
- .map(([key, value]) => {
542
- // Use original syntax information if available
543
- if (originalSyntax[key] === 'string') {
544
- return `${key}="${value}"`;
545
- } else if (originalSyntax[key] === 'jsx') {
546
- // Check if the JSX expression is actually a string literal (e.g., 'a' or "a")
547
- if (
548
- typeof value === 'string' &&
549
- ((value.startsWith("'") &&
550
- value.endsWith("'") &&
551
- value.length > 1) ||
552
- (value.startsWith('"') &&
553
- value.endsWith('"') &&
554
- value.length > 1))
555
- ) {
556
- // It's a string literal in JSX, convert to string prop
557
- const stringValue = value.slice(1, -1); // Remove quotes
558
- return `${key}="${stringValue}"`;
559
- } else {
560
- // It's a real JSX expression, keep as is
561
- return `${key}={${value}}`;
562
- }
563
- } else if (originalSyntax[key] === 'boolean') {
564
- return value ? key : '';
565
- } else {
566
- // Fallback logic for when originalSyntax is not available
567
- if (typeof value === 'string' && !value.includes('{')) {
568
- return `${key}="${value}"`;
569
- } else if (
570
- typeof value === 'string' &&
571
- value.startsWith('{') &&
572
- value.endsWith('}')
573
- ) {
574
- // Already a JSX object, don't add extra braces
575
- return `${key}={${value}}`;
576
- } else {
577
- return `${key}={${value}}`;
578
- }
579
- }
580
- })
581
- .filter(prop => prop.length > 0) // Remove empty props (like false booleans)
582
- .join(' ')
583
- );
584
- }
585
-
586
- // Update imports in content
587
- function updateImports(content) {
588
- let updatedContent = content;
589
- let changes = 0;
590
-
591
- // Handle CSS imports separately - these should stay with the main package
592
- const cssImportPattern = /from\s+['"`]@entur\/typography\/styles['"`]/g;
593
- if (cssImportPattern.test(content)) {
594
- // CSS imports should remain unchanged as they're still in the main package
595
- // No changes needed for CSS imports
596
- }
597
-
598
- // Handle component imports - only migrate if they contain components that need migration
599
- const importRegex =
600
- /import\s*{([^}]+)}\s*from\s*['"']@entur\/typography['"']/g;
601
-
602
- updatedContent = updatedContent.replace(importRegex, (match, importList) => {
603
- const components = importList
604
- .split(',')
605
- .map(comp => comp.trim())
606
- .filter(comp => comp);
607
-
608
- // Check if any of the imported components need migration
609
- // Need to check both the full import (e.g., "Link as Li") and just the component name (e.g., "Link")
610
- const needsMigration = components.some(comp => {
611
- // Extract the actual component name from aliased imports
612
- const componentName = comp.includes(' as ')
613
- ? comp.split(' as ')[0].trim()
614
- : comp;
615
- return Object.keys(COMPONENT_MAPPING).includes(componentName);
616
- });
617
-
618
- if (!needsMigration) {
619
- // No migration needed, keep the import as is
620
- return match;
621
- }
622
-
623
- let updatedImportList = importList;
624
- let hasChanges = false;
625
- const uniqueComponents = new Set();
626
- const processedComponents = new Set(); // Track which components we've already processed
627
-
628
- // First, collect all existing components that should be preserved
629
- const existingComponents = components.filter(comp => {
630
- // Extract the actual component name from aliased imports
631
- const componentName = comp.includes(' as ')
632
- ? comp.split(' as ')[0].trim()
633
- : comp;
634
-
635
- // Keep components that are:
636
- // 1. Not in the migration mapping (old components), OR
637
- // 2. Are the target components (new beta components)
638
- const isOldComponent =
639
- Object.keys(COMPONENT_MAPPING).includes(componentName);
640
- const isTargetComponent = Object.values(COMPONENT_MAPPING).some(
641
- mapping => mapping.component === componentName,
642
- );
643
-
644
- return !isOldComponent || isTargetComponent;
645
- });
646
-
647
- // Then, update components that need migration
648
- Object.entries(COMPONENT_MAPPING).forEach(([oldComponent, mapping]) => {
649
- // Check if this old component exists in any form (aliased or not)
650
- const hasComponent = components.some(comp => {
651
- const componentName = comp.includes(' as ')
652
- ? comp.split(' as ')[0].trim()
653
- : comp;
654
- return componentName === oldComponent;
655
- });
656
-
657
- if (hasComponent && !processedComponents.has(oldComponent)) {
658
- // Replace the old component with the new one, preserving aliases
659
- const componentRegex = new RegExp(`\\b${oldComponent}\\b`, 'g');
660
- if (componentRegex.test(updatedImportList)) {
661
- updatedImportList = updatedImportList.replace(
662
- componentRegex,
663
- mapping.component,
664
- );
665
-
666
- // Only add to uniqueComponents if the component isn't already present in aliased form
667
- const componentAlreadyPresent = components.some(comp => {
668
- const componentName = comp.includes(' as ')
669
- ? comp.split(' as ')[0].trim()
670
- : comp;
671
- return componentName === mapping.component;
672
- });
673
-
674
- if (!componentAlreadyPresent) {
675
- uniqueComponents.add(mapping.component);
676
- }
677
-
678
- processedComponents.add(oldComponent);
679
- hasChanges = true;
680
- }
681
- }
682
- });
683
-
684
- if (hasChanges) {
685
- changes++;
686
- // Combine existing components with migrated components
687
- const allComponents = [
688
- ...existingComponents,
689
- ...Array.from(uniqueComponents),
690
- ];
691
-
692
- // Filter out any empty components and deduplicate
693
- const finalComponents = allComponents
694
- .filter(comp => comp && comp.trim())
695
- .filter((comp, index, arr) => arr.indexOf(comp) === index); // Remove duplicates
696
-
697
- const finalImportList = finalComponents.join(', ');
698
- return `import {${finalImportList}} from '${BETA_IMPORT}'`;
699
- }
700
-
701
- return match;
702
- });
703
-
704
- return { content: updatedContent, changes };
705
- }
706
-
707
- // Update component usage with better prop handling
708
- function updateComponents(content) {
709
- let updatedContent = content;
710
- let changes = 0;
711
- let warnings = [];
712
-
713
- Object.entries(COMPONENT_MAPPING).forEach(([oldComponent, mapping]) => {
714
- // More robust regex to handle complex JSX including self-closing tags
715
- const componentRegex = new RegExp(
716
- `<${oldComponent}(\\s+[^>]*?)?(?:/>|>)`,
717
- 'g',
718
- );
719
-
720
- updatedContent = updatedContent.replace(
721
- componentRegex,
722
- (match, propsString) => {
723
- changes++;
724
-
725
- // Check if this is a self-closing tag
726
- const isSelfClosing = match.endsWith('/>');
727
-
728
- // Parse existing props
729
- const {
730
- props: existingProps,
731
- warnings: parseWarnings,
732
- spreadProps,
733
- originalSyntax,
734
- } = parseJSXProps(propsString);
735
- warnings.push(...parseWarnings);
736
-
737
- // Migrate props
738
- const { props: migratedProps, warnings: migrateWarnings } =
739
- migrateProps(existingProps, oldComponent);
740
- warnings.push(...migrateWarnings);
741
-
742
- // Build new props from mapping
743
- const newProps = { ...migratedProps };
744
-
745
- // Add mapping props (but don't override existing ones)
746
- Object.entries(mapping).forEach(([key, value]) => {
747
- if (key !== 'component' && !newProps[key]) {
748
- newProps[key] = value;
749
- }
750
- });
751
-
752
- // Handle Heading components
753
- if (mapping.component === 'Heading') {
754
- // Preserve existing 'as' prop if it exists, otherwise use mapping default
755
- const asValue = existingProps.as || mapping.as;
756
- // Preserve existing 'variant' prop if it exists, otherwise use mapping default
757
- const variantValue = existingProps.variant || mapping.variant;
758
-
759
- // Remove as and variant from props since we'll add them separately
760
- delete newProps.as;
761
- delete newProps.variant;
762
-
763
- // Create props object with as and variant, preserving original syntax
764
- const headingProps = {
765
- as: asValue,
766
- variant: variantValue,
767
- ...newProps,
768
- };
769
-
770
- // Create original syntax object for as and variant
771
- const headingOriginalSyntax = {
772
- as: originalSyntax.as || 'string',
773
- variant: originalSyntax.variant || 'string',
774
- ...originalSyntax,
775
- };
776
-
777
- const propsString = propsToString(
778
- headingProps,
779
- headingOriginalSyntax,
780
- );
781
- const spreadPropsString =
782
- spreadProps.length > 0 ? ` {...${spreadProps.join(', ...')}}` : '';
783
- const closingTag = isSelfClosing ? '/>' : '>';
784
- return `<Heading${propsString}${spreadPropsString}${closingTag}`;
785
- }
786
-
787
- // Handle Label components with special case for htmlFor prop
788
- if (oldComponent === 'Label' && mapping.component === 'Text') {
789
- // If htmlFor prop exists, add as="label" to ensure proper semantic HTML
790
- // Otherwise, use existing as prop or default to undefined (no as prop)
791
- const asValue = existingProps.htmlFor
792
- ? 'label'
793
- : existingProps.as || undefined;
794
- const variantValue = existingProps.variant || mapping.variant;
795
-
796
- // Remove as and variant from props since we'll add them separately
797
- delete newProps.as;
798
- delete newProps.variant;
799
-
800
- // Ensure mapping props come first
801
- const orderedProps = {};
802
- if (newProps.spacing) {
803
- orderedProps.spacing = newProps.spacing;
804
- delete newProps.spacing;
805
- }
806
- Object.assign(orderedProps, newProps);
807
-
808
- const propsString = propsToString(orderedProps, originalSyntax);
809
- const spreadPropsString =
810
- spreadProps.length > 0 ? ` {...${spreadProps.join(', ...')}}` : '';
811
-
812
- // Only add as prop if it has a value
813
- const asProp = asValue ? ` as="${asValue}"` : '';
814
- const closingTag = isSelfClosing ? '/>' : '>';
815
- return `<Text${asProp} variant="${variantValue}"${propsString}${spreadPropsString}${closingTag}`;
816
- }
817
-
818
- // Handle other components
819
- const componentName = mapping.component;
820
-
821
- // Remove mapping props from newProps since they're already set
822
- Object.keys(mapping).forEach(key => {
823
- if (key !== 'component') {
824
- delete newProps[key];
825
- }
826
- });
827
-
828
- // Add mapping props in the correct order
829
- const finalProps = {};
830
- Object.entries(mapping).forEach(([key, value]) => {
831
- if (key !== 'component') {
832
- finalProps[key] = value;
833
- }
834
- });
835
- Object.assign(finalProps, newProps);
836
-
837
- const otherPropsString = propsToString(finalProps, originalSyntax);
838
- const spreadPropsString =
839
- spreadProps.length > 0 ? ` {...${spreadProps.join(', ...')}}` : '';
840
- const closingTag = isSelfClosing ? '/>' : '>';
841
- return `<${componentName}${otherPropsString}${spreadPropsString}${closingTag}`;
842
- },
843
- );
844
-
845
- // Update closing tags (only for non-self-closing tags)
846
- const closingTagRegex = new RegExp(`</${oldComponent}>`, 'g');
847
- const componentName = mapping.component;
848
- updatedContent = updatedContent.replace(
849
- closingTagRegex,
850
- `</${componentName}>`,
851
- );
852
- });
853
-
854
- return { content: updatedContent, changes, warnings };
855
- }
856
-
857
- /**
858
- * Find files matching the given pattern in allowed directories
859
- *
860
- * Uses glob if available for better pattern matching, falls back to Node.js built-ins
861
- *
862
- * @param {string} pattern - File pattern to match (e.g., '*.{ts,tsx,js,jsx}')
863
- * @returns {string[]} Array of matching file paths
864
- */
865
- function findFiles(pattern) {
866
- if (useGlob) {
867
- return findFilesWithGlob(pattern);
868
- } else {
869
- return findFilesWithNode(pattern);
870
- }
871
- }
872
-
873
- /**
874
- * Find files using glob package (preferred method)
875
- */
876
- function findFilesWithGlob(pattern) {
877
- const allFiles = [];
878
-
879
- // Process directory patterns
880
- const directoryPatterns = ALLOWED_DIRECTORIES.filter(dir =>
881
- dir.includes('**'),
882
- );
883
- const filePatterns = ALLOWED_DIRECTORIES.filter(dir => !dir.includes('**'));
884
-
885
- // Handle directory patterns (e.g., src/**, app/**)
886
- if (directoryPatterns.length > 0) {
887
- const combinedDirPattern = `{${directoryPatterns.join(',')}}/${pattern}`;
888
- const dirFiles = glob.sync(combinedDirPattern, {
889
- ignore: BLOCKED_DIRECTORIES,
890
- nodir: true,
891
- absolute: false,
892
- });
893
- allFiles.push(...dirFiles);
894
- }
895
-
896
- // Handle file patterns (e.g., *.jsx, *.tsx)
897
- filePatterns.forEach(filePattern => {
898
- const files = glob.sync(filePattern, {
899
- ignore: BLOCKED_DIRECTORIES,
900
- nodir: true,
901
- absolute: false,
902
- });
903
- allFiles.push(...files);
904
- });
905
-
906
- // Use Set for efficient deduplication and filtering
907
- const fileExtensions = new Set([
908
- '.ts',
909
- '.tsx',
910
- '.js',
911
- '.jsx',
912
- '.scss',
913
- '.css',
914
- ]);
915
-
916
- const uniqueFiles = allFiles.filter(file => {
917
- const ext = path.extname(file).toLowerCase();
918
- return fileExtensions.has(ext);
919
- });
920
-
921
- return uniqueFiles;
922
- }
923
-
924
- /**
925
- * Find files using Node.js built-ins (fallback method)
926
- */
927
- function findFilesWithNode(pattern) {
928
- const allFiles = [];
929
-
930
- // Parse the pattern to extract extensions
931
- const extensions = pattern.match(/\*\.\{([^}]+)\}/);
932
- const fileExtensions = extensions
933
- ? extensions[1].split(',').map(ext => `.${ext.trim()}`)
934
- : ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css'];
935
-
936
- const extensionSet = new Set(fileExtensions);
937
-
938
- // Helper function to check if a path should be ignored
939
- function shouldIgnore(filePath) {
940
- return BLOCKED_DIRECTORIES.some(blockedPattern => {
941
- // Simple pattern matching for common blocked directories
942
- if (blockedPattern.includes('**')) {
943
- const basePattern = blockedPattern.replace('/**', '');
944
- return filePath.includes(basePattern);
945
- }
946
- return filePath.includes(blockedPattern);
947
- });
948
- }
949
-
950
- // Helper function to recursively find files
951
- function findFilesRecursive(dir, relativePath = '') {
952
- try {
953
- const items = fs.readdirSync(dir, { withFileTypes: true });
954
-
955
- for (const item of items) {
956
- const itemPath = path.join(dir, item.name);
957
- const relativeItemPath = path.join(relativePath, item.name);
958
-
959
- // Skip if this path should be ignored
960
- if (shouldIgnore(relativeItemPath)) {
961
- continue;
962
- }
963
-
964
- if (item.isDirectory()) {
965
- // Recursively search subdirectories
966
- findFilesRecursive(itemPath, relativeItemPath);
967
- } else if (item.isFile()) {
968
- // Check if file has matching extension
969
- const ext = path.extname(item.name).toLowerCase();
970
- if (extensionSet.has(ext)) {
971
- allFiles.push(relativeItemPath);
972
- }
973
- }
974
- }
975
- } catch (error) {
976
- // Skip directories that can't be read (permissions, etc.)
977
- console.warn(
978
- `Warning: Could not read directory ${dir}: ${error.message}`,
979
- );
980
- }
981
- }
982
-
983
- // Process each allowed directory
984
- for (const allowedDir of ALLOWED_DIRECTORIES) {
985
- if (allowedDir.includes('**')) {
986
- // Directory pattern (e.g., src/**)
987
- const baseDir = allowedDir.replace('/**', '');
988
- const fullPath = path.resolve(baseDir);
989
-
990
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isDirectory()) {
991
- findFilesRecursive(fullPath, baseDir);
992
- }
993
- } else {
994
- // File pattern (e.g., *.jsx) - not supported in this implementation
995
- // as it would require more complex pattern matching
996
- console.warn(
997
- `Warning: File pattern "${allowedDir}" not supported in Node.js-only mode. Use directory patterns like "src/**" instead.`,
998
- );
999
- }
1000
- }
1001
-
1002
- // Remove duplicates and return
1003
- return [...new Set(allFiles)];
1004
- }
1005
-
1006
- function updateImportsAndComponents(content) {
1007
- let updatedContent = content;
1008
- let changes = 0;
1009
- let warnings = [];
1010
-
1011
- // Update both imports and components
1012
- const { content: newContent, changes: importChanges } =
1013
- updateImports(content);
1014
- const {
1015
- content: finalContent,
1016
- changes: componentChanges,
1017
- warnings: componentWarnings,
1018
- } = updateComponents(newContent);
1019
- updatedContent = finalContent;
1020
- changes = importChanges + componentChanges;
1021
- warnings = componentWarnings;
1022
-
1023
- return { content: updatedContent, changes, warnings };
1024
- }
1025
-
1026
- function generateMigrationReport(files, isDryRun = false) {
1027
- const report = {
1028
- strategy: 'complete',
1029
- totalFiles: files.length,
1030
- migratedFiles: 0,
1031
- totalChanges: 0,
1032
- totalWarnings: 0,
1033
- files: [],
1034
- warnings: [],
1035
- isDryRun,
1036
- };
1037
-
1038
- files.forEach(file => {
1039
- try {
1040
- const content = fs.readFileSync(file, 'utf8');
1041
-
1042
- // Analyze file for problematic patterns BEFORE migration
1043
- const fileAnalysis = analyzeFile(file, content);
1044
-
1045
- const {
1046
- content: updatedContent,
1047
- changes,
1048
- warnings,
1049
- } = updateImportsAndComponents(content);
1050
-
1051
- // Combine migration warnings with file analysis warnings
1052
- const allWarnings = [...warnings, ...fileAnalysis.warnings];
1053
-
1054
- if (changes > 0 || fileAnalysis.warnings.length > 0) {
1055
- if (!isDryRun) {
1056
- fs.writeFileSync(file, updatedContent, 'utf8');
1057
- }
1058
- if (changes > 0) {
1059
- report.migratedFiles++;
1060
- report.totalChanges += changes;
1061
- }
1062
- report.totalWarnings += allWarnings.length;
1063
- report.files.push({ file, changes, warnings: allWarnings });
1064
- report.warnings.push(
1065
- ...allWarnings.map(warning => `${file}: ${warning}`),
1066
- );
1067
- }
1068
- } catch (error) {
1069
- report.warnings.push(`${file}: Error processing file - ${error.message}`);
1070
- }
1071
- });
1072
-
1073
- return report;
1074
- }
1075
-
1076
- function printReport(report) {
1077
- console.log('\nšŸŽ‰ Migration Report');
1078
- console.log('==================');
1079
- console.log(`Strategy: ${report.strategy}`);
1080
- console.log(`Total files scanned: ${report.totalFiles}`);
1081
- console.log(`Files migrated: ${report.migratedFiles}`);
1082
- console.log(`Total changes: ${report.totalChanges}`);
1083
- console.log(`Total warnings: ${report.totalWarnings}`);
1084
-
1085
- if (report.files.length > 0) {
1086
- console.log('\nMigrated files:');
1087
- report.files.forEach(({ file, changes, warnings }) => {
1088
- console.log(
1089
- ` āœ… ${file} (${changes} changes${
1090
- warnings.length > 0 ? `, ${warnings.length} warnings` : ''
1091
- })`,
1092
- );
1093
- });
1094
- }
1095
-
1096
- if (report.warnings.length > 0) {
1097
- console.log('\nāš ļø Warnings:');
1098
-
1099
- // Group warnings by type
1100
- const marginWarnings = report.warnings.filter(w => w.includes('Migrated'));
1101
- const semanticWarnings = report.warnings.filter(w =>
1102
- w.includes('expected'),
1103
- );
1104
- const conflictWarnings = report.warnings.filter(w =>
1105
- w.includes('check for conflicts'),
1106
- );
1107
-
1108
- // New warning types from file analysis
1109
- const styleConflictWarnings = report.warnings.filter(
1110
- w => w.includes('style conflicts') || w.includes('style and margin'),
1111
- );
1112
- const nestedTypographyWarnings = report.warnings.filter(w =>
1113
- w.includes('nested typography'),
1114
- );
1115
- const accessibilityWarnings = report.warnings.filter(
1116
- w => w.includes('missing as prop') || w.includes('accessibility'),
1117
- );
1118
- const semanticMismatchWarnings = report.warnings.filter(w =>
1119
- w.includes('semantic mismatch'),
1120
- );
1121
-
1122
- if (marginWarnings.length > 0) {
1123
- console.log(
1124
- `\n šŸ”„ Margin → Spacing Migrations (${marginWarnings.length}):`,
1125
- );
1126
- // Show first 5 warnings, then summarize the rest
1127
- marginWarnings
1128
- .slice(0, 5)
1129
- .forEach(warning => console.log(` ${warning}`));
1130
- if (marginWarnings.length > 5) {
1131
- console.log(
1132
- ` ... and ${marginWarnings.length - 5} more similar warnings`,
1133
- );
1134
- }
1135
- }
1136
-
1137
- if (semanticWarnings.length > 0) {
1138
- console.log(`\n šŸŽÆ Semantic HTML Issues (${semanticWarnings.length}):`);
1139
- // Show first 5 warnings, then summarize the rest
1140
- semanticWarnings
1141
- .slice(0, 5)
1142
- .forEach(warning => console.log(` ${warning}`));
1143
- if (semanticWarnings.length > 5) {
1144
- console.log(
1145
- ` ... and ${semanticWarnings.length - 5} more similar warnings`,
1146
- );
1147
- }
1148
- }
1149
-
1150
- if (conflictWarnings.length > 0) {
1151
- console.log(`\n 🚨 Style Conflicts (${conflictWarnings.length}):`);
1152
- // Show first 5 warnings, then summarize the rest
1153
- conflictWarnings
1154
- .slice(0, 5)
1155
- .forEach(warning => console.log(` ${warning}`));
1156
- if (conflictWarnings.length > 5) {
1157
- console.log(
1158
- ` ... and ${conflictWarnings.length - 5} more similar warnings`,
1159
- );
1160
- }
1161
- console.log(` → Review these components for styling conflicts`);
1162
- }
1163
-
1164
- // Display new warning types
1165
- if (styleConflictWarnings.length > 0) {
1166
- console.log(
1167
- `\n šŸŽØ Style + Margin Conflicts (${styleConflictWarnings.length}):`,
1168
- );
1169
- styleConflictWarnings
1170
- .slice(0, 5)
1171
- .forEach(warning => console.log(` ${warning}`));
1172
- if (styleConflictWarnings.length > 5) {
1173
- console.log(
1174
- ` ... and ${
1175
- styleConflictWarnings.length - 5
1176
- } more similar warnings`,
1177
- );
1178
- }
1179
- console.log(` → Remove margin prop when using inline styles`);
1180
- }
1181
-
1182
- if (nestedTypographyWarnings.length > 0) {
1183
- console.log(
1184
- `\n 🚫 Nested Typography (${nestedTypographyWarnings.length}):`,
1185
- );
1186
- nestedTypographyWarnings
1187
- .slice(0, 5)
1188
- .forEach(warning => console.log(` ${warning}`));
1189
- if (nestedTypographyWarnings.length > 5) {
1190
- console.log(
1191
- ` ... and ${
1192
- nestedTypographyWarnings.length - 5
1193
- } more similar warnings`,
1194
- );
1195
- }
1196
- console.log(
1197
- ` → Use spans or other inline elements instead of nested Text components`,
1198
- );
1199
- }
1200
-
1201
- if (accessibilityWarnings.length > 0) {
1202
- console.log(
1203
- `\n ♿ Accessibility Issues (${accessibilityWarnings.length}):`,
1204
- );
1205
- accessibilityWarnings
1206
- .slice(0, 5)
1207
- .forEach(warning => console.log(` ${warning}`));
1208
- if (accessibilityWarnings.length > 5) {
1209
- console.log(
1210
- ` ... and ${
1211
- accessibilityWarnings.length - 5
1212
- } more similar warnings`,
1213
- );
1214
- }
1215
- console.log(
1216
- ` → Add 'as' prop to Heading components for proper semantic HTML`,
1217
- );
1218
- }
1219
-
1220
- if (semanticMismatchWarnings.length > 0) {
1221
- console.log(
1222
- `\n šŸ” Semantic Mismatches (${semanticMismatchWarnings.length}):`,
1223
- );
1224
- semanticMismatchWarnings
1225
- .slice(0, 5)
1226
- .forEach(warning => console.log(` ${warning}`));
1227
- if (semanticMismatchWarnings.length > 5) {
1228
- console.log(
1229
- ` ... and ${
1230
- semanticMismatchWarnings.length - 5
1231
- } more similar warnings`,
1232
- );
1233
- }
1234
- console.log(` → Review heading level and variant combinations`);
1235
- }
1236
-
1237
- console.log('\nšŸ“‹ Summary:');
1238
- if (marginWarnings.length > 0)
1239
- console.log(
1240
- ` • ${marginWarnings.length} margin props migrated to spacing`,
1241
- );
1242
- if (semanticWarnings.length > 0)
1243
- console.log(
1244
- ` • ${semanticWarnings.length} semantic HTML issues need review`,
1245
- );
1246
- if (conflictWarnings.length > 0)
1247
- console.log(
1248
- ` • ${conflictWarnings.length} style conflicts need manual review`,
1249
- );
1250
- if (styleConflictWarnings.length > 0)
1251
- console.log(
1252
- ` • ${styleConflictWarnings.length} style + margin conflicts detected`,
1253
- );
1254
- if (nestedTypographyWarnings.length > 0)
1255
- console.log(
1256
- ` • ${nestedTypographyWarnings.length} nested typography components found`,
1257
- );
1258
- if (accessibilityWarnings.length > 0)
1259
- console.log(
1260
- ` • ${accessibilityWarnings.length} accessibility issues need attention`,
1261
- );
1262
- if (semanticMismatchWarnings.length > 0)
1263
- console.log(
1264
- ` • ${semanticMismatchWarnings.length} semantic mismatches detected`,
1265
- );
1266
-
1267
- // Add helpful note about warning limits
1268
- if (report.warnings.length > 15) {
1269
- console.log(
1270
- '\nšŸ’” Note: Only showing first 5 warnings of each type to avoid overwhelming output.',
1271
- );
1272
- console.log(
1273
- ' All warnings are still logged in the migration report above.',
1274
- );
1275
- }
1276
- }
1277
- }
1278
-
1279
- function showNextSteps() {
1280
- console.log('\nšŸ“ Next Steps');
1281
- console.log('=============');
1282
-
1283
- console.log('1. 🧪 Test your application thoroughly');
1284
- console.log('2. šŸ”„ Review and adjust any component props if needed');
1285
- console.log('3. šŸ“š Read the migration guide on our website');
1286
-
1287
- console.log('\nāš ļø Important Notes:');
1288
- console.log('- Check warnings above for potential issues');
1289
- console.log('- Review migrated components for prop conflicts');
1290
- console.log('- Test thoroughly, especially components with custom styling');
1291
- }
1292
-
1293
- async function main() {
1294
- // Initialize glob detection
1295
- await initializeGlob();
1296
-
1297
- // Show help if requested
1298
- if (process.argv.includes('--help') || process.argv.includes('-h')) {
1299
- console.log('šŸŽØ Typography Migration Script');
1300
- console.log('==============================');
1301
- console.log('');
1302
- console.log('Usage:');
1303
- console.log(' # From npm package (recommended)');
1304
- console.log(' npx @entur/typography@latest migrate [options]');
1305
- console.log(' yarn dlx @entur/typography@latest migrate [options]');
1306
- console.log('');
1307
- console.log(' # Direct execution (uses Node.js built-ins, glob optional)');
1308
- console.log(' node scripts/migrate-typography.js [options]');
1309
- console.log('');
1310
- console.log(' # Local development');
1311
- console.log(' npm run migrate');
1312
- console.log('');
1313
- console.log('Options:');
1314
- console.log(
1315
- ' --dry-run Show what would be changed without modifying files',
1316
- );
1317
- console.log(' --help, -h Show this help message');
1318
- console.log('');
1319
- console.log('Migration Mode:');
1320
- console.log(' šŸš€ Complete Mode: Updates everything');
1321
- console.log(' - Replaces old components with beta components');
1322
- console.log(' - Heading1-6 → Heading with as/variant props');
1323
- console.log(' - Text components → Text with variant props');
1324
- console.log(' - All typography components migrate to beta versions');
1325
- console.log(' - Import paths change to @entur/typography/beta');
1326
- console.log(' - May require prop/styling updates (margin → spacing)');
1327
- console.log(' - Test thoroughly after migration');
1328
- console.log('');
1329
- console.log('Examples:');
1330
- console.log(' # See what would be changed');
1331
- console.log(' npx @entur/typography@latest migrate --dry-run');
1332
- console.log('');
1333
- console.log(' # Complete migration: update everything (default)');
1334
- console.log(' npx @entur/typography@latest migrate');
1335
-
1336
- console.log('Environment Variables:');
1337
- console.log(
1338
- ' TYPOGRAPHY_MIGRATION_DIRS Comma-separated list of directories to scan',
1339
- );
1340
- console.log(' Example: "src/**,app/**"');
1341
- console.log('');
1342
- console.log('šŸŽÆ Customizing Scan Directories:');
1343
- console.log(' Option 1: Edit MIGRATION_FOLDERS in the script (EASIEST)');
1344
- console.log(
1345
- ' Open the script and find the "MIGRATION FOLDERS CONFIGURATION" section',
1346
- );
1347
- console.log(' Add/remove folder patterns between the šŸ‘‡ and šŸ‘† markers');
1348
- console.log(' Examples: "src/**", "app/**", "packages/my-app/**"');
1349
- console.log('');
1350
- console.log(' Option 2: Set environment variable');
1351
- console.log(
1352
- ' export TYPOGRAPHY_MIGRATION_DIRS="src/**,app/**,components/**"',
1353
- );
1354
- console.log(' node scripts/migrate-typography.js');
1355
- console.log('');
1356
- console.log('Security Features:');
1357
- console.log(' - Only scans allowed directories (src/**, app/**, etc.)');
1358
- console.log(' - Never scans node_modules, dist, build, .git, etc.)');
1359
- console.log(' - Dry-run mode for safe testing');
1360
- console.log('');
1361
- process.exit(0);
1362
- }
1363
-
1364
- console.log('šŸŽØ Typography Migration Script');
1365
- console.log('==============================');
1366
- console.log('');
1367
- console.log(
1368
- 'This script helps you migrate from old typography to new beta typography.',
1369
- );
1370
- console.log('');
1371
-
1372
- // Find files to migrate - use a single efficient pattern
1373
- const allFiles = findFiles('*.{ts,tsx,js,jsx,scss,css}');
1374
-
1375
- console.log(`Found ${allFiles.length} files to scan for typography imports.`);
1376
- console.log('');
1377
-
1378
- // Security check
1379
- console.log('šŸ”’ Security: Only scanning allowed directories:');
1380
- ALLOWED_DIRECTORIES.forEach(dir => {
1381
- console.log(` āœ… ${dir}`);
1382
- });
1383
- console.log('');
1384
-
1385
- // Safety check
1386
- if (allFiles.length === 0) {
1387
- console.log('āš ļø No files found to scan. This might mean:');
1388
- console.log(" - You're not in the right directory");
1389
- console.log(" - Your project structure doesn't match the allow-list");
1390
- console.log(' - You need to run this from your project root');
1391
- console.log('');
1392
- console.log('Allowed directory patterns:');
1393
- ALLOWED_DIRECTORIES.forEach(dir => console.log(` ${dir}`));
1394
- process.exit(1);
1395
- }
1396
-
1397
- console.log('šŸ“ Files will be scanned in these locations:');
1398
- const scannedDirs = [
1399
- ...new Set(allFiles.map(file => path.dirname(file))),
1400
- ].slice(0, 10);
1401
-
1402
- // Show relative paths safely
1403
- scannedDirs.forEach(dir => {
1404
- // Ensure we don't show absolute paths
1405
- const safeDir = path.isAbsolute(dir)
1406
- ? path.relative(process.cwd(), dir)
1407
- : dir;
1408
- console.log(` šŸ“‚ ${safeDir}`);
1409
- });
1410
-
1411
- if (allFiles.length > 10) {
1412
- console.log(` ... and ${allFiles.length - 10} more files`);
1413
- }
1414
- console.log('');
1415
-
1416
- // Parse command line options
1417
- const isDryRun = process.argv.includes('--dry-run');
1418
-
1419
- if (isDryRun) {
1420
- console.log('šŸ” DRY RUN MODE: No files will be modified');
1421
- console.log('');
1422
- }
1423
-
1424
- console.log('šŸš€ COMPLETE MIGRATION: Updating imports + component usage');
1425
- console.log('āš ļø WARNING: This will modify your component usage!');
1426
- console.log(' - Old components will be replaced with beta components');
1427
- console.log(' - Import paths will change to @entur/typography/beta');
1428
- console.log(
1429
- ' - Link → Link, Blockquote → Blockquote, Lists → List components (from beta)',
1430
- );
1431
- console.log(
1432
- ' - List components → UnorderedList, NumberedList, ListItem (from beta)',
1433
- );
1434
- console.log(' - Props may change (margin → spacing)');
1435
- console.log(' - Test thoroughly after migration');
1436
-
1437
- console.log('');
1438
-
1439
- // Perform migration
1440
- const report = generateMigrationReport(allFiles, isDryRun);
1441
- printReport(report);
1442
- showNextSteps();
1443
-
1444
- console.log('\nšŸŽÆ Migration complete!');
1445
- }
1446
-
1447
- // Check if this module is being run directly
1448
- if (import.meta.url === `file://${process.argv[1]}`) {
1449
- main().catch(error => {
1450
- console.error('āŒ Migration failed:', error);
1451
- process.exit(1);
1452
- });
1453
- }
1454
-
1455
- export {
1456
- updateImportsAndComponents,
1457
- generateMigrationReport,
1458
- COMPONENT_MAPPING,
1459
- PROPS_MAPPING,
1460
- parseJSXProps,
1461
- propsToString,
1462
- };