@oxy.so/bloom-language-codemod 0.0.0-stage → 0.2.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.
package/lib/style.js ADDED
@@ -0,0 +1,475 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ABSOLUTE_FILL = void 0;
37
+ exports.textDeclaration = textDeclaration;
38
+ exports.styleUtilities = styleUtilities;
39
+ /**
40
+ * A static `style` as the Tailwind utilities that write the same declarations,
41
+ * so it lands through the className table like any class (and conflicts with
42
+ * a class that sets the same thing, as two classes would). Only layout values
43
+ * Tailwind writes exactly are taken: a length that is a step of the spacing
44
+ * scale (`gap: 12` is `gap-3`, 0.25rem steps at the preset's 16px rem), `100%`,
45
+ * and the flex keywords. Anything else is a reason.
46
+ */
47
+ const node_fs_1 = require("node:fs");
48
+ const node_path_1 = require("node:path");
49
+ const recast = __importStar(require("recast"));
50
+ const table_1 = require("./table");
51
+ const { scales, enums } = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(table_1.LANGUAGE_PACKAGE, 'spec/language.json'), 'utf8'));
52
+ /** A frame's length relative to its parent by its percentage (`'50%'` is `'1/2'`, `'90%'` itself). */
53
+ const LENGTH_BY_PERCENT = new Map(Object.entries(scales.length)
54
+ .filter(([name, value]) => name !== '$comment' && typeof value === 'string')
55
+ .map(([name, value]) => [value, name]));
56
+ /** The percentages a pinned view's edge takes (`top: '25%'`). */
57
+ const INSET_PERCENT = new Set(enums.insetPercent);
58
+ /** A scale's tokens by value, a named rung over a numeric token of the same value. */
59
+ function byValue(scale) {
60
+ const out = new Map();
61
+ for (const [name, value] of Object.entries(scale)) {
62
+ if (typeof value !== 'number')
63
+ continue;
64
+ const named = !/^-?\d/.test(name);
65
+ if (named || !out.has(value))
66
+ out.set(value, name);
67
+ }
68
+ return out;
69
+ }
70
+ const CORNER = byValue(scales.corner);
71
+ const Z_INDEX = byValue(scales.zIndex);
72
+ const FONT_SIZE = byValue(scales.fontSize);
73
+ const LEADING_PX = byValue(scales.leadingPx);
74
+ /**
75
+ * A text's own `fontSize` and `lineHeight` written out, as the language's
76
+ * size and line: `fontSize: 15` is `.font('md')` (a named rung over a numeric
77
+ * token of the same points, `fontSize: 14` `.font('14')`), `lineHeight: 20`
78
+ * `.leading('20px')`. A size or a line no token holds stays a reason.
79
+ */
80
+ function textDeclaration(key, value) {
81
+ if (!n.NumericLiteral.check(value))
82
+ return undefined;
83
+ const number = value.value;
84
+ if (key === 'fontSize') {
85
+ const token = FONT_SIZE.get(number);
86
+ return token === undefined ? undefined : { name: 'font', args: [token] };
87
+ }
88
+ if (key === 'lineHeight') {
89
+ const token = LEADING_PX.get(number);
90
+ return token === undefined ? undefined : { name: 'leading', args: [token] };
91
+ }
92
+ return undefined;
93
+ }
94
+ const n = recast.types.namedTypes;
95
+ /** A style key whose numeric value is a spacing-scale step: its utility prefix. */
96
+ const LENGTH = {
97
+ gap: 'gap',
98
+ rowGap: 'gap-y',
99
+ columnGap: 'gap-x',
100
+ padding: 'p',
101
+ paddingHorizontal: 'px',
102
+ paddingVertical: 'py',
103
+ paddingTop: 'pt',
104
+ paddingBottom: 'pb',
105
+ paddingLeft: 'pl',
106
+ paddingRight: 'pr',
107
+ paddingStart: 'ps',
108
+ paddingEnd: 'pe',
109
+ margin: 'm',
110
+ marginHorizontal: 'mx',
111
+ marginVertical: 'my',
112
+ marginTop: 'mt',
113
+ marginBottom: 'mb',
114
+ marginLeft: 'ml',
115
+ marginRight: 'mr',
116
+ width: 'w',
117
+ height: 'h',
118
+ minWidth: 'min-w',
119
+ minHeight: 'min-h',
120
+ maxWidth: 'max-w',
121
+ maxHeight: 'max-h',
122
+ top: 'top',
123
+ right: 'right',
124
+ bottom: 'bottom',
125
+ left: 'left',
126
+ };
127
+ /** A style key and keyword value as its utility. */
128
+ const KEYWORD = {
129
+ flexDirection: { row: 'flex-row', column: 'flex-col' },
130
+ flexWrap: { wrap: 'flex-wrap', nowrap: 'flex-nowrap' },
131
+ alignItems: {
132
+ center: 'items-center',
133
+ 'flex-start': 'items-start',
134
+ 'flex-end': 'items-end',
135
+ stretch: 'items-stretch',
136
+ baseline: 'items-baseline',
137
+ },
138
+ alignSelf: {
139
+ center: 'self-center',
140
+ 'flex-start': 'self-start',
141
+ 'flex-end': 'self-end',
142
+ stretch: 'self-stretch',
143
+ },
144
+ justifyContent: {
145
+ center: 'justify-center',
146
+ 'flex-start': 'justify-start',
147
+ 'flex-end': 'justify-end',
148
+ 'space-between': 'justify-between',
149
+ 'space-around': 'justify-around',
150
+ 'space-evenly': 'justify-evenly',
151
+ },
152
+ position: { absolute: 'absolute', relative: 'relative' },
153
+ // A view draws what overflows it by default: the className table drops `overflow-visible`.
154
+ overflow: { hidden: 'overflow-hidden', visible: 'overflow-visible' },
155
+ // An auto margin takes the free space on its side (the language's `.margin(edge, 'auto')`).
156
+ marginTop: { auto: 'mt-auto' },
157
+ marginBottom: { auto: 'mb-auto' },
158
+ marginLeft: { auto: 'ml-auto' },
159
+ marginRight: { auto: 'mr-auto' },
160
+ borderStyle: { solid: 'border-solid', dashed: 'border-dashed', dotted: 'border-dotted' },
161
+ // A text's weight, as Tailwind's `font-*` writes it.
162
+ fontWeight: {
163
+ '300': 'font-light',
164
+ '400': 'font-normal',
165
+ '500': 'font-medium',
166
+ '600': 'font-semibold',
167
+ '700': 'font-bold',
168
+ '800': 'font-extrabold',
169
+ bold: 'font-bold',
170
+ normal: 'font-normal',
171
+ },
172
+ };
173
+ /**
174
+ * A numeric key whose value is a utility of its own. (React Native's `flex: 1`
175
+ * is no utility: Tailwind's `flex-1` is grow 1, shrink 1, basis 0%, which
176
+ * React Native draws differently; measured on the corpus. It is the
177
+ * language's `.grow()`, which writes `flex: 1` itself: `DIRECT`.)
178
+ */
179
+ const NUMERIC = {
180
+ flexGrow: { 1: 'grow', 0: 'grow-0' },
181
+ flexShrink: { 1: 'shrink', 0: 'shrink-0' },
182
+ };
183
+ /** A corner's own radius key as the language's corner side. */
184
+ const CORNER_SIDE = {
185
+ borderTopLeftRadius: 'top-left',
186
+ borderTopRightRadius: 'top-right',
187
+ borderBottomLeftRadius: 'bottom-left',
188
+ borderBottomRightRadius: 'bottom-right',
189
+ borderTopStartRadius: 'top-leading',
190
+ borderTopEndRadius: 'top-trailing',
191
+ borderBottomStartRadius: 'bottom-leading',
192
+ borderBottomEndRadius: 'bottom-trailing',
193
+ };
194
+ /**
195
+ * A style key and value the language writes itself, as its modifier: React
196
+ * Native's `flex: 1` is `.grow()`; a radius, a stacking level and an aspect
197
+ * ratio are the tokens (or number) of their exact value, a corner's own
198
+ * radius (`borderTopLeftRadius`) its side's. A radius of 999 is `full` (9999):
199
+ * both round any box under 1998pt fully, so they draw alike.
200
+ */
201
+ function direct(key, value) {
202
+ const number = n.NumericLiteral.check(value)
203
+ ? value.value
204
+ : n.UnaryExpression.check(value) &&
205
+ value.operator === '-' &&
206
+ n.NumericLiteral.check(value.argument)
207
+ ? -value.argument.value
208
+ : undefined;
209
+ if (number === undefined)
210
+ return undefined;
211
+ if (key === 'flex' && number === 1)
212
+ return { name: 'grow', args: [] };
213
+ if (key === 'borderRadius' || CORNER_SIDE[key]) {
214
+ const token = number === 999 ? 'full' : CORNER.get(number);
215
+ const side = CORNER_SIDE[key];
216
+ return token === undefined
217
+ ? undefined
218
+ : { name: 'corner', args: side ? [token, side] : [token] };
219
+ }
220
+ if (key === 'zIndex') {
221
+ const token = Z_INDEX.get(number);
222
+ return token === undefined ? undefined : { name: 'zIndex', args: [token] };
223
+ }
224
+ if (key === 'aspectRatio' && number > 0)
225
+ return { name: 'aspectRatio', args: [number] };
226
+ return undefined;
227
+ }
228
+ /** One declaration as its utility, or undefined. */
229
+ function utility(key, value) {
230
+ if (n.NumericLiteral.check(value)) {
231
+ const prefix = LENGTH[key];
232
+ // A whole number of points is a step of Tailwind's spacing scale: 0.25rem, 4 points (`gap-3` is 12).
233
+ if (prefix)
234
+ return Number.isInteger(value.value) && value.value >= 0
235
+ ? `${prefix}-${value.value / 4}`
236
+ : undefined;
237
+ return NUMERIC[key]?.[String(value.value)];
238
+ }
239
+ if (n.StringLiteral.check(value)) {
240
+ if (value.value === '100%' &&
241
+ LENGTH[key] &&
242
+ /^(w|h|min-w|min-h|max-w|max-h)$/.test(LENGTH[key]))
243
+ return `${LENGTH[key]}-full`;
244
+ return KEYWORD[key]?.[value.value];
245
+ }
246
+ return undefined;
247
+ }
248
+ const FLEX_KEYS = ['flexGrow', 'flexShrink', 'flexBasis'];
249
+ const FLEX = Object.entries(scales.flex).filter(([name]) => name !== '$comment');
250
+ /** A style's literal grow, shrink and basis, all three, as the flex token that writes them, or undefined. */
251
+ function flexToken(object) {
252
+ const values = new Map();
253
+ for (const property of object.properties)
254
+ if ((n.ObjectProperty.check(property) || n.Property.check(property)) &&
255
+ n.Identifier.check(property.key) &&
256
+ FLEX_KEYS.includes(property.key.name) &&
257
+ (n.NumericLiteral.check(property.value) || n.StringLiteral.check(property.value)))
258
+ values.set(property.key.name, property.value.value);
259
+ if (values.size !== 3)
260
+ return undefined;
261
+ return FLEX.find(([, [grow, shrink, basis]]) => grow === values.get('flexGrow') &&
262
+ shrink === values.get('flexShrink') &&
263
+ basis === values.get('flexBasis'))?.[0];
264
+ }
265
+ /**
266
+ * React Native's `StyleSheet.absoluteFill`: pinned to every edge of its parent
267
+ * (`absolute inset-0`), and the declarations it holds, written out for the
268
+ * parity's before side.
269
+ */
270
+ exports.ABSOLUTE_FILL = {
271
+ classes: ['absolute', 'top-0', 'right-0', 'bottom-0', 'left-0'],
272
+ literal: "position: 'absolute', left: 0, right: 0, top: 0, bottom: 0",
273
+ };
274
+ /** Each physical side a padding or margin key sets, and how specific it is (React Native's precedence). */
275
+ const EDGE_KEYS = {
276
+ '': { sides: ['Top', 'Bottom', 'Left', 'Right'], rank: 0 },
277
+ Horizontal: { sides: ['Left', 'Right'], rank: 1 },
278
+ Vertical: { sides: ['Top', 'Bottom'], rank: 1 },
279
+ Top: { sides: ['Top'], rank: 2 },
280
+ Bottom: { sides: ['Bottom'], rank: 2 },
281
+ Left: { sides: ['Left'], rank: 2 },
282
+ Right: { sides: ['Right'], rank: 2 },
283
+ };
284
+ /**
285
+ * A style's paddings and margins as React Native resolves them when keys of
286
+ * one side meet (`marginHorizontal: 8, marginLeft: 4`): a side's own key over
287
+ * its axis's, an axis's over the whole, whatever their order. Where they
288
+ * meet, a key overridden on a side is the sides it still holds, each its own
289
+ * (`marginLeft: 4, marginRight: 8`), so no two utilities set one side; every
290
+ * other key stays as written. A
291
+ * `Start` or `End` key beside them is left to the conflict it is.
292
+ */
293
+ function sidesResolved(properties) {
294
+ const out = [...properties];
295
+ for (const prefix of ['padding', 'margin']) {
296
+ const own = out.filter((property) => (n.ObjectProperty.check(property) || n.Property.check(property)) &&
297
+ !property.computed &&
298
+ n.Identifier.check(property.key) &&
299
+ property.key.name.startsWith(prefix) &&
300
+ EDGE_KEYS[property.key.name.slice(prefix.length)] !== undefined);
301
+ const set = new Map();
302
+ let meet = false;
303
+ for (const property of own) {
304
+ const { sides, rank } = EDGE_KEYS[property.key.name.slice(prefix.length)];
305
+ for (const side of sides) {
306
+ const prior = set.get(side);
307
+ if (prior)
308
+ meet = true;
309
+ if (!prior || rank >= prior.rank)
310
+ set.set(side, { rank, value: property.value });
311
+ }
312
+ }
313
+ if (!meet)
314
+ continue;
315
+ // A key that holds every side it names stays; one a more specific key overrides is the
316
+ // sides it still holds, each its own key.
317
+ for (const property of own) {
318
+ const { sides } = EDGE_KEYS[property.key.name.slice(prefix.length)];
319
+ const held = sides.filter((side) => set.get(side)?.value === property.value);
320
+ if (held.length === sides.length)
321
+ continue;
322
+ const keys = held.map((side) => recast.types.builders.objectProperty(recast.types.builders.identifier(`${prefix}${side}`), property.value));
323
+ out.splice(out.indexOf(property), 1, ...keys);
324
+ }
325
+ }
326
+ return out;
327
+ }
328
+ /** A frame's own length keys (spec `objects.frame`). */
329
+ const FRAME_KEYS = new Set(['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight']);
330
+ /** A pinned view's physical edges, as React Native's keys (spec `objects.edges`). */
331
+ const PINNED_EDGES = new Set(['top', 'bottom', 'left', 'right']);
332
+ /**
333
+ * Geometry computed at render as the language's points (spec `points`):
334
+ * `width: itemSize` is `.frame({ width: itemSize })`, `top: insets.top + 8`
335
+ * `.position({ top: insets.top + 8 })` (which joins the view's `absolute`),
336
+ * `zIndex: count - index` `.zIndex(count - index)`. Only a value `computed`
337
+ * says the view works out as it renders; a number written out is a token.
338
+ */
339
+ function pointsDeclaration(key, value) {
340
+ const points = { node: value, hole: 'points' };
341
+ if (FRAME_KEYS.has(key))
342
+ return { name: 'frame', args: [{ [key]: points }] };
343
+ if (PINNED_EDGES.has(key))
344
+ return { name: 'position', args: [{ [key]: points }] };
345
+ if (key === 'zIndex')
346
+ return { name: 'zIndex', args: [points] };
347
+ return undefined;
348
+ }
349
+ /** A style's own declaration by its key, or undefined. */
350
+ function declared(object, key) {
351
+ return object.properties.find((property) => (n.ObjectProperty.check(property) || n.Property.check(property)) &&
352
+ !property.computed &&
353
+ n.Identifier.check(property.key) &&
354
+ property.key.name === key)?.value;
355
+ }
356
+ /**
357
+ * The side of a square a radius is half of (`width: size, height: size,
358
+ * borderRadius: size / 2`), which is `.corner('full')`: the box is a circle
359
+ * either way, since a radius over half the side draws as half of it. The
360
+ * style sets the side twice as one expression and no minimum that could grow
361
+ * the box past it.
362
+ */
363
+ function halfSquareSide(object, value) {
364
+ const [width, height] = [declared(object, 'width'), declared(object, 'height')];
365
+ if (!width ||
366
+ !height ||
367
+ declared(object, 'minWidth') ||
368
+ declared(object, 'minHeight') ||
369
+ !n.BinaryExpression.check(value) ||
370
+ value.operator !== '/' ||
371
+ !n.NumericLiteral.check(value.right) ||
372
+ value.right.value !== 2)
373
+ return undefined;
374
+ const side = recast.print(value.left).code;
375
+ return recast.print(width).code === side && recast.print(height).code === side
376
+ ? value.left
377
+ : undefined;
378
+ }
379
+ /**
380
+ * A percentage of the parent the language names: a frame's length token of
381
+ * that percentage (`maxHeight: '90%'` is `.frame({ maxHeight: '90%' })`,
382
+ * `width: '50%'` `.frame({ width: '1/2' })`), a pinned view's edge
383
+ * (`left: '25%'` is `.position({ left: '25%' })`).
384
+ */
385
+ function percentDeclaration(key, value) {
386
+ if (!n.StringLiteral.check(value))
387
+ return undefined;
388
+ const length = LENGTH_BY_PERCENT.get(value.value);
389
+ if (FRAME_KEYS.has(key) && length !== undefined)
390
+ return { name: 'frame', args: [{ [key]: length }] };
391
+ if (PINNED_EDGES.has(key) && INSET_PERCENT.has(value.value))
392
+ return { name: 'position', args: [{ [key]: value.value }] };
393
+ return undefined;
394
+ }
395
+ /**
396
+ * An object literal of a style as utilities, and the literal itself (for the
397
+ * parity's before side, where `styles.x` is not in scope). A spread `spreadOf`
398
+ * reads is what it writes; any other is a style built at runtime.
399
+ */
400
+ function styleUtilities(object, { read, spreadOf, numberOf, computed } = {}) {
401
+ if (!n.ObjectExpression.check(object))
402
+ return { ok: false, subject: 'style', why: 'a style that is no object literal' };
403
+ const classes = [];
404
+ const mods = [];
405
+ const held = [];
406
+ let literal = recast.print(object).code;
407
+ // A grow, shrink and basis that are one of Tailwind's flex utilities (`flex-1`) are `.flex()`.
408
+ const flex = flexToken(object);
409
+ if (flex)
410
+ mods.push({ subject: 'flexBasis', mod: { name: 'flex', args: [flex] } });
411
+ for (const property of sidesResolved(object.properties)) {
412
+ if (flex &&
413
+ (n.ObjectProperty.check(property) || n.Property.check(property)) &&
414
+ n.Identifier.check(property.key) &&
415
+ FLEX_KEYS.includes(property.key.name))
416
+ continue;
417
+ const spread = n.SpreadElement.check(property) ? spreadOf?.(property.argument) : undefined;
418
+ if (spread) {
419
+ classes.push(...spread.classes);
420
+ for (const mod of spread.mods)
421
+ mods.push({ subject: 'fontFamily', mod });
422
+ if (spread.literal !== undefined)
423
+ literal = literal.replace(recast.print(property).code, spread.literal);
424
+ continue;
425
+ }
426
+ if (!(n.ObjectProperty.check(property) || n.Property.check(property)) ||
427
+ property.computed ||
428
+ !n.Identifier.check(property.key))
429
+ return { ok: false, subject: 'style', why: 'a style built at runtime' };
430
+ const key = property.key.name;
431
+ const known = numberOf?.(property.value);
432
+ const value = known === undefined
433
+ ? property.value
434
+ : known < 0
435
+ ? recast.types.builders.unaryExpression('-', recast.types.builders.numericLiteral(-known))
436
+ : recast.types.builders.numericLiteral(known);
437
+ const side = key === 'borderRadius' ? halfSquareSide(object, value) : undefined;
438
+ if (side) {
439
+ mods.push({ subject: key, mod: { name: 'corner', args: ['full'] } });
440
+ if (computed?.(side))
441
+ held.push(side);
442
+ continue;
443
+ }
444
+ const mod = direct(key, value) ??
445
+ read?.(key, value) ??
446
+ (computed?.(value) ? pointsDeclaration(key, value) : undefined);
447
+ if (mod) {
448
+ for (const one of Array.isArray(mod) ? mod : [mod])
449
+ mods.push({ subject: key, mod: one });
450
+ continue;
451
+ }
452
+ // `inset` is its four edges, as React Native resolves it.
453
+ if (key === 'inset') {
454
+ const edges = ['top', 'right', 'bottom', 'left'].map((edge) => utility(edge, value));
455
+ if (edges.every((edge) => edge !== undefined)) {
456
+ classes.push(...edges);
457
+ continue;
458
+ }
459
+ }
460
+ const found = utility(key, value);
461
+ const percent = found ? undefined : percentDeclaration(key, value);
462
+ if (percent) {
463
+ mods.push({ subject: key, mod: percent });
464
+ continue;
465
+ }
466
+ if (!found)
467
+ return {
468
+ ok: false,
469
+ subject: key,
470
+ why: `a style \`${key}\` whose value no Tailwind utility writes exactly`,
471
+ };
472
+ classes.push(found);
473
+ }
474
+ return { ok: true, classes, mods, literal, held };
475
+ }
package/lib/table.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A number of points the view computes as it renders (`itemSize`,
3
+ * `insets.top + 8`), carried over as written: geometry only, a frame's
4
+ * lengths, a pinned view's edges and its stacking order (spec `points`).
5
+ */
6
+ export interface PointsArg {
7
+ readonly node: unknown;
8
+ readonly hole: 'points';
9
+ }
10
+ export type Arg = string | number | boolean | PointsArg | Readonly<Record<string, string | PointsArg>>;
11
+ export declare const isPoints: (arg: unknown) => arg is PointsArg;
12
+ /** Modifiers (or variants of them) as a comparable string, each points value by where it is written. */
13
+ export declare const modKey: (mods: unknown) => string;
14
+ /** One modifier call, as the codemod writes it. */
15
+ export interface Mod {
16
+ readonly name: string;
17
+ readonly args: readonly Arg[];
18
+ }
19
+ export type Status = 'mapped' | 'structure' | 'drop' | 'token' | 'appToken' | 'modifier' | 'motion' | 'app';
20
+ export interface Entry {
21
+ readonly status: Status;
22
+ /** The table's words for the utility. */
23
+ readonly language: string;
24
+ /** The chain, when the table maps the utility to plain literal modifiers. */
25
+ readonly mods: readonly Mod[] | null;
26
+ readonly scale?: string;
27
+ readonly value?: string;
28
+ }
29
+ export interface Table {
30
+ readonly utilities: ReadonlyMap<string, Entry>;
31
+ /** What a bare Bloom icon element (no fill) becomes: its primary paint. */
32
+ readonly bareIcon: readonly Mod[];
33
+ }
34
+ /**
35
+ * The Bloom language package the codemod writes for: the one installed beside
36
+ * it (its peer), whose spec, exports and className table it reads.
37
+ */
38
+ export declare const LANGUAGE_PACKAGE: string;
39
+ /** `.a('x').b({ k: 'v' })` as mods, or null when it is anything but literal calls. */
40
+ export declare function chainOf(language: string): Mod[] | null;
41
+ export declare function loadTable(path?: string): Table;
package/lib/table.js ADDED
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LANGUAGE_PACKAGE = exports.modKey = exports.isPoints = void 0;
4
+ exports.chainOf = chainOf;
5
+ exports.loadTable = loadTable;
6
+ /**
7
+ * The className table (`packages/bloom-language/codemod/classnames.generated.json`)
8
+ * as modifier calls: each utility the table maps to a plain chain of literal
9
+ * modifiers is read into `Mod`s; everything else keeps its status and the
10
+ * table's words, which the resolver reports.
11
+ */
12
+ const node_fs_1 = require("node:fs");
13
+ const node_module_1 = require("node:module");
14
+ const node_path_1 = require("node:path");
15
+ const parser_1 = require("@babel/parser");
16
+ const isPoints = (arg) => typeof arg === 'object' && arg !== null && arg.hole === 'points';
17
+ exports.isPoints = isPoints;
18
+ /** Modifiers (or variants of them) as a comparable string, each points value by where it is written. */
19
+ const modKey = (mods) => JSON.stringify(mods, (_, value) => (0, exports.isPoints)(value)
20
+ ? `#${value.node.start}:${value.node.end}`
21
+ : value);
22
+ exports.modKey = modKey;
23
+ /**
24
+ * The Bloom language package the codemod writes for: the one installed beside
25
+ * it (its peer), whose spec, exports and className table it reads.
26
+ */
27
+ exports.LANGUAGE_PACKAGE = (0, node_path_1.dirname)((0, node_module_1.createRequire)(__filename).resolve('@oxy.so/bloom-language/package.json'));
28
+ function literal(node) {
29
+ switch (node.type) {
30
+ case 'StringLiteral':
31
+ case 'NumericLiteral':
32
+ case 'BooleanLiteral':
33
+ return node.value;
34
+ case 'ObjectExpression': {
35
+ const out = {};
36
+ for (const property of node.properties) {
37
+ if (property.type !== 'ObjectProperty' || property.computed)
38
+ return undefined;
39
+ const key = property.key.type === 'Identifier'
40
+ ? property.key.name
41
+ : property.key.type === 'StringLiteral'
42
+ ? property.key.value
43
+ : undefined;
44
+ if (key === undefined || property.value.type !== 'StringLiteral')
45
+ return undefined;
46
+ out[key] = property.value.value;
47
+ }
48
+ return out;
49
+ }
50
+ default:
51
+ return undefined;
52
+ }
53
+ }
54
+ /** `.a('x').b({ k: 'v' })` as mods, or null when it is anything but literal calls. */
55
+ function chainOf(language) {
56
+ let expression;
57
+ try {
58
+ expression = (0, parser_1.parseExpression)(`$${language}`);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ const mods = [];
64
+ let at = expression;
65
+ while (at.type === 'CallExpression') {
66
+ const callee = at.callee;
67
+ if (callee.type !== 'MemberExpression' || callee.property.type !== 'Identifier')
68
+ return null;
69
+ const args = [];
70
+ for (const argument of at.arguments) {
71
+ if (argument.type === 'SpreadElement' || argument.type === 'ArgumentPlaceholder')
72
+ return null;
73
+ const value = literal(argument);
74
+ if (value === undefined)
75
+ return null;
76
+ args.push(value);
77
+ }
78
+ mods.unshift({ name: callee.property.name, args });
79
+ at = callee.object;
80
+ }
81
+ return at.type === 'Identifier' && at.name === '$' && mods.length > 0 ? mods : null;
82
+ }
83
+ function loadTable(path = (0, node_path_1.join)(exports.LANGUAGE_PACKAGE, 'codemod/classnames.generated.json')) {
84
+ const raw = JSON.parse((0, node_fs_1.readFileSync)(path, 'utf8'));
85
+ const utilities = new Map();
86
+ for (const [name, entry] of Object.entries(raw.utilities)) {
87
+ utilities.set(name, {
88
+ status: entry.status,
89
+ language: entry.language,
90
+ mods: entry.status === 'mapped' ? chainOf(entry.language) : null,
91
+ scale: entry.scale,
92
+ value: entry.value,
93
+ });
94
+ }
95
+ return { utilities, bareIcon: chainOf(raw.icons.bare) ?? [] };
96
+ }
@@ -0,0 +1,24 @@
1
+ /** Bloom's own entry: Tailwind, NativeWind's theme and Bloom's tokens, what the className table was built against. */
2
+ export declare const BLOOM_BASELINE_CSS: string;
3
+ /** Package roots given by hand (a package the app installs that Bloom does not, read from its own repository). */
4
+ export type PackageRoots = Readonly<Record<string, string>>;
5
+ /** The directory of package `name` in the first `node_modules` above any of `from`, in order. */
6
+ export declare function packageRoot(name: string, from: readonly string[]): string | undefined;
7
+ export interface Stylesheet {
8
+ /** The CSS Tailwind writes for these classes, as the app's build writes it. */
9
+ build(classes: readonly string[]): string;
10
+ }
11
+ /**
12
+ * Compiles `css` (an app's entry, read from `from`) as Tailwind does in the
13
+ * app's build; its packages are read from `roots`, then above `from`, then
14
+ * above `packages` (default: this package).
15
+ */
16
+ export declare function tailwind(css: string, from: string, roots?: PackageRoots, packages?: string): Promise<Stylesheet>;
17
+ /**
18
+ * The class candidates in a package's built JavaScript, as an app's `@source`
19
+ * glob over it (`node_modules/@oxy.so/bloom/lib/**\/*.{js,jsx}`) hands them to
20
+ * Tailwind: every word of each file, split at whitespace, quotes and template
21
+ * holes. Tailwind writes CSS only for the words that are utilities, so a word
22
+ * that is not one adds nothing.
23
+ */
24
+ export declare function packageCandidates(dir: string): string[];