@plumeria/utils 0.29.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,3 @@
1
+ export { CSSObject, FileStyles } from './types';
2
+ export { createCSS, createVars, createTokens } from './transform';
3
+ export { scanForDefineConsts, scanForDefineTokens, scanForKeyframes, scanForViewTransition, objectExpressionToObject, collectLocalConsts, traverse, t, tables, } from './parser';
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tables = exports.t = exports.traverse = exports.collectLocalConsts = exports.objectExpressionToObject = exports.scanForViewTransition = exports.scanForKeyframes = exports.scanForDefineTokens = exports.scanForDefineConsts = exports.createTokens = exports.createVars = exports.createCSS = void 0;
4
+ var transform_1 = require("./transform");
5
+ Object.defineProperty(exports, "createCSS", { enumerable: true, get: function () { return transform_1.createCSS; } });
6
+ Object.defineProperty(exports, "createVars", { enumerable: true, get: function () { return transform_1.createVars; } });
7
+ Object.defineProperty(exports, "createTokens", { enumerable: true, get: function () { return transform_1.createTokens; } });
8
+ var parser_1 = require("./parser");
9
+ Object.defineProperty(exports, "scanForDefineConsts", { enumerable: true, get: function () { return parser_1.scanForDefineConsts; } });
10
+ Object.defineProperty(exports, "scanForDefineTokens", { enumerable: true, get: function () { return parser_1.scanForDefineTokens; } });
11
+ Object.defineProperty(exports, "scanForKeyframes", { enumerable: true, get: function () { return parser_1.scanForKeyframes; } });
12
+ Object.defineProperty(exports, "scanForViewTransition", { enumerable: true, get: function () { return parser_1.scanForViewTransition; } });
13
+ Object.defineProperty(exports, "objectExpressionToObject", { enumerable: true, get: function () { return parser_1.objectExpressionToObject; } });
14
+ Object.defineProperty(exports, "collectLocalConsts", { enumerable: true, get: function () { return parser_1.collectLocalConsts; } });
15
+ Object.defineProperty(exports, "traverse", { enumerable: true, get: function () { return parser_1.traverse; } });
16
+ Object.defineProperty(exports, "t", { enumerable: true, get: function () { return parser_1.t; } });
17
+ Object.defineProperty(exports, "tables", { enumerable: true, get: function () { return parser_1.tables; } });
@@ -0,0 +1,43 @@
1
+ import type { CSSObject, ConstTable, KeyframesHashTable, KeyframesObjectTable, TokensTable, ViewTransitionObjectTable, ViewTransitionHashTable, Tables } from './types';
2
+ import { Module, CallExpression, Identifier, KeyValueProperty, StringLiteral, NumericLiteral, BooleanLiteral, ObjectExpression, MemberExpression, TemplateLiteral, BinaryExpression, UnaryExpression, VariableDeclaration, VariableDeclarator, ExportDeclaration } from '@swc/core';
3
+ export declare const t: {
4
+ isObjectExpression: (node: any) => node is ObjectExpression;
5
+ isObjectProperty: (node: any) => node is KeyValueProperty;
6
+ isIdentifier: (node: any, opts?: {
7
+ name?: string;
8
+ }) => node is Identifier;
9
+ isStringLiteral: (node: any) => node is StringLiteral;
10
+ isNumericLiteral: (node: any) => node is NumericLiteral;
11
+ isBooleanLiteral: (node: any) => node is BooleanLiteral;
12
+ isMemberExpression: (node: any) => node is MemberExpression;
13
+ isUnaryExpression: (node: any) => node is UnaryExpression;
14
+ isTemplateLiteral: (node: any) => node is TemplateLiteral;
15
+ isBinaryExpression: (node: any) => node is BinaryExpression;
16
+ isVariableDeclaration: (node: any) => node is VariableDeclaration;
17
+ isExportDeclaration: (node: any) => node is ExportDeclaration;
18
+ isVariableDeclarator: (node: any) => node is VariableDeclarator;
19
+ isCallExpression: (node: any) => node is CallExpression;
20
+ isNullLiteral: (node: any) => boolean;
21
+ };
22
+ export declare function traverse(node: Module, visitor: {
23
+ [key: string]: (path: {
24
+ node: any;
25
+ stop: () => void;
26
+ }) => void;
27
+ }): void;
28
+ export declare const tables: Tables;
29
+ export declare function objectExpressionToObject(node: ObjectExpression, constTable: ConstTable, keyframesHashTable: KeyframesHashTable, viewTransitionHashTable: ViewTransitionHashTable, tokensTable: TokensTable): CSSObject;
30
+ export declare function collectLocalConsts(ast: Module): Record<string, any>;
31
+ export declare function scanForKeyframes(addDependency: (path: string) => void): {
32
+ keyframesHashTableLocal: KeyframesHashTable;
33
+ keyframesObjectTableLocal: KeyframesObjectTable;
34
+ };
35
+ export declare function scanForViewTransition(addDependency: (path: string) => void): {
36
+ viewTransitionHashTableLocal: ViewTransitionHashTable;
37
+ viewTransitionObjectTableLocal: ViewTransitionObjectTable;
38
+ };
39
+ export declare function scanForDefineConsts(addDependency: (path: string) => void): ConstTable;
40
+ export declare function scanForDefineTokens(addDependency: (path: string) => void): {
41
+ tokensTableLocal: Record<string, Record<string, any>>;
42
+ defineTokensObjectTableLocal: Record<string, any>;
43
+ };
package/dist/parser.js ADDED
@@ -0,0 +1,543 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.tables = exports.t = void 0;
7
+ exports.traverse = traverse;
8
+ exports.objectExpressionToObject = objectExpressionToObject;
9
+ exports.collectLocalConsts = collectLocalConsts;
10
+ exports.scanForKeyframes = scanForKeyframes;
11
+ exports.scanForViewTransition = scanForViewTransition;
12
+ exports.scanForDefineConsts = scanForDefineConsts;
13
+ exports.scanForDefineTokens = scanForDefineTokens;
14
+ const core_1 = require("@swc/core");
15
+ const path_1 = __importDefault(require("path"));
16
+ const fs_1 = __importDefault(require("fs"));
17
+ const zss_engine_1 = require("zss-engine");
18
+ exports.t = {
19
+ isObjectExpression: (node) => node?.type === 'ObjectExpression',
20
+ isObjectProperty: (node) => node?.type === 'KeyValueProperty',
21
+ isIdentifier: (node, opts) => {
22
+ if (node?.type !== 'Identifier')
23
+ return false;
24
+ if (opts?.name && node.value !== opts.name)
25
+ return false;
26
+ return true;
27
+ },
28
+ isStringLiteral: (node) => node?.type === 'StringLiteral',
29
+ isNumericLiteral: (node) => node?.type === 'NumericLiteral',
30
+ isBooleanLiteral: (node) => node?.type === 'BooleanLiteral',
31
+ isMemberExpression: (node) => node?.type === 'MemberExpression',
32
+ isUnaryExpression: (node) => node?.type === 'UnaryExpression',
33
+ isTemplateLiteral: (node) => node?.type === 'TemplateLiteral',
34
+ isBinaryExpression: (node) => node?.type === 'BinaryExpression',
35
+ isVariableDeclaration: (node) => node?.type === 'VariableDeclaration',
36
+ isExportDeclaration: (node) => node?.type === 'ExportDeclaration',
37
+ isVariableDeclarator: (node) => node?.type === 'VariableDeclarator',
38
+ isCallExpression: (node) => node?.type === 'CallExpression',
39
+ isNullLiteral: (node) => node?.type === 'NullLiteral',
40
+ };
41
+ function traverse(node, visitor) {
42
+ let stopped = false;
43
+ const stop = () => {
44
+ stopped = true;
45
+ };
46
+ function walk(n) {
47
+ if (stopped)
48
+ return;
49
+ if (!n || typeof n !== 'object')
50
+ return;
51
+ if (n.type && visitor[n.type]) {
52
+ visitor[n.type]({ node: n, stop });
53
+ }
54
+ for (const key in n) {
55
+ if (key === 'span')
56
+ continue;
57
+ const child = n[key];
58
+ if (Array.isArray(child)) {
59
+ for (const c of child) {
60
+ walk(c);
61
+ }
62
+ }
63
+ else {
64
+ walk(child);
65
+ }
66
+ }
67
+ }
68
+ walk(node);
69
+ }
70
+ const PROJECT_ROOT = process.cwd().split('node_modules')[0];
71
+ const PATTERN_PATH = path_1.default.join(PROJECT_ROOT, '**/*.{js,jsx,ts,tsx}');
72
+ const GLOB_OPTIONS = {
73
+ exclude: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.next/**'],
74
+ cwd: PROJECT_ROOT,
75
+ };
76
+ exports.tables = {
77
+ constTable: {},
78
+ tokensTable: {},
79
+ keyframesHashTable: {},
80
+ keyframesObjectTable: {},
81
+ viewTransitionHashTable: {},
82
+ viewTransitionObjectTable: {},
83
+ defineTokensObjectTable: {},
84
+ };
85
+ function objectExpressionToObject(node, constTable, keyframesHashTable, viewTransitionHashTable, tokensTable) {
86
+ const obj = {};
87
+ node.properties.forEach((prop) => {
88
+ if (!exports.t.isObjectProperty(prop))
89
+ return;
90
+ const key = getPropertyKey(prop.key, constTable);
91
+ if (!key)
92
+ return;
93
+ const val = prop.value;
94
+ if (exports.t.isIdentifier(val) || exports.t.isMemberExpression(val)) {
95
+ const resolvedKeyframe = resolveKeyframesTableMemberExpression(val, keyframesHashTable);
96
+ if (resolvedKeyframe !== undefined) {
97
+ obj[key] = 'kf-' + resolvedKeyframe;
98
+ return;
99
+ }
100
+ const resolvedViewTransitioin = resolveViewTransitionTableMemberExpression(val, viewTransitionHashTable);
101
+ if (resolvedViewTransitioin !== undefined) {
102
+ obj[key] = 'vt-' + resolvedViewTransitioin;
103
+ return;
104
+ }
105
+ const resolvedTheme = resolveTokensTableMemberExpressionByNode(val, tokensTable);
106
+ if (resolvedTheme !== undefined) {
107
+ obj[key] = resolvedTheme;
108
+ return;
109
+ }
110
+ }
111
+ if (exports.t.isStringLiteral(val) ||
112
+ exports.t.isNumericLiteral(val) ||
113
+ exports.t.isBooleanLiteral(val)) {
114
+ obj[key] = val.value;
115
+ }
116
+ else if (exports.t.isUnaryExpression(val)) {
117
+ obj[key] = evaluateUnaryExpression(val);
118
+ }
119
+ else if (exports.t.isObjectExpression(val)) {
120
+ obj[key] = objectExpressionToObject(val, constTable, keyframesHashTable, viewTransitionHashTable, tokensTable);
121
+ }
122
+ else if (exports.t.isMemberExpression(val)) {
123
+ const resolved = resolveConstTableMemberExpression(val, constTable);
124
+ obj[key] = resolved !== undefined ? resolved : '[unresolved]';
125
+ }
126
+ else if (exports.t.isIdentifier(val)) {
127
+ if (constTable[val.value] !== undefined) {
128
+ obj[key] = constTable[val.value];
129
+ }
130
+ else {
131
+ obj[key] = '[unresolved identifier]';
132
+ }
133
+ }
134
+ else {
135
+ obj[key] = '[unsupported value type]';
136
+ }
137
+ });
138
+ return obj;
139
+ }
140
+ function collectLocalConsts(ast) {
141
+ const localConsts = {};
142
+ traverse(ast, {
143
+ VariableDeclarator({ node }) {
144
+ if (exports.t.isIdentifier(node.id) && node.init) {
145
+ if (exports.t.isStringLiteral(node.init)) {
146
+ localConsts[node.id.value] = node.init.value;
147
+ }
148
+ else if (exports.t.isObjectExpression(node.init)) {
149
+ localConsts[node.id.value] = objectExpressionToObject(node.init, localConsts, exports.tables.keyframesHashTable, exports.tables.viewTransitionHashTable, exports.tables.tokensTable);
150
+ }
151
+ }
152
+ },
153
+ });
154
+ return localConsts;
155
+ }
156
+ function getPropertyKey(node, constTable) {
157
+ if (exports.t.isIdentifier(node)) {
158
+ if (constTable[node.value] && typeof constTable[node.value] === 'string') {
159
+ return constTable[node.value];
160
+ }
161
+ return node.value;
162
+ }
163
+ if (exports.t.isStringLiteral(node)) {
164
+ return node.value;
165
+ }
166
+ if (node.type === 'Computed') {
167
+ const expr = node.expression;
168
+ if (exports.t.isStringLiteral(expr)) {
169
+ return expr.value;
170
+ }
171
+ if (exports.t.isIdentifier(expr)) {
172
+ if (constTable[expr.value] &&
173
+ typeof constTable[expr.value] === 'string') {
174
+ return constTable[expr.value];
175
+ }
176
+ }
177
+ if (exports.t.isMemberExpression(expr)) {
178
+ const result = resolveConstTableMemberExpression(expr, constTable);
179
+ if (typeof result === 'string')
180
+ return result;
181
+ }
182
+ if (exports.t.isTemplateLiteral(expr)) {
183
+ return evaluateTemplateLiteral(expr, constTable);
184
+ }
185
+ if (exports.t.isBinaryExpression(expr)) {
186
+ return evaluateBinaryExpression(expr, constTable);
187
+ }
188
+ return '';
189
+ }
190
+ if (exports.t.isTemplateLiteral(node)) {
191
+ return evaluateTemplateLiteral(node, constTable);
192
+ }
193
+ if (exports.t.isBinaryExpression(node)) {
194
+ return evaluateBinaryExpression(node, constTable);
195
+ }
196
+ return '';
197
+ }
198
+ function evaluateTemplateLiteral(node, constTable) {
199
+ let result = '';
200
+ for (let i = 0; i < node.quasis.length; i++) {
201
+ result += node.quasis[i].cooked || node.quasis[i].raw;
202
+ if (i < node.expressions.length) {
203
+ const expr = node.expressions[i];
204
+ const evaluatedExpr = evaluateExpression(expr, constTable);
205
+ result += String(evaluatedExpr);
206
+ }
207
+ }
208
+ return result;
209
+ }
210
+ function evaluateBinaryExpression(node, constTable) {
211
+ const left = evaluateExpression(node.left, constTable);
212
+ const right = evaluateExpression(node.right, constTable);
213
+ if (node.operator === '+') {
214
+ return String(left) + String(right);
215
+ }
216
+ throw new Error(`Unsupported binary operator: ${node.operator}`);
217
+ }
218
+ function evaluateExpression(node, constTable) {
219
+ if (exports.t.isStringLiteral(node)) {
220
+ return node.value;
221
+ }
222
+ if (exports.t.isNumericLiteral(node)) {
223
+ return node.value;
224
+ }
225
+ if (exports.t.isBooleanLiteral(node)) {
226
+ return node.value;
227
+ }
228
+ if (exports.t.isNullLiteral(node)) {
229
+ return null;
230
+ }
231
+ if (exports.t.isIdentifier(node)) {
232
+ if (constTable[node.value] !== undefined) {
233
+ return constTable[node.value];
234
+ }
235
+ if (exports.tables.keyframesHashTable[node.value] !== undefined) {
236
+ return exports.tables.keyframesHashTable[node.value];
237
+ }
238
+ if (exports.tables.viewTransitionHashTable[node.value] !== undefined) {
239
+ return exports.tables.viewTransitionHashTable[node.value];
240
+ }
241
+ return `[unresolved: ${node.value}]`;
242
+ }
243
+ if (exports.t.isMemberExpression(node)) {
244
+ const resolved = resolveConstTableMemberExpression(node, constTable);
245
+ if (resolved !== undefined) {
246
+ return resolved;
247
+ }
248
+ const resolvedTheme = resolveTokensTableMemberExpressionByNode(node, exports.tables.tokensTable);
249
+ if (resolvedTheme !== undefined) {
250
+ return resolvedTheme;
251
+ }
252
+ return `[unresolved member expression]`;
253
+ }
254
+ if (exports.t.isBinaryExpression(node)) {
255
+ return evaluateBinaryExpression(node, constTable);
256
+ }
257
+ if (exports.t.isTemplateLiteral(node)) {
258
+ return evaluateTemplateLiteral(node, constTable);
259
+ }
260
+ if (exports.t.isUnaryExpression(node)) {
261
+ return evaluateUnaryExpression(node);
262
+ }
263
+ throw new Error(`Unsupported expression type: ${node.type}`);
264
+ }
265
+ function evaluateUnaryExpression(node) {
266
+ const arg = node.argument;
267
+ switch (node.operator) {
268
+ case '-':
269
+ if (exports.t.isNumericLiteral(arg))
270
+ return -arg.value;
271
+ break;
272
+ case '+':
273
+ if (exports.t.isNumericLiteral(arg))
274
+ return +arg.value;
275
+ break;
276
+ default:
277
+ throw new Error(`Unsupported unary operator: ${node.operator}`);
278
+ }
279
+ throw new Error(`Unsupported UnaryExpression argument type: ${arg.type}`);
280
+ }
281
+ function resolveKeyframesTableMemberExpression(node, keyframesHashTable) {
282
+ if (exports.t.isIdentifier(node)) {
283
+ return keyframesHashTable[node.value];
284
+ }
285
+ if (exports.t.isMemberExpression(node)) {
286
+ if (exports.t.isIdentifier(node.object)) {
287
+ return keyframesHashTable[node.object.value];
288
+ }
289
+ }
290
+ }
291
+ function resolveViewTransitionTableMemberExpression(node, viewTransitionHashTable) {
292
+ if (exports.t.isIdentifier(node)) {
293
+ return viewTransitionHashTable[node.value];
294
+ }
295
+ if (exports.t.isMemberExpression(node)) {
296
+ if (exports.t.isIdentifier(node.object)) {
297
+ return viewTransitionHashTable[node.object.value];
298
+ }
299
+ }
300
+ }
301
+ function resolveConstTableMemberExpression(node, constTable) {
302
+ if (exports.t.isIdentifier(node.object) && exports.t.isIdentifier(node.property)) {
303
+ const varName = node.object.value;
304
+ const key = node.property.value;
305
+ const tableValue = constTable[varName];
306
+ if (tableValue && typeof tableValue === 'object' && key in tableValue) {
307
+ return tableValue[key];
308
+ }
309
+ }
310
+ return undefined;
311
+ }
312
+ function resolveTokensTableMemberExpressionByNode(node, tokensTable) {
313
+ if (exports.t.isMemberExpression(node) && exports.t.isIdentifier(node.object)) {
314
+ const varName = node.object.value;
315
+ let key;
316
+ if (exports.t.isIdentifier(node.property)) {
317
+ key = node.property.value;
318
+ }
319
+ else if (node.property.type === 'Computed' &&
320
+ exports.t.isStringLiteral(node.property.expression)) {
321
+ key = node.property.expression.value;
322
+ }
323
+ if (key &&
324
+ tokensTable[varName] &&
325
+ tokensTable[varName][key] !== undefined) {
326
+ const cssVarName = (0, zss_engine_1.camelToKebabCase)(key);
327
+ return `var(--${cssVarName})`;
328
+ }
329
+ }
330
+ return undefined;
331
+ }
332
+ function scanForKeyframes(addDependency) {
333
+ const keyframesHashTableLocal = {};
334
+ const keyframesObjectTableLocal = {};
335
+ const files = fs_1.default.globSync(PATTERN_PATH, GLOB_OPTIONS);
336
+ for (const filePath of files) {
337
+ if (!isCSSDefineFile(filePath, 'keyframes'))
338
+ continue;
339
+ addDependency(filePath);
340
+ const source = fs_1.default.readFileSync(filePath, 'utf8');
341
+ const ast = (0, core_1.parseSync)(source, {
342
+ syntax: 'typescript',
343
+ tsx: true,
344
+ target: 'es2022',
345
+ });
346
+ for (const node of ast.body) {
347
+ let declarations = [];
348
+ if (exports.t.isVariableDeclaration(node)) {
349
+ declarations = node.declarations;
350
+ }
351
+ else if (exports.t.isExportDeclaration(node) &&
352
+ exports.t.isVariableDeclaration(node.declaration)) {
353
+ declarations = node.declaration.declarations;
354
+ }
355
+ for (const decl of declarations) {
356
+ if (exports.t.isVariableDeclarator(decl) &&
357
+ exports.t.isIdentifier(decl.id) &&
358
+ decl.init &&
359
+ exports.t.isCallExpression(decl.init) &&
360
+ exports.t.isMemberExpression(decl.init.callee) &&
361
+ exports.t.isIdentifier(decl.init.callee.object, { name: 'css' }) &&
362
+ exports.t.isIdentifier(decl.init.callee.property, { name: 'keyframes' }) &&
363
+ decl.init.arguments.length > 0 &&
364
+ exports.t.isObjectExpression(decl.init.arguments[0].expression)) {
365
+ const varName = decl.id.value;
366
+ const obj = objectExpressionToObject(decl.init.arguments[0].expression, exports.tables.constTable, keyframesHashTableLocal, exports.tables.viewTransitionHashTable, exports.tables.tokensTable);
367
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
368
+ keyframesHashTableLocal[varName] = hash;
369
+ keyframesObjectTableLocal[hash] = obj;
370
+ }
371
+ }
372
+ }
373
+ }
374
+ return {
375
+ keyframesHashTableLocal,
376
+ keyframesObjectTableLocal,
377
+ };
378
+ }
379
+ function scanForViewTransition(addDependency) {
380
+ const viewTransitionHashTableLocal = {};
381
+ const viewTransitionObjectTableLocal = {};
382
+ const files = fs_1.default.globSync(PATTERN_PATH, GLOB_OPTIONS);
383
+ for (const filePath of files) {
384
+ if (!isCSSDefineFile(filePath, 'viewTransition'))
385
+ continue;
386
+ addDependency(filePath);
387
+ const source = fs_1.default.readFileSync(filePath, 'utf8');
388
+ const ast = (0, core_1.parseSync)(source, {
389
+ syntax: 'typescript',
390
+ tsx: true,
391
+ target: 'es2022',
392
+ });
393
+ for (const node of ast.body) {
394
+ let declarations = [];
395
+ if (exports.t.isVariableDeclaration(node)) {
396
+ declarations = node.declarations;
397
+ }
398
+ else if (exports.t.isExportDeclaration(node) &&
399
+ exports.t.isVariableDeclaration(node.declaration)) {
400
+ declarations = node.declaration.declarations;
401
+ }
402
+ for (const decl of declarations) {
403
+ if (exports.t.isVariableDeclarator(decl) &&
404
+ exports.t.isIdentifier(decl.id) &&
405
+ decl.init &&
406
+ exports.t.isCallExpression(decl.init) &&
407
+ exports.t.isMemberExpression(decl.init.callee) &&
408
+ exports.t.isIdentifier(decl.init.callee.object, { name: 'css' }) &&
409
+ exports.t.isIdentifier(decl.init.callee.property, {
410
+ name: 'viewTransition',
411
+ }) &&
412
+ decl.init.arguments.length > 0 &&
413
+ exports.t.isObjectExpression(decl.init.arguments[0].expression)) {
414
+ const varName = decl.id.value;
415
+ const obj = objectExpressionToObject(decl.init.arguments[0].expression, exports.tables.constTable, exports.tables.keyframesHashTable, viewTransitionHashTableLocal, exports.tables.tokensTable);
416
+ const hash = (0, zss_engine_1.genBase36Hash)(obj, 1, 8);
417
+ viewTransitionHashTableLocal[varName] = hash;
418
+ viewTransitionObjectTableLocal[hash] = obj;
419
+ }
420
+ }
421
+ }
422
+ }
423
+ return {
424
+ viewTransitionHashTableLocal,
425
+ viewTransitionObjectTableLocal,
426
+ };
427
+ }
428
+ function scanForDefineConsts(addDependency) {
429
+ const constTableLocal = {};
430
+ const files = fs_1.default.globSync(PATTERN_PATH, GLOB_OPTIONS);
431
+ for (const filePath of files) {
432
+ if (!isCSSDefineFile(filePath, 'defineConsts'))
433
+ continue;
434
+ addDependency(filePath);
435
+ const source = fs_1.default.readFileSync(filePath, 'utf8');
436
+ const ast = (0, core_1.parseSync)(source, {
437
+ syntax: 'typescript',
438
+ tsx: true,
439
+ target: 'es2022',
440
+ });
441
+ for (const node of ast.body) {
442
+ let declarations = [];
443
+ if (exports.t.isVariableDeclaration(node)) {
444
+ declarations = node.declarations;
445
+ }
446
+ else if (exports.t.isExportDeclaration(node) &&
447
+ exports.t.isVariableDeclaration(node.declaration)) {
448
+ declarations = node.declaration.declarations;
449
+ }
450
+ for (const decl of declarations) {
451
+ if (exports.t.isVariableDeclarator(decl) &&
452
+ exports.t.isIdentifier(decl.id) &&
453
+ decl.init &&
454
+ exports.t.isCallExpression(decl.init) &&
455
+ exports.t.isMemberExpression(decl.init.callee) &&
456
+ exports.t.isIdentifier(decl.init.callee.object, { name: 'css' }) &&
457
+ exports.t.isIdentifier(decl.init.callee.property, { name: 'defineConsts' }) &&
458
+ decl.init.arguments.length > 0 &&
459
+ exports.t.isObjectExpression(decl.init.arguments[0].expression)) {
460
+ const varName = decl.id.value;
461
+ const obj = objectExpressionToObject(decl.init.arguments[0].expression, constTableLocal, exports.tables.keyframesHashTable, exports.tables.viewTransitionHashTable, exports.tables.tokensTable);
462
+ constTableLocal[varName] = obj;
463
+ }
464
+ }
465
+ }
466
+ }
467
+ return constTableLocal;
468
+ }
469
+ function scanForDefineTokens(addDependency) {
470
+ const tokensTableLocal = {};
471
+ const defineTokensObjectTableLocal = {};
472
+ const files = fs_1.default.globSync(PATTERN_PATH, GLOB_OPTIONS);
473
+ for (const filePath of files) {
474
+ if (!isCSSDefineFile(filePath, 'defineTokens'))
475
+ continue;
476
+ addDependency(filePath);
477
+ const source = fs_1.default.readFileSync(filePath, 'utf8');
478
+ const ast = (0, core_1.parseSync)(source, {
479
+ syntax: 'typescript',
480
+ tsx: true,
481
+ target: 'es2022',
482
+ });
483
+ for (const node of ast.body) {
484
+ let declarations = [];
485
+ if (exports.t.isVariableDeclaration(node)) {
486
+ declarations = node.declarations;
487
+ }
488
+ else if (exports.t.isExportDeclaration(node) &&
489
+ exports.t.isVariableDeclaration(node.declaration)) {
490
+ declarations = node.declaration.declarations;
491
+ }
492
+ for (const decl of declarations) {
493
+ if (exports.t.isVariableDeclarator(decl) &&
494
+ exports.t.isIdentifier(decl.id) &&
495
+ decl.init &&
496
+ exports.t.isCallExpression(decl.init) &&
497
+ exports.t.isMemberExpression(decl.init.callee) &&
498
+ exports.t.isIdentifier(decl.init.callee.object, { name: 'css' }) &&
499
+ exports.t.isIdentifier(decl.init.callee.property, { name: 'defineTokens' }) &&
500
+ decl.init.arguments.length > 0 &&
501
+ exports.t.isObjectExpression(decl.init.arguments[0].expression)) {
502
+ const varName = decl.id.value;
503
+ const obj = objectExpressionToObject(decl.init.arguments[0].expression, exports.tables.constTable, exports.tables.keyframesHashTable, exports.tables.viewTransitionHashTable, tokensTableLocal);
504
+ tokensTableLocal[varName] = obj;
505
+ defineTokensObjectTableLocal[varName] = obj;
506
+ }
507
+ }
508
+ }
509
+ }
510
+ return { tokensTableLocal, defineTokensObjectTableLocal };
511
+ }
512
+ function isCSSDefineFile(filePath, target) {
513
+ if (fs_1.default.statSync(filePath).isDirectory())
514
+ return false;
515
+ const code = fs_1.default.readFileSync(filePath, 'utf8');
516
+ let ast;
517
+ try {
518
+ ast = (0, core_1.parseSync)(code, {
519
+ syntax: 'typescript',
520
+ tsx: true,
521
+ target: 'es2022',
522
+ });
523
+ }
524
+ catch (err) {
525
+ console.log(err);
526
+ return false;
527
+ }
528
+ let found = false;
529
+ traverse(ast, {
530
+ CallExpression({ node, stop }) {
531
+ const callee = node.callee;
532
+ if (callee.type === 'MemberExpression' &&
533
+ callee.object.type === 'Identifier' &&
534
+ callee.object.value === 'css' &&
535
+ callee.property.type === 'Identifier' &&
536
+ callee.property.value === target) {
537
+ found = true;
538
+ stop();
539
+ }
540
+ },
541
+ });
542
+ return found;
543
+ }
@@ -0,0 +1,5 @@
1
+ import type { CSSProperties, CreateStyleType, CreateTokens, CreateValues } from 'zss-engine';
2
+ declare function createCSS<T extends Record<string, CSSProperties>>(object: CreateStyleType<T>): string;
3
+ declare const createVars: <const T extends CreateValues>(object: T) => Record<string, CreateValues>;
4
+ declare const createTokens: <const T extends CreateTokens>(object: T) => Record<string, Record<string, string | number | object>>;
5
+ export { createCSS, createVars, createTokens };
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTokens = exports.createVars = void 0;
4
+ exports.createCSS = createCSS;
5
+ const zss_engine_1 = require("zss-engine");
6
+ function compileToSingleCSS(object) {
7
+ const baseSheets = [];
8
+ const querySheets = [];
9
+ const processedHashes = new Set();
10
+ Object.entries(object).forEach(([key, styleObj]) => {
11
+ const flat = {};
12
+ const nonFlat = {};
13
+ (0, zss_engine_1.splitAtomicAndNested)(styleObj, flat, nonFlat);
14
+ const finalFlat = (0, zss_engine_1.overrideLonghand)(flat);
15
+ const records = [];
16
+ Object.entries(finalFlat).forEach(([prop, value]) => {
17
+ const hashes = new Set();
18
+ const sheets = new Set();
19
+ (0, zss_engine_1.processAtomicProps)({ [prop]: value }, hashes, sheets);
20
+ const hashArray = [...hashes];
21
+ const sheetArray = [...sheets];
22
+ const baseSheetParts = [];
23
+ const baseHashParts = [];
24
+ const querySheetParts = [];
25
+ const queryHashParts = [];
26
+ for (let i = 0; i < sheetArray.length; i++) {
27
+ const sheet = sheetArray[i];
28
+ const hash = hashArray[i];
29
+ if (sheet.includes('@media') || sheet.includes('@container')) {
30
+ querySheetParts.push(sheet.replace(`.${hash}`, `.${hash}:not(#\\#)`));
31
+ queryHashParts.push(hash);
32
+ }
33
+ else {
34
+ baseSheetParts.push(sheet);
35
+ baseHashParts.push(hash);
36
+ }
37
+ }
38
+ if (baseSheetParts.length > 0) {
39
+ records.push({
40
+ key: prop,
41
+ hash: baseHashParts.join(' '),
42
+ sheet: baseSheetParts.join(''),
43
+ });
44
+ }
45
+ if (querySheetParts.length > 0) {
46
+ records.push({
47
+ key: prop + '__queries__',
48
+ hash: queryHashParts.join(' '),
49
+ sheet: querySheetParts.join(''),
50
+ });
51
+ }
52
+ });
53
+ if (Object.keys(nonFlat).length > 0) {
54
+ const modNonFlat = (0, zss_engine_1.transformNestedSelectors)(nonFlat);
55
+ const nonFlatObj = { [key]: modNonFlat };
56
+ const nonFlatHash = (0, zss_engine_1.genBase36Hash)(nonFlatObj, 1, 7);
57
+ const { styleSheet } = (0, zss_engine_1.transpile)(nonFlatObj, nonFlatHash);
58
+ const isQuery = styleSheet.includes('@media') || styleSheet.includes('@container');
59
+ const finalSheet = isQuery
60
+ ? styleSheet.replace(`.${nonFlatHash}`, `.${nonFlatHash}:not(#\\#)`)
61
+ : styleSheet;
62
+ Object.entries(nonFlat).forEach(([atRule, nestedObj]) => {
63
+ Object.keys(nestedObj).forEach((prop) => {
64
+ records.push({
65
+ key: atRule + prop,
66
+ hash: nonFlatHash,
67
+ sheet: finalSheet,
68
+ });
69
+ });
70
+ });
71
+ }
72
+ records.reverse().forEach(({ hash, sheet }) => {
73
+ if (!processedHashes.has(hash)) {
74
+ processedHashes.add(hash);
75
+ if (sheet.includes('@media') || sheet.includes('@container')) {
76
+ querySheets.push(sheet);
77
+ }
78
+ else {
79
+ baseSheets.push(sheet);
80
+ }
81
+ }
82
+ });
83
+ });
84
+ return [...baseSheets, ...querySheets].filter(Boolean).join('');
85
+ }
86
+ function createCSS(object) {
87
+ const compiledCSS = compileToSingleCSS(object);
88
+ return compiledCSS;
89
+ }
90
+ const createVars = (object) => {
91
+ const styles = {
92
+ ':root': {},
93
+ };
94
+ Object.entries(object).forEach(([key, value]) => {
95
+ styles[':root'][`--${key}`] = value;
96
+ });
97
+ return styles;
98
+ };
99
+ exports.createVars = createVars;
100
+ const createTokens = (object) => {
101
+ const styles = {};
102
+ Object.entries(object).forEach(([key, value]) => {
103
+ const kebabKey = (0, zss_engine_1.camelToKebabCase)(key);
104
+ Object.entries(value).forEach(([subKey, subValue]) => {
105
+ if (subKey.startsWith('@media')) {
106
+ styles[':root'] ||= {};
107
+ styles[':root'][subKey] ||= {};
108
+ styles[':root'][subKey][`--${kebabKey}`] = subValue;
109
+ }
110
+ else {
111
+ const themeSelector = subKey === 'default' ? ':root' : `:root[data-theme="${subKey}"]`;
112
+ styles[themeSelector] ||= {};
113
+ styles[themeSelector][`--${kebabKey}`] = subValue;
114
+ }
115
+ });
116
+ });
117
+ return styles;
118
+ };
119
+ exports.createTokens = createTokens;
@@ -0,0 +1,29 @@
1
+ type CSSPrimitive = string | number | boolean | null;
2
+ type ParseErrorString = `[unresolved]` | `[unresolved identifier]` | `[unsupported value type]` | `[unresolved: ${string}]` | `[unresolved member expression]`;
3
+ export type CSSValue = CSSPrimitive | CSSObject | ParseErrorString;
4
+ export type CSSObject = {
5
+ [key: string]: CSSValue;
6
+ };
7
+ export type ConstTable = Record<string, CSSObject | string>;
8
+ export type TokensTable = Record<string, CSSObject>;
9
+ export type KeyframesHashTable = Record<string, string>;
10
+ export type KeyframesObjectTable = Record<string, CSSObject>;
11
+ export type ViewTransitionHashTable = Record<string, string>;
12
+ export type ViewTransitionObjectTable = Record<string, CSSObject>;
13
+ export type DefineTokensObjectTable = Record<string, CSSObject>;
14
+ export interface Tables {
15
+ constTable: ConstTable;
16
+ tokensTable: TokensTable;
17
+ keyframesHashTable: KeyframesHashTable;
18
+ keyframesObjectTable: KeyframesObjectTable;
19
+ viewTransitionHashTable: ViewTransitionHashTable;
20
+ viewTransitionObjectTable: ViewTransitionObjectTable;
21
+ defineTokensObjectTable: DefineTokensObjectTable;
22
+ }
23
+ export interface FileStyles {
24
+ baseStyles?: string;
25
+ keyframeStyles?: string;
26
+ viewTransitionStyles?: string;
27
+ tokenStyles?: string;
28
+ }
29
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@plumeria/utils",
3
+ "version": "0.29.0",
4
+ "description": "Plumeria Utils",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/zss-in-js/plumeria.git",
8
+ "directory": "packages/utils"
9
+ },
10
+ "license": "MIT",
11
+ "sideEffects": false,
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist/"
16
+ ],
17
+ "scripts": {
18
+ "build": "rimraf dist && pnpm cjs",
19
+ "cjs": "tsc --project tsconfig.cjs.json"
20
+ },
21
+ "dependencies": {
22
+ "@swc/core": "1.15.2"
23
+ },
24
+ "devDependencies": {
25
+ "zss-engine": "^0.2.102"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ }
30
+ }