-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
executable file
·2072 lines (1832 loc) · 70.4 KB
/
Copy pathbuild.js
File metadata and controls
executable file
·2072 lines (1832 loc) · 70.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require("fs");
const path = require("path");
const { pathToFileURL } = require("url");
const chokidar = require("chokidar");
const { parseTokenBlocks } = require("./src/token-parser");
const {
generateUtilities,
generateTokenDocs,
mergeTokenBlocksByTypeAndLabel,
normalizeTokenBlocksConfig,
validateTokenDocsConfig,
withResolvedOutputs,
} = require("./src/generators");
/**
* SwatchKit Build Script
* Refactored for Phase 1 Expansion
*/
// --- 1. CLI Argument Parsing ---
function parseArgs(args) {
const options = {
command: null,
watch: false,
config: null,
input: null,
outDir: null,
cssDir: null,
force: false,
dryRun: false,
app: false,
astro: false,
standalone: false,
};
for (let i = 2; i < args.length; i++) {
const arg = args[i];
if (arg === "init") {
options.command = "init";
} else if (arg === "--app") {
options.app = true;
} else if (arg === "--astro") {
options.astro = true;
} else if (arg === "--standalone") {
options.standalone = true;
} else if (arg === "-w" || arg === "--watch") {
options.watch = true;
} else if (arg === "-h" || arg === "--help") {
options.command = "help";
} else if (arg === "-v" || arg === "--version") {
options.command = "version";
} else if (arg === "-f" || arg === "--force") {
options.force = true;
} else if (arg === "--dry-run") {
options.dryRun = true;
} else if (arg === "-c" || arg === "--config") {
// Handle case where flag is last arg
if (i + 1 < args.length) {
options.config = args[++i];
}
} else if (arg === "-i" || arg === "--input") {
if (i + 1 < args.length) {
options.input = args[++i];
}
} else if (arg === "-o" || arg === "--outDir") {
if (i + 1 < args.length) {
options.outDir = args[++i];
}
} else if (arg === "--cssDir") {
if (i + 1 < args.length) {
options.cssDir = args[++i];
}
}
}
return options;
}
// --- 2. Config Loading ---
const CONFIG_FILES = [
"swatchkit.config.cjs",
"swatchkit.config.mjs",
"swatchkit.config.js",
];
function findConfigPath(searchPath) {
if (searchPath) {
const resolved = path.resolve(process.cwd(), searchPath);
if (fs.existsSync(resolved)) {
return resolved;
}
return null;
}
for (const filename of CONFIG_FILES) {
const candidate = path.join(process.cwd(), filename);
if (fs.existsSync(candidate)) {
return candidate;
}
}
return null;
}
// Unwrap a config export to a plain config object.
// In Node 22+, require() of an ESM file returns a Module namespace
// ({ default: { ...config } }) instead of throwing. Without unwrapping
// .default, fileConfig.cssDir would be undefined and SwatchKit would
// silently fall back to the default cssDir.
function normalizeConfigExport(config) {
if (
config &&
typeof config === "object" &&
"default" in config &&
typeof config.default === "object"
) {
return config.default;
}
return config || {};
}
async function loadConfig(configPath) {
const finalPath = findConfigPath(configPath);
if (!finalPath) {
return {};
}
console.log(`[SwatchKit] Loading config from ${finalPath}`);
if (finalPath.endsWith(".cjs")) {
return normalizeConfigExport(require(finalPath));
}
if (finalPath.endsWith(".mjs")) {
const { pathToFileURL } = require("url");
const url = pathToFileURL(finalPath).href + "?t=" + Date.now();
const mod = await import(url);
return normalizeConfigExport(mod);
}
// .js: try require first, fall back to dynamic import for ESM projects.
// On Node 22+, require() of an ESM file succeeds and returns a namespace,
// so normalizeConfigExport unwraps .default either way.
try {
return normalizeConfigExport(require(finalPath));
} catch (requireError) {
if (requireError.message.includes("module is not defined")) {
try {
const { pathToFileURL } = require("url");
const url = pathToFileURL(finalPath).href + "?t=" + Date.now();
const mod = await import(url);
if (mod.default && typeof mod.default === "object") {
return mod.default;
}
throw new Error("Config must use 'export default' syntax in ESM projects.");
} catch (importError) {
throw new Error(
`[SwatchKit] Could not load config.\n\n` +
`If your project uses "type": "module", use ESM syntax:\n\n` +
` // swatchkit.config.js\n` +
` export default {\n` +
` cssDir: "./css"\n` +
` };\n\n` +
`Or rename to .cjs for CommonJS syntax:\n\n` +
` // swatchkit.config.cjs\n` +
` module.exports = {\n` +
` cssDir: "./css"\n` +
` };`
);
}
}
throw requireError;
}
}
// Detect whether the project is an ESM package (has "type": "module"
// in its package.json). Used by `swatchkit new` to generate the right
// config syntax.
function projectUsesEsm(cwd = process.cwd()) {
const packageJsonPath = path.join(cwd, "package.json");
if (!fs.existsSync(packageJsonPath)) return false;
try {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
return packageJson.type === "module";
} catch {
return false;
}
}
// Ensure package.json exists and is ESM ("type": "module"). Used by
// `init --app`, whose starter (config + build scripts) is ESM. This MUST run
// before the ESM swatchkit.config.js is written/loaded, otherwise Node loads
// the config as CommonJS and fails with "Unexpected token 'export'".
// Returns true if it created or modified package.json.
function ensureEsmPackageJson(cwd = process.cwd()) {
const packageJsonPath = path.join(cwd, "package.json");
let pkg = {};
let existed = false;
if (fs.existsSync(packageJsonPath)) {
existed = true;
try {
pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
} catch {
// Leave an unparseable package.json untouched; warn instead.
console.warn(
"[SwatchKit] Could not parse package.json — please add '\"type\": \"module\"' yourself.",
);
return false;
}
}
if (pkg.type === "module") return false;
pkg.name = pkg.name || path.basename(cwd);
pkg.version = pkg.version || "1.0.0";
pkg.private = pkg.private !== undefined ? pkg.private : true;
pkg.type = "module";
fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + "\n");
console.log(
` ${existed ? "~ Updated" : "+ Created"}: package.json ("type": "module")`,
);
return true;
}
// --- 2.5 Glob Matching Helper ---
function matchesGlob(filename, pattern) {
// Simple wildcard support
if (pattern.includes("*")) {
const parts = pattern.split("*");
// Handle "foo*"
if (pattern.endsWith("*") && !pattern.startsWith("*")) {
return filename.startsWith(parts[0]);
}
// Handle "*bar"
if (pattern.startsWith("*") && !pattern.endsWith("*")) {
return filename.endsWith(parts[1]);
}
// Handle "*bar*"
if (pattern.startsWith("*") && pattern.endsWith("*")) {
return filename.includes(parts[1]);
}
}
return filename === pattern;
}
function toTitleCase(str) {
return str.replace(/-/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
}
function categorySlug(category) {
if (category === "Design Tokens") return "tokens";
if (category === "Patterns") return "patterns";
return category.toLowerCase().replace(/\s+/g, "-");
}
function applyConfiguredOrder(items, orderedSlugs, getSlug, getLabel) {
if (!Array.isArray(orderedSlugs)) return items;
const rank = new Map(orderedSlugs.map((slug, index) => [slug, index]));
return items.slice().sort((a, b) => {
const aRank = rank.has(getSlug(a)) ? rank.get(getSlug(a)) : Number.MAX_SAFE_INTEGER;
const bRank = rank.has(getSlug(b)) ? rank.get(getSlug(b)) : Number.MAX_SAFE_INTEGER;
if (aRank !== bRank) return aRank - bRank;
return getLabel(a).localeCompare(getLabel(b));
});
}
function defaultSectionSort(a, b) {
if (a === "Design Tokens") return -1;
if (b === "Design Tokens") return 1;
if (a === "Patterns") return 1;
if (b === "Patterns") return -1;
return a.localeCompare(b);
}
const defaultRenderers = {
renderSidebarSection: ({ category, categorySlug, items }) => {
return `<h2>${category}</h2>
<ul role="list">
${items.map(p => ` <li><a href="#${p.slug}">${p.name}</a></li>`).join("\n")}
</ul>`;
},
renderSwatchSection: ({
slug,
name,
category,
categorySlug,
description,
previewHref,
escapedContent,
showSource = true,
}) => {
return `
<section id="${slug}" class="region flow">
<h2>${name} <small style="font-weight: normal; opacity: 0.6; font-size: 0.7em">(${category})</small></h2>
${description ? `<div class="swatch-description">${description}</div>` : ""}
<iframe src="${previewHref}" style="width: 100%; border: var(--stroke); min-height: 25rem; resize: auto; overflow: auto;"></iframe>
<a href="${previewHref}">View full screen</a>
${showSource ? `<details>
<summary>View source</summary>
<pre><code>${escapedContent}</code></pre>
</details>` : ""}
</section>`;
},
};
// --- 3. Smart Defaults & Path Resolution ---
function resolveSettings(cliOptions, fileConfig) {
const cwd = process.cwd();
// Helper to find patterns dir
function findSwatchkitDir() {
// 1. Explicit input
if (cliOptions.input) return path.resolve(cwd, cliOptions.input);
if (fileConfig.input) return path.resolve(cwd, fileConfig.input);
// 2. Default
return path.join(cwd, "swatchkit");
}
const swatchkitDir = findSwatchkitDir();
// Output Dir
// Default: dist/swatchkit
const outDir = cliOptions.outDir
? path.resolve(cwd, cliOptions.outDir)
: fileConfig.outDir
? path.resolve(cwd, fileConfig.outDir)
: path.join(cwd, "dist/swatchkit");
// CSS directory - where tokens.css and user's main.css live
// Default: css/ at project root
const cssDir = fileConfig.cssDir
? path.resolve(cwd, fileConfig.cssDir)
: path.join(cwd, "css");
// Token sources (v5): CSS files that may contain @swatchkit token blocks.
// Default: the scaffolded global/tokens.css, plus the conventional
// tokens.css / tokens/*.css locations inside cssDir. Users add theme files
// explicitly (e.g. a Nova theme) when needed.
const cssDirRel = path.relative(cwd, cssDir) || ".";
const tokenSources =
fileConfig.tokenSources ||
[
`${cssDirRel}/global/tokens.css`,
`${cssDirRel}/tokens.css`,
`${cssDirRel}/tokens/*.css`,
];
// Exclude patterns
const exclude = fileConfig.exclude || [];
// CSS copy behavior
// When true (default), copies cssDir into outDir/css/ for a self-contained build.
// When false, skips the copy — expects CSS to already exist at cssPath relative to output.
const cssCopy = fileConfig.cssCopy !== undefined ? fileConfig.cssCopy : true;
// Relative path from SwatchKit HTML output to the user's CSS directory.
// Only used when cssCopy is false. Derived from cssDir basename by default
// (e.g., cssDir: "./src/css" -> "../css/", cssDir: "./styles" -> "../styles/").
const cssPath =
fileConfig.cssPath || (cssCopy ? "css/" : `../${path.basename(cssDir)}/`);
// Some static servers, including Astro's public-directory dev server, do not
// resolve a directory URL to its index.html file. Keep traditional directory
// URLs by default, with an opt-in for those environments.
const explicitHtmlLinks = fileConfig.explicitHtmlLinks === true;
// Render callbacks - merge user config with defaults
const renderSidebarSection =
fileConfig.renderSidebarSection || defaultRenderers.renderSidebarSection;
const renderSwatchSection =
fileConfig.renderSwatchSection || defaultRenderers.renderSwatchSection;
const tokenDocs = fileConfig.tokenDocs || {};
validateTokenDocsConfig(tokenDocs);
const tokenBlocks = normalizeTokenBlocksConfig(fileConfig.tokenBlocks || {});
const order = fileConfig.order || {};
return {
swatchkitDir,
outDir,
cssDir,
tokenSources,
exclude,
cssCopy,
cssPath,
explicitHtmlLinks,
allowRootOutDir: fileConfig.allowRootOutDir === true,
tokenDocs,
tokenBlocks,
order,
fileConfig, // Expose config to init
// Internal layout templates (relative to this script)
internalLayout: path.join(__dirname, "src/swatchkit.html"),
internalPreviewLayout: path.join(__dirname, "src/preview-layout.html"),
// Project specific layout overrides
projectLayout: path.join(swatchkitDir, "_swatchkit.html"),
projectPreviewLayout: path.join(swatchkitDir, "_preview.html"),
projectClientScript: path.join(swatchkitDir, "swatchkit.js"),
// Derived paths
distCssDir: path.join(outDir, "css"),
distJsDir: path.join(outDir, "js"),
distPreviewDir: path.join(outDir, "preview"),
outputFile: path.join(outDir, "index.html"),
utilitiesDir: path.join(cssDir, "utilities"),
mainCssFile: path.join(cssDir, "main.css"),
// Render callbacks
renderSidebarSection,
renderSwatchSection,
};
}
// --- 4. Init Manifest & Dry Run ---
// Builds a list of all files that init manages.
// Each entry maps a blueprint source to a project destination.
// Used by both the actual init and the dry-run status report.
// Returns the next available backup path for a file.
// e.g. foo.css → foo.css.bak, then foo.css.bak2, foo.css.bak3, etc.
function getBackupPath(filePath) {
const candidate = `${filePath}.bak`;
if (!fs.existsSync(candidate)) return candidate;
let i = 2;
while (fs.existsSync(`${filePath}.bak${i}`)) i++;
return `${filePath}.bak${i}`;
}
function buildInitManifest(settings) {
const manifest = [];
const blueprintsDir = path.join(__dirname, "src/blueprints");
const templatesDir = path.join(__dirname, "src/templates");
// Hello swatch (default example in swatchkit/swatches/hello/)
for (const file of ["index.html", "README.md"]) {
manifest.push({
src: path.join(templatesDir, "hello", file),
dest: path.join(settings.swatchkitDir, "swatches", "hello", file),
});
}
// Swatches CSS folder (css/swatches/)
for (const file of ["index.css", "hello.css"]) {
manifest.push({
src: path.join(blueprintsDir, "swatches", file),
dest: path.join(settings.cssDir, "swatches", file),
});
}
// Utility and composition display templates — walk each subfolder
for (const section of ["utilities", "compositions"]) {
const sectionSrc = path.join(templatesDir, section);
if (!fs.existsSync(sectionSrc)) continue;
const folders = fs
.readdirSync(sectionSrc)
.filter((f) => fs.statSync(path.join(sectionSrc, f)).isDirectory());
for (const folder of folders) {
const folderSrc = path.join(sectionSrc, folder);
const files = fs
.readdirSync(folderSrc)
.filter((f) => f.endsWith(".html"));
for (const file of files) {
manifest.push({
src: path.join(folderSrc, file),
dest: path.join(settings.swatchkitDir, section, folder, file),
transform: (content) => content.trim(),
});
}
}
}
// CSS entry point
manifest.push({
src: path.join(blueprintsDir, "main.css"),
dest: settings.mainCssFile,
});
// SwatchKit UI styles
manifest.push({
src: path.join(blueprintsDir, "swatchkit-ui.css"),
dest: path.join(settings.cssDir, "swatchkit-ui.css"),
});
// SwatchKit preview styles (loaded only by preview pages)
manifest.push({
src: path.join(blueprintsDir, "swatchkit-preview.css"),
dest: path.join(settings.cssDir, "swatchkit-preview.css"),
});
// SwatchKit client script (loaded by the main UI and preview pages)
manifest.push({
src: path.join(blueprintsDir, "swatchkit.js"),
dest: settings.projectClientScript,
});
// CSS folder blueprints (global, compositions, utilities)
const cssFolders = ["global", "compositions", "utilities"];
for (const folder of cssFolders) {
const srcDir = path.join(blueprintsDir, folder);
if (fs.existsSync(srcDir)) {
const files = fs
.readdirSync(srcDir)
.filter((f) => !fs.statSync(path.join(srcDir, f)).isDirectory());
for (const file of files) {
manifest.push({
src: path.join(srcDir, file),
dest: path.join(settings.cssDir, folder, file),
});
}
}
}
// Layout files
manifest.push({
src: settings.internalLayout,
dest: settings.projectLayout,
});
manifest.push({
src: settings.internalPreviewLayout,
dest: settings.projectPreviewLayout,
});
return manifest;
}
// Directories that init ensures exist.
function getInitDirs(settings) {
return [
settings.swatchkitDir,
path.join(settings.swatchkitDir, "tokens"),
path.join(settings.swatchkitDir, "utilities"),
path.join(settings.swatchkitDir, "compositions"),
path.join(settings.swatchkitDir, "swatches"),
path.join(settings.swatchkitDir, "swatches", "hello"),
settings.cssDir,
path.join(settings.cssDir, "global"),
path.join(settings.cssDir, "utilities"),
path.join(settings.cssDir, "swatches"),
];
}
// Compare init-managed files against their blueprint sources and print a
// status report showing what would be created, changed, or is up to date.
function reportInitStatus(settings) {
const cwd = process.cwd();
const manifest = buildInitManifest(settings);
const dirs = getInitDirs(settings);
const newDirs = [];
const created = [];
const changed = [];
const upToDate = [];
for (const dir of dirs) {
if (!fs.existsSync(dir)) {
newDirs.push(path.relative(cwd, dir) + "/");
}
}
for (const entry of manifest) {
const relDest = path.relative(cwd, entry.dest);
if (!fs.existsSync(entry.dest)) {
created.push(relDest);
} else {
let srcContent = fs.readFileSync(entry.src, "utf-8");
if (entry.transform) srcContent = entry.transform(srcContent);
const destContent = fs.readFileSync(entry.dest, "utf-8");
if (srcContent !== destContent) {
changed.push(relDest);
} else {
upToDate.push(relDest);
}
}
}
if (newDirs.length === 0 && created.length === 0 && changed.length === 0) {
console.log("[SwatchKit] All init-managed files are up to date.");
return;
}
if (newDirs.length > 0 || created.length > 0) {
console.log("\n New (will be created):");
for (const d of newDirs) console.log(` + ${d}`);
for (const f of created) console.log(` + ${f}`);
}
if (changed.length > 0) {
console.log("\n Changed (differs from latest blueprint):");
for (const f of changed) console.log(` ~ ${f}`);
}
if (upToDate.length > 0) {
console.log("\n Up to date:");
for (const f of upToDate) console.log(` = ${f}`);
}
console.log("");
if (changed.length > 0 || created.length > 0 || newDirs.length > 0) {
console.log(
" Run 'swatchkit init --force' to update all files to latest blueprints.\n",
);
}
}
// --- 5. Config Generation ---
function generateConfig(cssDir, app = false, standalone = false, astro = false) {
// Astro owns the application build. Keep the generated library under public
// so Astro serves it in dev and copies it into the final build unchanged.
// The source CSS is copied into the library to avoid relying on Astro's
// hashed CSS output paths.
if (astro) {
const astroBody = `{
outDir: "./public/swatchkit",
cssDir: "${cssDir}",
cssCopy: true,
explicitHtmlLinks: true,
}`;
return `// swatchkit.config.mjs\nexport default ${astroBody};\n`;
}
// App mode: integrated config (a build tool owns the CSS, so SwatchKit
// references the shared stylesheet rather than copying it). The app starter
// always sets "type": "module" in package.json, so the config is ESM.
if (app) {
const appBody = `{
cssDir: "${cssDir}",
// Integrated app: esbuild (scripts/build-assets.js) owns the CSS, so
// SwatchKit references the shared stylesheet instead of copying it. Both the
// app and the pattern library point at dist/css/main.css.
cssCopy: false,
cssPath: "../css/",
}`;
return `// swatchkit.config.js\nexport default ${appBody};\n`;
}
if (standalone) {
const standaloneBody = `{
// Standalone mode: SwatchKit is the whole hosted site.
// This writes dist/index.html, dist/preview/*, dist/css/*, and dist/js/*.
outDir: "./dist",
allowRootOutDir: true,
cssDir: "${cssDir}",
cssCopy: true,
}`;
if (projectUsesEsm()) {
return `// swatchkit.config.js
export default ${standaloneBody};
`;
}
return `// swatchkit.config.js
module.exports = ${standaloneBody};
`;
}
const body = `{
// Where your CSS lives. SwatchKit scaffolds blueprints here and reads
// your @swatchkit token blocks from here when building the pattern library.
cssDir: "${cssDir}",
// Set to false if a build tool (Vite, Astro, Eleventy, etc.) is already
// handling your CSS and you don't need SwatchKit to copy it.
cssCopy: true,
// CSS files scanned for @swatchkit token blocks (supports a trailing * glob).
// Default: ["<cssDir>/global/tokens.css", "<cssDir>/tokens.css", "<cssDir>/tokens/*.css"].
// Add theme files explicitly, e.g. ["${cssDir}/global/tokens.css", "${cssDir}/theme.css"].
// tokenSources: ["${cssDir}/global/tokens.css", "${cssDir}/theme.css"],
// Where the built pattern library is output.
// outDir: "./dist/swatchkit",
// Files or folders to exclude from the pattern library (supports globs).
// exclude: [],
// Control sidebar section order and swatch order inside each section.
// Order lists are partial: listed slugs come first; unlisted items follow
// alphabetically. Ordering runs after exclude and tokenBlocks docs filters.
// order: {
// sections: ["tokens", "components", "compositions", "utilities", "patterns"],
// swatches: {
// tokens: ["aries-brand-colors", "colors", "fonts"],
// components: ["button", "card"],
// },
// },
// Control generated outputs from @swatchkit token blocks. CSS token blocks
// define token groups; config controls generated outputs. Omitted output keys
// use defaults: docs true, utilities true when supported.
// tokenBlocks: {
// textSizes: {
// docs: { excludeLabels: ["Steps"] },
// utilities: { excludeLabels: ["Typography"] },
// labels: {
// Steps: { docs: false, utilities: true },
// Typography: { docs: true, utilities: false },
// },
// },
// },
// Customize generated token documentation presentation. Output visibility is
// controlled by tokenBlocks, not tokenDocs.
// tokenDocs: {
// showSource: false, // generated token docs hide source by default
// colors: {
// columns: ["name", "value", "customProperty"],
// columnLabels: { customProperty: "CSS variable" },
// },
// },
// Render callbacks for customizing generated markup.
// If omitted, SwatchKit uses its default rendering.
// renderSidebarSection: ({ category, categorySlug, items }) => string,
// renderSwatchSection: ({ slug, name, category, categorySlug, description, previewHref, content, escapedContent, sourceKind, showSource }) => string,
}`;
if (projectUsesEsm()) {
return `// swatchkit.config.js
export default ${body};
`;
}
return `// swatchkit.config.js
module.exports = ${body};
`;
}
// Ensure swatchkit.config.js exists. Returns a promise resolving to the
// resolved cssDir (relative form, e.g. "./src/css"). If the config already
// exists, resolves with null (the caller keeps the existing settings).
function ensureConfig(cliOptions) {
const cwd = process.cwd();
const existingConfigPath = CONFIG_FILES.map((f) => path.join(cwd, f)).find(
(f) => fs.existsSync(f),
);
const configPath =
cliOptions.astro && existingConfigPath
? existingConfigPath
: path.join(cwd, cliOptions.astro ? "swatchkit.config.mjs" : "swatchkit.config.js");
const configExists = Boolean(existingConfigPath);
if (configExists && !cliOptions.force) {
return Promise.resolve(null);
}
const writeConfig = (cssDir) => {
if (fs.existsSync(configPath) && cliOptions.force) {
const backupPath = getBackupPath(configPath);
fs.copyFileSync(configPath, backupPath);
console.log(
` ~ Backed up: swatchkit.config.js → ${path.basename(backupPath)}`,
);
}
fs.writeFileSync(
configPath,
generateConfig(
cssDir,
cliOptions.app,
cliOptions.standalone,
cliOptions.astro,
),
);
const mode = cliOptions.app
? ", integrated app"
: cliOptions.standalone
? ", standalone"
: "";
console.log(
`+ Created: ${path.basename(configPath)} (cssDir: ${cssDir}${mode})`,
);
return cssDir;
};
// Non-interactive: --cssDir provided.
if (cliOptions.cssDir) {
const cssDir = `./${cliOptions.cssDir.trim().replace(/^\.\//, "")}`;
return Promise.resolve(writeConfig(cssDir));
}
// Interactive prompt.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question("Where does your CSS live? [src/css]: ", (answer) => {
rl.close();
const cssDir = answer.trim()
? `./${answer.trim().replace(/^\.\//, "")}`
: "./src/css";
resolve(writeConfig(cssDir));
});
});
}
// --- 6. Init Command Logic (merged config + scaffold) ---
function scaffold(settings, options) {
const isInitialized = fs.existsSync(settings.swatchkitDir);
// --dry-run: always just report status, change nothing.
// Already initialized without --force: auto dry-run.
if (options.dryRun || (isInitialized && !options.force)) {
if (isInitialized && !options.dryRun) {
console.log("[SwatchKit] Project already initialized.");
}
reportInitStatus(settings);
return;
}
// Sanity check: internal layout template must exist
if (!fs.existsSync(settings.internalLayout)) {
console.error(
`Error: Internal layout file not found at ${settings.internalLayout}`,
);
process.exit(1);
}
console.log("[SwatchKit] Scaffolding project structure...");
// Ensure directories exist
const cwd = process.cwd();
for (const dir of getInitDirs(settings)) {
if (!fs.existsSync(dir)) {
console.log(`+ Directory: ${path.relative(cwd, dir)}/`);
fs.mkdirSync(dir, { recursive: true });
}
}
// Files that are auto-generated by SwatchKit — never back these up
const swatchkitOwned = [path.join(settings.utilitiesDir, "utilities.css")];
// Copy all manifest files
const manifest = buildInitManifest(settings);
for (const entry of manifest) {
const exists = fs.existsSync(entry.dest);
if (options.force || !exists) {
// Ensure parent directory exists (for CSS subdirs like compositions/)
const parentDir = path.dirname(entry.dest);
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, { recursive: true });
}
// Back up existing user-owned files before overwriting with --force
if (exists && options.force && !swatchkitOwned.includes(entry.dest)) {
const backupPath = getBackupPath(entry.dest);
fs.copyFileSync(entry.dest, backupPath);
console.log(
` ~ Backed up: ${path.relative(cwd, entry.dest)} → ${path.basename(backupPath)}`,
);
}
let content = fs.readFileSync(entry.src, "utf-8");
if (entry.transform) content = entry.transform(content);
fs.writeFileSync(entry.dest, content);
const label = path.relative(cwd, entry.dest);
console.log(`${exists ? "~ Updated" : "+ Created"}: ${label}`);
}
}
// Generate utilities.css from the scaffolded tokens.css @swatchkit blocks.
try {
const blocks = parseTokenBlocks(settings.tokenSources, cwd);
if (blocks.length > 0) {
generateUtilities(blocks, settings.utilitiesDir);
console.log(
`+ Generated: ${path.relative(cwd, path.join(settings.utilitiesDir, "utilities.css"))} (do not edit manually)`,
);
}
} catch (e) {
console.warn(`[SwatchKit] Could not generate utilities: ${e.message}`);
}
// App/standalone starters print their own next-steps messages.
if (options.app || options.standalone) return;
const tokensCssRel = path.relative(
cwd,
path.join(settings.cssDir, "global", "tokens.css"),
);
const outputIndexRel = options.standalone
? "dist/index.html"
: "dist/swatchkit/index.html";
console.log(`
Done! Here's what to do next:
1. Edit your design tokens in ${tokensCssRel}
Tokens live in /* @swatchkit <type> "Label" */ ... /* @swatchkit end */
blocks. Edit the values directly — it's plain, hand-editable CSS.
2. Run "swatchkit" to build the pattern library
3. Open ${outputIndexRel} to view it
`);
}
// --- 6.4 Astro Starter Scaffold (swatchkit init --app --astro) ---
// Adds the shared render-function examples and pattern swatches to an existing
// Astro project. Astro owns pages, layouts, and asset bundling; SwatchKit writes
// its separate static site into public/swatchkit.
function scaffoldAstro(settings, options) {
const cwd = process.cwd();
const appTemplates = path.join(__dirname, "src/templates/app");
console.log("\n[SwatchKit] Scaffolding Astro app integration...");
const fileMap = [
["src/components/button.js", "src/components/button.js"],
["src/components/card.js", "src/components/card.js"],
["css/button.css", path.join(settings.cssDir, "swatches", "button.css")],
["css/card.css", path.join(settings.cssDir, "swatches", "card.css")],
["swatches/button/index.js", "swatchkit/swatches/button/index.js"],
[
"swatches/button/description.html",
"swatchkit/swatches/button/description.html",
],
["swatches/card/index.js", "swatchkit/swatches/card/index.js"],
[
"swatches/card/description.html",
"swatchkit/swatches/card/description.html",
],
];
for (const [rel, destRel] of fileMap) {
const src = path.join(appTemplates, rel);
const dest = path.isAbsolute(destRel) ? destRel : path.join(cwd, destRel);
const exists = fs.existsSync(dest);
if (exists && !options.force) {
console.log(` = Skipped (exists): ${path.relative(cwd, dest)}`);
continue;
}
fs.mkdirSync(path.dirname(dest), { recursive: true });
if (exists && options.force) {
const backupPath = getBackupPath(dest);
fs.copyFileSync(dest, backupPath);
console.log(
` ~ Backed up: ${path.relative(cwd, dest)} → ${path.basename(backupPath)}`,
);
}
fs.copyFileSync(src, dest);
console.log(` ${exists ? "~ Updated" : "+ Created"}: ${path.relative(cwd, dest)}`);
}
// Register example component styles in the shared SwatchKit stylesheet.
const swatchIndex = path.join(settings.cssDir, "swatches", "index.css");
if (fs.existsSync(swatchIndex)) {
let css = fs.readFileSync(swatchIndex, "utf-8");
let changed = false;
for (const imp of ['@import "button.css";', '@import "card.css";']) {
if (!css.includes(imp)) {
css = css.trimEnd() + "\n" + imp + "\n";
changed = true;
}
}
if (changed) {
fs.writeFileSync(swatchIndex, css);
console.log(
` ~ Updated: ${path.relative(cwd, swatchIndex)} (registered button.css, card.css)`,
);
}
}
const pkgPath = path.join(cwd, "package.json");
const pkgExisted = fs.existsSync(pkgPath);
let pkg = {};
if (pkgExisted) {
try {
pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
} catch {
console.warn(" ! Could not parse existing package.json — leaving it untouched.");
pkg = null;
}
}
if (pkg) {
const before = pkgExisted ? fs.readFileSync(pkgPath, "utf-8") : null;
pkg.name = pkg.name || path.basename(cwd);
pkg.version = pkg.version || "1.0.0";
pkg.private = pkg.private !== undefined ? pkg.private : true;
pkg.type = "module";
pkg.scripts = pkg.scripts || {};
if (pkg.scripts["build:swatchkit"] === undefined || options.force) {
pkg.scripts["build:swatchkit"] = "swatchkit";
}
if (pkg.scripts["swatchkit:watch"] === undefined || options.force) {
pkg.scripts["swatchkit:watch"] = "swatchkit --watch";
}