Gradient Gen Developer Reference
A source-level map of @auric-artisan/gradient-gen: package exports, data contracts,
interpolation engines, metrics, streaming writers, exporters, API adapters and tests.
Overview
A source-level map of @auric-artisan/gradient-gen : package exports, data contracts, interpolation engines, metrics, streaming writers, exporters, API adapters and tests.
1. Package contract
+
tool/gradient-gen/package.json defines an ESM package named
@auric-artisan/gradient-gen. It requires Node 20 or newer and exposes both the main
package entry and subpath exports.
| Export | Source | Purpose |
|---|---|---|
. |
src/index.js |
Complete public API and re-export surface. |
./core |
src/core/index.js |
Color conversion helpers and gradient data structure functions. |
./interpolation |
src/interpolation/index.js |
Easing curves and interpolation spaces. |
./algorithms |
src/algorithms/index.js |
Procedural methods, complexity profiles and recipe generation. |
./metrics |
src/metrics/index.js |
Delta E, contrast and gradient scoring. |
./dataset_engine |
src/dataset_engine/index.js |
Batch, streaming and raw dataset generation. |
./export |
src/export/index.js |
JSON, NDJSON, CSV, CSS and SVG file exporters. |
./gpu |
src/gpu/index.js |
CPU seed fallback, WebGPU-facing pipeline and WGSL shader source. |
./api |
src/api/index.js |
High-level generation, dataset, metrics and discovery functions. |
./utils |
src/utils/index.js |
RNG, math, formatting, timers and weighted picks. |
2. Public API
+
src/index.js re-exports every module except utils and names the common entry points from
src/api/api.js.
| Function | Behavior |
|---|---|
generateGradient(options) |
Creates a handmade gradient when colors or stops are passed, otherwise creates a procedural gradient. |
generateDataset(options) |
Initializes GradientDatasetGenerator and streams a dataset to disk. |
evaluateGradient(gradient) |
Runs the metric engine and returns score, Delta E, luminance, chroma, contrast, hue, banding and complexity data. |
gradientCSS(gradient, options) |
Returns linear, radial or conic CSS from gradient metadata and downsampled colors. |
getAvailableMethods() |
Returns methods, complexity profiles, interpolation spaces, easing methods and export formats. |
getSupportedFormats() |
Returns ["json", "ndjson", "csv", "css", "svg"]. |
generateGradientBatch(), generateGradientRecipe(),
generateStopColors() and exportDataset() are also available through
the default API object and module re-exports.
3. Core data model
+
src/core/gradient.js is the central model. createGradient() normalizes
stops, samples colors and returns a gradient object.
{
gradient_id: "grad_...",
name: "Auric Gradient",
stops: [
{
index: 0,
position: 0,
label: "stop-1",
hex: "#0ea5e9",
rgb: [14, 165, 233],
hsl: [199.7, 0.83, 0.48],
lab: [...],
lch: [...],
oklab: [...],
oklch: [...],
luminance: 0.3204
}
],
colors: [
{
index: 0,
position: 0,
travel: 0,
source_stop: [0, 0],
hex: "#0ea5e9",
rgb: [14, 165, 233],
...
}
],
metadata: {
topology: "linear",
angle: 90,
interpolation_space: "oklch-short",
easing: "linear",
stop_count: 3,
sample_count: 128,
complexity: 0.0932,
css: "linear-gradient(...)"
}
}
Stop normalization accepts stops entries with color, hex,
position and label, or a simpler colors array. Positions are clamped from 0 to 1,
sorted and forced to start at 0 and end at 1.
createBinaryGradient() encodes a compact binary buffer with AAGD
magic, version, stop count, sample count, channel count and RGB bytes. decodeBinaryGradient()
validates that magic and returns HEX samples.
4. Color conversion layer
+
src/core/color.js is dependency-free and uses D65 assumptions for XYZ and Lab
conversions. It includes:
- sRGB transfer functions:
srgbToLinear()andlinearToSrgb(). - HEX and RGB helpers:
rgbToHex(),hexToRgb()andnormalizeRgb(). - HSL conversion:
rgbToHsl()andhslToRgb(). - XYZ and Lab conversion:
rgbToXyz(),xyzToRgb(),rgbToLab(),labToRgb(). - LCH conversion and gamut clipping:
rgbToLch(),lchToRgb(),lchToRgbGamut(). - OKLab and OKLCH conversion and gamut clipping:
rgbToOklab(),rgbToOklch(),oklchToRgbGamut(). - Hue mixing helpers for short and long hue travel.
colorRecord() is the shared conversion bundle used for both source stops and sampled
colors.
5. Procedural algorithms
+
src/algorithms/generators.js defines the procedural recipe engine. It exports
GRADIENT_METHODS, COMPLEXITY_PROFILES,
generateStopColors(), generateGradientRecipe() and
generateComplexGradient().
simple: 2 to 4 stops, 64 recommended steps, low jitter.detailed: 5 to 12 stops, 256 recommended steps, moderate jitter.extreme: 16 to 64 stops, 1,024 recommended steps, high jitter.
The method functions combine seeded RNG, HSL conversion, OKLCH gamut clipping, sinusoidal hue
movement, harmonic hue relationships and weighted method selection. mixed is not a
direct method; it resolves through weightedPick() using the method weights.
Recipes return method, complexity, normalized stop objects and
recommendedSteps. generateComplexGradient() then calls
createGradient() with metadata containing method, profile, seed and generated flag.
6. Interpolation and easing
+
src/interpolation/spaces.js exports INTERPOLATION_SPACES and
interpolateColor(). Each branch normalizes RGB inputs and mixes in the requested
color space.
| Space | Implementation |
|---|---|
srgb |
Direct channel lerp with rounded RGB output. |
linear-rgb |
Converts channels to linear light, lerps, then converts back to sRGB. |
hsl-short, hsl-long |
Interpolates HSL with short or long hue travel. |
lab |
Interpolates CIELAB coordinates and converts back to RGB. |
lch-short, lch-long |
Interpolates Lab LCH and clamps chroma to stay in sRGB gamut. |
oklab |
Interpolates OKLab coordinates and converts back to RGB. |
oklch-short, oklch-long |
Interpolates OKLCH and clamps chroma to stay in sRGB gamut. |
src/interpolation/easing.js provides linear, polynomial, sine, exponential, smoothstep,
smootherstep and stepped easing modes. sampleGradientStops() applies easing to the
travel value, finds the active stop segment and stores both original position and eased travel.
7. Metrics Engine
+
src/metrics/metrics.js provides direct metrics and the full
evaluateGradient() report.
deltaE76()anddeltaE2000()operate on Lab coordinates.deltaERgb()converts RGB to Lab before measuring color difference.contrastRatio()computes relative-luminance contrast.evaluateGradient()accepts a gradient object or an array of RGB values.
The report computes adjacent Delta E, adjacent contrast, luminance statistics, OKLCH chroma statistics, total hue travel, luminance monotonicity, Delta E uniformity, banding risk, complexity and a weighted score. The score weights uniformity, monotonicity, banding risk and complexity.
classifyBanding() is heuristic: a very low minimum Delta E on a ramp of more than 128 samples can indicate subtle
compression, while very high mean Delta E can indicate visible step risk. Treat it as a useful
design signal, not a formal visual threshold.
8. Dataset Engine
+
src/dataset_engine/generator.js contains GradientDatasetGenerator.
Its constructor stores batchSize, seed, includeMetrics,
steps, complexity and total generated count.
generateDataset() creates a StreamingGradientWriter, generates
gradients in batches, rotates interpolation spaces and easing methods with weighted picks, and
calls the optional progress callback after each batch.
generateRawDataset() writes an AAGR binary header followed by raw RGB
rows, one gradient at a time. It uses stream backpressure and reports total bytes, elapsed time
and generation rate.
generateGradientBatch(size, options) is the small-batch helper used by examples,
benchmarks and tests. It returns an array and should not be used for million-scale output.
9. Streaming and export formats
+There are two export layers. The streaming writer supports long-running dataset jobs. The file exporters write already-materialized arrays.
| Module | Formats | Notes |
|---|---|---|
StreamingGradientWriter |
json, ndjson, csv, binary |
Uses writable streams, optional gzip and compact gradient payloads. |
exportDataset() |
json, ndjson, csv, css, svg |
Dispatches to format-specific exporters and throws on unsupported formats. |
compactGradient() keeps gradient_id, name, stops,
sampled HEX colors and metadata. This is the shape used by JSON, NDJSON and streaming output.
SVG export creates horizontal strips with linearGradient definitions. CSS export
creates class rules with a configurable prefix, defaulting to aa-gradient.
10. GPU-facing helpers
+
src/gpu/gpu-pipeline.js currently provides a CPU fallback and exports WGSL source
for browser or WebGPU integration.
generateGradientSeedsCPU(count, maxStops, seed)returns packed RGB seed bytes.GPUPipeline.init()detectsnavigator.gpubut still uses the CPU generator today.GPUPipeline.generateBatched()splits work into batches and invokes an optional batch callback.WGSL_GRADIENT_SEED_GENERATORis a compute shader for future direct GPU generation.
Treat this module as GPU-adjacent infrastructure. The production path is still CPU generation with a dependency-free fallback.
11. Generated site data
+
scripts/generate-data.js adapts package gradients into the existing site gradient
collection shape. The output directory is data/gradient-gen.
| File | Purpose |
|---|---|
gradients.json |
Site-compatible JSON array with angle, type, stops and meta. |
gradients.ndjson |
Streaming-friendly equivalent with one gradient per line. |
index.json |
Generation manifest, count, seed, methods, interpolation spaces, easing methods and score ranges. |
README.md |
Short data folder note for maintainers. |
toSiteGradient() maps stops to { pos, hex, oklch }, names gradients
by method and index, and stores score, complexity score, Delta E mean, uniformity, banding,
CSS preview, source and seed in meta.
12. API integration
+Several server-side handlers import the package directly:
api/lib/handlers/gradient.jsimportsgenerateGradientandgradientCSSfor/v1/gradient/generate.api/lib/handlers/image.jsimportsgenerateGradientfor gradient PNG rendering.api/lib/handlers/graphql.jsexposes agradientresolver.api/lib/handlers/meta.jsimportsgetAvailableMethodsfor/v1/methods/gradient.api/lib/exporters/gradient.jsimportsgradientToCssfor API export payloads.
Maintenance note: the direct package option is interpolationSpace. The current
/v1/gradient/generate adapter parses a request field named interpolation
into opts.interpolation, so update the adapter if that endpoint must expose
interpolation-space selection.
13. Tests and benchmarks
+
tests/gradient.test.js uses Node's built-in node:test. It covers:
- Multi-stop perceptual gradient creation.
- Procedural aurora generation with extreme complexity.
- Metric evaluation on a 32-sample gradient.
- CSS output and binary encoding/decoding.
- Async batch generation.
cd tool/gradient-gen
npm test
npm run benchmark
benchmarks/benchmark.js measures handmade generation, procedural generation,
evaluation, CPU seed generation and a 10,000-gradient simple batch. Use benchmark results as
relative signals after engine changes, not as absolute product guarantees.
14. Maintenance checklist
+- Keep README examples, user docs and developer docs aligned when public options change.
- Add tests whenever adding an interpolation space, easing mode, export format or metric field.
- Update
getAvailableMethods()when methods, complexity profiles, spaces, easing modes or formats change. - Regenerate
data/gradient-genwhen site-facing method plans, metadata or data shapes change. - Keep
compactGradient(), CSV headers and API exporters synchronized when metadata changes. - Validate gzip output when changing
StreamingGradientWritercompression behavior. - Review API adapters after renaming package options such as
interpolationSpace. - Run package tests, root validation and documentation discovery generation before shipping docs or data changes.
For workflow-level usage, see the Gradient Gen User Guide.