@halftone-ds/tokens 1.4.0 → 1.6.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/README.md +54 -6
- package/cli.mjs +21 -12
- package/lib/doctor.mjs +360 -0
- package/lib/generate.mjs +28 -0
- package/lib/import-cli.mjs +87 -0
- package/lib/init.mjs +18 -3
- package/lib/resolve.mjs +18 -1
- package/lib/system/generate.mjs +5 -1
- package/lib/system/import.mjs +552 -0
- package/lib/system/index.d.mts +20 -1
- package/lib/system/index.mjs +2 -0
- package/lib/system/schema.mjs +67 -1
- package/lib/theme/apply.mjs +17 -2
- package/lib/theme/codec.mjs +13 -7
- package/lib/theme/generate.mjs +3 -0
- package/lib/theme/index.d.mts +36 -0
- package/lib/theme/index.mjs +3 -2
- package/lib/theme/motion.mjs +99 -0
- package/lib/theme/recipe.mjs +11 -1
- package/lib/theme/vars.mjs +18 -0
- package/package.json +1 -1
- package/targets/design-md.mjs +8 -3
- package/targets/figma.mjs +3 -0
- package/targets/llms.mjs +1 -1
- package/targets/nativewind3.mjs +4 -1
- package/targets/shadcn-web.mjs +32 -2
- package/targets/ts-theme.mjs +28 -1
- package/templates/tokens.json +37 -0
package/README.md
CHANGED
|
@@ -7,6 +7,8 @@ and every build checks the palette against WCAG AA.
|
|
|
7
7
|
```bash
|
|
8
8
|
npm install -D @halftone-ds/tokens
|
|
9
9
|
npx halftone-tokens init # set up an existing app, web or Expo (below)
|
|
10
|
+
npx halftone-tokens doctor # check the app's setup for kit components; says how to fix each problem
|
|
11
|
+
npx halftone-tokens import ./brand/tokens.json # a brand's own DTCG tokens into a system file (below)
|
|
10
12
|
npx halftone-tokens build # write every output in tokens/tokens.config.json
|
|
11
13
|
npx halftone-tokens check # write nothing; exit 1 if an output is stale (CI)
|
|
12
14
|
npx halftone-tokens build --strict # fail on contrast instead of warning (or HALFTONE_STRICT=1)
|
|
@@ -34,6 +36,28 @@ points. A theme with its own fonts installs their `@expo-google-fonts` packages
|
|
|
34
36
|
instead). After each `npx shadcn add`, run `npx halftone-tokens build`: the registry brings `lib/theme.ts` and
|
|
35
37
|
`lib/fonts.ts` with Halftone's default brand.
|
|
36
38
|
|
|
39
|
+
## Checking an app
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npx halftone-tokens doctor [--platform web|expo] [--offline] [--json]
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Read-only. It checks what kit components need and prints a fix for each problem (exit 1 if there is one):
|
|
46
|
+
|
|
47
|
+
- the tokens are set up and every generated file is up to date (after a `shadcn add` in an Expo app, `lib/theme.ts`
|
|
48
|
+
and `lib/fonts.ts` are not);
|
|
49
|
+
- the stylesheet imports `tokens.css` after Tailwind and `fonts.css` first (web), or `global.css` imports the
|
|
50
|
+
tokens first and `tailwind.config.js` uses the kit's preset (Expo);
|
|
51
|
+
- `components.json` is on the new-york style, and the `@/` aliases resolve in `tsconfig.json` (and `vite.config.ts`);
|
|
52
|
+
- no kit file in `components/ui` has been replaced by shadcn's or react-native-reusables' stock version: it compares
|
|
53
|
+
each one with the kit's registry (the URL in `components.json`) and the upstream one, ignoring the imports shadcn
|
|
54
|
+
rewrites. `--offline` skips this.
|
|
55
|
+
|
|
56
|
+
It warns, without failing, about rules in the app's own CSS or Tailwind config that win over the kit's, nothing
|
|
57
|
+
setting the `.dark` class, kit links without `KitLinkProvider`, an Expo app without `KitThemeProvider` or
|
|
58
|
+
`useFonts(FONT_ASSETS)`, and a `lib/utils.ts` with its own `cn` (clsx + tailwind-merge) next to the `cn` package
|
|
59
|
+
that kit and shadcn files import. `--json` prints `{ ok, results: [{ level, message, fix }] }` for an agent or CI.
|
|
60
|
+
|
|
37
61
|
## Inputs
|
|
38
62
|
|
|
39
63
|
- `tokens/tokens.json`: `primitive` ramps and scales, and `semantic.color.<name>` with a `{ light, dark }`
|
|
@@ -60,13 +84,13 @@ instead). After each `npx shadcn add`, run `npx halftone-tokens build`: the regi
|
|
|
60
84
|
|
|
61
85
|
| Target | Writes |
|
|
62
86
|
|---|---|
|
|
63
|
-
| `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind theme extension: `css` + `tailwind` (the whole stylesheet and a map to spread), or `css` + `partial: true` + `preset` (variables only, imported first by the app's `global.css`, and a Tailwind preset) |
|
|
64
|
-
| `shadcn-web` | Tailwind 4 / shadcn v4 CSS: oklch variables in `:root` + `.dark`, `@theme inline`, base layer |
|
|
65
|
-
| `ts-theme` | `THEME` (hex per scheme), `TOKENS` (space, radius, type, motion) and an optional React Navigation theme |
|
|
87
|
+
| `nativewind3` | NativeWind 4 / Tailwind 3 CSS variables (HSL, `:root` + `.dark:root`) and the Tailwind theme extension (`duration-fast`, `ease-standard`… included): `css` + `tailwind` (the whole stylesheet and a map to spread), or `css` + `partial: true` + `preset` (variables only, imported first by the app's `global.css`, and a Tailwind preset) |
|
|
88
|
+
| `shadcn-web` | Tailwind 4 / shadcn v4 CSS: oklch variables in `:root` + `.dark`, `@theme inline`, base layer; motion as `--duration-*`, `--ease-*` and `--spring-*` (a `linear()` easing and its duration), with `duration-*`, `ease-*` and `spring-*` classes |
|
|
89
|
+
| `ts-theme` | `THEME` (hex per scheme), `TOKENS` (space, radius, type, motion), `MOTION` (durations, easings and springs, typed for Motion and Reanimated) and an optional React Navigation theme |
|
|
66
90
|
| `registry-theme` | the theme as shadcn registry `cssVars`, native and web |
|
|
67
91
|
| `design-md` | a [DESIGN.md](https://github.com/google-labs-code/design.md) (spec alpha) |
|
|
68
92
|
| `llms` | a tokens section for `llms.txt` |
|
|
69
|
-
| `figma` | the input `halftone-tokens figma` pushes to Figma Variables |
|
|
93
|
+
| `figma` | the input `halftone-tokens figma` pushes to Figma Variables (durations included; easings and springs have no variable type) |
|
|
70
94
|
| `fonts` | the theme's fonts as loading code: `platform: 'expo'` (expo-google-fonts), `'next'` (next/font) or `'web'` (a Google Fonts `@import` and `--kit-font-*`, imported first in the app's stylesheet) |
|
|
71
95
|
|
|
72
96
|
## Themes
|
|
@@ -140,8 +164,32 @@ npx halftone-tokens theme encode ./acme.halftone.json # its ht- code, when it h
|
|
|
140
164
|
|
|
141
165
|
From code (`@halftone-ds/tokens/system`, also in `/theme`, browser-safe): `normalizeSystem` / `validateSystem`,
|
|
142
166
|
`createSystem`, `migrate(recipe | code, brand)` and `systemToRecipe`, `generateSystem(system, tokens)` (the same
|
|
143
|
-
shape as `generateTheme`, plus `warnings`), `systemRamps`, `textStyles`, `systemRadii`, `systemCode
|
|
144
|
-
`applySystem
|
|
167
|
+
shape as `generateTheme`, plus `warnings`), `systemRamps`, `textStyles`, `systemRadii`, `systemCode`,
|
|
168
|
+
`applySystem`, and `systemFromTokens` / `fontFamiliesToCheck` (the import, below). The document's shape is
|
|
169
|
+
described in `lib/system/schema.mjs`.
|
|
170
|
+
|
|
171
|
+
### Importing a brand's own tokens
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
npx halftone-tokens import ./brand/tokens.json --name "Acme" # writes acme.halftone.json
|
|
175
|
+
npx halftone-tokens import ./tokens.json --google "Lato" --offline --json # for an agent; no network
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
It reads any DTCG `tokens.json` (hex strings or 2025.10 colour objects, aliases, inherited `$type`) in the brand's own
|
|
179
|
+
words, and writes a system:
|
|
180
|
+
- **Colour sets:** the lightest page is light and the darkest is dark. A third set, or a colour no role takes, is an
|
|
181
|
+
extra colour. With no dark set, dark is generated.
|
|
182
|
+
- **Roles by name** (`background-secondary` → muted, `stroke` → border, `brand` → primary when there's no `primary`),
|
|
183
|
+
as the brand's exact hex: the fixer never moves them, so a pairing below AA is a warning. A "muted" that reads as
|
|
184
|
+
text on the page becomes `muted-foreground`. A see-through colour is mixed onto its page.
|
|
185
|
+
- **Ramps:** brand from primary, neutral and the statuses from a numbered family that holds their colour, its steps
|
|
186
|
+
kept.
|
|
187
|
+
- **Fonts** when the family is on Google Fonts (the CLI asks; `--offline` skips, `--google` vouches); others stay out.
|
|
188
|
+
**Corners and shadows** by name or by size.
|
|
189
|
+
- **Everything else** (spacing, a line weight, a grid) goes in the system's `tokens` section, whole: not drawn by the
|
|
190
|
+
kits, carried into `tokens.json`'s record. A system with it has no `ht-` code.
|
|
191
|
+
|
|
192
|
+
It prints one line per guess. Check them before `theme apply`.
|
|
145
193
|
|
|
146
194
|
## Guarantees
|
|
147
195
|
|
package/cli.mjs
CHANGED
|
@@ -3,10 +3,12 @@
|
|
|
3
3
|
* halftone-tokens — turns tokens/tokens.json into everything an app reads.
|
|
4
4
|
*
|
|
5
5
|
* halftone-tokens init set up tokens in an existing app, web or Expo (see lib/init.mjs)
|
|
6
|
+
* halftone-tokens doctor check an app's setup for kit components and say how to fix it (see lib/doctor.mjs)
|
|
6
7
|
* halftone-tokens build resolve, check contrast, write every target in tokens.config.json
|
|
7
8
|
* halftone-tokens check same, but write nothing; exit 1 if any generated file is stale (CI)
|
|
8
9
|
* halftone-tokens figma mirror the tokens into Figma Variables (see push-figma.mjs)
|
|
9
10
|
* halftone-tokens theme apply, show or list themes (see lib/theme-cli.mjs)
|
|
11
|
+
* halftone-tokens import a brand's own tokens.json into a system file (see lib/import-cli.mjs)
|
|
10
12
|
* halftone-tokens --version
|
|
11
13
|
* halftone-tokens --help (USAGE below)
|
|
12
14
|
*
|
|
@@ -25,8 +27,8 @@ import { dirname, join, resolve } from 'node:path';
|
|
|
25
27
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
26
28
|
|
|
27
29
|
import { checkContrast, AA, componentFailures, describeSubtle, describeTintLimits, textOnSubtle, textOnTintLimits } from './lib/contrast.mjs';
|
|
30
|
+
import { loadContext, renderTargets } from './lib/generate.mjs';
|
|
28
31
|
import { scanTintText } from './lib/scan.mjs';
|
|
29
|
-
import { loadTokens } from './lib/resolve.mjs';
|
|
30
32
|
|
|
31
33
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
32
34
|
|
|
@@ -38,10 +40,15 @@ Usage: halftone-tokens <command> [options]
|
|
|
38
40
|
Commands:
|
|
39
41
|
init set up Halftone's tokens in an existing app (any React app, or Expo with NativeWind)
|
|
40
42
|
[--theme <code|preset|file.halftone.json>] [--css <stylesheet>] [--platform web|expo] [--force]
|
|
43
|
+
doctor check the app's setup for kit components (tokens, stylesheet, aliases, stock files that
|
|
44
|
+
replaced kit ones, dark mode, links) and say how to fix each; exit 1 on a problem
|
|
45
|
+
[--platform web|expo] [--offline] [--json]
|
|
41
46
|
build resolve, check contrast, write every target in tokens.config.json (the default)
|
|
42
47
|
check the same, but write nothing; exit 1 if a generated file is stale (for CI)
|
|
43
48
|
theme apply, show or list themes: halftone-tokens theme apply <code|preset|file.halftone.json>
|
|
44
|
-
|
|
49
|
+
import a brand's own tokens.json (DTCG) into a system file, and what it guessed:
|
|
50
|
+
halftone-tokens import <tokens.json> [--name <name>] [--out <file>] [--google "A,B"] [--offline] [--force] [--json]
|
|
51
|
+
figma mirror the tokens into Figma Variables
|
|
45
52
|
--version print the version
|
|
46
53
|
--help print this
|
|
47
54
|
|
|
@@ -54,7 +61,7 @@ tokens.config.json: { "source": "tokens/tokens.json", "targets": { "<target>": {
|
|
|
54
61
|
Docs: https://halftonedesignsystem.com/install.md`;
|
|
55
62
|
|
|
56
63
|
/** Flags that take a value; every other --flag is a boolean. */
|
|
57
|
-
const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform']);
|
|
64
|
+
const VALUE_FLAGS = new Set(['root', 'config', 'out', 'fonts-url', 'theme', 'css', 'platform', 'name', 'google']);
|
|
58
65
|
|
|
59
66
|
function parseArgs(argv) {
|
|
60
67
|
const [command = 'build', ...rest] = argv;
|
|
@@ -85,12 +92,20 @@ export async function run(argv = process.argv.slice(2)) {
|
|
|
85
92
|
await import(pathToFileURL(join(here, 'push-figma.mjs')).href);
|
|
86
93
|
return;
|
|
87
94
|
}
|
|
95
|
+
if (command === 'doctor') {
|
|
96
|
+
const { doctorCommand } = await import('./lib/doctor.mjs');
|
|
97
|
+
return doctorCommand({ root, flags });
|
|
98
|
+
}
|
|
88
99
|
if (command === 'init') {
|
|
89
100
|
const { initCommand } = await import('./lib/init.mjs');
|
|
90
101
|
return initCommand({ root, flags, positional, run });
|
|
91
102
|
}
|
|
103
|
+
if (command === 'import') {
|
|
104
|
+
const { importCommand } = await import('./lib/import-cli.mjs');
|
|
105
|
+
return importCommand({ root, flags, positional });
|
|
106
|
+
}
|
|
92
107
|
if (command !== 'build' && command !== 'check' && command !== 'theme') {
|
|
93
|
-
console.error(`halftone-tokens: unknown command "${command}". Use init, build, check, theme or figma (halftone-tokens --help for more).`);
|
|
108
|
+
console.error(`halftone-tokens: unknown command "${command}". Use init, doctor, build, check, theme, import or figma (halftone-tokens --help for more).`);
|
|
94
109
|
process.exit(2);
|
|
95
110
|
}
|
|
96
111
|
|
|
@@ -107,9 +122,7 @@ export async function run(argv = process.argv.slice(2)) {
|
|
|
107
122
|
const rebuild = ['build', '--root', root, ...(flags.config ? ['--config', flags.config] : []), ...(flags.strict ? ['--strict'] : [])];
|
|
108
123
|
return themeCommand({ positional, flags, root, sourcePath: join(root, source), config, build: () => run(rebuild) });
|
|
109
124
|
}
|
|
110
|
-
const ctx = await
|
|
111
|
-
ctx.root = root;
|
|
112
|
-
ctx.header = `GENERATED by \`npm run tokens:build\` from ${source} — do not edit by hand.`;
|
|
125
|
+
const ctx = await loadContext(root, source);
|
|
113
126
|
|
|
114
127
|
// Contrast is checked on every build. By default a problem is a warning (the palette is the designer's
|
|
115
128
|
// call); --strict or HALFTONE_STRICT=1 makes it an error, which is how Halftone's own CI builds the kits.
|
|
@@ -153,11 +166,7 @@ export async function run(argv = process.argv.slice(2)) {
|
|
|
153
166
|
}
|
|
154
167
|
const contrast = warnings ? `${warnings} contrast warning(s), run with --strict to fail` : 'contrast AA ✓';
|
|
155
168
|
|
|
156
|
-
const files =
|
|
157
|
-
for (const [name, options] of Object.entries(config.targets ?? {})) {
|
|
158
|
-
const { default: target } = await import(pathToFileURL(join(here, 'targets', `${name}.mjs`)).href);
|
|
159
|
-
files.push(...(await target(ctx, options ?? {})));
|
|
160
|
-
}
|
|
169
|
+
const files = await renderTargets(ctx, config);
|
|
161
170
|
|
|
162
171
|
if (command === 'check') {
|
|
163
172
|
const stale = files.filter((f) => {
|
package/lib/doctor.mjs
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `halftone-tokens doctor` — check that an app is set up for Halftone's kit components, and say how to fix what isn't.
|
|
3
|
+
* Read-only: it never changes a file.
|
|
4
|
+
*
|
|
5
|
+
* halftone-tokens doctor [--platform web|expo] [--offline] [--json]
|
|
6
|
+
*
|
|
7
|
+
* Problems (exit 1): tokens not set up or out of date; the stylesheet (web) or global.css (Expo) not importing them;
|
|
8
|
+
* the Tailwind preset missing (Expo); a components.json on another style; `@/` aliases that don't resolve; a kit
|
|
9
|
+
* file in components/ui that shadcn's or react-native-reusables' stock version has replaced.
|
|
10
|
+
* Warnings: rules in the app's own files that win over the kit's; nothing that sets dark mode; kit links without
|
|
11
|
+
* KitLinkProvider; fonts not loaded (Expo); a second `cn` in lib/utils.ts.
|
|
12
|
+
*
|
|
13
|
+
* The stock-file check reads the kit's registry (the URL in components.json) and the upstream one: --offline skips it.
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
16
|
+
import { basename, join, posix, relative } from 'node:path';
|
|
17
|
+
|
|
18
|
+
import { loadContext, renderTargets } from './generate.mjs';
|
|
19
|
+
import { detectPlatform, overridingExtends, overridingRules, STYLESHEETS, STYLESHEETS_EXPO } from './init.mjs';
|
|
20
|
+
|
|
21
|
+
/** Where the stock version of a kit-changed ui file comes from, by platform. */
|
|
22
|
+
export const UPSTREAM = {
|
|
23
|
+
web: { registry: '@halftone-web', url: 'https://ui.shadcn.com/r/styles/new-york-v4/{name}.json', label: "shadcn/ui's" },
|
|
24
|
+
expo: { registry: '@halftone-native', url: 'https://reactnativereusables.com/r/nativewind/{name}.json', label: "react-native-reusables'" },
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const toPosix = (p) => p.split('\\').join('/');
|
|
28
|
+
const read = (path) => readFileSync(path, 'utf8');
|
|
29
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
30
|
+
|
|
31
|
+
/** JSON with comments and trailing commas (tsconfig), read without mistaking "@/*" for a comment. */
|
|
32
|
+
export function parseJsonc(text) {
|
|
33
|
+
let out = '';
|
|
34
|
+
for (let i = 0; i < text.length; i++) {
|
|
35
|
+
const c = text[i];
|
|
36
|
+
if (c === '"') {
|
|
37
|
+
let j = i + 1;
|
|
38
|
+
while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1;
|
|
39
|
+
out += text.slice(i, j + 1);
|
|
40
|
+
i = j;
|
|
41
|
+
} else if (c === '/' && text[i + 1] === '/') {
|
|
42
|
+
while (i < text.length && text[i] !== '\n') i++;
|
|
43
|
+
out += '\n';
|
|
44
|
+
} else if (c === '/' && text[i + 1] === '*') {
|
|
45
|
+
i = text.indexOf('*/', i + 2);
|
|
46
|
+
if (i === -1) break;
|
|
47
|
+
i++;
|
|
48
|
+
} else out += c;
|
|
49
|
+
}
|
|
50
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* A file's code without its imports, directives and whitespace: what `shadcn add` leaves alone. It rewrites import
|
|
55
|
+
* paths to the app's aliases and drops "use client" outside RSC, so those can't tell two copies apart.
|
|
56
|
+
*/
|
|
57
|
+
export function normalizeSource(src) {
|
|
58
|
+
return src
|
|
59
|
+
.replace(/^\s*['"]use client['"];?/gm, '')
|
|
60
|
+
.replace(/^\s*import\s[\s\S]*?\sfrom\s*['"][^'"]+['"];?/gm, '')
|
|
61
|
+
.replace(/^\s*import\s*['"][^'"]+['"];?/gm, '')
|
|
62
|
+
.replace(/\s+/g, '');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The `paths` of the app's tsconfig (tsconfig.json, then tsconfig.app.json, as Vite splits them). */
|
|
66
|
+
export function tsPaths(root) {
|
|
67
|
+
for (const file of ['tsconfig.json', 'tsconfig.app.json']) {
|
|
68
|
+
try {
|
|
69
|
+
const paths = parseJsonc(read(join(root, file))).compilerOptions?.paths;
|
|
70
|
+
if (paths && Object.keys(paths).length) return { file, paths };
|
|
71
|
+
} catch {
|
|
72
|
+
// missing or unreadable: try the next
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { file: null, paths: {} };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** An import alias (`@/components/ui`) as a folder relative to the root (`src/components/ui`), or null. */
|
|
79
|
+
export function aliasDir(paths, alias) {
|
|
80
|
+
for (const [key, targets] of Object.entries(paths)) {
|
|
81
|
+
const prefix = key.replace(/\*$/, '');
|
|
82
|
+
const target = Array.isArray(targets) ? targets[0] : null;
|
|
83
|
+
if (!key.endsWith('*') || typeof target !== 'string' || !alias.startsWith(prefix)) continue;
|
|
84
|
+
return posix.normalize(posix.join(target.replace(/\*$/, '') || '.', alias.slice(prefix.length)));
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Files under dir (relative to root), skipping dependencies, builds and the kit's own folders. */
|
|
90
|
+
function sourceFiles(root, dir, found = []) {
|
|
91
|
+
const full = join(root, dir);
|
|
92
|
+
if (!existsSync(full)) return found;
|
|
93
|
+
for (const name of readdirSync(full)) {
|
|
94
|
+
if (/^(node_modules|dist|build|\.next|\.expo|\.git|ios|android|tokens|ui|kit)$/.test(name)) continue;
|
|
95
|
+
const rel = posix.join(dir, name);
|
|
96
|
+
const stat = statSync(join(root, rel));
|
|
97
|
+
if (stat.isDirectory()) sourceFiles(root, rel, found);
|
|
98
|
+
else if (/\.(tsx?|jsx?|html)$/.test(name)) found.push(rel);
|
|
99
|
+
}
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
const anySource = (root, dirs, re) => dirs.some((dir) => sourceFiles(root, dir).some((f) => re.test(read(join(root, f)))));
|
|
103
|
+
|
|
104
|
+
async function fetchJson(url) {
|
|
105
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
|
|
106
|
+
if (!res.ok) throw new Error(`${res.status} ${url}`);
|
|
107
|
+
return res.json();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function doctorCommand({ root, flags }) {
|
|
111
|
+
const results = await doctor({ root, flags });
|
|
112
|
+
const problems = results.filter((r) => r.level === 'problem');
|
|
113
|
+
const warnings = results.filter((r) => r.level === 'warning');
|
|
114
|
+
if (flags.json) {
|
|
115
|
+
console.log(JSON.stringify({ ok: problems.length === 0, results }, null, 2));
|
|
116
|
+
} else {
|
|
117
|
+
const mark = { ok: '✓', problem: '✗', warning: '!', info: '·' };
|
|
118
|
+
for (const r of results) {
|
|
119
|
+
console.log(`${mark[r.level]} ${r.message}`);
|
|
120
|
+
if (r.fix) console.log(` ${r.fix.split('\n').join('\n ')}`);
|
|
121
|
+
}
|
|
122
|
+
const summary = [problems.length && `${problems.length} problem(s)`, warnings.length && `${warnings.length} warning(s)`].filter(Boolean);
|
|
123
|
+
console.log(`\nhalftone-tokens doctor: ${summary.length ? summary.join(', ') : 'all good'}.`);
|
|
124
|
+
}
|
|
125
|
+
if (problems.length) process.exitCode = 1;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Every check, as [{ level: ok|problem|warning|info, message, fix? }]. */
|
|
129
|
+
export async function doctor({ root, flags = {} }) {
|
|
130
|
+
const results = [];
|
|
131
|
+
const ok = (message) => results.push({ level: 'ok', message });
|
|
132
|
+
const problem = (message, fix) => results.push({ level: 'problem', message, fix });
|
|
133
|
+
const warning = (message, fix) => results.push({ level: 'warning', message, fix });
|
|
134
|
+
const info = (message, fix) => results.push({ level: 'info', message, fix });
|
|
135
|
+
|
|
136
|
+
let pkg = {};
|
|
137
|
+
try {
|
|
138
|
+
pkg = JSON.parse(read(join(root, 'package.json')));
|
|
139
|
+
} catch {
|
|
140
|
+
problem('No package.json here.', 'Run doctor in the app’s root folder, or pass --root <dir>.');
|
|
141
|
+
return results;
|
|
142
|
+
}
|
|
143
|
+
const platform = flags.platform === 'web' || flags.platform === 'expo' ? flags.platform : detectPlatform(pkg);
|
|
144
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
145
|
+
info(platform === 'expo' ? 'An Expo app (NativeWind).' : 'A React app (Tailwind 4).');
|
|
146
|
+
|
|
147
|
+
// components.json: the style, the aliases, the registry.
|
|
148
|
+
let components = null;
|
|
149
|
+
try {
|
|
150
|
+
components = JSON.parse(read(join(root, 'components.json')));
|
|
151
|
+
} catch {
|
|
152
|
+
warning('No components.json: shadcn needs one to add kit components.', 'install.md, path ' + (platform === 'expo' ? 'C' : 'D') + ', step 1, has the file to write.');
|
|
153
|
+
}
|
|
154
|
+
if (components) {
|
|
155
|
+
if (components.style && components.style !== 'new-york') {
|
|
156
|
+
problem(
|
|
157
|
+
`components.json has style "${components.style}". Kit components are built on Radix with the new-york style.`,
|
|
158
|
+
'Set "style": "new-york" (install.md, path D, step 1). A Base UI app can’t use kit components.'
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
const upstream = UPSTREAM[platform];
|
|
162
|
+
if (!components.registries?.[upstream.registry]) {
|
|
163
|
+
warning(`components.json has no "${upstream.registry}" registry.`, `Add it: "registries": { "${upstream.registry}": "https://halftonedesignsystem.com/r/${platform === 'expo' ? 'native' : 'web'}/{name}.json" }`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The @/ aliases kit components import through.
|
|
168
|
+
const { file: tsFile, paths } = tsPaths(root);
|
|
169
|
+
const aliases = components?.aliases ?? { ui: '@/components/ui', lib: '@/lib', utils: '@/lib/utils', components: '@/components' };
|
|
170
|
+
const uiDir = aliasDir(paths, aliases.ui ?? '@/components/ui');
|
|
171
|
+
const libDir = aliasDir(paths, aliases.lib ?? '@/lib');
|
|
172
|
+
if (!uiDir) {
|
|
173
|
+
problem(
|
|
174
|
+
`${tsFile ?? 'tsconfig.json'} doesn't map "${aliases.ui ?? '@/components/ui'}": kit components import through the @/ aliases.`,
|
|
175
|
+
`Add "paths": { "@/*": ["./${platform === 'expo' ? '' : 'src/'}*"] } to compilerOptions${platform === 'expo' ? '' : ' (and the same alias to vite.config.ts in a Vite app)'}.`
|
|
176
|
+
);
|
|
177
|
+
} else {
|
|
178
|
+
ok(`The @/ aliases resolve (${aliases.ui} → ${uiDir}).`);
|
|
179
|
+
const vite = ['vite.config.ts', 'vite.config.js', 'vite.config.mts', 'vite.config.mjs'].find((f) => existsSync(join(root, f)));
|
|
180
|
+
if (vite && !/['"]@['"]\s*:|find:\s*['"]@['"]|tsconfigPaths|tsconfig-paths/.test(read(join(root, vite)))) {
|
|
181
|
+
warning(`${vite} has no "@" alias: TypeScript resolves @/ imports, but the build won't.`, "resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }");
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// The tokens: set up, built, up to date.
|
|
186
|
+
const configPath = join(root, flags.config ?? 'tokens/tokens.config.json');
|
|
187
|
+
let config = null;
|
|
188
|
+
if (!existsSync(configPath)) {
|
|
189
|
+
problem('Halftone’s tokens aren’t set up (no tokens/tokens.config.json).', 'npx halftone-tokens init # or: npx halftone-tokens init --theme <code>');
|
|
190
|
+
} else {
|
|
191
|
+
config = JSON.parse(read(configPath));
|
|
192
|
+
const source = config.source ?? 'tokens/tokens.json';
|
|
193
|
+
if (!existsSync(join(root, source))) {
|
|
194
|
+
problem(`${source} is missing.`, 'npx halftone-tokens init --force');
|
|
195
|
+
config = null;
|
|
196
|
+
} else {
|
|
197
|
+
const ctx = await loadContext(root, source);
|
|
198
|
+
const files = await renderTargets(ctx, config);
|
|
199
|
+
const stale = files.filter((f) => !existsSync(join(root, f.path)) || read(join(root, f.path)) !== f.contents);
|
|
200
|
+
if (stale.length) {
|
|
201
|
+
problem(
|
|
202
|
+
`${stale.length} generated file(s) out of date: ${stale.map((f) => f.path).join(', ')}.`,
|
|
203
|
+
'npx halftone-tokens build' + (platform === 'expo' ? ' (after every `shadcn add`: the registry brings lib/theme.ts and lib/fonts.ts with Halftone’s default brand)' : '')
|
|
204
|
+
);
|
|
205
|
+
} else ok(`The tokens are built and up to date (${files.length} files).`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (platform === 'expo') expoChecks({ root, deps, config, components, ok, problem, warning });
|
|
210
|
+
else webChecks({ root, deps, config, components, libDir, ok, problem, warning });
|
|
211
|
+
|
|
212
|
+
// One cn: kit and shadcn files import it from the `cn` package; an older lib/utils.ts has its own.
|
|
213
|
+
if (platform === 'web') {
|
|
214
|
+
const utilsDir = aliasDir(paths, posix.dirname(aliases.utils ?? '@/lib/utils'));
|
|
215
|
+
const utils = utilsDir && ['ts', 'tsx', 'js'].map((ext) => posix.join(utilsDir, `${basename(aliases.utils ?? 'utils')}.${ext}`)).find((f) => existsSync(join(root, f)));
|
|
216
|
+
if (utils) {
|
|
217
|
+
const src = read(join(root, utils));
|
|
218
|
+
if (/\bcn\b/.test(src) && !/from\s+['"]cn['"]/.test(src) && /twMerge|clsx/.test(src)) {
|
|
219
|
+
warning(
|
|
220
|
+
`${utils} has its own cn (clsx + tailwind-merge). Kit and shadcn files import cn from the \`cn\` package, so the app has two.`,
|
|
221
|
+
`Make ${utils} re-export it, as shadcn's own utils does now: export { cn } from 'cn';\nKeep any other helpers in the file. Then remove clsx and tailwind-merge if nothing else imports them.`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (uiDir && !flags.offline) await stockChecks({ root, platform, components, uiDir, ok, problem, info, warning });
|
|
228
|
+
return results;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function webChecks({ root, deps, config, components, libDir, ok, problem, warning }) {
|
|
232
|
+
const cssRel = components?.tailwind?.css ?? STYLESHEETS.find((p) => existsSync(join(root, p)));
|
|
233
|
+
if (!cssRel || !existsSync(join(root, cssRel))) {
|
|
234
|
+
problem(`No stylesheet found${cssRel ? ` at ${cssRel}` : ''}.`, 'Set "tailwind": { "css": "<your main stylesheet>" } in components.json.');
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const css = read(join(root, cssRel));
|
|
238
|
+
const importsOf = [...css.matchAll(/^\s*@import\s+(?:url\()?['"]([^'"]+)['"]/gm)].map((m) => m[1]);
|
|
239
|
+
const wants = (target) => {
|
|
240
|
+
const out = config?.targets?.[target]?.out;
|
|
241
|
+
if (!out) return null;
|
|
242
|
+
const rel = toPosix(relative(posix.dirname(cssRel), out));
|
|
243
|
+
return rel.startsWith('.') ? rel : `./${rel}`;
|
|
244
|
+
};
|
|
245
|
+
if (!importsOf.includes('tailwindcss')) problem(`${cssRel} doesn't import tailwindcss: kit components need Tailwind 4.`, `@import 'tailwindcss';`);
|
|
246
|
+
if (!importsOf.includes('tw-animate-css')) {
|
|
247
|
+
warning(`${cssRel} doesn't import tw-animate-css: dialogs, menus and sheets won't animate.`, `npm install tw-animate-css, then @import 'tw-animate-css'; after tailwindcss in ${cssRel}.`);
|
|
248
|
+
}
|
|
249
|
+
const tokens = wants('shadcn-web');
|
|
250
|
+
if (config && tokens) {
|
|
251
|
+
if (!importsOf.includes(tokens)) problem(`${cssRel} doesn't import ${tokens}: kit components get no colours, sizes or type.`, `@import '${tokens}'; after tailwindcss in ${cssRel}.`);
|
|
252
|
+
else if (importsOf.indexOf(tokens) < importsOf.indexOf('tailwindcss')) warning(`${cssRel} imports ${tokens} before tailwindcss.`, `Move @import '${tokens}'; after @import 'tailwindcss';.`);
|
|
253
|
+
else ok(`${cssRel} imports ${tokens}.`);
|
|
254
|
+
}
|
|
255
|
+
// The fonts target writes CSS for a plain web app (platform: 'web'); a Next app loads them in code (next/font).
|
|
256
|
+
const fonts = /\.css$/.test(config?.targets?.fonts?.out ?? '') ? wants('fonts') : null;
|
|
257
|
+
if (config && fonts) {
|
|
258
|
+
if (!importsOf.includes(fonts)) problem(`${cssRel} doesn't import ${fonts}: the theme's fonts won't load.`, `@import '${fonts}'; as the first line of ${cssRel}.`);
|
|
259
|
+
else if (importsOf[0] !== fonts) warning(`${fonts} isn't the first import in ${cssRel}: a font @import after other rules is ignored.`, `Move @import '${fonts}'; to the top.`);
|
|
260
|
+
}
|
|
261
|
+
const overrides = overridingRules(css);
|
|
262
|
+
if (overrides.length) {
|
|
263
|
+
warning(
|
|
264
|
+
`${cssRel} has rules that tokens.css also defines, and they win over it: ${overrides.map((o) => `line ${o.line} ${o.name}`).join(', ')}.`,
|
|
265
|
+
'Delete them unless you mean to override the kit.'
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
// Dark mode: something has to put .dark on <html>.
|
|
269
|
+
const setsDark = deps['next-themes'] || anySource(root, ['src', 'app', '.'].filter((d) => d !== '.' || existsSync(join(root, 'index.html'))), /classList\.(add|toggle)\(\s*['"]dark['"]|class=["'][^"']*\bdark\b/);
|
|
270
|
+
if (!setsDark) warning('Nothing here sets the .dark class, so dark mode never shows.', 'next-themes with attribute="class" (Next.js), or your own code that toggles .dark on <html>.');
|
|
271
|
+
// Kit links: without KitLinkProvider they reload the page.
|
|
272
|
+
if (libDir && existsSync(join(root, libDir, 'link.tsx')) && !anySource(root, ['src', 'app', 'components'], /KitLinkProvider/)) {
|
|
273
|
+
warning('Kit components link through @/lib/link, but nothing sets KitLinkProvider: kit links reload the page.', "Wrap the app once in <KitLinkProvider link={…} usePathname={…}> (install.md, path D, step 5).");
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function expoChecks({ root, deps, config, components, ok, problem, warning }) {
|
|
278
|
+
if (!deps.nativewind) problem('NativeWind isn’t installed: kit components are NativeWind classes.', 'npx expo install nativewind');
|
|
279
|
+
const cssRel = components?.tailwind?.css ?? STYLESHEETS_EXPO.find((p) => existsSync(join(root, p)));
|
|
280
|
+
const tokensOut = config?.targets?.nativewind3?.css;
|
|
281
|
+
if (cssRel && existsSync(join(root, cssRel)) && tokensOut) {
|
|
282
|
+
const css = read(join(root, cssRel));
|
|
283
|
+
const rel = toPosix(relative(posix.dirname(cssRel), tokensOut));
|
|
284
|
+
const spec = rel.startsWith('.') ? rel : `./${rel}`;
|
|
285
|
+
const first = css.replace(/\/\*[\s\S]*?\*\//g, '').split('\n').find((l) => l.trim());
|
|
286
|
+
if (!new RegExp(`@import\\s+['"]${escape(spec)}['"]`).test(css)) problem(`${cssRel} doesn't import ${spec}: kit components get no colours or sizes.`, `@import '${spec}'; as the first line of ${cssRel}.`);
|
|
287
|
+
else if (!first?.includes(spec)) warning(`${spec} isn't the first line of ${cssRel}: Tailwind only inlines an @import that comes first.`, `Move @import '${spec}'; to the top.`);
|
|
288
|
+
else ok(`${cssRel} imports ${spec} first.`);
|
|
289
|
+
const overrides = overridingRules(css);
|
|
290
|
+
if (overrides.length) warning(`${cssRel} has rules that win over the kit's: ${overrides.map((o) => `line ${o.line} ${o.name}`).join(', ')}.`, 'Delete them unless you mean to override the kit.');
|
|
291
|
+
}
|
|
292
|
+
const presetOut = config?.targets?.nativewind3?.preset;
|
|
293
|
+
const configRel = ['tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.ts'].find((f) => existsSync(join(root, f)));
|
|
294
|
+
if (presetOut) {
|
|
295
|
+
const spec = `./${presetOut.replace(/\.js$/, '')}`;
|
|
296
|
+
if (!configRel) problem('No tailwind.config.js: NativeWind needs one, with the kit’s preset.', `presets: [require('nativewind/preset'), require('${spec}')]`);
|
|
297
|
+
else {
|
|
298
|
+
const tw = read(join(root, configRel));
|
|
299
|
+
if (!tw.includes(presetOut.replace(/\.js$/, ''))) problem(`${configRel} doesn't use the kit's preset: kit classes like h-button-md don't exist.`, `presets: [require('nativewind/preset'), require('${spec}')]`);
|
|
300
|
+
else ok(`${configRel} uses the kit's preset.`);
|
|
301
|
+
const own = overridingExtends(tw);
|
|
302
|
+
if (own.length) warning(`${configRel} extends ${own.join(', ')} itself, and those win over the kit's preset.`, 'Delete them from theme.extend unless you mean to override the kit.');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const dirs = ['app', 'src'];
|
|
306
|
+
if (!anySource(root, dirs, /KitThemeProvider/)) {
|
|
307
|
+
warning('Nothing wraps the app in KitThemeProvider: light, dark and the system setting won’t follow the kit.', `npx shadcn@latest add @halftone-native/lib-theme-context, then wrap the root layout in <KitThemeProvider>.`);
|
|
308
|
+
}
|
|
309
|
+
if (config?.targets?.fonts && !anySource(root, dirs, /FONT_ASSETS/)) {
|
|
310
|
+
warning("Nothing loads the theme's fonts: text falls back to the system font.", `useFonts(FONT_ASSETS) from '${components?.aliases?.lib ?? '@/lib'}/fonts' at the root (expo-font).`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Kit-changed files in components/ui, compared with the kit's copy and, when they differ, the stock one. */
|
|
315
|
+
async function stockChecks({ root, platform, components, uiDir, ok, problem, info, warning }) {
|
|
316
|
+
const upstream = UPSTREAM[platform];
|
|
317
|
+
const entry = components?.registries?.[upstream.registry];
|
|
318
|
+
const template = typeof entry === 'string' ? entry : entry?.url;
|
|
319
|
+
if (!template) return;
|
|
320
|
+
let index;
|
|
321
|
+
try {
|
|
322
|
+
index = await fetchJson(template.replace('{name}', 'registry'));
|
|
323
|
+
} catch (e) {
|
|
324
|
+
info(`Couldn't read the kit's registry (${e.message}), so kit files weren't compared. --offline skips this.`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const ui = (index.items ?? []).filter((i) => i.type === 'registry:ui').flatMap((i) => (i.files ?? []).map((f) => ({ item: i.name, path: f.path })));
|
|
328
|
+
const installed = ui.map((f) => ({ ...f, local: posix.join(uiDir, posix.basename(f.path)) })).filter((f) => existsSync(join(root, f.local)));
|
|
329
|
+
if (!installed.length) return;
|
|
330
|
+
const replaced = [];
|
|
331
|
+
const edited = [];
|
|
332
|
+
await Promise.all(
|
|
333
|
+
installed.map(async (f) => {
|
|
334
|
+
const local = normalizeSource(read(join(root, f.local)));
|
|
335
|
+
const kit = await fetchJson(template.replace('{name}', f.item)).catch(() => null);
|
|
336
|
+
const kitFile = kit?.files?.find((x) => x.path === f.path);
|
|
337
|
+
if (!kitFile || normalizeSource(kitFile.content) === local) return;
|
|
338
|
+
const name = posix.basename(f.path).replace(/\.tsx?$/, '');
|
|
339
|
+
const stock = await fetchJson(upstream.url.replace('{name}', name)).catch(() => null);
|
|
340
|
+
const stockFile = stock?.files?.find((x) => posix.basename(x.path) === posix.basename(f.path)) ?? stock?.files?.[0];
|
|
341
|
+
if (stockFile && normalizeSource(stockFile.content) === local) replaced.push(f);
|
|
342
|
+
else edited.push(f);
|
|
343
|
+
})
|
|
344
|
+
);
|
|
345
|
+
const ns = upstream.registry;
|
|
346
|
+
if (replaced.length) {
|
|
347
|
+
problem(
|
|
348
|
+
`${replaced.map((f) => f.local).join(', ')}: ${upstream.label} stock version replaced the kit's, so kit components look and behave wrong.`,
|
|
349
|
+
`npx shadcn@latest add ${replaced.map((f) => `${ns}/${f.item}`).join(' ')} --overwrite`
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
if (edited.length) {
|
|
353
|
+
warning(
|
|
354
|
+
`${edited.map((f) => f.local).join(', ')} differ${edited.length === 1 ? 's' : ''} from the kit's version (edited here, or from an older kit).`,
|
|
355
|
+
`Fine if you meant it. To take the kit's again: npx shadcn@latest add ${edited.map((f) => `${ns}/${f.item}`).join(' ')} --overwrite`
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
const same = installed.length - replaced.length - edited.length;
|
|
359
|
+
if (same) ok(`${same} kit file(s) in ${uiDir} match the kit's registry.`);
|
|
360
|
+
}
|
package/lib/generate.mjs
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `build` writes, without writing it: every target in tokens.config.json, rendered. `build` writes these,
|
|
3
|
+
* `check` compares them with the files on disk, `doctor` names the stale ones.
|
|
4
|
+
*/
|
|
5
|
+
import { dirname, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
|
|
8
|
+
import { loadTokens } from './resolve.mjs';
|
|
9
|
+
|
|
10
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
|
|
12
|
+
/** The resolved tokens, with what every target reads besides them: the app root and the generated-file header. */
|
|
13
|
+
export async function loadContext(root, source) {
|
|
14
|
+
const ctx = await loadTokens(join(root, source));
|
|
15
|
+
ctx.root = root;
|
|
16
|
+
ctx.header = `GENERATED by \`npm run tokens:build\` from ${source} — do not edit by hand.`;
|
|
17
|
+
return ctx;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** [{ path, contents }] for every target in the config, relative to the app root. */
|
|
21
|
+
export async function renderTargets(ctx, config) {
|
|
22
|
+
const files = [];
|
|
23
|
+
for (const [name, options] of Object.entries(config.targets ?? {})) {
|
|
24
|
+
const { default: target } = await import(pathToFileURL(join(here, '..', 'targets', `${name}.mjs`)).href);
|
|
25
|
+
files.push(...(await target(ctx, options ?? {})));
|
|
26
|
+
}
|
|
27
|
+
return files;
|
|
28
|
+
}
|