@tenphi/tasty 3.19.0 → 3.19.2

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/README.md CHANGED
@@ -585,7 +585,7 @@ See [Debug Utilities](docs/debug.md).
585
585
 
586
586
  Style definitions are declarative and fully typed, so agents can read and write them reliably. [Style Rules for AI Agents](docs/ai-agents.md) is a one-page brief to add to an agent's context.
587
587
 
588
- The package also ships a harness for coding agents such as Claude Code and Codex, in [`harness/`](harness). With [harnesspm](https://www.npmjs.com/package/@tenphi/harnesspm), a project that depends on Tasty gets:
588
+ The package also ships a harness for coding agents such as Claude Code and Codex, in [`harness/`](https://github.com/tenphi/tasty/tree/main/harness). With [harnesspm](https://www.npmjs.com/package/@tenphi/harnesspm), a project that depends on Tasty gets:
589
589
 
590
590
  - a short rule: read the brief and the project's config first, use tokens and units, write state maps right;
591
591
  - the docs index, so an agent reads the pages in `docs/` of the installed version;
@@ -81,13 +81,29 @@ const PRESET_MODIFIERS = new Set([
81
81
  'normal',
82
82
  ]);
83
83
 
84
- /**
85
- * Where `configure()` keeps its `tokens` (and the typography tokens that
86
- * `presets` generate). Tasty shares them through `globalThis` so that every
87
- * copy of the engine sees them; the tool reads them only to check preset
88
- * names. `src/harness.test.ts` fails if the key changes.
89
- */
84
+ // Tasty shares these configured resources across copies through globalThis.
90
85
  const CONFIG_TOKENS_KEY = '__tasty_cfg_tokens__';
86
+ const CONFIG_PROPERTIES_KEY = '__tasty_cfg_properties__';
87
+ const CONFIG_GLOBAL_STYLES_KEY = '__tasty_cfg_global_styles__';
88
+
89
+ // The core entry point does not expose its default @property definitions.
90
+ const DEFAULT_PROPERTIES = [
91
+ '--tasty-second-fill-color',
92
+ '--current-color',
93
+ '--white-color',
94
+ '--black-color',
95
+ '--border-color',
96
+ '--outline-color',
97
+ '--gap',
98
+ '--radius',
99
+ '--border-width',
100
+ '--outline-width',
101
+ '--transition',
102
+ '--sharp-radius',
103
+ '--bold-font-weight',
104
+ '--font-sans-fallback',
105
+ '--font-mono-fallback',
106
+ ];
91
107
 
92
108
  /** The parts of the configuration that a setup module changes. */
93
109
  export function configSummary(t) {
@@ -99,7 +115,16 @@ export function configSummary(t) {
99
115
  };
100
116
  }
101
117
 
102
- /** Whether two `configSummary()` results differ. */
118
+ /**
119
+ * The parts of the configuration that belong to one copy of Tasty. Tokens are
120
+ * left out: Tasty shares them between copies through `globalThis`.
121
+ */
122
+ export function configFingerprint(t) {
123
+ const { units, states, recipes } = configSummary(t);
124
+ return { units, states, recipes };
125
+ }
126
+
127
+ /** Whether two `configSummary()` or `configFingerprint()` results differ. */
103
128
  export function configChanged(before, after) {
104
129
  return JSON.stringify(before) !== JSON.stringify(after);
105
130
  }
@@ -127,6 +152,7 @@ export function parseCss(css) {
127
152
  const stack = [root];
128
153
  let buffer = '';
129
154
  let quote = '';
155
+ let escaped = false;
130
156
  let depth = 0;
131
157
 
132
158
  const flush = () => {
@@ -147,7 +173,9 @@ export function parseCss(css) {
147
173
  for (const char of css) {
148
174
  if (quote) {
149
175
  buffer += char;
150
- if (char === quote) quote = '';
176
+ if (escaped) escaped = false;
177
+ else if (char === '\\') escaped = true;
178
+ else if (char === quote) quote = '';
151
179
  continue;
152
180
  }
153
181
  if (char === '"' || char === "'") {
@@ -200,17 +228,24 @@ export function formatCss(css) {
200
228
  return lines.join('\n');
201
229
  }
202
230
 
203
- /** Every declaration in CSS text, at any depth. */
204
- function declarationsOf(css) {
205
- const found = [];
231
+ /** Declarations and @property names at any depth. */
232
+ function inspectCss(css) {
233
+ const declarations = [];
234
+ const properties = new Set();
206
235
  const walk = (nodes) => {
207
236
  for (const node of nodes) {
208
- if ('prelude' in node) walk(node.children);
209
- else if (node.property) found.push(node);
237
+ if ('prelude' in node) {
238
+ const registration = /^@property\s+(--[\w-]+)$/.exec(node.prelude);
239
+ if (registration) properties.add(registration[1]);
240
+ walk(node.children);
241
+ } else if (node.property) {
242
+ declarations.push(node);
243
+ if (node.property.startsWith('--')) properties.add(node.property);
244
+ }
210
245
  }
211
246
  };
212
247
  walk(parseCss(css));
213
- return found;
248
+ return { declarations, properties };
214
249
  }
215
250
 
216
251
  /**
@@ -242,6 +277,87 @@ function valuesOf(styles, property) {
242
277
  return found;
243
278
  }
244
279
 
280
+ function cssNameOf(token, normalize = false) {
281
+ const sigil = token[0];
282
+ if (sigil !== '#' && sigil !== '$') {
283
+ return token.startsWith('--') ? token : `--${token}`;
284
+ }
285
+ const name = token.slice(1);
286
+ // The DSL folds the first letter. Registered CSS properties keep their name.
287
+ const cssName = normalize
288
+ ? name.charAt(0).toLowerCase() + name.slice(1)
289
+ : name;
290
+ return `--${cssName}${sigil === '#' ? '-color' : ''}`;
291
+ }
292
+
293
+ function withoutLiterals(value) {
294
+ return value
295
+ .replace(
296
+ /\/\*[\s\S]*?\*\/|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'/g,
297
+ ' ',
298
+ )
299
+ .replace(/\burl\((?:\\[\s\S]|[^)\\])*\)/gi, ' ');
300
+ }
301
+
302
+ /** Authored DSL references that survive rendering as a var() without a fallback. */
303
+ function findTokenIssues(t, styles, tokens, { declarations, properties }) {
304
+ const references = new Set();
305
+ for (const { value } of declarations) {
306
+ for (const [, name] of withoutLiterals(value).matchAll(
307
+ /(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi,
308
+ )) {
309
+ references.add(name);
310
+ }
311
+ }
312
+ if (references.size === 0) return [];
313
+
314
+ const defined = new Set([
315
+ ...DEFAULT_PROPERTIES,
316
+ ...properties,
317
+ ...tokens.map((token) => cssNameOf(token, true)),
318
+ ...Object.keys(globalThis[CONFIG_PROPERTIES_KEY] ?? {}).map((name) =>
319
+ cssNameOf(name),
320
+ ),
321
+ ]);
322
+ const missing = new Map();
323
+ const walk = (value) => {
324
+ if (typeof value === 'string') {
325
+ for (const [token] of withoutLiterals(value).matchAll(
326
+ /(?<![#$\\])[#$][\w-]+/g,
327
+ )) {
328
+ const name = cssNameOf(token, true);
329
+ if (references.has(name) && !defined.has(name))
330
+ missing.set(token, name);
331
+ }
332
+ } else if (value && typeof value === 'object') {
333
+ for (const child of Object.values(value)) walk(child);
334
+ }
335
+ };
336
+ walk(styles);
337
+ if (missing.size === 0) return [];
338
+
339
+ for (const [selector, globalStyles] of Object.entries(
340
+ globalThis[CONFIG_GLOBAL_STYLES_KEY] ?? {},
341
+ )) {
342
+ for (const rule of t.renderStyles(globalStyles, selector)) {
343
+ for (const property of inspectCss(rule.declarations).properties) {
344
+ defined.add(property);
345
+ }
346
+ }
347
+ }
348
+
349
+ return [...missing]
350
+ .filter(([, name]) => !defined.has(name))
351
+ .map(([token, name]) => {
352
+ const color = token.startsWith('#');
353
+ const known = tokens.filter((key) => key[0] === token[0]).slice(0, 8);
354
+ const example = known.length
355
+ ? ` Known ${color ? 'colors' : 'tokens'} include ${known.join(', ')}.`
356
+ : '';
357
+ return `${color ? 'Color' : 'Token'} "${token}" is not in the loaded config. Its CSS variable var(${name}) needs a value from other CSS.${example}`;
358
+ });
359
+ }
360
+
245
361
  /**
246
362
  * Values the CSS shows Tasty did not resolve, and names the loaded
247
363
  * configuration does not define. Each issue is one sentence that says what to
@@ -290,8 +406,13 @@ export function findIssues(t, styles, css) {
290
406
  }
291
407
  }
292
408
 
409
+ const rendered = inspectCss(css);
410
+ if (tokens.length > 0) {
411
+ issues.push(...findTokenIssues(t, styles, tokens, rendered));
412
+ }
413
+
293
414
  const rawUnits = new Map();
294
- for (const { property, value } of declarationsOf(css)) {
415
+ for (const { property, value } of rendered.declarations) {
295
416
  if (property.startsWith('--')) continue;
296
417
  for (const match of value.matchAll(
297
418
  /(?<![\w#.$-])(-?(?:\d+\.?\d*|\.\d+))([a-zA-Z]+)(?![\w(-])/g,
@@ -1,13 +1,20 @@
1
1
  /**
2
2
  * tasty:styles — prints the CSS Tasty generates for a styles object, with the
3
- * app's configuration loaded first, and flags values that stayed unresolved.
3
+ * app's configuration loaded first, and reports problems found during rendering.
4
4
  */
5
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
5
+ import {
6
+ existsSync,
7
+ readFileSync,
8
+ readdirSync,
9
+ realpathSync,
10
+ statSync,
11
+ } from 'node:fs';
6
12
  import { createRequire } from 'node:module';
7
13
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
8
14
  import { fileURLToPath, pathToFileURL } from 'node:url';
9
15
  import {
10
16
  configChanged,
17
+ configFingerprint,
11
18
  configSummary,
12
19
  describeUnits,
13
20
  findIssues,
@@ -30,12 +37,22 @@ selector or an at-rule. To see what a state key becomes, put it in a state map.
30
37
  for several modules. TypeScript needs Node 22.18 or later.
31
38
  --json print the result as JSON
32
39
 
40
+ Run it from the package whose styles you check. Package paths in --setup resolve
41
+ from there, and the CSS comes from the copy of @tenphi/tasty that the setup
42
+ modules configure, which in a monorepo can differ from package to package.
43
+
44
+ When the loaded config defines tokens, the tool warns about unknown #color
45
+ and $token references that still need a value in the generated CSS.
46
+
33
47
  Without --setup, the CSS uses Tasty's defaults (x = 8px, r = 6px, ...) and none
34
48
  of the app's units, presets, recipes or state aliases.`;
35
49
 
36
- const PACKAGE_ROOT = fileURLToPath(new URL('../../../', import.meta.url));
50
+ const PACKAGE_ROOT = realpathSync(
51
+ fileURLToPath(new URL('../../../', import.meta.url)),
52
+ );
37
53
  const BUILD = join(PACKAGE_ROOT, 'dist/core/index.js');
38
- const projectDir = process.env.HARNESSPM_PROJECT_DIR || process.cwd();
54
+ const cwd = process.cwd();
55
+ const projectDir = process.env.HARNESSPM_PROJECT_DIR || cwd;
39
56
 
40
57
  function fail(message) {
41
58
  console.error(`tasty: ${message}`);
@@ -96,15 +113,22 @@ const tastyWarnings = [];
96
113
  const warn = console.warn;
97
114
  console.warn = (...args) => tastyWarnings.push(args.map(String).join(' '));
98
115
 
99
- const t = await import(pathToFileURL(BUILD).href);
100
- const version = JSON.parse(
101
- readFileSync(join(PACKAGE_ROOT, 'package.json'), 'utf8'),
102
- ).version;
116
+ // Every copy of @tenphi/tasty this run can see, by its real folder. A setup
117
+ // module configures the copy it imports, which in a monorepo or with a second
118
+ // version installed need not be this tool's own.
119
+ const copies = new Map();
120
+ const own = await copyAt(PACKAGE_ROOT);
121
+ const appRoot = tastyRootFrom(cwd);
122
+ const app = appRoot === undefined ? undefined : await copyAt(appRoot);
103
123
 
104
- const before = configSummary(t);
105
124
  const loaded = [];
106
125
  for (const spec of options.setup) {
107
126
  const file = resolveSetup(spec);
127
+ const nearRoot = tastyRootFrom(dirname(realpathSync(file)));
128
+ const near = nearRoot === undefined ? undefined : await copyAt(nearRoot);
129
+ const before = new Map(
130
+ [...copies.values()].map((c) => [c.root, configFingerprint(c.t)]),
131
+ );
108
132
  let mod;
109
133
  try {
110
134
  mod = await import(pathToFileURL(file).href);
@@ -113,33 +137,74 @@ for (const spec of options.setup) {
113
137
  fail(`cannot import --setup ${spec}: ${importHint(file, error)}`);
114
138
  }
115
139
  const config = mod.default;
116
- if (config && Object.getPrototypeOf(config) === Object.prototype) {
140
+ const isConfig =
141
+ config !== null &&
142
+ typeof config === 'object' &&
143
+ Object.getPrototypeOf(config) === Object.prototype;
144
+ let changed;
145
+ if (isConfig) {
146
+ const target = near ?? app ?? own;
117
147
  try {
118
- t.configure(config);
148
+ target.t.configure(config);
119
149
  } catch (error) {
120
150
  console.warn = warn;
121
151
  fail(
122
152
  `configure() rejected the default export of ${spec}: ${error instanceof Error ? error.message : error}`,
123
153
  );
124
154
  }
125
- loaded.push({ module: spec, configured: 'default export' });
155
+ changed = [target];
126
156
  } else {
127
- loaded.push({ module: spec, configured: 'on import' });
157
+ changed = [...copies.values()].filter((c) =>
158
+ configChanged(before.get(c.root), configFingerprint(c.t)),
159
+ );
128
160
  }
161
+ loaded.push({
162
+ module: spec,
163
+ configured: isConfig
164
+ ? 'default export'
165
+ : changed.length > 0
166
+ ? 'on import'
167
+ : 'nothing',
168
+ tasty: changed.map((c) => ({ version: c.version, path: show(c.root) })),
169
+ });
170
+ for (const c of changed) c.setups.push(spec);
129
171
  }
172
+
173
+ const configured = [...copies.values()].filter((c) => c.setups.length > 0);
174
+ const chosen =
175
+ configured.length === 0
176
+ ? (app ?? own)
177
+ : configured.includes(app)
178
+ ? app
179
+ : configured.reduce((a, b) =>
180
+ b.setups.length > a.setups.length ? b : a,
181
+ );
182
+ const t = chosen.t;
183
+ const version = chosen.version;
130
184
  const config = configSummary(t);
131
185
 
132
186
  const warnings = [];
133
187
  if (loaded.length === 0) {
134
- const candidates = findSetupCandidates(projectDir);
188
+ const candidates = findSetupCandidates(
189
+ cwd.startsWith(projectDir) ? cwd : projectDir,
190
+ );
135
191
  warnings.push(
136
192
  candidates.length > 0
137
193
  ? `No --setup: this is the CSS for Tasty's defaults, not the app's config. These files configure Tasty: ${candidates.join(', ')}. Run again with --setup <file>.`
138
194
  : "No --setup: this is the CSS for Tasty's defaults. No file in this project calls configure() from @tenphi/tasty. If the app configures Tasty elsewhere, such as in a UI library, pass that module with --setup.",
139
195
  );
140
- } else if (!configChanged(before, config)) {
196
+ }
197
+ for (const entry of loaded.filter((l) => l.configured === 'nothing')) {
198
+ warnings.push(
199
+ `--setup ${entry.module} changed no Tasty config this tool can see. It may call configure() only inside a function, or configure a copy of @tenphi/tasty that neither this package nor the other setup modules use.`,
200
+ );
201
+ }
202
+ if (configured.length > 1) {
203
+ const parts = configured.map(
204
+ (c) => `${c.version} (${show(c.root)}) got ${c.setups.join(', ')}`,
205
+ );
141
206
  warnings.push(
142
- `The --setup modules did not change the configuration of the Tasty copy this tool uses (${relative(projectDir, PACKAGE_ROOT) || '.'}). They may configure another copy of @tenphi/tasty, or call configure() only inside a function.`,
207
+ `The --setup modules configure ${configured.length} copies of @tenphi/tasty, so this CSS has only part of the config: ${parts.join('; ')}. This CSS comes from ${chosen.version} (${show(chosen.root)}). The app runs these copies too, each with part of the config: make every package use one version of @tenphi/tasty.`,
143
208
  );
144
209
  }
145
210
 
@@ -162,7 +227,7 @@ if (options.json) {
162
227
  console.log(
163
228
  JSON.stringify(
164
229
  {
165
- tasty: { version, path: relative(projectDir, PACKAGE_ROOT) || '.' },
230
+ tasty: { version, path: show(chosen.root) },
166
231
  setup: loaded,
167
232
  config,
168
233
  classNames: result.classNames,
@@ -183,7 +248,8 @@ function render() {
183
248
  loaded.length > 0
184
249
  ? `setup ${loaded.map((l) => l.module).join(', ')}`
185
250
  : 'no setup, Tasty defaults';
186
- out.push(`Tasty ${version}, ${setup}`);
251
+ const from = chosen === own ? '' : ` (${show(chosen.root)})`;
252
+ out.push(`Tasty ${version}${from}, ${setup}`);
187
253
  const parts = [`units ${describeUnits(config.units)}`];
188
254
  if (config.states.length > 0) parts.push(`states ${list(config.states)}`);
189
255
  if (config.recipes.length > 0) parts.push(`recipes ${list(config.recipes)}`);
@@ -220,17 +286,64 @@ function resolveSetup(spec) {
220
286
  if (!existsSync(asPath)) fail(`cannot find --setup ${spec}`);
221
287
  return asPath;
222
288
  }
289
+ // From the current package first: in a monorepo, each package can install
290
+ // its own version.
291
+ for (const base of new Set([cwd, projectDir])) {
292
+ try {
293
+ return createRequire(join(base, 'noop.js')).resolve(spec);
294
+ } catch {
295
+ // A path the package's exports do not list, such as a file in its dist/.
296
+ }
297
+ for (let dir = base; ; dir = dirname(dir)) {
298
+ const candidate = join(dir, 'node_modules', spec);
299
+ if (existsSync(candidate)) return candidate;
300
+ if (dirname(dir) === dir) break;
301
+ }
302
+ }
303
+ return fail(`cannot resolve --setup ${spec} from ${cwd}`);
304
+ }
305
+
306
+ /** The real folder of the @tenphi/tasty that code in `dir` imports. */
307
+ function tastyRootFrom(dir) {
308
+ let entry;
223
309
  try {
224
- return createRequire(join(projectDir, 'package.json')).resolve(spec);
310
+ entry = createRequire(join(dir, 'noop.js')).resolve('@tenphi/tasty');
225
311
  } catch {
226
- // A path the package's exports do not list, such as a file in its dist/.
312
+ return undefined;
227
313
  }
228
- for (let dir = projectDir; ; dir = dirname(dir)) {
229
- const candidate = join(dir, 'node_modules', spec);
230
- if (existsSync(candidate)) return candidate;
231
- if (dirname(dir) === dir) break;
314
+ for (let d = dirname(entry); dirname(d) !== d; d = dirname(d)) {
315
+ const manifest = join(d, 'package.json');
316
+ if (
317
+ existsSync(manifest) &&
318
+ JSON.parse(readFileSync(manifest, 'utf8')).name === '@tenphi/tasty'
319
+ ) {
320
+ return realpathSync(d);
321
+ }
232
322
  }
233
- return fail(`cannot resolve --setup ${spec} from ${projectDir}`);
323
+ return undefined;
324
+ }
325
+
326
+ /** Loads a copy of Tasty once; undefined when it has no usable build. */
327
+ async function copyAt(root) {
328
+ if (copies.has(root)) return copies.get(root);
329
+ const build = join(root, 'dist/core/index.js');
330
+ if (!existsSync(build)) return undefined;
331
+ const core = await import(pathToFileURL(build).href);
332
+ if (typeof core.computeStyles !== 'function') return undefined;
333
+ const copy = {
334
+ root,
335
+ version: JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
336
+ .version,
337
+ t: core,
338
+ setups: [],
339
+ };
340
+ copies.set(root, copy);
341
+ return copy;
342
+ }
343
+
344
+ /** A path as the person sees it: relative to the current folder. */
345
+ function show(path) {
346
+ return relative(cwd, path) || '.';
234
347
  }
235
348
 
236
349
  function importHint(file, error) {
@@ -11,7 +11,7 @@
11
11
  "scripts": {
12
12
  "styles": {
13
13
  "file": "./dev.harnesspm/scripts/styles.mjs",
14
- "description": "Print the CSS a Tasty styles object produces, with the app's configure() loaded through --setup, and flag values that stayed unresolved",
14
+ "description": "Print the CSS a Tasty styles object produces and report rendering warnings, including unknown token references when the --setup config defines tokens",
15
15
  "allow": true
16
16
  }
17
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tenphi/tasty",
3
- "version": "3.19.0",
3
+ "version": "3.19.2",
4
4
  "description": "A design-system-integrated styling system and DSL for concise, state-aware UI styling",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -175,8 +175,8 @@
175
175
  "@eslint/js": "^10.0.1",
176
176
  "@size-limit/esbuild": "^14.1.0",
177
177
  "@size-limit/file": "^14.1.0",
178
- "@tenphi/eslint-plugin-tasty": "^1.17.0",
179
- "@tenphi/harnesspm": "^0.1.0",
178
+ "@tenphi/eslint-plugin-tasty": "^1.21.1",
179
+ "@tenphi/harnesspm": "^0.3.0",
180
180
  "@testing-library/jest-dom": "^7.0.1",
181
181
  "@testing-library/react": "^16.3.3",
182
182
  "@types/node": "^24.19.1",