@multiplatform.one/cli 9.17.0 → 10.0.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.
@@ -0,0 +1,1003 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ import spawn from "nano-spawn";
4
+ import ts from "typescript";
5
+
6
+ //#region src/commands/themeKeyRenames.json
7
+ var themeKeyRenames_default = {
8
+ accent1: "accent-1",
9
+ accent10: "accent-10",
10
+ accent11: "accent-11",
11
+ accent12: "accent-12",
12
+ accent2: "accent-2",
13
+ accent3: "accent-3",
14
+ accent4: "accent-4",
15
+ accent5: "accent-5",
16
+ accent6: "accent-6",
17
+ accent7: "accent-7",
18
+ accent8: "accent-8",
19
+ accent9: "accent-9",
20
+ accentBackground: "accent-background",
21
+ accentColor: "accent-color",
22
+ accentOnSurface: "accent-on-surface",
23
+ background: "background",
24
+ background0: "background-0",
25
+ background02: "background-02",
26
+ background04: "background-04",
27
+ background06: "background-06",
28
+ background08: "background-08",
29
+ backgroundActive: "background-active",
30
+ backgroundFocus: "background-focus",
31
+ backgroundHover: "background-hover",
32
+ backgroundPress: "background-press",
33
+ blue1: "blue-1",
34
+ blue10: "blue-10",
35
+ blue11: "blue-11",
36
+ blue12: "blue-12",
37
+ blue2: "blue-2",
38
+ blue3: "blue-3",
39
+ blue4: "blue-4",
40
+ blue5: "blue-5",
41
+ blue6: "blue-6",
42
+ blue7: "blue-7",
43
+ blue8: "blue-8",
44
+ blue9: "blue-9",
45
+ borderColor: "border-color",
46
+ borderColorControl: "border-color-control",
47
+ borderColorField: "border-color-field",
48
+ borderColorFieldHover: "border-color-field-hover",
49
+ borderColorFocus: "border-color-focus",
50
+ borderColorHairline: "border-color-hairline",
51
+ borderColorHover: "border-color-hover",
52
+ borderColorPress: "border-color-press",
53
+ borderStrong: "border-strong",
54
+ boundaryColor: "boundary-color",
55
+ color: "color",
56
+ color0: "color-0",
57
+ color02: "color-02",
58
+ color04: "color-04",
59
+ color06: "color-06",
60
+ color08: "color-08",
61
+ color1: "color-1",
62
+ color10: "color-10",
63
+ color11: "color-11",
64
+ color12: "color-12",
65
+ color2: "color-2",
66
+ color3: "color-3",
67
+ color4: "color-4",
68
+ color5: "color-5",
69
+ color6: "color-6",
70
+ color7: "color-7",
71
+ color8: "color-8",
72
+ color9: "color-9",
73
+ colorFocus: "color-focus",
74
+ colorHover: "color-hover",
75
+ colorPress: "color-press",
76
+ colorTransparent: "color-transparent",
77
+ gray1: "gray-1",
78
+ gray10: "gray-10",
79
+ gray11: "gray-11",
80
+ gray12: "gray-12",
81
+ gray2: "gray-2",
82
+ gray3: "gray-3",
83
+ gray4: "gray-4",
84
+ gray5: "gray-5",
85
+ gray6: "gray-6",
86
+ gray7: "gray-7",
87
+ gray8: "gray-8",
88
+ gray9: "gray-9",
89
+ green1: "green-1",
90
+ green10: "green-10",
91
+ green11: "green-11",
92
+ green12: "green-12",
93
+ green2: "green-2",
94
+ green3: "green-3",
95
+ green4: "green-4",
96
+ green5: "green-5",
97
+ green6: "green-6",
98
+ green7: "green-7",
99
+ green8: "green-8",
100
+ green9: "green-9",
101
+ identityInk: "identity-ink",
102
+ neutral1: "neutral-1",
103
+ neutral10: "neutral-10",
104
+ neutral11: "neutral-11",
105
+ neutral12: "neutral-12",
106
+ neutral2: "neutral-2",
107
+ neutral3: "neutral-3",
108
+ neutral4: "neutral-4",
109
+ neutral5: "neutral-5",
110
+ neutral6: "neutral-6",
111
+ neutral7: "neutral-7",
112
+ neutral8: "neutral-8",
113
+ neutral9: "neutral-9",
114
+ orange1: "orange-1",
115
+ orange10: "orange-10",
116
+ orange11: "orange-11",
117
+ orange12: "orange-12",
118
+ orange2: "orange-2",
119
+ orange3: "orange-3",
120
+ orange4: "orange-4",
121
+ orange5: "orange-5",
122
+ orange6: "orange-6",
123
+ orange7: "orange-7",
124
+ orange8: "orange-8",
125
+ orange9: "orange-9",
126
+ outlineColor: "outline-color",
127
+ pink1: "pink-1",
128
+ pink10: "pink-10",
129
+ pink11: "pink-11",
130
+ pink12: "pink-12",
131
+ pink2: "pink-2",
132
+ pink3: "pink-3",
133
+ pink4: "pink-4",
134
+ pink5: "pink-5",
135
+ pink6: "pink-6",
136
+ pink7: "pink-7",
137
+ pink8: "pink-8",
138
+ pink9: "pink-9",
139
+ placeholderColor: "placeholder-color",
140
+ purple1: "purple-1",
141
+ purple10: "purple-10",
142
+ purple11: "purple-11",
143
+ purple12: "purple-12",
144
+ purple2: "purple-2",
145
+ purple3: "purple-3",
146
+ purple4: "purple-4",
147
+ purple5: "purple-5",
148
+ purple6: "purple-6",
149
+ purple7: "purple-7",
150
+ purple8: "purple-8",
151
+ purple9: "purple-9",
152
+ red1: "red-1",
153
+ red10: "red-10",
154
+ red11: "red-11",
155
+ red12: "red-12",
156
+ red2: "red-2",
157
+ red3: "red-3",
158
+ red4: "red-4",
159
+ red5: "red-5",
160
+ red6: "red-6",
161
+ red7: "red-7",
162
+ red8: "red-8",
163
+ red9: "red-9",
164
+ selectFill: "select-fill",
165
+ selectPress: "select-press",
166
+ selectedBackground: "selected-background",
167
+ selectedColor: "selected-color",
168
+ shadow1: "shadow-1",
169
+ shadow2: "shadow-2",
170
+ shadow3: "shadow-3",
171
+ shadow4: "shadow-4",
172
+ shadow5: "shadow-5",
173
+ shadow6: "shadow-6",
174
+ shadowColor: "shadow-color",
175
+ surfaceMuted: "surface-muted",
176
+ surfaceStrong: "surface-strong",
177
+ switchThumb: "switch-thumb",
178
+ switchTrackOff: "switch-track-off",
179
+ switchTrackOffBorder: "switch-track-off-border",
180
+ switchTrackOffHover: "switch-track-off-hover",
181
+ switchTrackOffPress: "switch-track-off-press",
182
+ syntaxBlue: "syntax-blue",
183
+ syntaxGreen: "syntax-green",
184
+ syntaxOrange: "syntax-orange",
185
+ syntaxPurple: "syntax-purple",
186
+ syntaxRed: "syntax-red",
187
+ teal1: "teal-1",
188
+ teal10: "teal-10",
189
+ teal11: "teal-11",
190
+ teal12: "teal-12",
191
+ teal2: "teal-2",
192
+ teal3: "teal-3",
193
+ teal4: "teal-4",
194
+ teal5: "teal-5",
195
+ teal6: "teal-6",
196
+ teal7: "teal-7",
197
+ teal8: "teal-8",
198
+ teal9: "teal-9",
199
+ textMuted: "text-muted",
200
+ textSubtle: "text-subtle",
201
+ yellow1: "yellow-1",
202
+ yellow10: "yellow-10",
203
+ yellow11: "yellow-11",
204
+ yellow12: "yellow-12",
205
+ yellow2: "yellow-2",
206
+ yellow3: "yellow-3",
207
+ yellow4: "yellow-4",
208
+ yellow5: "yellow-5",
209
+ yellow6: "yellow-6",
210
+ yellow7: "yellow-7",
211
+ yellow8: "yellow-8",
212
+ yellow9: "yellow-9"
213
+ };
214
+
215
+ //#endregion
216
+ //#region src/commands/themeKeys.ts
217
+ const themeKeyForms = [
218
+ "token",
219
+ "css-var",
220
+ "flat",
221
+ "member",
222
+ "element",
223
+ "destructure",
224
+ "definition",
225
+ "key-list",
226
+ "call-arg",
227
+ "family"
228
+ ];
229
+ const codeExtensions = new Set([
230
+ ".ts",
231
+ ".tsx",
232
+ ".mts",
233
+ ".cts",
234
+ ".js",
235
+ ".jsx",
236
+ ".mjs",
237
+ ".cjs"
238
+ ]);
239
+ const cssExtensions = new Set([".css"]);
240
+ const skippedDirectories = new Set([
241
+ "node_modules",
242
+ "dist",
243
+ ".git",
244
+ ".turbo",
245
+ ".expo",
246
+ ".tamagui",
247
+ ".next",
248
+ "coverage"
249
+ ]);
250
+ const themeKeysSkipMarker = "mpo-theme-keys: skip-file";
251
+ const generatedHeader = /@generated|do not edit|auto-?generated/iu;
252
+ /** Tamagui's lookups that take a theme key or token as their first argument. */
253
+ const lookupCalls = new Set([
254
+ "getVariable",
255
+ "getVariableValue",
256
+ "getVariableName",
257
+ "getTokenValue",
258
+ "getToken",
259
+ "getTokenObject"
260
+ ]);
261
+ /** Theme keys that are also style property names: outside a theme they are style keys. */
262
+ const styleNamedKeys = new Set([
263
+ "borderColor",
264
+ "shadowColor",
265
+ "outlineColor",
266
+ "accentColor",
267
+ "placeholderColor"
268
+ ]);
269
+ const styleValueProps = new Set([
270
+ "bg",
271
+ "bc",
272
+ "boc",
273
+ "background",
274
+ "backgroundImage",
275
+ "border",
276
+ "borderTop",
277
+ "borderRight",
278
+ "borderBottom",
279
+ "borderLeft",
280
+ "borderBlock",
281
+ "borderInline",
282
+ "boxShadow",
283
+ "textShadow",
284
+ "outline",
285
+ "fill",
286
+ "stroke"
287
+ ]);
288
+ /** A prop or style key whose value is a colour or carries one. */
289
+ function isStyleValueProp(name) {
290
+ return name === "color" || name.endsWith("Color") || styleValueProps.has(name);
291
+ }
292
+ function buildRenamer(renames) {
293
+ const map = /* @__PURE__ */ new Map();
294
+ for (const [from, to] of Object.entries(renames)) if (from !== to) map.set(from, to);
295
+ const steps = /* @__PURE__ */ new Map();
296
+ for (const [from, to] of map) {
297
+ const step = /^([A-Za-z]+)(\d+)$/u.exec(from);
298
+ if (!step) continue;
299
+ const ok = to === `${step[1]}-${step[2]}`;
300
+ steps.set(step[1], (steps.get(step[1]) ?? true) && ok);
301
+ }
302
+ const families = new Set([...steps].filter(([, ok]) => ok).map(([prefix]) => prefix));
303
+ return {
304
+ map,
305
+ known: new Set(Object.keys(renames)),
306
+ families
307
+ };
308
+ }
309
+ const defaultRenamer = buildRenamer(themeKeyRenames_default);
310
+ function renamerFor(renames) {
311
+ return renames ? buildRenamer(renames) : defaultRenamer;
312
+ }
313
+ const tokenPattern = /(?<![A-Za-z0-9_$])\$([A-Za-z][A-Za-z0-9]*)(?![A-Za-z0-9_-])/gu;
314
+ const cssVarPattern = /(?<![A-Za-z0-9_-])--([A-Za-z][A-Za-z0-9]*)(?![A-Za-z0-9_-])/gu;
315
+ const barePattern = /(?<=^|[\s:(,])([A-Za-z][A-Za-z0-9]*)(?=$|[\s,)])/gu;
316
+ const tokenFamilyTail = /(?<![A-Za-z0-9_$])\$([A-Za-z]+)$/u;
317
+ const cssVarFamilyTail = /(?<![A-Za-z0-9_-])--([A-Za-z]+)$/u;
318
+ const bareFamilyTail = /(?<=^|[\s:(,])([A-Za-z]+)$/u;
319
+ function bump(counts, form, by = 1) {
320
+ if (by) counts[form] = (counts[form] ?? 0) + by;
321
+ }
322
+ function replaceKeys(text, pattern, renamer, wrap) {
323
+ let count = 0;
324
+ return {
325
+ text: text.replace(pattern, (whole, key) => {
326
+ const renamed = renamer.map.get(key);
327
+ if (!renamed) return whole;
328
+ count += 1;
329
+ return wrap(renamed);
330
+ }),
331
+ count
332
+ };
333
+ }
334
+ /** `var(--color12)` and `--color12:` in a CSS file or a CSS string. */
335
+ function renameCssVars(text, renames) {
336
+ return replaceKeys(text, cssVarPattern, renamerFor(renames), (next) => `--${next}`);
337
+ }
338
+ function scriptKindFor(file) {
339
+ const ext = path.extname(file);
340
+ if (ext === ".tsx") return ts.ScriptKind.TSX;
341
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return ts.ScriptKind.TS;
342
+ return ts.ScriptKind.JSX;
343
+ }
344
+ function parseErrors(sf) {
345
+ return sf.parseDiagnostics ?? [];
346
+ }
347
+ function unwrap(node) {
348
+ let current = node;
349
+ while (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isNonNullExpression(current) || ts.isTypeAssertionExpression(current)) current = current.expression;
350
+ return current;
351
+ }
352
+ function calleeName(expression) {
353
+ const callee = unwrap(expression);
354
+ if (ts.isIdentifier(callee)) return callee.text;
355
+ if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
356
+ }
357
+ function propertyNameText(name) {
358
+ if (!name) return void 0;
359
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;
360
+ if (ts.isComputedPropertyName(name)) {
361
+ const inner = unwrap(name.expression);
362
+ if (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) return inner.text;
363
+ }
364
+ }
365
+ const themeName = /theme/iu;
366
+ const themesName = /themes$/iu;
367
+ const themeTypeName = /Theme(?!Name)/u;
368
+ function isThemeIdentifierName(name) {
369
+ return themeName.test(name) && !themesName.test(name);
370
+ }
371
+ /**
372
+ * Rewrites one source file's theme keys. `file` names the file in reports and
373
+ * picks the parser (TS, TSX, or JS with JSX).
374
+ */
375
+ function renameThemeKeysInSource(source, file, renames) {
376
+ const renamer = renamerFor(renames);
377
+ const counts = {};
378
+ const unclassified = [];
379
+ const sf = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, scriptKindFor(file));
380
+ if (parseErrors(sf).length) return {
381
+ output: source,
382
+ counts,
383
+ unclassified,
384
+ error: "does not parse"
385
+ };
386
+ const edits = [];
387
+ const handled = /* @__PURE__ */ new Set();
388
+ const themeVars = /* @__PURE__ */ new Set();
389
+ const themeRecords = /* @__PURE__ */ new Set();
390
+ const libraryPalettes = /* @__PURE__ */ new Set();
391
+ const lines = source.split("\n");
392
+ const report = (node, key, reason) => {
393
+ const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
394
+ unclassified.push({
395
+ file,
396
+ line: line + 1,
397
+ column: character + 1,
398
+ key,
399
+ reason,
400
+ text: (lines[line] ?? "").trim().slice(0, 160)
401
+ });
402
+ };
403
+ const isRenamable = (key) => key !== void 0 && renamer.map.has(key);
404
+ const isStyleNamed = (key) => styleNamedKeys.has(key);
405
+ const typeMentionsTheme = (type) => type ? themeTypeName.test(type.getText(sf)) : false;
406
+ const rootIdentifier = (expression) => {
407
+ let current = unwrap(expression);
408
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) current = unwrap(current.expression);
409
+ return ts.isIdentifier(current) ? current : void 0;
410
+ };
411
+ const isLibraryPalette = (expression) => {
412
+ const root = rootIdentifier(expression);
413
+ return root !== void 0 && libraryPalettes.has(root.text);
414
+ };
415
+ const isThemeRecord = (node) => {
416
+ const expression = unwrap(node);
417
+ if (ts.isIdentifier(expression)) return themesName.test(expression.text) || themeRecords.has(expression.text);
418
+ if (ts.isPropertyAccessExpression(expression)) return themesName.test(expression.name.text);
419
+ if (ts.isCallExpression(expression)) return calleeName(expression.expression) === "getThemes";
420
+ return false;
421
+ };
422
+ const isTheme = (node) => {
423
+ const expression = unwrap(node);
424
+ if (ts.isCallExpression(expression)) return calleeName(expression.expression) === "useTheme";
425
+ if (ts.isIdentifier(expression)) {
426
+ if (libraryPalettes.has(expression.text)) return false;
427
+ return themeVars.has(expression.text) || isThemeIdentifierName(expression.text);
428
+ }
429
+ if (ts.isPropertyAccessExpression(expression)) {
430
+ if (isThemeIdentifierName(expression.name.text)) return true;
431
+ return isThemeRecord(expression.expression);
432
+ }
433
+ if (ts.isElementAccessExpression(expression)) return isThemeRecord(expression.expression);
434
+ if (ts.isBinaryExpression(expression)) {
435
+ const op = expression.operatorToken.kind;
436
+ if (op === ts.SyntaxKind.QuestionQuestionToken || op === ts.SyntaxKind.BarBarToken) return isTheme(expression.left) || isTheme(expression.right);
437
+ return false;
438
+ }
439
+ if (ts.isConditionalExpression(expression)) return isTheme(expression.whenTrue) || isTheme(expression.whenFalse);
440
+ return false;
441
+ };
442
+ const collectBindings = (node) => {
443
+ if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
444
+ if (/(^|\/)colors$/u.test(node.moduleSpecifier.text) && node.importClause) {
445
+ const { name, namedBindings } = node.importClause;
446
+ if (name) libraryPalettes.add(name.text);
447
+ if (namedBindings && ts.isNamedImports(namedBindings)) for (const element of namedBindings.elements) libraryPalettes.add(element.name.text);
448
+ if (namedBindings && ts.isNamespaceImport(namedBindings)) libraryPalettes.add(namedBindings.name.text);
449
+ }
450
+ }
451
+ if (ts.isVariableDeclaration(node) && node.initializer && isLibraryPalette(node.initializer)) {
452
+ if (ts.isIdentifier(node.name)) libraryPalettes.add(node.name.text);
453
+ if (ts.isObjectBindingPattern(node.name)) {
454
+ for (const element of node.name.elements) if (ts.isIdentifier(element.name)) libraryPalettes.add(element.name.text);
455
+ }
456
+ } else if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name)) {
457
+ const name = node.name.text;
458
+ if (node.initializer && isThemeRecord(node.initializer)) themeRecords.add(name);
459
+ else if (node.initializer && isTheme(node.initializer) || typeMentionsTheme(node.type)) {
460
+ if (!themesName.test(name)) themeVars.add(name);
461
+ }
462
+ }
463
+ if (ts.isParameter(node) && ts.isIdentifier(node.name) && typeMentionsTheme(node.type)) {
464
+ if (!themesName.test(node.name.text)) themeVars.add(node.name.text);
465
+ }
466
+ if (ts.isForOfStatement(node) && ts.isVariableDeclarationList(node.initializer)) {
467
+ const declaration = node.initializer.declarations[0];
468
+ const iterated = unwrap(node.expression);
469
+ if (declaration && ts.isCallExpression(iterated) && ts.isPropertyAccessExpression(iterated.expression) && ts.isIdentifier(iterated.expression.expression) && iterated.expression.expression.text === "Object" && iterated.arguments[0] && isThemeRecord(iterated.arguments[0])) {
470
+ const method = iterated.expression.name.text;
471
+ if (method === "values" && ts.isIdentifier(declaration.name)) themeVars.add(declaration.name.text);
472
+ if (method === "entries" && ts.isArrayBindingPattern(declaration.name)) {
473
+ const second = declaration.name.elements[1];
474
+ if (second && ts.isBindingElement(second) && ts.isIdentifier(second.name)) themeVars.add(second.name.text);
475
+ }
476
+ }
477
+ }
478
+ ts.forEachChild(node, collectBindings);
479
+ };
480
+ for (let pass = 0; pass < 3; pass += 1) {
481
+ const before = themeVars.size + themeRecords.size;
482
+ collectBindings(sf);
483
+ if (themeVars.size + themeRecords.size === before) break;
484
+ }
485
+ const literalInner = (node) => {
486
+ const start = node.getStart(sf);
487
+ const end = node.end;
488
+ switch (node.kind) {
489
+ case ts.SyntaxKind.TemplateHead:
490
+ case ts.SyntaxKind.TemplateMiddle: return [start + 1, end - 2];
491
+ case ts.SyntaxKind.RegularExpressionLiteral: return [start, end];
492
+ default: return [start + 1, end - 1];
493
+ }
494
+ };
495
+ const keyLiteral = (key) => JSON.stringify(key);
496
+ const replaceLiteral = (node, next, form) => {
497
+ handled.add(node);
498
+ const [start, end] = literalInner(node);
499
+ edits.push({
500
+ start,
501
+ end,
502
+ text: next
503
+ });
504
+ bump(counts, form);
505
+ };
506
+ /** Edits the text of a string, template piece or regex in place. */
507
+ const rewriteText = (node, bare) => {
508
+ const [start, end] = literalInner(node);
509
+ let text = source.slice(start, end);
510
+ const original = text;
511
+ const token = replaceKeys(text, tokenPattern, renamer, (next) => `$${next}`);
512
+ text = token.text;
513
+ bump(counts, "token", token.count);
514
+ const cssVar = replaceKeys(text, cssVarPattern, renamer, (next) => `--${next}`);
515
+ text = cssVar.text;
516
+ bump(counts, "css-var", cssVar.count);
517
+ if (bare && node.kind !== ts.SyntaxKind.RegularExpressionLiteral) {
518
+ const flat = replaceKeys(text, barePattern, renamer, (next) => next);
519
+ text = flat.text;
520
+ bump(counts, "flat", flat.count);
521
+ }
522
+ if (node.kind === ts.SyntaxKind.TemplateHead || node.kind === ts.SyntaxKind.TemplateMiddle) {
523
+ const tails = [
524
+ [
525
+ tokenFamilyTail,
526
+ "$",
527
+ true
528
+ ],
529
+ [
530
+ cssVarFamilyTail,
531
+ "--",
532
+ true
533
+ ],
534
+ [
535
+ bareFamilyTail,
536
+ "",
537
+ bare
538
+ ]
539
+ ];
540
+ for (const [pattern, sigil, active] of tails) {
541
+ const match = active ? pattern.exec(text) : null;
542
+ if (match && renamer.families.has(match[1])) {
543
+ text = `${text.slice(0, match.index)}${sigil}${match[1]}-`;
544
+ bump(counts, "family");
545
+ break;
546
+ }
547
+ }
548
+ }
549
+ if (text !== original) edits.push({
550
+ start,
551
+ end,
552
+ text
553
+ });
554
+ };
555
+ const renameName = (name, form) => {
556
+ const key = propertyNameText(name);
557
+ if (!isRenamable(key)) return;
558
+ const next = renamer.map.get(key);
559
+ if (ts.isComputedPropertyName(name)) replaceLiteral(unwrap(name.expression), next, form);
560
+ else if (ts.isStringLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) replaceLiteral(name, next, form);
561
+ else {
562
+ edits.push({
563
+ start: name.getStart(sf),
564
+ end: name.end,
565
+ text: keyLiteral(next)
566
+ });
567
+ bump(counts, form);
568
+ }
569
+ };
570
+ const ownerName = (object) => {
571
+ let child = object;
572
+ let parent = object.parent;
573
+ while (parent && (ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent))) {
574
+ child = parent;
575
+ parent = parent.parent;
576
+ }
577
+ if (!parent) return void 0;
578
+ if (ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent)) return parent.initializer === child ? propertyNameText(parent.name) : void 0;
579
+ };
580
+ const isThemeDefinitionObject = (object) => {
581
+ let child = object;
582
+ let parent = object.parent;
583
+ while (parent && (ts.isParenthesizedExpression(parent) || ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent))) {
584
+ if ((ts.isAsExpression(parent) || ts.isSatisfiesExpression(parent)) && typeMentionsTheme(parent.type)) return true;
585
+ child = parent;
586
+ parent = parent.parent;
587
+ }
588
+ if (!parent) return false;
589
+ if (ts.isVariableDeclaration(parent) && parent.initializer === child) {
590
+ if (typeMentionsTheme(parent.type)) return true;
591
+ if (ts.isIdentifier(parent.name) && isThemeIdentifierName(parent.name.text)) return true;
592
+ }
593
+ if (ts.isPropertyAssignment(parent) && parent.initializer === child) {
594
+ if (isThemeIdentifierName(propertyNameText(parent.name) ?? "")) return true;
595
+ if (themesName.test(ownerName(parent.parent) ?? "")) return true;
596
+ }
597
+ if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.right === child) {
598
+ const left = unwrap(parent.left);
599
+ if (isThemeIdentifierName(ts.isIdentifier(left) ? left.text : ts.isPropertyAccessExpression(left) ? left.name.text : "")) return true;
600
+ }
601
+ const fn = ts.isArrowFunction(parent) && parent.body === child ? parent : ts.isReturnStatement(parent) ? ts.findAncestor(parent, ts.isFunctionLike) : void 0;
602
+ if (fn) {
603
+ const holder = fn.parent;
604
+ if ((ts.isFunctionDeclaration(fn) ? fn.name?.text : holder && (ts.isPropertyAssignment(holder) || ts.isVariableDeclaration(holder)) ? propertyNameText(holder.name) : void 0) === "getTheme") return true;
605
+ }
606
+ const properties = object.properties.filter(ts.isPropertyAssignment);
607
+ if (!properties.length || properties.length !== object.properties.length) return false;
608
+ if (!properties.map((property) => propertyNameText(property.name)).some(isRenamable)) return false;
609
+ return properties.every((property) => {
610
+ const value = unwrap(property.initializer);
611
+ return ts.isObjectLiteralExpression(value) && value.properties.some((inner) => propertyNameText(inner.name) === "val");
612
+ });
613
+ };
614
+ const isKeyList = (elements) => {
615
+ if (elements.length < 2) return false;
616
+ for (const element of elements) {
617
+ if (!ts.isStringLiteral(element) && !ts.isNoSubstitutionTemplateLiteral(element)) return false;
618
+ if (!renamer.known.has(element.text)) return false;
619
+ }
620
+ return elements.some((element) => {
621
+ const key = element.text;
622
+ return renamer.map.has(key) && !isStyleNamed(key);
623
+ });
624
+ };
625
+ const renameKeyList = (elements) => {
626
+ for (const element of elements) {
627
+ handled.add(element);
628
+ const next = renamer.map.get(element.text);
629
+ if (next) replaceLiteral(element, next, "key-list");
630
+ }
631
+ };
632
+ const isModuleSpecifier = (node) => {
633
+ const parent = node.parent;
634
+ if (!parent) return false;
635
+ if ((ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) && parent.moduleSpecifier === node) return true;
636
+ if (ts.isExternalModuleReference(parent)) return true;
637
+ if (ts.isLiteralTypeNode(parent) && ts.isImportTypeNode(parent.parent)) return true;
638
+ if (ts.isCallExpression(parent)) {
639
+ if (calleeName(parent.expression) === "require") return true;
640
+ if (parent.expression.kind === ts.SyntaxKind.ImportKeyword) return true;
641
+ }
642
+ return false;
643
+ };
644
+ const isPropertyNameOfParent = (node) => {
645
+ const parent = node.parent;
646
+ if (!parent) return false;
647
+ if (parent.name === node && !ts.isJsxAttribute(parent)) return true;
648
+ if (ts.isBindingElement(parent) && parent.propertyName === node) return true;
649
+ return ts.isComputedPropertyName(parent);
650
+ };
651
+ const visitObject = (node, style) => {
652
+ const definition = isThemeDefinitionObject(node);
653
+ for (const property of node.properties) {
654
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
655
+ visit(property, false);
656
+ continue;
657
+ }
658
+ const key = propertyNameText(property.name);
659
+ if (isRenamable(key)) {
660
+ if (definition && ts.isShorthandPropertyAssignment(property)) {
661
+ edits.push({
662
+ start: property.name.getStart(sf),
663
+ end: property.name.end,
664
+ text: `${keyLiteral(renamer.map.get(key))}: ${property.name.text}`
665
+ });
666
+ bump(counts, "definition");
667
+ } else if (definition) renameName(property.name, "definition");
668
+ else if (!isStyleNamed(key) && !style) report(property.name, key, "object key named like a theme key outside a theme definition");
669
+ }
670
+ if (ts.isComputedPropertyName(property.name)) visit(property.name.expression, false);
671
+ if (ts.isPropertyAssignment(property)) visit(property.initializer, style || !definition && isStyleValueProp(key ?? ""));
672
+ }
673
+ };
674
+ const visitElementAccess = (node) => {
675
+ const argument = unwrap(node.argumentExpression);
676
+ const theme = isTheme(node.expression);
677
+ if (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) {
678
+ if (isRenamable(argument.text)) {
679
+ if (theme) replaceLiteral(argument, renamer.map.get(argument.text), "element");
680
+ else if (isLibraryPalette(node.expression)) handled.add(argument);
681
+ }
682
+ } else if (ts.isTemplateExpression(argument)) {
683
+ const head = argument.head;
684
+ const span = argument.templateSpans[0];
685
+ const isFamily = renamer.families.has(head.text) && argument.templateSpans.length === 1 && span?.literal.text === "";
686
+ if (isFamily && theme) {
687
+ handled.add(head);
688
+ handled.add(span.literal);
689
+ const [start, end] = literalInner(head);
690
+ edits.push({
691
+ start,
692
+ end,
693
+ text: `${head.text}-`
694
+ });
695
+ bump(counts, "family");
696
+ } else if (isFamily && !isLibraryPalette(node.expression)) {
697
+ handled.add(head);
698
+ handled.add(span.literal);
699
+ report(argument, `${head.text}\${n}`, "ramp step built by a template on a receiver not known to be a theme");
700
+ }
701
+ }
702
+ visit(node.expression, false);
703
+ visit(node.argumentExpression, false);
704
+ };
705
+ const visitBindingDeclaration = (node) => {
706
+ const fromTheme = node.initializer ? isTheme(node.initializer) : false;
707
+ for (const element of node.name.elements) {
708
+ const key = propertyNameText(element.propertyName ?? element.name);
709
+ if (isRenamable(key)) {
710
+ if (fromTheme && element.propertyName) renameName(element.propertyName, "destructure");
711
+ else if (fromTheme) {
712
+ edits.push({
713
+ start: element.name.getStart(sf),
714
+ end: element.name.end,
715
+ text: `${keyLiteral(renamer.map.get(key))}: ${element.name.getText(sf)}`
716
+ });
717
+ bump(counts, "destructure");
718
+ } else if (!isStyleNamed(key)) report(element, key, "destructured from a receiver not known to be a theme");
719
+ }
720
+ if (element.initializer) visit(element.initializer, false);
721
+ }
722
+ if (node.type) visit(node.type, false);
723
+ if (node.initializer) visit(node.initializer, false);
724
+ };
725
+ const visit = (node, style) => {
726
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isRegularExpressionLiteral(node)) {
727
+ if (handled.has(node) || isModuleSpecifier(node) || isPropertyNameOfParent(node)) return;
728
+ rewriteText(node, style);
729
+ if (!style && !ts.isRegularExpressionLiteral(node) && isRenamable(node.text) && !isStyleNamed(node.text)) report(node, node.text, "bare key string outside a theme or style value");
730
+ return;
731
+ }
732
+ if (ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) {
733
+ if (!handled.has(node)) rewriteText(node, style);
734
+ return;
735
+ }
736
+ if (ts.isJsxAttribute(node)) {
737
+ if (node.initializer) visit(node.initializer, isStyleValueProp(node.name.getText(sf)));
738
+ return;
739
+ }
740
+ if (ts.isJsxExpression(node)) {
741
+ if (node.expression) visit(node.expression, style);
742
+ return;
743
+ }
744
+ if (ts.isObjectLiteralExpression(node)) {
745
+ visitObject(node, style);
746
+ return;
747
+ }
748
+ if (ts.isArrayLiteralExpression(node)) {
749
+ if (isKeyList(node.elements)) renameKeyList(node.elements);
750
+ for (const element of node.elements) visit(element, style);
751
+ return;
752
+ }
753
+ if (ts.isUnionTypeNode(node)) {
754
+ const literals = node.types.map((type) => ts.isLiteralTypeNode(type) ? type.literal : type);
755
+ if (isKeyList(literals)) renameKeyList(literals);
756
+ ts.forEachChild(node, (child) => visit(child, false));
757
+ return;
758
+ }
759
+ if (ts.isPropertySignature(node) || ts.isPropertyDeclaration(node)) {
760
+ const key = propertyNameText(node.name);
761
+ if (isRenamable(key)) {
762
+ const owner = node.parent;
763
+ const name = ts.isInterfaceDeclaration(owner) || ts.isClassDeclaration(owner) ? owner.name?.text : ts.isTypeLiteralNode(owner) && ts.isTypeAliasDeclaration(owner.parent) ? owner.parent.name.text : void 0;
764
+ if (name && themeTypeName.test(name)) renameName(node.name, "definition");
765
+ else if (!isStyleNamed(key)) report(node.name, key, "type member named like a theme key");
766
+ }
767
+ ts.forEachChild(node, (child) => {
768
+ if (child !== node.name) visit(child, false);
769
+ });
770
+ return;
771
+ }
772
+ if (ts.isPropertyAccessExpression(node)) {
773
+ const key = node.name.text;
774
+ if (isRenamable(key)) {
775
+ if (isTheme(node.expression)) {
776
+ const optional = node.questionDotToken ? "?." : "";
777
+ edits.push({
778
+ start: node.expression.end,
779
+ end: node.name.end,
780
+ text: `${optional}[${keyLiteral(renamer.map.get(key))}]`
781
+ });
782
+ bump(counts, "member");
783
+ } else if (!isStyleNamed(key) && !isLibraryPalette(node.expression)) report(node.name, key, "property read on a receiver not known to be a theme");
784
+ }
785
+ visit(node.expression, false);
786
+ return;
787
+ }
788
+ if (ts.isElementAccessExpression(node)) {
789
+ visitElementAccess(node);
790
+ return;
791
+ }
792
+ if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name)) {
793
+ visitBindingDeclaration(node);
794
+ return;
795
+ }
796
+ if (ts.isCallExpression(node)) {
797
+ const name = calleeName(node.expression);
798
+ const first = node.arguments[0] ? unwrap(node.arguments[0]) : void 0;
799
+ if (name && lookupCalls.has(name) && first && (ts.isStringLiteral(first) || ts.isNoSubstitutionTemplateLiteral(first)) && isRenamable(first.text)) replaceLiteral(first, renamer.map.get(first.text), "call-arg");
800
+ if (node.arguments.some((argument) => isTheme(argument))) for (const argument of node.arguments) {
801
+ const inner = unwrap(argument);
802
+ if ((ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) && !handled.has(inner) && isRenamable(inner.text)) replaceLiteral(inner, renamer.map.get(inner.text), "call-arg");
803
+ }
804
+ ts.forEachChild(node, (child) => visit(child, false));
805
+ return;
806
+ }
807
+ if (ts.isConditionalExpression(node)) {
808
+ visit(node.condition, false);
809
+ visit(node.whenTrue, style);
810
+ visit(node.whenFalse, style);
811
+ return;
812
+ }
813
+ if (ts.isBinaryExpression(node)) {
814
+ const op = node.operatorToken.kind;
815
+ const fallback = op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken;
816
+ visit(node.left, fallback ? style : false);
817
+ visit(node.right, fallback || op === ts.SyntaxKind.AmpersandAmpersandToken ? style : false);
818
+ return;
819
+ }
820
+ if (ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node) || ts.isTemplateExpression(node) || ts.isTemplateSpan(node)) {
821
+ ts.forEachChild(node, (child) => visit(child, ts.isTypeNode(child) ? false : style));
822
+ return;
823
+ }
824
+ ts.forEachChild(node, (child) => visit(child, false));
825
+ };
826
+ visit(sf, false);
827
+ if (!edits.length) return {
828
+ output: source,
829
+ counts,
830
+ unclassified
831
+ };
832
+ edits.sort((a, b) => b.start - a.start);
833
+ let output = source;
834
+ let floor = Number.POSITIVE_INFINITY;
835
+ for (const edit of edits) {
836
+ if (edit.end > floor) return {
837
+ output: source,
838
+ counts: {},
839
+ unclassified,
840
+ error: `overlapping edits at ${edit.start}`
841
+ };
842
+ output = output.slice(0, edit.start) + edit.text + output.slice(edit.end);
843
+ floor = edit.start;
844
+ }
845
+ if (parseErrors(ts.createSourceFile(file, output, ts.ScriptTarget.Latest, false, scriptKindFor(file))).length) return {
846
+ output: source,
847
+ counts: {},
848
+ unclassified,
849
+ error: "the rewrite would not parse"
850
+ };
851
+ return {
852
+ output,
853
+ counts,
854
+ unclassified
855
+ };
856
+ }
857
+ /** Rewrites a CSS file's custom properties (`var(--color12)`, `--color12:`). */
858
+ function renameThemeKeysInCss(source, renames) {
859
+ const result = renameCssVars(source, renames);
860
+ const counts = {};
861
+ bump(counts, "css-var", result.count);
862
+ return {
863
+ output: result.text,
864
+ counts,
865
+ unclassified: []
866
+ };
867
+ }
868
+ function inside(relative, prefixes) {
869
+ return prefixes.some((prefix) => {
870
+ const clean = prefix.replace(/^\.\//u, "").replace(/\/+$/u, "");
871
+ return relative === clean || relative.startsWith(`${clean}/`);
872
+ });
873
+ }
874
+ async function walk(root, directory, out) {
875
+ let entries;
876
+ try {
877
+ entries = await fs.readdir(directory, { withFileTypes: true });
878
+ } catch {
879
+ return;
880
+ }
881
+ for (const entry of entries) if (entry.isDirectory()) {
882
+ if (!skippedDirectories.has(entry.name)) await walk(root, path.join(directory, entry.name), out);
883
+ } else if (entry.isFile()) out.push(path.relative(root, path.join(directory, entry.name)).split(path.sep).join("/"));
884
+ }
885
+ async function gitFiles(root, scope) {
886
+ try {
887
+ const { stdout } = await spawn("git", [
888
+ "-C",
889
+ root,
890
+ "ls-files",
891
+ "-z",
892
+ "--cached",
893
+ "--others",
894
+ "--exclude-standard",
895
+ "--",
896
+ ...scope.length ? scope : ["."]
897
+ ]);
898
+ return stdout.split("\0").filter(Boolean);
899
+ } catch {
900
+ return;
901
+ }
902
+ }
903
+ /**
904
+ * The files the pass reads: git's tracked and untracked-but-not-ignored files
905
+ * when `root` is a repository, else a walk that skips node_modules, dist and
906
+ * build caches. Paths come back relative to `root`, with forward slashes.
907
+ */
908
+ async function listThemeKeyFiles(root, paths = [], exclude = []) {
909
+ const scope = paths.map((entry) => path.relative(root, path.resolve(root, entry)).split(path.sep).join("/"));
910
+ let files = await gitFiles(root, scope);
911
+ if (!files) {
912
+ files = [];
913
+ for (const entry of scope.length ? scope : [""]) {
914
+ const absolute = path.join(root, entry);
915
+ const stat = await fs.stat(absolute).catch(() => void 0);
916
+ if (stat?.isFile()) files.push(entry);
917
+ else if (stat?.isDirectory()) await walk(root, absolute, files);
918
+ }
919
+ }
920
+ return [...new Set(files)].filter((file) => {
921
+ const ext = path.extname(file);
922
+ if (!codeExtensions.has(ext) && !cssExtensions.has(ext)) return false;
923
+ if (file.split("/").some((segment) => skippedDirectories.has(segment))) return false;
924
+ if (/\.(generated|gen|min)\.[cm]?[jt]sx?$/u.test(file)) return false;
925
+ return !inside(file, exclude);
926
+ }).sort();
927
+ }
928
+ function totalOf(counts) {
929
+ return Object.values(counts).reduce((sum, count) => sum + (count ?? 0), 0);
930
+ }
931
+ /** Runs the pass over `root`, or the given paths under it. Writes only with `write`. */
932
+ async function runThemeKeys(root, options = {}) {
933
+ const files = await listThemeKeyFiles(root, options.paths, options.exclude);
934
+ const report = {
935
+ root,
936
+ write: Boolean(options.write),
937
+ scanned: 0,
938
+ files: [],
939
+ skipped: []
940
+ };
941
+ for (const file of files) {
942
+ const absolute = path.join(root, file);
943
+ let source;
944
+ try {
945
+ source = await fs.readFile(absolute, "utf8");
946
+ } catch {
947
+ continue;
948
+ }
949
+ const head = source.slice(0, 500);
950
+ if (head.includes("mpo-theme-keys: skip-file")) {
951
+ report.skipped.push({
952
+ file,
953
+ reason: themeKeysSkipMarker
954
+ });
955
+ continue;
956
+ }
957
+ if (generatedHeader.test(head)) {
958
+ report.skipped.push({
959
+ file,
960
+ reason: "generated"
961
+ });
962
+ continue;
963
+ }
964
+ report.scanned += 1;
965
+ const result = cssExtensions.has(path.extname(file)) ? renameThemeKeysInCss(source, options.renames) : renameThemeKeysInSource(source, file, options.renames);
966
+ if (result.error) report.skipped.push({
967
+ file,
968
+ reason: result.error
969
+ });
970
+ const total = totalOf(result.counts);
971
+ if (!total && !result.unclassified.length) continue;
972
+ report.files.push({
973
+ file,
974
+ counts: result.counts,
975
+ total,
976
+ unclassified: result.unclassified
977
+ });
978
+ if (options.write && total && result.output !== source) await fs.writeFile(absolute, result.output);
979
+ }
980
+ return report;
981
+ }
982
+ /** The console report: per-file counts, the totals, then every unclassified site. */
983
+ function formatThemeKeysReport(report) {
984
+ const lines = [];
985
+ const changed = report.files.filter((file) => file.total > 0);
986
+ for (const file of changed) {
987
+ const forms = themeKeyForms.filter((form) => file.counts[form]).map((form) => `${form} ${file.counts[form]}`).join(", ");
988
+ lines.push(`${String(file.total).padStart(5)} ${file.file} (${forms})`);
989
+ }
990
+ const renamed = changed.reduce((sum, file) => sum + file.total, 0);
991
+ const byForm = themeKeyForms.map((form) => [form, changed.reduce((sum, file) => sum + (file.counts[form] ?? 0), 0)]).filter(([, count]) => count).map(([form, count]) => `${form} ${count}`).join(", ");
992
+ lines.push(`${renamed} theme keys ${report.write ? "renamed" : "to rename"} in ${changed.length} of ${report.scanned} files${byForm ? ` (${byForm})` : ""}${report.write ? "" : "; dry run, nothing written (--write applies it)"}`);
993
+ const unclassified = report.files.flatMap((file) => file.unclassified);
994
+ if (unclassified.length) {
995
+ lines.push(`${unclassified.length} sites left alone, not tied to a theme; check each by hand:`);
996
+ for (const site of unclassified) lines.push(` ${site.file}:${site.line}:${site.column} ${site.key} ${site.reason}`);
997
+ }
998
+ for (const skipped of report.skipped.filter((entry) => entry.reason !== "generated")) lines.push(`skipped ${skipped.file}: ${skipped.reason}`);
999
+ return lines.join("\n");
1000
+ }
1001
+
1002
+ //#endregion
1003
+ export { renameThemeKeysInCss as a, themeKeyForms as c, renameCssVars as i, themeKeysSkipMarker as l, isStyleValueProp as n, renameThemeKeysInSource as o, listThemeKeyFiles as r, runThemeKeys as s, formatThemeKeysReport as t };