@raketa-cloud/design-cli 1.0.3 → 1.1.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
@@ -43,6 +43,18 @@ Configuration, preview HTML and `_theme_preview.html` are trusted local inputs;
43
43
 
44
44
  Run `npm test` here for tooling behavior. Consumers should separately validate integration and preview appearance; the build does not change their production wiring.
45
45
 
46
+ ## Repository-backed presets
47
+
48
+ Set `"preset": { "repo": "git@github.com:example/admin-ui.git", "ref": "main" }` in `.design/config.json`. The repository contains `.design/` for shared design inputs and `raketa/` for runtime assets. Run `design preset update` to resolve the ref and write `.design/preset.lock.json`; commit the lock. On a fresh checkout run `design preset install` before building. Generate and serve do not fetch; updates are explicit and reviewable. Git access must be available without an interactive prompt.
49
+
50
+ The disposable `.design/.preset/` cache is ignored by its own ignore file. Install and update link `.design/.preset/runtime` to the selected `raketa/` directory; host CSS and JavaScript can import from that path. Run generate or serve after changing the selected preset. Production builds must install first and include the generated theme and runtime assets using the host's framework-specific wiring.
51
+
52
+ For live preset development, set `DESIGN_PRESET_DIR` to a local checkout and run generate or serve. Changes to that checkout are visible through the runtime link and showcase. This override is forbidden when `CI` is set. Restart the showcase after changing the checkout location.
53
+
54
+ Token JSON objects merge recursively; arrays replace wholesale. Local component and layout pattern directories replace the entire matching preset pattern. Additional local component CSS follows preset CSS. `tokenOverrides` maps `:root` and `.dark` to existing CSS variable names and values; unknown names are rejected. For example: `"tokenOverrides": { ":root": { "--color-action": "#123456" } }`. Not every valid CSS color expression can be rendered in catalog swatches; inspect the actual preview and generated CSS.
55
+
56
+ Preset repositories, previews and runtime JavaScript are trusted inputs. The installer does not invoke preset install scripts, but Git uses your configuration and credentials, including any configured checkout filters. Using preset CSS, JavaScript or Tailwind plugins can execute or load untrusted content. Review changes and test framework integration separately.
57
+
46
58
  ## Publishing
47
59
 
48
60
  The package is public on npm even though this repository is private. In npm package settings, add a GitHub Actions trusted publisher for organization `studioraketa`, repository `design-system-tools`, workflow filename `publish.yml`, with direct `npm publish` allowed and no environment name. The workflow uses GitHub OIDC rather than an npm token; Node 24 supplies the required npm 11.5.1 or later. Complete the first publish within two days of creating the trusted publisher. Private repositories do not generate npm provenance.
package/build.mjs CHANGED
@@ -1,6 +1,7 @@
1
- import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
2
- import { dirname, join, relative } from 'node:path';
1
+ import { lstat, mkdir, readFile, realpath, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
3
  import { tokenSource, themePath } from './config.mjs';
4
+ import { overlayJson, overlayFiles } from './overlay.mjs';
4
5
 
5
6
  const validName = /^--[a-z][a-z0-9-]*$/;
6
7
  const safeValue = value => {
@@ -45,16 +46,12 @@ function block(selector, declarations) {
45
46
  for (const [key, value] of Object.entries(declarations)) { if (!validName.test(key)) throw new Error('Invalid CSS token name: ' + key); safeValue(value); }
46
47
  return selector + ' {\n' + Object.entries(declarations).map(([key, value]) => ` ${key}: ${value};`).join('\n') + '\n}\n';
47
48
  }
48
- async function jsonIfPresent(path) {
49
- try { return JSON.parse(await readFile(path, 'utf8')); }
50
- catch (error) { if (error.code === 'ENOENT') return null; throw error; }
51
- }
52
- async function tokenCSS(designDir) {
53
- const { input, type } = await tokenSource(designDir);
49
+ export async function tokenCSS(context) {
50
+ const { input, type } = await tokenSource(context);
54
51
  const native = type === 'raketa-css';
55
52
  let css = '';
56
53
  if (native) {
57
- const extra = await jsonIfPresent(join(designDir, 'tokens/palettes.json')) || {};
54
+ const extra = await overlayJson(context, 'tokens/palettes.json') || {};
58
55
  for (const selector of Object.keys(extra)) if (![':root', '.dark'].includes(selector)) throw new Error('Unsupported palette selector: ' + selector);
59
56
  const root = { ...(extra[':root'] || {}) };
60
57
  let dark = { ...(extra['.dark'] || {}) };
@@ -69,7 +66,7 @@ async function tokenCSS(designDir) {
69
66
  }
70
67
  }
71
68
  css += block(':root', root) + block('.dark', { ...themedAliases, ...dark });
72
- const components = await jsonIfPresent(join(designDir, 'tokens/components.json'));
69
+ const components = await overlayJson(context, 'tokens/components.json');
73
70
  if (components?.components) {
74
71
  const baseRoles = flattenTokens(components.components, true, ['components']);
75
72
  const darkRoles = components.themes?.dark?.components ? flattenTokens(components.themes.dark.components, true, ['components']) : {};
@@ -85,27 +82,95 @@ async function tokenCSS(designDir) {
85
82
  css += block(name === 'dark' ? '.dark' : '.theme-' + name, { ...themed, ...flattenTokens(values, false) });
86
83
  }
87
84
  }
85
+ const overrides = context.config?.tokenOverrides;
86
+ if (overrides !== undefined) {
87
+ if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) throw new Error('Invalid tokenOverrides');
88
+ const names = new Set([...css.matchAll(/(--[a-z][a-z0-9-]*)\s*:/g)].map(match => match[1]));
89
+ for (const [selector, values] of Object.entries(overrides)) {
90
+ if (![':root', '.dark'].includes(selector) || !values || typeof values !== 'object' || Array.isArray(values)) throw new Error('Invalid tokenOverrides selector: ' + selector);
91
+ for (const [name, value] of Object.entries(values)) {
92
+ if (!names.has(name)) throw new Error('Unknown CSS variable override: ' + name);
93
+ if (typeof value !== 'string') throw new Error('Invalid CSS token value');
94
+ safeValue(value);
95
+ }
96
+ }
97
+ const darkBlocks = [...css.matchAll(/\.dark \{\n[^}]*\}\n/g)].map(match => match[0]).join('');
98
+ css = css.replace(/\.dark \{\n[^}]*\}\n/g, '');
99
+ if (overrides[':root']) css += block(':root', overrides[':root']);
100
+ css += darkBlocks;
101
+ if (overrides['.dark']) css += block('.dark', overrides['.dark']);
102
+ }
88
103
  return css;
89
104
  }
