@tenphi/glaze 0.0.0-snapshot.c13086f → 0.0.0-snapshot.c61bbdf

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/AGENTS.md ADDED
@@ -0,0 +1,158 @@
1
+ # AGENTS.md — @tenphi/glaze
2
+
3
+ ## Package Overview
4
+
5
+ - **Package:** `@tenphi/glaze`
6
+ - **Repository:** [https://github.com/tenphi/glaze](https://github.com/tenphi/glaze)
7
+ - **Description:** Zero-dependency color theme generator built on OKHST (OKHSL with a contrast-uniform **tone** axis), with WCAG + APCA contrast solving for light, dark, and high-contrast schemes.
8
+ - **Runtime:** Node >= 20, browsers, edge. Pure math, no I/O.
9
+ - **Output formats:** ESM + CJS, with full `.d.ts`.
10
+
11
+ ## Project Structure
12
+
13
+ ```
14
+ glaze/
15
+ ├── src/ Source
16
+ ├── docs/ Long-form docs: concepts, guides, reference (md/mdx, rendered by the site)
17
+ ├── docs-site/ Site-only files: home page + live-example components
18
+ ├── playground/ Interactive playground (Vite)
19
+ ├── assets/ Logo + brand assets
20
+ ├── scripts/ Repo helpers
21
+ ├── README.md Compact intro
22
+ ├── AGENTS.md This file
23
+ ├── CHANGELOG.md Auto-generated by Changesets
24
+ ├── package.json
25
+ ├── tsconfig.json
26
+ ├── tsdown.config.ts Build config
27
+ ├── vitest.config.ts Test config
28
+ ├── astro.config.ts Docs site (Astro + Cookbook)
29
+ ├── docs.config.ts Docs site config: navigation, theme, `@hc` state
30
+ └── eslint.config.js
31
+ ```
32
+
33
+ ### `src/` files
34
+
35
+ | File | Description |
36
+ |---|---|
37
+ | [src/index.ts](src/index.ts) | Public barrel; re-exports `glaze`, every public type, the contrast-solver utilities, and the OKHSL/sRGB/OKLab math helpers. |
38
+ | [src/glaze.ts](src/glaze.ts) | `glaze()` factory + attached statics: `palette`, `paletteFrom`, `color`, `colorFrom`, `themeFrom`, `from` (alias), `fromHex`, `fromRgb`, `shadow`, `glow`, `format`, `configure`, `getConfig`, `resetConfig`, `isThemeExport` / `isColorTokenExport` / `isPaletteExport`. Thin wiring layer over the focused modules below. |
39
+ | [src/theme.ts](src/theme.ts) | Single-theme factory (`createTheme`). Owns the mutable `ColorMap`, the `resolve()` cache (versioned against `getConfigVersion()`), and the `tokens` / `tasty` / `json` / `css` / `extend` / `export` methods. `export(override?)` deep-clones defs and freezes effective config with `kind`/`version`. |
40
+ | [src/palette.ts](src/palette.ts) | Multi-theme composition (`createPalette` / `createPaletteFromExport`). Shared per-theme driver `buildPaletteOutput` handles prefix resolution, primary duplication, collision filtering. Authoring: `export(override?)`, `theme` / `themes` / `list` / `primary`. |
41
+ | [src/color-token.ts](src/color-token.ts) | Standalone `glaze.color()` tokens. Parses values through `color-value.ts`; owns the structured-input validator, the two factory paths, sparse local config + live resolve, and the JSON-safe export / `glaze.colorFrom` rehydrate round-trip. |
42
+ | [src/color-value.ts](src/color-value.ts) | `GlazeColorValue` parsing + validation: hex (3/6/8), the `rgb()` / `hsl()` / `okhsl()` / `okhst()` / `oklch()` functions, and the four value-object shapes, all normalized to OKHSL by `extractOkhslFromValue`. Split out of `color-token.ts` so the resolver can reach it for a theme color's `from` without closing an import cycle. Leaf module — depends only on the color math. |
43
+ | [src/serialize.ts](src/serialize.ts) | Authoring-export helpers: `GLAZE_EXPORT_VERSION` (2 since Glaze 3), `assertExportKind` / `assertExportVersion`, `assertNoLegacyShadows` (rejects a version-1 theme snapshot with shadow defs or `shadowTuning`, since shadows changed meaning in 3.0; palettes pass their version down to each theme), and `isThemeExport` / `isColorTokenExport` / `isPaletteExport` type guards. |
44
+ | [src/resolver.ts](src/resolver.ts) | Four-pass solver (light → light-HC → dark → dark-HC), dropping to two-pass (light → dark) with mirrored HC slots only at `contrastLevel: 100`, where the normal passes already are the HC ones (`hcMirrorsNormal`). Under any other manual level `passTone` / `passNumber` / `resolveContrastSpec` feed interpolated inputs into the two *normal* passes and a probe solve at the nearer endpoint pins which side of its base a contrast-solved color sits on; the HC passes bypass the level and the probe entirely, so the HC tier is bit-identical to `'auto'`. Stores canonical tone (`t`) in variants; per-scheme branches for regular, shadow / glow (one shared `resolveLightingForScheme`), and mix defs; integrates the contrast solver, and the OKHST tone helpers. `resolveChannels` owns per-scheme hue/saturation (incl. the `darkHue` / `darkSaturation` seed + def overrides, the `darkDesaturation` bypass, and the absolute hue/saturation a `from` color carries in place of the seed factor) and feeds both the emitted variant and the contrast solver. `configForColor` gives a `from` color a local `lightTone: false` so its light variant reproduces the authored value. Converts to/from OKHSL lightness only at the mix / shadow / glow edges. Pre-seeds externally-resolved bases for `glaze.color({ base })`. |
45
+ | [src/okhst.ts](src/okhst.ts) | The OKHST tone layer. `REF_EPS`, tone↔lightness transfers (`toTone`/`fromTone`, `toneFromY`/`yFromTone`), OKHST↔OKHSL conversions, `variantToOkhsl` (tone→lightness at render), `normalizeToneWindow` (`[lo,hi]` / `{lo,hi,eps}` / `false` → `{lo,hi,eps}`), `mapToneForScheme` (scheme inversion + window remap, HC bypass), `mapSaturationDark` (the `darkDesaturation` reducer the resolver skips when a dark saturation is authored), and `schemeToneRange` for the solver. `activeWindow` owns the HC window bypass and its continuous form under `contrastLevel`. Only tone adapts here — hue/saturation are the resolver's business. |
46
+ | [src/contrast-solver.ts](src/contrast-solver.ts) | Tone-based binary-search solver for WCAG **and** APCA. Public API: `findToneForContrast` (incl. the `preferInitial` tie-break the manual level uses on its normal passes to keep a color's side stable), `findValueForMixContrast`, `resolveContrastForMode`, `resolveContrastForLevel` (both ends resolved, target interpolated for a manual `contrastLevel`; throws on a metric switch), `contrastMetricOf`, `resolveMinContrast`, `apcaContrast`. Closed-form WCAG seed + tone search. |
47
+ | [src/lighting.ts](src/lighting.ts) | Shadow / glow / mix def predicates (`isShadowDef`, `isGlowDef`, `isLightingDef`, `isMixDef`), `DEFAULT_LIGHTING_TUNING` + `resolveLightingTuning` (defaults ← global `shadowTuning` / `glowTuning` ← per-color, field by field), `circularLerp`, and the exact solver `computeLighting`: object factor `k = max(0, 1 + β·d·(t_bg − t_fg)/100)` (`objectFactor`), the pigment (pure black / white unless `reach` / `tint` / `hueBleed` say otherwise), and a bisection on opacity against browser compositing so the composite's luminance tone lands exactly `intensity × k` tones darker (shadow) / lighter (glow). Out-of-reach steps pin to the pigment's strongest composite (a golden-section search covers tinted shadow pigments whose channels diverge) and report `reached` for the warning. |
48
+ | [src/hc-pair.ts](src/hc-pair.ts) | Tiny shared helpers: HC-pair selection (`pairNormal` / `pairHC`), HC-pair interpolation for the manual contrast level (`contrastFraction`, `hcMirrorsNormal` — the level-100 "HC slots are duplicates" predicate, `levelFraction`, `numberAt`, `parseToneValueAt`, `PAIR_SWITCH`), tone-value parsing (`parseToneValue` for absolute / relative / `'max'`/`'min'` extremes, `isExtremeTone`), root-tone discrimination (`isAbsoluteTone`, now incl. extremes), `clamp` / `lerp`, hue resolution (`resolveEffectiveHue`), relative-value parsing. Leaf module — types only, so every other module can import it. |
49
+ | [src/formatters.ts](src/formatters.ts) | Variant→string dispatch (`okhsl` / `rgb` / `hsl` / `oklch`) and the four token-map shapes Glaze emits: `buildTokenMap` ([Tasty](https://tasty.style) `#name` keys + state aliases), `buildFlatTokenMap` (per-variant maps), `buildJsonMap` (per-color JSON), `buildCssMap` (CSS custom-property declarations). For `splitHue` it emits the light hue declarations plus, via `darkHueDeclarations` in `channels.ts`, the whole dark set when a `darkHue` makes it differ. Also the `resolveModes` helper used everywhere. |
50
+ | [src/okhsl-color-math.ts](src/okhsl-color-math.ts) | OKHSL ↔ linear-sRGB ↔ gamma-sRGB ↔ OKLab conversions, hex parsing (3/6/8 digits), gamut clamping, browser compositing (`toDisplayGamma` / `compositeOverGamma` — `source-over` on gamma-encoded sRGB, shared by transparent mixes and shadows / glows), and the `formatOkhsl` / `formatOkhst` / `formatRgb` / `formatHsl` / `formatOklch` writers. Converters and writers share one scale — `h` 0–360, `s` / `l` / `t` 0–1 — so any converter composes with any writer (the 0–100 tone axis lives in `okhst.ts`'s `toTone` / `fromTone`, not here); `warnPercentScale` catches pre-2.0 percentage-scale input instead of emitting a plausible wrong color. The only file with the actual color science. |
51
+ | [src/config.ts](src/config.ts) | Global config singleton. `defaultConfig()` is the one source of truth for defaults; `configure()` mutates the live object and bumps a monotonic `configVersion` so theme caches invalidate. `snapshotConfig()` powers `glaze.getConfig()`. `freezeConfigForExport()` freezes resolve-relevant fields for authoring export (`pastel` is instance-only; `contrastLevel` is frozen only when instance-authored, since a global level is a live preference). `normalizeContrastLevel()` validates the manual contrast level. |
52
+ | [src/validation.ts](src/validation.ts) | `validateColorDefs` (missing references, shadow / glow `bg` / `fg` cannot be a shadow or glow, mixes and regular bases cannot reference one, contrast-without-base, relative-without-base, WCAG-vs-APCA metric switch in a `contrast` pair, etc.) + `topoSort` so the resolver processes each color after its dependencies. |
53
+ | [src/warnings.ts](src/warnings.ts) | Deduped resolve-time warnings: contrast unmet, chromatic contrast drift, and out-of-reach shadow / glow steps (`warnLightingUnreachable`). Caps cache at 256 entries to keep dev-server output bounded. |
54
+ | [src/types.ts](src/types.ts) | All public TypeScript types: `HCPair`, `MinContrast`, `ContrastSpec`, `RelativeValue`, `ExtremeValue` (`'max'`/`'min'`), `ToneValue`, `AdaptationMode`, `OkhstColor`, `ToneWindow` (`[lo,hi]` \| `{lo,hi,eps}` \| `false`), `ColorDef` discriminated union (regular with `tone` + `flip` + `darkHue` / `darkSaturation`; `ShadowColorDef` / `GlowColorDef`; `MixColorDef`), `LightingTuning` (aliased as `ShadowTuning` / `GlowTuning`), `GlazeConfig` (with `lightTone` / `darkTone` / `autoFlip` / `contrastLevel` / `shadowTuning` / `glowTuning`), `GlazeThemeSeed` (`hue` / `saturation` + optional dark pair), `GlazeTheme`, `GlazePalette`, `GlazeColorToken`, the `*Export` shapes, etc. `ResolvedColorVariant` stores `{ h, s, t, alpha }`. |
55
+ | `src/glaze.test.ts` | Main test suite — covers the factory surface, resolver behavior, palette composition, shadow / glow (per-surface step uniformity, object influence, unreachable steps, v1 snapshot rejection) and mix algorithms, the manual contrast level, and the standalone color token round-trip. |
56
+ | `src/contrast-solver.test.ts` | Tests for the binary-search solver in isolation. |
57
+ | `src/hc-pair.test.ts` | Tests for the pure HC-pair selection and interpolation helpers. |
58
+ | `src/okhsl-color-math.test.ts` | Tests for the format writers' 0–1 scale contract, the percentage-scale guard, and producer→writer composition. |
59
+
60
+ ### `docs/` files
61
+
62
+ The documentation site (Cookbook on Astro) renders `docs/**/*.{md,mdx}` at the
63
+ path without the extension, plus `docs-site/index.mdx` as the home page.
64
+ Navigation lives in `docs.config.ts`. Concept and guide pages are `.mdx` with
65
+ live examples; reference pages are plain Markdown.
66
+
67
+ | File | Description |
68
+ |---|---|
69
+ | [docs/getting-started.mdx](docs/getting-started.mdx) | Install, a first theme built step by step, four schemes, and export. |
70
+ | [docs/okhst.mdx](docs/okhst.mdx) | The OKHST color model spec — tone math, `REF_EPS`, the T↔L invariant, the scheme pipeline, calibrated window defaults, the contrast metric, and the APCA verification step. Source of truth for the color model. |
71
+ | [docs/schemes.mdx](docs/schemes.mdx) | Light, dark, and high contrast: inversion + tone windows, adaptation modes, dark seed, HC pairs, the manual contrast level. |
72
+ | [docs/contrast.mdx](docs/contrast.mdx) | Contrast solving: WCAG / APCA floors, roles and polarity, `autoFlip`, HC escalation, warnings. |
73
+ | [docs/shadows-and-glows.mdx](docs/shadows-and-glows.mdx) | `shadow` / `glow`: exact tone steps, object influence, state layers, elevation, tuning. |
74
+ | [docs/mixes.mdx](docs/mixes.mdx) | Opaque and transparent mixes, blend spaces, contrast on mixes. |
75
+ | [docs/methodology.mdx](docs/methodology.mdx) | Palette design methodology — building a complete palette step by step, with the palette shown live as it grows. |
76
+ | [docs/exporting.mdx](docs/exporting.mdx) | Choosing an export shape, wiring tokens into [Tasty](https://tasty.style) / CSS / JSON / DTCG / Tailwind, prefix maps, the `primary` alias. |
77
+ | [docs/migration.md](docs/migration.md) | Migrating an existing color system, upgrading between majors (`3.0 — shadows and glows` is referenced by `src/serialize.ts` errors), common pitfalls. |
78
+ | [docs/reference/](docs/reference/index.md) | API reference: `index` (map of every export + conventions), `theme`, `color-definitions`, `contrast`, `color-tokens`, `palette`, `output`, `configuration`, `utilities`. Lookup, not tutorial. |
79
+
80
+ ### `docs-site/` files
81
+
82
+ | File | Description |
83
+ |---|---|
84
+ | [docs-site/index.mdx](docs-site/index.mdx) | Home page. |
85
+ | [docs-site/components/](docs-site/components/README.md) | Live-example components (`Example`, `Swatches`, `UiPreview`, `SchemeGrid`, `ToneRamp`, page-specific folders). They resolve themes from `src/` at build time and pass colors through Tasty `styles` — Cookbook rejects `style` attributes and non-Tasty CSS. See the folder's README before adding one. |
86
+
87
+ ## Commands
88
+
89
+ | Command | Description |
90
+ |---|---|
91
+ | `pnpm build` | Build ESM + CJS via tsdown (with `.d.ts` and sourcemaps). |
92
+ | `pnpm test` | Run all tests (Vitest 4). |
93
+ | `pnpm test -- <pattern>` | Run a subset of tests. |
94
+ | `pnpm test:watch` | Tests in watch mode. |
95
+ | `pnpm test:coverage` | Tests with coverage report. |
96
+ | `pnpm typecheck` | Type-check without emitting. |
97
+ | `pnpm lint` | ESLint over `src/`. |
98
+ | `pnpm lint:fix` | ESLint with `--fix`. |
99
+ | `pnpm format` | Prettier write `src/**/*.ts`. |
100
+ | `pnpm format:check` | Prettier check (no writes). |
101
+ | `pnpm changeset` | Create a changeset entry. |
102
+ | `pnpm release` | Build and publish (used by CI). |
103
+ | `pnpm docs` | Docs site dev server (Astro + Cookbook). |
104
+ | `pnpm build:docs` | Build the docs site into `dist/` (overwrites the library build there). |
105
+ | `pnpm build:site` | Docs site + playground, as deployed to GitHub Pages. |
106
+ | `pnpm docs:doctor` | Cookbook configuration / content checks. |
107
+
108
+ ## Stack
109
+
110
+ - **Language:** TypeScript (strict mode, `consistent-type-imports` enforced)
111
+ - **Build:** [tsdown](https://github.com/rolldown/tsdown) — ESM + CJS, unbundled, dts + sourcemaps
112
+ - **Test:** [Vitest 4](https://vitest.dev/) with globals enabled
113
+ - **Lint:** ESLint 10 + typescript-eslint + `eslint-config-prettier`
114
+ - **Format:** Prettier — single quotes, semicolons, trailing commas, 80 cols
115
+ - **Versioning:** [Changesets](https://github.com/changesets/changesets)
116
+ - **Package manager:** pnpm 11
117
+
118
+ ## Code Conventions
119
+
120
+ - TypeScript strict mode; `consistent-type-imports` enforced.
121
+ - Test files use `*.test.ts` and live next to the module they test in `src/`.
122
+ - Unused vars prefixed with `_` are allowed.
123
+ - **No runtime dependencies** — every bit of math is implemented from scratch.
124
+ - Functional API pattern: `glaze()` factory with attached static methods; no classes.
125
+ - Each module starts with a JSDoc block describing its responsibility — keep these in sync when behavior changes.
126
+
127
+ ## Adding a New Color Type
128
+
129
+ If you need to add another `ColorDef` variant (alongside regular / shadow / glow / mix), touch these files in order:
130
+
131
+ 1. [src/types.ts](src/types.ts) — add the new interface and extend the `ColorDef` discriminated union.
132
+ 2. [src/lighting.ts](src/lighting.ts) — add a discriminator predicate (`isFooDef`).
133
+ 3. [src/validation.ts](src/validation.ts) — extend `validateColorDefs` (missing-reference / cycle handling) and `topoSort` (record the new dependency edges).
134
+ 4. [src/resolver.ts](src/resolver.ts) — add a per-scheme `resolveFooForScheme` branch and dispatch from `resolveColorForScheme`.
135
+ 5. [src/formatters.ts](src/formatters.ts) — only if the output shape differs (it usually doesn't; the resolver returns a normal `ResolvedColorVariant`).
136
+ 6. `src/glaze.test.ts` — add coverage for the new def, including HC pairs, dark-mode behavior, and inheritance through `extend`.
137
+
138
+ For a new public method on `glaze` (e.g. another statics entry), the wiring lives entirely in [src/glaze.ts](src/glaze.ts); the implementation should still go in a focused module.
139
+
140
+ ## CI/CD & Release
141
+
142
+ - **CI:** Runs lint, format check, typecheck, build, and tests on push to `main` and PRs.
143
+ - **Release:** On push to `main`, `changesets/action` either creates a version PR or publishes to npm.
144
+ - **Snapshot:** Comment `/snapshot` on a PR to publish a `0.0.0-snapshot.<sha>` release.
145
+ - **npm trusted publishing:** Uses OIDC provenance via the `release` GitHub environment; the workflow requires `environment: release` for npm to accept the OIDC token.
146
+ - **`RELEASE_TOKEN` secret:** Fine-grained GitHub PAT (repo-scoped, `contents: write` + `pull-requests: write`) used by `changesets/action` for Git pushes and PR creation. Rotate before expiry.
147
+ - **Repo settings required:** Settings → Actions → General → Workflow permissions → "Allow GitHub Actions to create and approve pull requests" must be enabled.
148
+
149
+ ## Before Pushing Changes
150
+
151
+ Follow [`.cursor/commands/submit-changes.md`](.cursor/commands/submit-changes.md) for the full release-oriented workflow. At minimum:
152
+
153
+ 1. **Typecheck** — `pnpm typecheck`. Stop and fix errors before continuing.
154
+ 2. **Lint** — `pnpm lint`. Stop and fix errors before continuing.
155
+ 3. **Format** — `pnpm format` so the diff matches Prettier output.
156
+ 4. **Changeset** — for any user-visible change (features, fixes, refactors, perf, docs that affect published behavior), add a markdown file in `.changeset/` with a `patch` / `minor` / `major` bump and a concise user-facing summary. Skip only for purely internal changes (CI, repo churn, tests with no behavior change).
157
+ 5. **Commit** — Conventional Commits (`feat`, `fix`, `refactor`, `test`, `docs`, `chore`, `perf`, `ci`). Optional scope. Keep the subject short. Include the changeset file in the same commit.
158
+ 6. **Push** — never push to `main`. Confirm the current branch, then `git push -u origin HEAD`.