zazz-ui 0.0.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,685 @@
1
+ import { i as offlineMiss, n as kitTooNew, r as kitTooOld, t as ZazzError } from "./errors-DC2U2USS.js";
2
+ import chalk from "chalk";
3
+ import { existsSync } from "node:fs";
4
+ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import pacote from "pacote";
8
+ import os from "node:os";
9
+ import * as clack from "@clack/prompts";
10
+ import { createHash } from "node:crypto";
11
+
12
+ //#region src/collisions.ts
13
+ /**
14
+ * @fileoverview The stray-file collision prompt, shared by every
15
+ * command that writes files it has no provenance record for.
16
+ * @description A write whose destination already exists is a conflict: prompt
17
+ * (default no), or overwrite everything under `--force`. Skipped paths are
18
+ * reported by the caller and turn the exit code to 2 — the file's pristine
19
+ * hash is still recorded, so repair/update can reason about it later.
20
+ */
21
+ async function filterCollisions(writes, context) {
22
+ if (context.force) return {
23
+ kept: writes,
24
+ skipped: []
25
+ };
26
+ const kept = [];
27
+ const skipped = [];
28
+ for (const write of writes) {
29
+ if (!existsSync(write.dest)) {
30
+ kept.push(write);
31
+ continue;
32
+ }
33
+ if (await context.ui.confirm(`${write.dest} already exists. Overwrite?`, false)) kept.push(write);
34
+ else skipped.push(write.dest);
35
+ }
36
+ return {
37
+ kept,
38
+ skipped
39
+ };
40
+ }
41
+
42
+ //#endregion
43
+ //#region src/config.ts
44
+ /**
45
+ * @fileoverview `zazz.json` — the project's vendoring provenance record.
46
+ * @description One file at the project root records what was vendored, from
47
+ * which kit version, and the sha256 of each file's pristine published bytes
48
+ * at vendor time (never the on-disk state, so edits stay detectable forever).
49
+ * Every command loads it by walking up from the cwd, and every successful
50
+ * transaction rewrites it exactly once.
51
+ */
52
+ const CONFIG_NAME = "zazz.json";
53
+ /** Walks up from `cwd` to find the nearest zazz.json. */
54
+ async function loadConfig(cwd) {
55
+ let dir = path.resolve(cwd);
56
+ for (;;) {
57
+ const file = path.join(dir, CONFIG_NAME);
58
+ let raw;
59
+ try {
60
+ raw = await readFile(file, "utf8");
61
+ } catch {
62
+ const parent = path.dirname(dir);
63
+ if (parent === dir) return null;
64
+ dir = parent;
65
+ continue;
66
+ }
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(raw);
70
+ } catch (error) {
71
+ throw new ZazzError(`${file} is not valid JSON: ${error.message}`);
72
+ }
73
+ return {
74
+ config: validateConfig(parsed, file),
75
+ root: dir
76
+ };
77
+ }
78
+ }
79
+ async function saveConfig(root, config) {
80
+ await writeFile(path.join(root, CONFIG_NAME), serializeConfig(config));
81
+ }
82
+ /** Stable key order so diffs of zazz.json stay readable. */
83
+ function serializeConfig(config) {
84
+ const ordered = {
85
+ kit: {
86
+ version: config.kit.version,
87
+ integrity: config.kit.integrity
88
+ },
89
+ dir: config.dir,
90
+ language: config.language,
91
+ legacy: config.legacy,
92
+ head: {
93
+ fonts: config.head.fonts,
94
+ themeScript: config.head.themeScript
95
+ },
96
+ base: {
97
+ ...config.base.version !== void 0 ? { version: config.base.version } : {},
98
+ files: sortKeys(config.base.files)
99
+ },
100
+ primitives: Object.fromEntries(Object.keys(config.primitives).sort().map((name) => {
101
+ const entry = config.primitives[name];
102
+ if (!entry) throw new ZazzError(`primitive entry vanished while saving: ${name}`);
103
+ return [name, {
104
+ version: entry.version,
105
+ files: sortKeys(entry.files)
106
+ }];
107
+ }))
108
+ };
109
+ return `${JSON.stringify(ordered, null, 2)}\n`;
110
+ }
111
+ function sortKeys(files) {
112
+ return Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b)));
113
+ }
114
+ /** Structural validation with pointed messages; throws ZazzError. */
115
+ function validateConfig(raw, source) {
116
+ const fail = (detail) => {
117
+ throw new ZazzError(`${source} is not a valid zazz config: ${detail}`, { hint: "if you edited it by hand, compare against a fresh `zazz-ui init` in an empty directory" });
118
+ };
119
+ if (typeof raw !== "object" || raw === null) fail("not an object");
120
+ const config = raw;
121
+ const kit = config.kit;
122
+ if (typeof kit !== "object" || kit === null || typeof kit.version !== "string") fail("kit.version missing");
123
+ if (typeof config.dir !== "string" || config.dir.length === 0) fail("dir missing");
124
+ if (config.language !== "js" && config.language !== "ts") fail("language must be js or ts");
125
+ if (config.legacy !== null && typeof config.legacy !== "string") fail("legacy must be a path or null");
126
+ const head = config.head;
127
+ if (typeof head !== "object" || head === null || typeof head.fonts !== "boolean" || typeof head.themeScript !== "boolean") fail("head.fonts / head.themeScript missing");
128
+ const base = config.base;
129
+ if (typeof base !== "object" || base === null || !isFileHashes(base.files)) fail("base.files missing");
130
+ if (base && base.version !== void 0 && typeof base.version !== "string") fail("base.version must be a string");
131
+ const primitives = config.primitives;
132
+ if (typeof primitives !== "object" || primitives === null) fail("primitives missing");
133
+ for (const [name, entry] of Object.entries(primitives)) {
134
+ const record = entry;
135
+ if (typeof record !== "object" || record === null || typeof record.version !== "string" || !isFileHashes(record.files)) fail(`primitives.${name} is malformed`);
136
+ }
137
+ return raw;
138
+ }
139
+ function isFileHashes(value) {
140
+ return typeof value === "object" && value !== null && Object.values(value).every((hash) => typeof hash === "string");
141
+ }
142
+
143
+ //#endregion
144
+ //#region src/kit.ts
145
+ /**
146
+ * @fileoverview The kit engine: npm tarball → validated, importable kit.
147
+ * @description Resolves a `@zazz-ui/core` spec through pacote (npm-identical
148
+ * semver/dist-tag resolution, SSRI verification, offline-capable caching),
149
+ * extracts the tarball into a version-keyed cache directory, then imports the
150
+ * kit's own compiled `src/manifest.js` and `src/head.js` straight out of the
151
+ * extract — the manifest in the tarball is the registry, and the
152
+ * kit's own `buildHead`/`resolveClosure` run rather than reimplementations.
153
+ * `MANIFEST_VERSION` gates everything: a kit newer than this CLI understands
154
+ * fails with "upgrade the CLI", never a parse error.
155
+ */
156
+ /** The one package the CLI vendors from. */
157
+ const KIT_PACKAGE = "@zazz-ui/core";
158
+ /** Inclusive range of kit manifest versions this CLI understands. */
159
+ const SUPPORTED_MANIFEST = {
160
+ min: 1,
161
+ max: 2
162
+ };
163
+ const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
164
+ /**
165
+ * @description Turns a user-facing version argument into a full pacote spec.
166
+ * The `ZAZZ_UI_KIT` environment variable overrides the whole spec (e2e tests
167
+ * point it at a `file:…tgz`); otherwise `@zazz-ui/core@<version>`. An
168
+ * override may contain `{version}`, substituted per request — the seam the
169
+ * update/diff e2e uses to serve different fixture tarballs per version.
170
+ */
171
+ function kitSpec(version) {
172
+ const override = process.env.ZAZZ_UI_KIT;
173
+ if (override !== void 0) return override.replaceAll("{version}", version);
174
+ return `${KIT_PACKAGE}@${version}`;
175
+ }
176
+ function isFileSpec(spec) {
177
+ return spec.startsWith("file:") || spec.endsWith(".tgz") || spec.startsWith("/");
178
+ }
179
+ /**
180
+ * @description Resolves a spec to an exact version, extracts the tarball
181
+ * (cache-keyed by version for registry specs; fresh temp dir for file specs,
182
+ * which can change between builds), and loads + validates the kit modules.
183
+ *
184
+ * @param spec - Anything pacote accepts: `@zazz-ui/core@0.5.0`, `…@latest`,
185
+ * a range, or a `file:` tarball.
186
+ * @param fetch - Flattened npm/pacote options from `loadFetchOptions`.
187
+ */
188
+ async function resolveKit(spec, fetch) {
189
+ const fileSpec = isFileSpec(spec);
190
+ const exact = !fileSpec && EXACT_VERSION.test(spec.slice(14));
191
+ const options = {
192
+ ...fetch,
193
+ preferOffline: exact || fetch.offline === true
194
+ };
195
+ let manifest;
196
+ try {
197
+ manifest = await pacote.manifest(spec, options);
198
+ } catch (error) {
199
+ if (fetch.offline || fetch.preferOffline) throw offlineMiss(spec);
200
+ throw new ZazzError(`could not resolve ${spec}: ${error.message}`);
201
+ }
202
+ const version = manifest.version;
203
+ const integrity = manifest.dist?.integrity ?? manifest._integrity ?? "";
204
+ return loadKitFromDir(fileSpec ? await extractFresh(spec, options) : await extractCached(version, options), {
205
+ version,
206
+ integrity
207
+ });
208
+ }
209
+ /** Registry tarballs are immutable → extract once per version, reuse forever. */
210
+ async function extractCached(version, options) {
211
+ const dir = path.join(options.cache, "extract", KIT_PACKAGE, version);
212
+ if (existsSync(path.join(dir, "package.json"))) return dir;
213
+ await mkdir(path.dirname(dir), { recursive: true });
214
+ const tmp = await mkdtemp(`${dir}.tmp-`);
215
+ try {
216
+ await pacote.extract(`${KIT_PACKAGE}@${version}`, tmp, options);
217
+ await rename(tmp, dir);
218
+ } catch (error) {
219
+ await rm(tmp, {
220
+ recursive: true,
221
+ force: true
222
+ });
223
+ if (existsSync(path.join(dir, "package.json"))) return dir;
224
+ throw error;
225
+ }
226
+ return dir;
227
+ }
228
+ /** file: tarballs can change between builds → always extract fresh. */
229
+ async function extractFresh(spec, options) {
230
+ const base = path.join(options.cache, "extract", "local");
231
+ await mkdir(base, { recursive: true });
232
+ const dir = await mkdtemp(path.join(base, "kit-"));
233
+ await pacote.extract(spec, dir, options);
234
+ return dir;
235
+ }
236
+ /**
237
+ * @description Imports and validates the kit modules from an extracted
238
+ * package directory. Exported separately from `resolveKit` so the gating
239
+ * logic is testable against plain fixture directories, no tarball involved.
240
+ */
241
+ async function loadKitFromDir(extractDir, meta) {
242
+ const srcDir = path.join(extractDir, "src");
243
+ let manifestModule;
244
+ let headModule;
245
+ try {
246
+ manifestModule = await import(pathToFileURL(path.join(srcDir, "manifest.js")).href);
247
+ headModule = await import(pathToFileURL(path.join(srcDir, "head.js")).href);
248
+ } catch (error) {
249
+ throw kitTooNew(meta.version, `its modules could not load: ${error.message}`);
250
+ }
251
+ const manifestVersion = manifestModule.MANIFEST_VERSION;
252
+ if (typeof manifestVersion !== "number" || !Number.isInteger(manifestVersion)) throw kitTooNew(meta.version, "it declares no manifest version");
253
+ if (manifestVersion > SUPPORTED_MANIFEST.max) throw kitTooNew(meta.version, `manifest v${manifestVersion} > supported v${SUPPORTED_MANIFEST.max}`);
254
+ if (manifestVersion < SUPPORTED_MANIFEST.min) throw kitTooOld(meta.version, `manifest v${manifestVersion} < supported v${SUPPORTED_MANIFEST.min}`);
255
+ const primitives = manifestModule.PRIMITIVES;
256
+ const cascade = manifestModule.CSS_CASCADE_ORDER;
257
+ const resolveClosure = manifestModule.resolveClosure;
258
+ const buildHead = headModule.buildHead;
259
+ if (typeof primitives !== "object" || primitives === null || !Array.isArray(cascade) || typeof resolveClosure !== "function" || typeof buildHead !== "function") throw kitTooNew(meta.version, "its manifest shape is unrecognized");
260
+ const baseCssPre = manifestModule.BASE_CSS_PRE;
261
+ const baseCssPost = manifestModule.BASE_CSS_POST;
262
+ const coreRuntime = manifestModule.CORE_RUNTIME;
263
+ const corePolyfills = manifestModule.CORE_POLYFILLS;
264
+ return {
265
+ version: meta.version,
266
+ integrity: meta.integrity,
267
+ extractDir,
268
+ manifest: {
269
+ manifestVersion,
270
+ primitives,
271
+ cssCascadeOrder: cascade,
272
+ resolveClosure,
273
+ ...Array.isArray(baseCssPre) ? { baseCssPre } : {},
274
+ ...Array.isArray(baseCssPost) ? { baseCssPost } : {},
275
+ ...Array.isArray(coreRuntime) ? { coreRuntime } : {},
276
+ ...Array.isArray(corePolyfills) && corePolyfills.every(isRuntimePolyfill) ? { corePolyfills } : {}
277
+ },
278
+ buildHead,
279
+ readFile: async (srcRelPath) => readFile(resolveWithin(srcDir, srcRelPath)),
280
+ has: (srcRelPath) => existsSync(resolveWithin(srcDir, srcRelPath))
281
+ };
282
+ }
283
+ function isRuntimePolyfill(value) {
284
+ if (typeof value !== "object" || value === null) return false;
285
+ const { file, supports } = value;
286
+ return typeof file === "string" && Array.isArray(supports) && supports.length === 2 && supports.every((part) => typeof part === "string");
287
+ }
288
+ /** Path-traversal guard for manifest-supplied paths. */
289
+ function resolveWithin(root, relative) {
290
+ const resolved = path.resolve(root, relative);
291
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new ZazzError(`kit manifest referenced a path outside the package: ${relative}`);
292
+ return resolved;
293
+ }
294
+
295
+ //#endregion
296
+ //#region src/npmrc.ts
297
+ /**
298
+ * @fileoverview npm configuration → pacote options.
299
+ * @description Loads the user's real npm config through `@npmcli/config`
300
+ * (builtin → project → user → global → env, npm's own precedence) so
301
+ * registries, scoped registries, proxies, and auth all behave exactly like
302
+ * `npm install` would. The flattened config is spread into every
303
+ * pacote call, then the CLI's own flags override. If the config machinery
304
+ * can't load (an npm-internals layout change), the CLI degrades to registry
305
+ * defaults rather than failing — a plain public-registry fetch needs nothing.
306
+ */
307
+ /** The CLI's own cacache directory (never npm's). */
308
+ function cacheDir() {
309
+ const base = process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache");
310
+ return path.join(base, "zazz-ui");
311
+ }
312
+ async function loadNpmFlatConfig(cwd) {
313
+ try {
314
+ const [{ default: Config }, defs] = await Promise.all([import("@npmcli/config"), import("@npmcli/config/lib/definitions/index.js")]);
315
+ const config = new Config({
316
+ definitions: defs.definitions,
317
+ shorthands: defs.shorthands,
318
+ flatten: defs.flatten,
319
+ npmPath: path.dirname(fileURLToPath(import.meta.url)),
320
+ argv: [],
321
+ cwd
322
+ });
323
+ await config.load();
324
+ return config.flat;
325
+ } catch {
326
+ return {};
327
+ }
328
+ }
329
+ /**
330
+ * @description Builds the pacote option bag: the user's npm config flattened,
331
+ * the zazz cache directory, then flag overrides on top.
332
+ */
333
+ async function loadFetchOptions(flags) {
334
+ const options = {
335
+ ...await loadNpmFlatConfig(flags.cwd),
336
+ cache: cacheDir()
337
+ };
338
+ if (flags.registry !== void 0) options.registry = flags.registry;
339
+ if (flags.offline) options.offline = true;
340
+ if (flags.preferOffline) options.preferOffline = true;
341
+ return options;
342
+ }
343
+
344
+ //#endregion
345
+ //#region src/plan.ts
346
+ /** The v1 base stylesheet inventory (kit `src/index.css` cascade shell). */
347
+ const V1_BASE_CSS_PRE = [
348
+ "base/_layers.css",
349
+ "base/_variables.css",
350
+ "base/_reset.css",
351
+ "base/_typography.css",
352
+ "base/_view-transitions.css"
353
+ ];
354
+ const V1_BASE_CSS_POST = ["base/_utilities.css", "base/_layout.css"];
355
+ /** The v1 core runtime — always vendored, never a per-primitive dependency. */
356
+ const V1_CORE_RUNTIME = [
357
+ "base/utils.js",
358
+ "base/signals.js",
359
+ "base/zazz-element.js",
360
+ "base/dialog-lifecycle.js"
361
+ ];
362
+ /** CSS-gated polyfills the entry loads where a feature is missing; none before the kit exports them. */
363
+ function corePolyfills(manifest) {
364
+ return manifest.corePolyfills ?? [];
365
+ }
366
+ /** Base stylesheets split around the primitives: pre loads first, post is the override layer. */
367
+ function baseCssSplit(manifest) {
368
+ return {
369
+ pre: manifest.baseCssPre ?? V1_BASE_CSS_PRE,
370
+ post: manifest.baseCssPost ?? V1_BASE_CSS_POST
371
+ };
372
+ }
373
+ function baseCss(manifest) {
374
+ const { pre, post } = baseCssSplit(manifest);
375
+ return [...pre, ...post];
376
+ }
377
+ function coreRuntime(manifest) {
378
+ return manifest.coreRuntime ?? V1_CORE_RUNTIME;
379
+ }
380
+ /** Maps an emitted `.js` path to what the language actually vendors. */
381
+ function scriptVariants(jsPath, language) {
382
+ if (language === "ts") return [jsPath.replace(/\.js$/, ".ts")];
383
+ return [jsPath, jsPath.replace(/\.js$/, ".d.ts")];
384
+ }
385
+ /** Everything `init` vendors: base css + core runtime and its polyfills, per language. */
386
+ function baseFiles(manifest, language) {
387
+ return [...baseCss(manifest), ...[...coreRuntime(manifest), ...corePolyfills(manifest).map((polyfill) => polyfill.file)].flatMap((jsPath) => scriptVariants(jsPath, language))];
388
+ }
389
+ /** Everything `add` vendors for one primitive (dependencies resolved by the caller). */
390
+ function primitiveFiles(entry, language, options) {
391
+ return [
392
+ ...entry.css,
393
+ ...entry.js.flatMap((jsPath) => scriptVariants(jsPath, language)),
394
+ ...options.examples ? entry.examples : []
395
+ ];
396
+ }
397
+ /** Base scripts a set of primitives requires (per language), deduped in order. */
398
+ function baseScriptFiles(entries, language) {
399
+ const seen = /* @__PURE__ */ new Set();
400
+ const files = [];
401
+ for (const entry of entries) for (const jsPath of entry.base) {
402
+ if (seen.has(jsPath)) continue;
403
+ seen.add(jsPath);
404
+ files.push(...scriptVariants(jsPath, language));
405
+ }
406
+ return files;
407
+ }
408
+
409
+ //#endregion
410
+ //#region src/transaction.ts
411
+ /**
412
+ * @fileoverview Staged, near-atomic application of a command's write plan.
413
+ * @description Every prompt is answered and every merge resolved before a
414
+ * transaction exists — `apply` only moves bytes. Writes stage to sibling
415
+ * `<dest>.zazz-tmp` files (same directory → same filesystem → atomic rename);
416
+ * a failure during staging unlinks the temps and leaves the project exactly
417
+ * as it was. `zazz.json` is written once, last, so a crash mid-commit leaves
418
+ * provenance at the old state and a re-run self-heals.
419
+ */
420
+ const TMP_SUFFIX = ".zazz-tmp";
421
+ /** The --dry-run rendering: relative path + note, one line per write. */
422
+ function describe(tx) {
423
+ const lines = tx.writes.map((write) => ` ${write.note.padEnd(7)} ${path.relative(tx.root, write.dest)}`);
424
+ const deletes = (tx.deletes ?? []).map((dest) => ` ${"delete".padEnd(7)} ${path.relative(tx.root, dest)}`);
425
+ return [
426
+ ...lines,
427
+ ...deletes,
428
+ ` config zazz.json`
429
+ ].join("\n");
430
+ }
431
+ async function apply(tx) {
432
+ const staged = [];
433
+ try {
434
+ for (const write of tx.writes) {
435
+ await mkdir(path.dirname(write.dest), { recursive: true });
436
+ const tmp = write.dest + TMP_SUFFIX;
437
+ await writeFile(tmp, write.content);
438
+ staged.push(tmp);
439
+ }
440
+ } catch (error) {
441
+ await Promise.all(staged.map((tmp) => rm(tmp, { force: true })));
442
+ throw error;
443
+ }
444
+ for (const [index, write] of tx.writes.entries()) {
445
+ const tmp = staged[index];
446
+ if (tmp) await rename(tmp, write.dest);
447
+ }
448
+ for (const dest of tx.deletes ?? []) await rm(dest, { force: true });
449
+ await saveConfig(tx.root, tx.config);
450
+ }
451
+
452
+ //#endregion
453
+ //#region src/ui.ts
454
+ /**
455
+ * @fileoverview The CLI's voice: clack prompts and spinners behind one
456
+ * injectable interface.
457
+ * @description Commands talk to `Ui`, never to @clack/prompts directly, so
458
+ * `--silent`, `-y`, and non-TTY environments degrade in one place and tests
459
+ * inject a scripted prompter. Happy paths never prompt; every
460
+ * prompt is a conflict with a safe non-interactive default.
461
+ */
462
+ function createUi(options) {
463
+ const interactive = !options.silent && !options.yes && (options.interactive ?? process.stdout.isTTY === true);
464
+ const quiet = options.silent;
465
+ return {
466
+ interactive,
467
+ intro(title) {
468
+ if (quiet) return;
469
+ if (interactive) clack.intro(chalk.inverse(` ${title} `));
470
+ else console.log(title);
471
+ },
472
+ outro(message) {
473
+ if (quiet) return;
474
+ if (interactive) clack.outro(message);
475
+ else console.log(message);
476
+ },
477
+ step(message) {
478
+ if (quiet) return;
479
+ if (interactive) clack.log.step(message);
480
+ else console.log(message);
481
+ },
482
+ warn(message) {
483
+ if (quiet) return;
484
+ if (interactive) clack.log.warn(message);
485
+ else console.warn(message);
486
+ },
487
+ async spinner(label, work, done) {
488
+ if (!interactive) {
489
+ const result = await work();
490
+ if (!quiet && done) console.log(done(result));
491
+ return result;
492
+ }
493
+ const spin = clack.spinner();
494
+ spin.start(label);
495
+ try {
496
+ const result = await work();
497
+ spin.stop(done ? done(result) : label);
498
+ return result;
499
+ } catch (error) {
500
+ spin.stop(chalk.red(label));
501
+ throw error;
502
+ }
503
+ },
504
+ async confirm(message, fallback) {
505
+ if (!interactive) return fallback;
506
+ const answer = await clack.confirm({
507
+ message,
508
+ initialValue: fallback
509
+ });
510
+ if (clack.isCancel(answer)) {
511
+ clack.cancel("Cancelled — nothing was written.");
512
+ process.exit(1);
513
+ }
514
+ return answer;
515
+ },
516
+ async select(message, choices, fallback) {
517
+ if (!interactive) return fallback;
518
+ const options = choices.map((choice) => ({
519
+ value: choice.value,
520
+ label: choice.label,
521
+ ...choice.hint !== void 0 ? { hint: choice.hint } : {}
522
+ }));
523
+ const answer = await clack.select({
524
+ message,
525
+ options,
526
+ initialValue: fallback
527
+ });
528
+ if (clack.isCancel(answer)) {
529
+ clack.cancel("Cancelled — nothing was written.");
530
+ process.exit(1);
531
+ }
532
+ return answer;
533
+ }
534
+ };
535
+ }
536
+
537
+ //#endregion
538
+ //#region src/vendor.ts
539
+ /**
540
+ * @fileoverview Vendoring: pristine tarball bytes → write entries + hashes.
541
+ * @description Reads each planned file's exact published bytes from the
542
+ * resolved kit and produces transaction writes plus the provenance hashes
543
+ * zazz.json records. Hashes are always of the pristine bytes — never what
544
+ * lands on disk — so a skipped overwrite or later edit reads as "edited"
545
+ * against the recorded version.
546
+ */
547
+ /** SSRI-style content hash: `sha256-<base64>`. */
548
+ function sha256(bytes) {
549
+ return `sha256-${createHash("sha256").update(bytes).digest("base64")}`;
550
+ }
551
+ /**
552
+ * @description Builds writes + hashes for a list of `src/`-relative kit files.
553
+ *
554
+ * @param kit - The resolved kit to read pristine bytes from.
555
+ * @param files - `src/`-relative paths (posix, straight from the manifest).
556
+ * @param destRoot - Absolute path of the project's vendor directory.
557
+ */
558
+ async function vendorFiles(kit, files, destRoot) {
559
+ const writes = [];
560
+ const hashes = {};
561
+ for (const file of files) {
562
+ const content = await kit.readFile(file);
563
+ hashes[file] = sha256(content);
564
+ writes.push({
565
+ dest: path.join(destRoot, ...file.split("/")),
566
+ content,
567
+ note: "vendor"
568
+ });
569
+ }
570
+ return {
571
+ writes,
572
+ hashes
573
+ };
574
+ }
575
+
576
+ //#endregion
577
+ //#region src/wiring.ts
578
+ /** The insertion anchor `add` looks for in an untouched index.css. */
579
+ const PRIMITIVES_MARKER = "/* Zazz primitives — zazz-ui add inserts imports here in cascade order. */";
580
+ const LEGACY_SLOT_COMMENT = "/* Legacy layer — import your legacy stylesheets into layer(legacy.imports) here: */\n/* @import \"./your-legacy.css\" layer(legacy.imports); */";
581
+ /** The v1 post-base anchor; newer kits pass `baseCssSplit(manifest).post[0]`. */
582
+ const V1_POST_ANCHOR = "base/_utilities.css";
583
+ /** Renders the vendored stylesheet entry (init; also repair regeneration). */
584
+ function renderIndexCss(options) {
585
+ const { pre, post } = baseCssSplit(options.kit.manifest);
586
+ const legacyBlock = options.legacy === null ? LEGACY_SLOT_COMMENT : `/* Legacy layer — existing styles cascade below the kit. */\n@import "${options.legacy}" layer(legacy.imports);`;
587
+ const primitiveImports = options.primitives.flatMap((p) => p.css).map((file) => `@import "./${file}";`).join("\n");
588
+ return `/**
589
+ * index.css — vendored Zazz entry (generated by zazz-ui; yours to edit).
590
+ * Order matters: _layers.css declares the cascade layers and must load first;
591
+ * the post-primitive base files (utilities) stay the final normal override layer.
592
+ */
593
+
594
+ /* base — order matters */
595
+ ${pre.map((file) => `@import "./${file}";`).join("\n")}
596
+
597
+ ${legacyBlock}
598
+
599
+ ${PRIMITIVES_MARKER}
600
+ ${primitiveImports}${primitiveImports ? "\n" : ""}
601
+ /* The generated utilities stay the final normal Zazz override layer. */
602
+ ${post.map((file) => `@import "./${file}";`).join("\n")}
603
+ `;
604
+ }
605
+ /** Renders the vendored script entry (init). */
606
+ function renderIndexJs(options) {
607
+ const runtime = coreRuntime(options.kit.manifest).map((jsPath) => importLine(jsPath, options.language));
608
+ const gates = corePolyfills(options.kit.manifest).map(({ file, supports: [property, value] }) => {
609
+ const [specifier] = scriptVariants(file, options.language);
610
+ return `if (typeof CSS !== "undefined" && !CSS.supports("${property}", "${value}")) {\n void import("./${specifier}");\n}`;
611
+ });
612
+ const polyfills = gates.length > 0 ? `\n// Polyfills load only where the browser lacks the CSS feature.\n${gates.join("\n")}\n` : "";
613
+ return `/**
614
+ * index.js — vendored Zazz behavior entry (generated by zazz-ui; yours to edit).
615
+ * zazz-ui add inserts primitive imports after the last import, in dependency order.
616
+ */
617
+
618
+ ${runtime.join("\n")}
619
+ ${polyfills}`;
620
+ }
621
+ function importLine(jsPath, language) {
622
+ const [file] = scriptVariants(jsPath, language);
623
+ return `import "./${file}";`;
624
+ }
625
+ /**
626
+ * @description Inserts primitive `@import` lines at their cascade position.
627
+ * Idempotent: already-imported primitives are skipped. Works on user-edited
628
+ * files — anchors, in order: the last existing primitive import with a lower
629
+ * cascade position, the primitives marker, the first post-base import, end.
630
+ */
631
+ function insertCssImports(existing, additions, cascadeOrder, postAnchor = V1_POST_ANCHOR) {
632
+ const position = new Map(cascadeOrder.map((name, index) => [name, index]));
633
+ const lines = existing.split("\n");
634
+ const sorted = [...additions].sort((a, b) => (position.get(a.name) ?? Infinity) - (position.get(b.name) ?? Infinity));
635
+ for (const addition of sorted) {
636
+ if (addition.css.length === 0) continue;
637
+ if (lines.some((line) => line.includes(`./primitives/${addition.name}/`))) continue;
638
+ const newPosition = position.get(addition.name) ?? Infinity;
639
+ let insertAt = -1;
640
+ for (const [index, line] of lines.entries()) {
641
+ const match = /@import "\.\/primitives\/([a-z-]+)\//.exec(line);
642
+ if (!match) continue;
643
+ if ((position.get(match[1] ?? "") ?? Infinity) < newPosition) insertAt = index + 1;
644
+ }
645
+ if (insertAt === -1) {
646
+ const marker = lines.findIndex((line) => line.includes("Zazz primitives"));
647
+ if (marker !== -1) insertAt = marker + 1;
648
+ }
649
+ if (insertAt === -1) {
650
+ const post = lines.findIndex((line) => line.includes(postAnchor));
651
+ insertAt = post !== -1 ? post : lines.length;
652
+ }
653
+ lines.splice(insertAt, 0, ...addition.css.map((file) => `@import "./${file}";`));
654
+ }
655
+ return lines.join("\n");
656
+ }
657
+ /**
658
+ * @description Inserts missing script imports (base scripts and primitive
659
+ * scripts, caller-ordered) after the entry's last static import, so they stay
660
+ * above the polyfill gates; appends when there is none. Idempotent.
661
+ */
662
+ function appendJsImports(existing, jsPaths, language) {
663
+ const additions = jsPaths.map((jsPath) => importLine(jsPath, language)).filter((line) => !existing.includes(line));
664
+ if (additions.length === 0) return existing;
665
+ const lines = (existing.endsWith("\n") ? existing : `${existing}\n`).split("\n");
666
+ let lastImport = -1;
667
+ for (let index = 0; index < lines.length; index++) {
668
+ if (!/^import\s/.test(lines[index])) continue;
669
+ while (index < lines.length - 1 && !/["'][^"']*["']\s*;?\s*$/.test(lines[index])) index++;
670
+ lastImport = index;
671
+ }
672
+ lines.splice(lastImport === -1 ? lines.length - 1 : lastImport + 1, 0, ...additions);
673
+ return lines.join("\n");
674
+ }
675
+ /** Renders head.html through the tarball's own buildHead. */
676
+ function renderHead(kit, config) {
677
+ return `<!-- head.html — generated by zazz-ui; regenerated on update. Paste into your <head>. -->\n${kit.buildHead({
678
+ base: `./${config.dir}`,
679
+ fontDisplay: config.head.fonts ? "swap" : false,
680
+ theme: config.head.themeScript
681
+ })}\n`;
682
+ }
683
+
684
+ //#endregion
685
+ export { resolveKit as _, renderIndexJs as a, createUi as c, baseCssSplit as d, baseFiles as f, kitSpec as g, loadFetchOptions as h, renderIndexCss as i, apply as l, primitiveFiles as m, insertCssImports as n, sha256 as o, baseScriptFiles as p, renderHead as r, vendorFiles as s, appendJsImports as t, describe as u, loadConfig as v, filterCollisions as y };