90
- async function styles(directory) {
91
- let entries;
92
- try { entries = await readdir(directory, { withFileTypes: true }); }
93
- catch (error) { if (error.code === 'ENOENT') return []; throw error; }
94
- return (await Promise.all(entries.map(entry => {
95
- const path = join(directory, entry.name);
96
- if (entry.isDirectory()) return styles(path);
97
- return entry.isFile() && entry.name.endsWith('.css') && entry.name !== 'preview.css' ? [path] : [];
98
- }))).flat().sort();
105
+ export function applyCatalogOverrides(input, overrides = {}) {
106
+ const data = structuredClone(input);
107
+ const paths = new Map();
108
+ function collect(group, path = []) {
109
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return;
110
+ if (Object.hasOwn(group, '$value')) { paths.set(cssName(path.join('.'), false), path.join('.')); return; }
111
+ for (const [key, child] of Object.entries(group)) if (!key.startsWith('$') && key !== 'themes') collect(child, [...path, key]);
112
+ }
113
+ collect(data);
114
+ let sequence = 0;
115
+ function colorReference(value) {
116
+ const variable = value.match(/^var\((--[a-z][a-z0-9-]*)\)$/)?.[1];
117
+ if (variable && paths.has(variable)) return `{${paths.get(variable)}}`;
118
+ const key = 'override-' + sequence++;
119
+ data.derived ||= {}; data.derived.color ||= {};
120
+ data.derived.color[key] = { $type: 'color', $value: value };
121
+ return `{derived.color.${key}}`;
122
+ }
123
+ function apply(group, values, path = []) {
124
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return;
125
+ if (Object.hasOwn(group, '$value')) {
126
+ const name = cssName(path.join('.'), false);
127
+ if (Object.hasOwn(values, name)) group.$value = group.$type === 'color' && ['semantic', 'components'].includes(path[0]) ? colorReference(values[name]) : values[name];
128
+ return;
129
+ }
130
+ for (const [key, child] of Object.entries(group)) if (!key.startsWith('$') && key !== 'themes') apply(child, values, [...path, key]);
131
+ }
132
+ apply(data, overrides[':root'] || {});
133
+ if (overrides['.dark']) {
134
+ data.themes ||= {}; data.themes.dark ||= {};
135
+ // Supply inherited groups so a dark-only override can target a root variable.
136
+ const inherited = structuredClone({ semantic: data.semantic, components: data.components || {} });
137
+ const merge = (a, b) => {
138
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || Array.isArray(a) || Array.isArray(b)) return b;
139
+ for (const [key, value] of Object.entries(b)) a[key] = key in a ? merge(a[key], value) : value;
140
+ return a;
141
+ };
142
+ data.themes.dark = merge(inherited, data.themes.dark);
143
+ apply(data.themes.dark, overrides['.dark']);
144
+ const replacements = new Map();
145
+ for (const [name, value] of Object.entries(overrides['.dark'])) {
146
+ const path = paths.get(name);
147
+ if (path?.startsWith('primitive.color.') || path?.startsWith('derived.color.')) replacements.set(`{${path}}`, colorReference(value));
148
+ }
149
+ function rewrite(group) {
150
+ if (!group || typeof group !== 'object' || Array.isArray(group)) return;
151
+ if (Object.hasOwn(group, '$value')) { if (replacements.has(group.$value)) group.$value = replacements.get(group.$value); return; }
152
+ for (const child of Object.values(group)) rewrite(child);
153
+ }
154
+ rewrite(data.themes.dark);
155
+ }
156
+ return data;
157
+ }
158
+ export async function renderTheme(context) {
159
+ let css = '/* Generated by design-tooling; edit the design sources instead. */\n' + await tokenCSS(context);
160
+ const files = (await overlayFiles(context, 'components')).filter(file => file.name.endsWith('.css') && !file.name.endsWith('/preview.css'));
161
+ const localRoot = await realpath(context.designDir);
162
+ files.sort((a, b) => Number(a.path.startsWith(localRoot + '/')) - Number(b.path.startsWith(localRoot + '/')) || a.name.localeCompare(b.name));
163
+ for (const { name, path } of files) {
164
+ const content = await readFile(path, 'utf8');
165
+ if (/@(?:apply|import|theme|source)\b/.test(content)) throw new Error('Component styles must be standalone CSS: ' + name);
166
+ css += `\n/* ${name} */\n` + content.trim() + '\n';
167
+ }
168
+ return css;
99
169
  }
100
170
  export async function build(context) {
101
171
  const output = themePath(context);
102
172
  const dir = dirname(output);
103
- let css = '/* Generated by design-tooling; edit the design sources instead. */\n' + await tokenCSS(context.designDir);
104
- for (const path of await styles(join(context.designDir, 'components'))) {
105
- const content = await readFile(path, 'utf8');
106
- if (/@(?:apply|import|theme|source)\b/.test(content)) throw new Error('Component styles must be standalone CSS: ' + relative(context.designDir, path));
107
- css += `\n/* ${relative(context.designDir, path).split('\\').join('/')} */\n` + content.trim() + '\n';
108
- }
173
+ const css = await renderTheme(context);
109
174
  const existing = await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
110
175
  if (existing && !existing.isFile()) throw new Error('Build output must be a regular file');
111
176
  await mkdir(dir, { recursive: true });
package/cli.mjs CHANGED
@@ -6,7 +6,7 @@ import { build } from './build.mjs';
6
6
 
7
7
  const [command, ...args] = process.argv.slice(2);
8
8
  if (command === '--help' || command === '-h' || !command) {
9
- console.log('Usage: design <init|generate|serve|new>\n\n init Set up a design system and agent skill\n generate Build the design system CSS\n serve Start the local showcase\n new <component|layout> <name> Scaffold a pattern');
9
+ console.log('Usage: design <init|generate|serve|new|preset>\n\n init Set up a design system and agent skill\n generate Build the design system CSS\n serve Start the local showcase\n new <component|layout> <name> Scaffold a pattern\n preset <update|install> Pin or install a preset');
10
10
  } else if (command === '--version' || command === '-v') {
11
11
  const { readFile } = await import('node:fs/promises');
12
12
  console.log(JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')).version);
@@ -14,6 +14,10 @@ if (command === '--help' || command === '-h' || !command) {
14
14
  if (args.length) throw new Error('Unexpected arguments');
15
15
  const { init } = await import('./init.mjs');
16
16
  await init();
17
+ } else if (command === 'preset') {
18
+ if (args.length !== 1 || !['update', 'install'].includes(args[0])) throw new Error('Usage: design preset <update|install>');
19
+ const { updatePreset, installPreset } = await import('./preset.mjs');
20
+ await (args[0] === 'update' ? updatePreset : installPreset)(await loadConfig());
17
21
  } else if (command === 'new') {
18
22
  const [kind, name, ...extra] = args;
19
23
  if (!['component', 'layout'].includes(kind) || !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(name || '') || extra.length) throw new Error('Usage: design new <component|layout> <kebab-case-name>');
@@ -34,8 +38,13 @@ if (command === '--help' || command === '-h' || !command) {
34
38
  console.log(`Created ${kind}: ${target}`);
35
39
  } else if (command === 'generate') {
36
40
  if (args.length) throw new Error('Unexpected arguments');
37
- await build(await loadConfig());
41
+ const context = await loadConfig();
42
+ const { refreshPresetRuntime } = await import('./preset.mjs');
43
+ await refreshPresetRuntime(context);
44
+ await build(context);
38
45
  } else if (command === 'serve') {
39
46
  if (args.length) throw new Error('Unexpected arguments');
47
+ const { refreshPresetRuntime } = await import('./preset.mjs');
48
+ await refreshPresetRuntime(await loadConfig());
40
49
  await import('./showcase/serve.mjs');
41
- } else throw new Error('Usage: design <init|generate|serve|new>');
50
+ } else throw new Error('Usage: design <init|generate|serve|new|preset>');
package/config.mjs CHANGED
@@ -3,6 +3,8 @@ import { dirname, resolve } from 'node:path';
3
3
  import { showcaseData } from './catalog/css-native.mjs';
4
4
  import { statusColors } from './catalog/status-colors.mjs';
5
5
  import { previewCss } from './preview-css.mjs';
6
+ import { overlayJson } from './overlay.mjs';
7
+ import { tokenCSS, applyCatalogOverrides } from './build.mjs';
6
8
 
7
9
  export async function loadConfig() {
8
10
  const designDir = await realpath(resolve(process.env.DESIGN_DIR || '.design'));
@@ -17,23 +19,33 @@ export function themePath({ config, projectDir }) {
17
19
  if (!build || typeof build.output !== 'string' || !build.output.trim()) throw new Error('build.output is required');
18
20
  return resolve(projectDir, build.output, system.id, 'theme.css');
19
21
  }
20
- export async function tokenSource(designDir) {
21
- const input = JSON.parse(await readFile(resolve(designDir, 'tokens/tokens.json'), 'utf8'));
22
+ export async function tokenSource(source) {
23
+ const context = typeof source === 'string' ? { designDir: source } : source;
24
+ const input = await overlayJson(context, 'tokens/tokens.json', true);
22
25
  const cssNative = Array.isArray(input?.blocks);
23
26
  const normalized = !!input?.primitive?.color && !!input?.semantic?.color;
24
27
  if (cssNative === normalized) throw new Error('Unrecognized or ambiguous tokens/tokens.json format');
25
28
  return { input, type: cssNative ? 'raketa-css' : 'tokens' };
26
29
  }
27
30
 
28
- export async function raketaInputs({ designDir }, input) {
29
- const componentTokens = JSON.parse(await readFile(resolve(designDir, 'tokens/components.json'), 'utf8'));
31
+ export async function raketaInputs(context, input) {
32
+ const componentTokens = await overlayJson(context, 'tokens/components.json', true);
30
33
  return { input, componentTokens };
31
34
  }
32
35
 
33
36
  export async function catalog(context) {
34
- const { input, type } = await tokenSource(context.designDir);
35
- if (type === 'tokens') return input;
37
+ const { input, type } = await tokenSource(context);
38
+ await tokenCSS(context); // Validate overrides even when only rendering the catalog.
39
+ if (type === 'tokens') return applyCatalogOverrides(input, context.config?.tokenOverrides);
36
40
  const { componentTokens } = await raketaInputs(context, input);
37
41
  const status = statusColors(await previewCss(context));
38
- return showcaseData(input, status, componentTokens);
42
+ const adjusted = structuredClone(input);
43
+ for (const [selector, values] of Object.entries(context.config?.tokenOverrides || {})) {
44
+ for (const [name, value] of Object.entries(values)) {
45
+ for (const entry of adjusted.blocks) {
46
+ if (entry.selector === selector || (selector === ':root' && ['@theme', '@theme inline'].includes(entry.selector) && Object.hasOwn(entry.tokens, name))) entry.tokens[name] = { $type: 'string', $value: value };
47
+ }
48
+ }
49
+ }
50
+ return showcaseData(adjusted, status, componentTokens);
39
51
  }
package/overlay.mjs ADDED
@@ -0,0 +1,75 @@
1
+ import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
2
+ import { join, resolve, sep } from 'node:path';
3
+
4
+ export async function presetDesign(context) {
5
+ // preset.mjs is supplied by the installer. Keep standalone callers working too.
6
+ let resolver;
7
+ try { ({ resolvePreset: resolver } = await import('./preset.mjs')); }
8
+ catch (error) { if (error.code === 'ERR_MODULE_NOT_FOUND' && error.message.includes("/preset.mjs")) return null; throw error; }
9
+ const root = await resolver(context);
10
+ if (!root) return null;
11
+ const directory = join(root, '.design');
12
+ const info = await lstat(directory);
13
+ if (!info.isDirectory()) throw new Error('Preset .design must be a directory, not a symlink');
14
+ return directory;
15
+ }
16
+ const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
17
+ export function mergeObjects(base, local) {
18
+ if (!object(base) || !object(local)) return local;
19
+ const result = { ...base };
20
+ for (const [key, value] of Object.entries(local)) {
21
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) throw new Error('Invalid token key: ' + key);
22
+ result[key] = Object.hasOwn(result, key) ? mergeObjects(result[key], value) : value;
23
+ }
24
+ return result;
25
+ }
26
+ async function json(root, path) {
27
+ try {
28
+ const actual = await realpath(join(root, path));
29
+ if (!actual.startsWith(await realpath(root) + sep)) throw new Error('Token path escapes design directory');
30
+ return JSON.parse(await readFile(actual, 'utf8'));
31
+ }
32
+ catch (error) { if (error.code === 'ENOENT') return undefined; throw error; }
33
+ }
34
+ export async function overlayJson(context, path, required = false) {
35
+ const base = await presetDesign(context);
36
+ const [a, b] = await Promise.all([base ? json(base, path) : undefined, json(context.designDir, path)]);
37
+ if (a === undefined && b === undefined && required) { const e = new Error('Missing ' + path); e.code = 'ENOENT'; throw e; }
38
+ return b === undefined ? a : a === undefined ? b : mergeObjects(a, b);
39
+ }
40
+ async function exists(path) { try { return await lstat(path); } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return null; throw e; } }
41
+ // Resolve only inside the selected root; a local pattern replaces the complete base pattern.
42
+ export async function overlayPath(context, name, resolvedBase) {
43
+ const parts = name.split('/');
44
+ if (parts.some(p => !p || p === '.' || p === '..' || p.startsWith('.'))) return null;
45
+ const base = resolvedBase === undefined ? await presetDesign(context) : resolvedBase;
46
+ let root = context.designDir;
47
+ const unit = ['components', 'layouts'].includes(parts[0]) ? parts.slice(0, 2) : parts[0] === 'assets' ? parts.slice(0, 3) : parts;
48
+ const localUnit = await exists(join(root, ...unit));
49
+ if (!localUnit && base) root = base;
50
+ const path = resolve(root, ...parts);
51
+ try {
52
+ let current = root;
53
+ for (const part of parts) {
54
+ current = join(current, part);
55
+ if ((await lstat(current)).isSymbolicLink()) return null;
56
+ }
57
+ const realRoot = await realpath(root), actual = await realpath(path);
58
+ if (!actual.startsWith(realRoot + sep) || !(await lstat(path)).isFile()) return null;
59
+ return actual;
60
+ } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return null; throw e; }
61
+ }
62
+ export async function overlayFiles(context, folder) {
63
+ const base = await presetDesign(context);
64
+ async function walk(root, dir) {
65
+ let entries; try { entries = await readdir(join(root, dir), { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') return []; throw e; }
66
+ return (await Promise.all(entries.filter(e => !e.name.startsWith('.')).map(e => {
67
+ const path = [dir, e.name].join('/');
68
+ return e.isDirectory() ? walk(root, path) : e.isFile() ? [path] : [];
69
+ }))).flat();
70
+ }
71
+ const names = new Set([...(base ? await walk(base, folder) : []), ...await walk(context.designDir, folder)]);
72
+ const files = [];
73
+ for (const name of [...names].sort()) { const path = await overlayPath(context, name, base); if (path) files.push({ name, path }); }
74
+ return files;
75
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raketa-cloud/design-cli",
3
- "version": "1.0.3",
3
+ "version": "1.1.2",
4
4
  "description": "CLI for building and previewing local design systems",
5
5
  "repository": {
6
6
  "type": "git",
package/preset.mjs ADDED
@@ -0,0 +1,158 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, resolve, sep } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+
7
+ const exec = promisify(execFile);
8
+ // Honor the user's Git credentials and SSH configuration while avoiding prompts.
9
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
10
+ async function git(args, cwd, readOnly = false) {
11
+ const { stdout } = await exec('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], { cwd, env: readOnly ? { ...env, GIT_OPTIONAL_LOCKS: '0' } : env, maxBuffer: 10 * 1024 * 1024 });
12
+ return stdout.trim();
13
+ }
14
+ function presetConfig(context) {
15
+ const preset = context.config?.preset;
16
+ if (preset == null) return null;
17
+ if (!preset || typeof preset !== 'object' || Array.isArray(preset) || typeof preset.repo !== 'string' || !preset.repo.trim() || preset.repo !== preset.repo.trim() || /[\x00-\x1f]/.test(preset.repo) || preset.repo.startsWith('-') || preset.repo.includes('::') || (preset.repo.includes('://') && !/^(?:https|ssh|git|file):\/\//i.test(preset.repo)) || typeof preset.ref !== 'string' || !preset.ref.trim() || preset.ref !== preset.ref.trim() || preset.ref.startsWith('-') || /[\x00-\x20\x7f]/.test(preset.ref)) throw new Error('Invalid config.preset: repo and ref are required');
18
+ return { repo: preset.repo, ref: preset.ref };
19
+ }
20
+ function source(repo, context) {
21
+ if (isAbsolute(repo) || repo.includes('://') || /^[^/]+@[^:]+:/.test(repo)) return repo;
22
+ return resolve(context.projectDir || process.cwd(), repo);
23
+ }
24
+ function cachePath(context, lock) {
25
+ const key = createHash('sha256').update(JSON.stringify([lock.repo, lock.ref, lock.commit])).digest('hex');
26
+ return join(context.designDir, '.preset', key);
27
+ }
28
+ async function readLock(context, preset) {
29
+ let lock;
30
+ try { lock = JSON.parse(await readFile(join(context.designDir, 'preset.lock.json'), 'utf8')); }
31
+ catch (error) { throw new Error(`Cannot read preset lock; run design preset update: ${error.message}`); }
32
+ if (!lock || typeof lock !== 'object' || Array.isArray(lock) || typeof lock.repo !== 'string' || !lock.repo || typeof lock.ref !== 'string' || !lock.ref || typeof lock.commit !== 'string' || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(lock.commit) || Object.keys(lock).sort().join(',') !== 'commit,ref,repo') throw new Error('Malformed preset lock; run design preset update');
33
+ if (lock.repo !== preset.repo || lock.ref !== preset.ref) throw new Error('Preset lock does not match config.preset; run design preset update');
34
+ return lock;
35
+ }
36
+ async function validateCheckout(context, lock) {
37
+ const path = cachePath(context, lock);
38
+ try {
39
+ if (!(await lstat(path)).isDirectory()) throw new Error('not a directory');
40
+ const [head, origin, status] = await Promise.all([
41
+ git(['rev-parse', '--verify', 'HEAD^{commit}'], path, true),
42
+ git(['config', '--get', 'remote.origin.url'], path, true),
43
+ git(['status', '--porcelain', '--untracked-files=all', '--ignore-submodules=none'], path, true),
44
+ ]);
45
+ if (head !== lock.commit || origin !== source(lock.repo, context) || status) throw new Error('checkout differs from lock or has local changes');
46
+ return path;
47
+ } catch (error) { throw new Error(`Preset checkout missing or invalid; run design preset install: ${error.message}`); }
48
+ }
49
+
50
+ // This function only returns data paths; it never imports or executes preset files.
51
+ export async function resolvePreset(context) {
52
+ if (process.env.DESIGN_PRESET_DIR !== undefined) {
53
+ if (process.env.CI !== undefined) throw new Error('DESIGN_PRESET_DIR is forbidden when CI is set');
54
+ if (!process.env.DESIGN_PRESET_DIR) throw new Error('DESIGN_PRESET_DIR must not be empty');
55
+ const path = await realpath(resolve(process.env.DESIGN_PRESET_DIR));
56
+ if (!(await lstat(path)).isDirectory()) throw new Error('DESIGN_PRESET_DIR must be a directory');
57
+ return path;
58
+ }
59
+ const preset = presetConfig(context);
60
+ if (!preset) return null;
61
+ return validateCheckout(context, await readLock(context, preset));
62
+ }
63
+
64
+ // Runtime assets are linked, never copied or executed, so local edits remain visible.
65
+ async function linkRuntime(preset, cache) {
66
+ const assets = join(preset, 'raketa');
67
+ let target;
68
+ try {
69
+ target = await realpath(assets);
70
+ if (!target.startsWith(await realpath(preset) + sep) || !(await lstat(target)).isDirectory()) throw new Error('not a directory inside the preset');
71
+ } catch (error) { throw new Error(`Invalid preset runtime directory ${assets}: ${error.message}`); }
72
+ const runtime = join(cache, 'runtime');
73
+ try {
74
+ if (!(await lstat(runtime)).isSymbolicLink()) throw new Error(`Refusing to replace non-symlink runtime path: ${runtime}`);
75
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
76
+ const temporary = join(cache, `.runtime-${randomUUID()}`);
77
+ try {
78
+ await symlink(target, temporary, 'dir');
79
+ await rename(temporary, runtime);
80
+ } finally { await rm(temporary, { force: true }); }
81
+ }
82
+
83
+ export async function refreshPresetRuntime(context) {
84
+ const preset = await resolvePreset(context);
85
+ if (!preset) return;
86
+ await withOperation(context, cache => linkRuntime(preset, cache));
87
+ }
88
+
89
+ function forbidCIOverride() {
90
+ if (process.env.DESIGN_PRESET_DIR !== undefined && process.env.CI !== undefined) throw new Error('DESIGN_PRESET_DIR is forbidden when CI is set');
91
+ }
92
+
93
+ async function withOperation(context, action) {
94
+ const cache = join(context.designDir, '.preset');
95
+ await mkdir(cache, { recursive: true });
96
+ // Ignore the entire disposable cache, including this ignore file itself.
97
+ await writeFile(join(cache, '.gitignore'), '*\n');
98
+ const mutex = join(cache, '.operation');
99
+ try { await mkdir(mutex); } catch (error) {
100
+ if (error.code === 'EEXIST') throw new Error('Another preset operation is in progress');
101
+ throw error;
102
+ }
103
+ try { return await action(cache); } finally { await rm(mutex, { recursive: true, force: true }); }
104
+ }
105
+ async function checkout(context, lock, temp) {
106
+ await git(['clone', '--no-checkout', '--no-hardlinks', '--', source(lock.repo, context), temp], context.projectDir);
107
+ if (!lock.commit) {
108
+ await git(['fetch', '--no-tags', 'origin', lock.ref], temp);
109
+ lock.commit = await git(['rev-parse', '--verify', 'FETCH_HEAD^{commit}'], temp);
110
+ } else {
111
+ try { await git(['cat-file', '-e', `${lock.commit}^{commit}`], temp); }
112
+ catch { await git(['fetch', '--no-tags', 'origin', lock.commit], temp); }
113
+ }
114
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(lock.commit)) throw new Error('Invalid preset commit');
115
+ await git(['checkout', '--detach', '--force', lock.commit], temp);
116
+ }
117
+ async function install(context, lock, cache) {
118
+ const temp = await mkdtemp(join(cache, '.staging-'));
119
+ try {
120
+ await checkout(context, lock, temp);
121
+ const target = cachePath(context, lock);
122
+ // Existing immutable checkouts are only reused if still valid.
123
+ try { await validateCheckout(context, lock); return target; } catch { /* replace invalid checkout */ }
124
+ const old = join(cache, `.old-${randomUUID()}`);
125
+ try { await rename(target, old); } catch (error) { if (error.code !== 'ENOENT') throw error; }
126
+ try { await rename(temp, target); } catch (error) {
127
+ try { await rename(old, target); } catch { /* no previous checkout */ }
128
+ throw error;
129
+ } finally { await rm(old, { recursive: true, force: true }); }
130
+ return target;
131
+ } finally { await rm(temp, { recursive: true, force: true }); }
132
+ }
133
+ export async function updatePreset(context) {
134
+ forbidCIOverride();
135
+ const preset = presetConfig(context);
136
+ if (!preset) throw new Error('config.preset is required');
137
+ return withOperation(context, async cache => {
138
+ const lock = { ...preset, commit: '' };
139
+ const path = await install(context, lock, cache);
140
+ await linkRuntime(path, cache);
141
+ const temporary = join(context.designDir, `.preset-lock-${randomUUID()}`);
142
+ try {
143
+ await writeFile(temporary, JSON.stringify(lock, null, 2) + '\n', { flag: 'wx' });
144
+ await rename(temporary, join(context.designDir, 'preset.lock.json'));
145
+ } finally { await rm(temporary, { force: true }); }
146
+ return path;
147
+ });
148
+ }
149
+ export async function installPreset(context) {
150
+ forbidCIOverride();
151
+ const preset = presetConfig(context);
152
+ if (!preset) throw new Error('config.preset is required');
153
+ return withOperation(context, async cache => {
154
+ const path = await install(context, await readLock(context, preset), cache);
155
+ await linkRuntime(path, cache);
156
+ return path;
157
+ });
158
+ }
package/preview-css.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { readFile, access } from 'node:fs/promises';
2
+ import { access } from 'node:fs/promises';
3
3
  import { createRequire } from 'node:module';
4
4
  import { dirname, resolve } from 'node:path';
5
- import { themePath } from './config.mjs';
5
+ import { themePath, tokenSource } from './config.mjs';
6
+ import { overlayFiles, presetDesign } from './overlay.mjs';
7
+ import { renderTheme } from './build.mjs';
6
8
 
7
9
  const require = createRequire(import.meta.url);
8
10
  const cli = resolve(dirname(require.resolve('@tailwindcss/cli/package.json')), 'dist/index.mjs');
@@ -11,7 +13,10 @@ const tailwind = require.resolve('tailwindcss/index.css');
11
13
  // Preview compilation is independent of the host application's toolchain.
12
14
  export async function previewCss(context) {
13
15
  const { projectDir, designDir, config } = context;
14
- const tokens = JSON.parse(await readFile(resolve(designDir, 'tokens/tokens.json'), 'utf8'));
16
+ const { input: tokens } = await tokenSource(context);
17
+ const base = await presetDesign(context);
18
+ const dynamic = !!base || !!config?.tokenOverrides;
19
+ const sources = dynamic ? [...await overlayFiles(context, 'components'), ...await overlayFiles(context, 'layouts')] : [];
15
20
  const extraCss = config?.preview?.css;
16
21
  if (extraCss !== undefined && (typeof extraCss !== 'string' || !extraCss.trim())) throw new Error('preview.css must be a non-empty path');
17
22
  const output = config ? themePath(context) : null;
@@ -24,12 +29,11 @@ export async function previewCss(context) {
24
29
  );
25
30
  const input = [
26
31
  `@import ${JSON.stringify(tailwind)} source(none);`,
27
- ...(generated ? [`@import ${JSON.stringify(output)};`] : []),
32
+ ...(dynamic ? [await renderTheme(context)] : generated ? [`@import ${JSON.stringify(output)};`] : []),
28
33
  ...(extraCss ? [`@import ${JSON.stringify(resolve(projectDir, extraCss))};`] : []),
29
34
  ...(typeof tokens.variant === 'string' ? [tokens.variant] : []),
30
35
  ...blocks,
31
- `@source ${JSON.stringify(resolve(designDir, 'components'))};`,
32
- `@source ${JSON.stringify(resolve(designDir, 'layouts'))};`,
36
+ ...(dynamic ? sources.map(file => `@source ${JSON.stringify(file.path)};`) : [`@source ${JSON.stringify(resolve(designDir, 'components'))};`, `@source ${JSON.stringify(resolve(designDir, 'layouts'))};`]),
33
37
  '@source inline("bg-{red,green,orange,yellow}-{50,{100..900..100},950}");'
34
38
  ].join('\n');
35
39
  return new Promise((resolvePromise, reject) => {
@@ -1,13 +1,15 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { watch } from 'node:fs';
3
- import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';
4
- import { dirname, extname, join, relative, resolve, sep } from 'node:path';
3
+ import { lstat, readFile, realpath } from 'node:fs/promises';
4
+ import { dirname, extname, join, sep } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { resolveThemeDetails, cssName } from '../tokens/themes.mjs';
7
7
  import { scanAssets } from './assets.mjs';
8
8
  import { assetGrid } from './asset-grid.mjs';
9
9
  import { loadConfig, catalog, themePath } from '../config.mjs';
10
10
  import { previewCss } from '../preview-css.mjs';
11
+ import { overlayFiles, overlayPath, presetDesign } from '../overlay.mjs';
12
+ import { renderTheme } from '../build.mjs';
11
13
  const toolDir = dirname(fileURLToPath(import.meta.url));
12
14
  const context = await loadConfig();
13
15
  const root = context.designDir;
@@ -36,28 +38,11 @@ async function designName() {
36
38
  return name.trim();
37
39
  }
38
40
  async function optionalFontsLink() {
39
- try {
40
- return (await stat(join(root, 'showcase-fonts.css'))).isFile() ? '<link rel="stylesheet" href="/showcase-fonts.css">' : '';
41
- } catch (error) {
42
- if (error.code === 'ENOENT') return '';
43
- throw error;
44
- }
41
+ return await overlayPath(await loadConfig(), 'showcase-fonts.css') ? '<link rel="stylesheet" href="/showcase-fonts.css">' : '';
45
42
  }
46
43
 
47
44
  async function files(folder) {
48
- const start = join(root, folder);
49
- async function walk(dir) {
50
- let entries;
51
- try { entries = await readdir(dir, { withFileTypes: true }); }
52
- catch (error) { if (error.code === 'ENOENT') return []; throw error; }
53
- const nested = await Promise.all(entries.map(async entry => {
54
- const path = join(dir, entry.name);
55
- if (entry.isDirectory()) return walk(path);
56
- return entry.isFile() ? [relative(root, path)] : [];
57
- }));
58
- return nested.flat();
59
- }
60
- return (await walk(start)).sort((a, b) => a.localeCompare(b));
45
+ return (await overlayFiles(await loadConfig(), folder)).map(file => file.name);
61
46
  }
62
47
  function tokensIn(group, path = []) {
63
48
  if (!group || typeof group !== 'object') return [];
@@ -127,7 +112,8 @@ async function exampleIndex(folder) {
127
112
  if (!examples.length) return '<p class="empty">No ' + escape(folder) + ' yet.</p>';
128
113
  const items = await Promise.all(examples.map(async path => {
129
114
  const companion = join(dirname(path), 'docs.md');
130
- const markdown = await readFile(join(root, companion), 'utf8').catch(error => { if (error.code === 'ENOENT') return ''; throw error; });
115
+ const companionPath = await overlayPath(await loadConfig(), companion);
116
+ const markdown = companionPath ? await readFile(companionPath, 'utf8') : '';
131
117
  const name = dirname(path).split(sep).pop().replace(/[-_]/g, ' ');
132
118
  const title = markdown.match(/^#\s+(.+)$/m)?.[1] || name;
133
119
  return '<li><a class="example-title" href="' + urlFor(path) + '">' + escape(title) + '</a><span class="links"><a href="' + urlFor(path) + '">Preview ↗</a>' + (markdown ? '<a href="' + urlFor(companion) + '">Docs ↗</a>' : '') + '</span></li>';
@@ -135,7 +121,23 @@ async function exampleIndex(folder) {
135
121
  return '<ul class="example-list">' + items.join('') + '</ul>';
136
122
  }
137
123
  async function assetIndex() {
138
- const { categories } = await scanAssets(root);
124
+ const current = await loadConfig();
125
+ const base = await presetDesign(current);
126
+ async function safeScan(directory) {
127
+ const info = await lstat(join(directory, 'assets')).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
128
+ return info?.isDirectory() ? scanAssets(directory) : { categories: [] };
129
+ }
130
+ const local = await safeScan(root);
131
+ const shared = base ? await safeScan(base) : { categories: [] };
132
+ const merged = new Map(shared.categories.map(category => [category.name, category]));
133
+ for (const category of local.categories) {
134
+ const prior = merged.get(category.name);
135
+ if (!prior) { merged.set(category.name, category); continue; }
136
+ const assets = new Map(prior.assets.map(asset => [asset.name, asset]));
137
+ for (const asset of category.assets) assets.set(asset.name, asset);
138
+ merged.set(category.name, { ...prior, ...category, docs: category.docs || prior.docs, invalid: [...prior.invalid, ...category.invalid], assets: [...assets.values()].sort((a, b) => a.name.localeCompare(b.name)) });
139
+ }
140
+ const categories = [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));
139
141
  if (!categories.length) return '<p class="empty">No asset categories included.</p>';
140
142
  return categories.map(category => {
141
143
  const title = category.name.replace(/[-_]/g, ' ');
@@ -213,8 +215,14 @@ function scheduleReload() {
213
215
  clearTimeout(reloadTimer);
214
216
  reloadTimer = setTimeout(() => { for (const client of clients) client.write('event: reload\ndata: changed\n\n'); }, 150);
215
217
  }
216
- for (const directory of [root, ...(!toolDir.startsWith(root + sep) && toolDir !== root ? [toolDir] : [])]) {
217
- const watcher = watch(directory, { recursive: true }, scheduleReload);
218
+ const sharedRoot = await presetDesign(context);
219
+ for (const directory of [...new Set([root, ...(sharedRoot ? [sharedRoot] : []), ...(!toolDir.startsWith(root + sep) && toolDir !== root ? [toolDir] : [])])]) {
220
+ const watcher = watch(directory, { recursive: true }, (_event, name) => {
221
+ // Git may refresh its index while preset validation runs during a request.
222
+ // Those metadata writes are not design changes and must not reload the page.
223
+ if (name && String(name).split(/[\\/]/).includes('.git')) return;
224
+ scheduleReload();
225
+ });
218
226
  watcher.on('error', error => console.error('Live reload watcher failed:', error));
219
227
  }
220
228
  // Watch the one configured output directory; theme generation occurs outside .design.
@@ -252,9 +260,11 @@ createServer(async (req, res) => {
252
260
  return res.end(req.method === 'HEAD' ? undefined : withReload(html));
253
261
  }
254
262
  if (pathname === '/__showcase/theme.css') {
255
- const output = themePath(await loadConfig());
256
- if (!(await lstat(output)).isFile()) { res.writeHead(404); return res.end('Not found'); }
257
- const css = await readFile(output);
263
+ const current = await loadConfig();
264
+ const output = themePath(current);
265
+ const dynamic = !!(await presetDesign(current)) || !!current.config?.tokenOverrides;
266
+ if (!dynamic && !(await lstat(output).catch(error => { if (error.code === 'ENOENT') return null; throw error; }))?.isFile()) { res.writeHead(404); return res.end('Not found'); }
267
+ const css = dynamic ? await renderTheme(current) : await readFile(output);
258
268
  res.writeHead(200, { 'Content-Type': mime['.css'], 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
259
269
  return res.end(req.method === 'HEAD' ? undefined : css);
260
270
  }
@@ -275,10 +285,11 @@ createServer(async (req, res) => {
275
285
  return res.end(req.method === 'HEAD' ? undefined : css);
276
286
  }
277
287
  if (pathname.includes('\0')) { res.writeHead(400); return res.end('Bad request'); }
278
- const candidate = resolve(root, '.' + pathname);
279
- if (candidate !== root && !candidate.startsWith(root + sep)) { res.writeHead(403); return res.end('Forbidden'); }
280
- const path = await realpath(candidate);
281
- if (!path.startsWith(root + sep) || !(await stat(path)).isFile()) { res.writeHead(404); return res.end('Not found'); }
288
+ const name = pathname.slice(1);
289
+ const segments = name.split('/');
290
+ if (segments.some(part => !part || part === '..' || part.startsWith('.')) || !['components', 'layouts', 'assets', 'DESIGN.md', '_theme_preview.html', 'showcase-fonts.css'].includes(segments[0])) { res.writeHead(404); return res.end('Not found'); }
291
+ const path = await overlayPath(await loadConfig(), name);
292
+ if (!path) { res.writeHead(404); return res.end('Not found'); }
282
293
  const data = await readFile(path);
283
294
  const extension = extname(path).toLowerCase();
284
295
  res.writeHead(200, { 'Content-Type': mime[extension] || 'application/octet-stream', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });