@takazudo/zudo-sg 0.3.5 → 0.4.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +3 -3
  3. package/dist/catalog/catalog-thumb.d.ts +19 -0
  4. package/dist/catalog/catalog-thumb.js +11 -0
  5. package/dist/catalog/descriptor-thumb.d.ts +20 -0
  6. package/dist/catalog/descriptor-thumb.js +31 -0
  7. package/dist/catalog/index.d.ts +4 -0
  8. package/dist/catalog/index.js +5 -0
  9. package/dist/code-panel/code-panel.d.ts +8 -1
  10. package/dist/code-panel/code-panel.js +76 -24
  11. package/dist/code-panel/editor-setup.d.ts +2 -0
  12. package/dist/code-panel/editor-setup.js +3 -0
  13. package/dist/code-panel/source-editor.d.ts +3 -1
  14. package/dist/code-panel/source-editor.js +10 -1
  15. package/dist/config/index.d.ts +54 -5
  16. package/dist/config/index.js +72 -12
  17. package/dist/host-paths.d.ts +2 -0
  18. package/dist/host-paths.js +5 -0
  19. package/dist/plugins/routes.d.ts +60 -11
  20. package/dist/plugins/routes.js +135 -23
  21. package/dist/preview/detail-workbench.d.ts +63 -1
  22. package/dist/preview/detail-workbench.js +112 -22
  23. package/dist/preview/index.d.ts +3 -3
  24. package/dist/preview/index.js +7 -1
  25. package/dist/preview/messages.d.ts +34 -5
  26. package/dist/preview/messages.js +34 -6
  27. package/dist/preview/preview-app.js +22 -10
  28. package/dist/preview/variant-frame.d.ts +50 -2
  29. package/dist/preview/variant-frame.js +64 -23
  30. package/dist/registry/catalog.d.ts +64 -0
  31. package/dist/registry/catalog.js +79 -0
  32. package/dist/registry/descriptors.d.ts +46 -0
  33. package/dist/registry/descriptors.js +148 -0
  34. package/dist/registry/index.d.ts +5 -1
  35. package/dist/registry/index.js +7 -1
  36. package/dist/registry/nav-nodes.d.ts +4 -1
  37. package/dist/registry/nav-nodes.js +4 -1
  38. package/dist/registry/registry.d.ts +15 -0
  39. package/dist/registry/registry.js +18 -9
  40. package/dist/safelist.css +1 -1
  41. package/dist/sg-context.d.ts +29 -0
  42. package/dist/sg-routes.d.ts +49 -1
  43. package/dist/sg-routes.js +15 -1
  44. package/dist/shared/tablist-keyboard.d.ts +14 -0
  45. package/dist/shared/tablist-keyboard.js +19 -0
  46. package/package.json +10 -5
  47. package/routes-src/_preview-app.tsx +2 -2
  48. package/routes-src/_registry.ts +31 -6
  49. package/routes-src/components-index.tsx +15 -8
  50. package/routes-src/components-preview.tsx +5 -0
  51. package/routes-src/components-slug.tsx +63 -31
  52. package/routes-src/tokens.tsx +9 -4
  53. package/styles.css +10 -0
  54. package/virtual-modules.d.ts +6 -0
@@ -1,13 +1,20 @@
1
1
  "use client";
2
2
  import { jsx, jsxs } from "preact/jsx-runtime";
3
- import { useEffect, useMemo, useRef, useState } from "preact/hooks";
3
+ import {
4
+ useEffect,
5
+ useLayoutEffect,
6
+ useRef,
7
+ useState
8
+ } from "preact/hooks";
4
9
  import { onAfterNavigate } from "@takazudo/zudo-doc/transitions";
5
10
  import {
6
11
  MSG_REQUEST_READY,
7
12
  MSG_SET_THEME,
8
13
  MSG_UPDATE_PROPS,
14
+ PROTOCOL_VERSION,
9
15
  isHeightMessage,
10
- isReadyMessage
16
+ isReadyMessage,
17
+ matchesPreviewIdentity
11
18
  } from "./messages.js";
12
19
  import { PREVIEW_ROUTE_PATH } from "./route.js";
13
20
  import {
@@ -27,6 +34,17 @@ const THEME_OPTIONS = [
27
34
  { id: "dark", label: "Dark" }
28
35
  ];
29
36
  const DEFAULT_THEME_MODE = "follow";
37
+ const RESERVED_PREVIEW_PARAMS = ["slug", "variant"];
38
+ function buildPreviewSrc(previewUrl, slug, exportName, previewParams) {
39
+ let src = `${previewUrl}?slug=${encodeURIComponent(slug)}&variant=${encodeURIComponent(exportName)}`;
40
+ if (previewParams) {
41
+ for (const [key, value] of Object.entries(previewParams)) {
42
+ if (RESERVED_PREVIEW_PARAMS.includes(key)) continue;
43
+ src += `&${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
44
+ }
45
+ }
46
+ return src;
47
+ }
30
48
  function viewportWidth(id) {
31
49
  const preset = VIEWPORTS.find((v) => v.id === id) ?? VIEWPORTS.at(-1);
32
50
  return preset?.width ?? "100%";
@@ -35,6 +53,12 @@ function readCatalogTheme() {
35
53
  const theme = document.documentElement.getAttribute("data-theme");
36
54
  return theme === "light" || theme === "dark" ? theme : null;
37
55
  }
56
+ const INITIAL_FRAME_HEIGHT = 180;
57
+ const DEFAULT_FRAME_SANDBOX = [
58
+ "allow-same-origin",
59
+ "allow-scripts",
60
+ "allow-forms"
61
+ ];
38
62
  function VariantFrame(props) {
39
63
  const {
40
64
  slug,
@@ -43,46 +67,62 @@ function VariantFrame(props) {
43
67
  controls,
44
68
  themeMode,
45
69
  viewportId,
46
- previewUrl = PREVIEW_ROUTE_PATH
70
+ previewUrl = PREVIEW_ROUTE_PATH,
71
+ frameSandbox = DEFAULT_FRAME_SANDBOX,
72
+ frameAllow,
73
+ previewParams,
74
+ fixedHeight
47
75
  } = props;
48
76
  const iframeRef = useRef(null);
49
77
  const readyRef = useRef(false);
50
78
  const themeModeRef = useRef(themeMode);
51
79
  themeModeRef.current = themeMode;
52
- const [height, setHeight] = useState(180);
53
- const src = useMemo(
54
- () => `${previewUrl}?slug=${encodeURIComponent(slug)}&variant=${encodeURIComponent(exportName)}`,
55
- [previewUrl, slug, exportName]
56
- );
80
+ const identityRef = useRef({ slug, variant: exportName });
81
+ identityRef.current = { slug, variant: exportName };
82
+ const fixedHeightRef = useRef(fixedHeight);
83
+ fixedHeightRef.current = fixedHeight;
84
+ const [height, setHeight] = useState(INITIAL_FRAME_HEIGHT);
85
+ const src = buildPreviewSrc(previewUrl, slug, exportName, previewParams);
86
+ function post(message) {
87
+ const origin = window.location.origin;
88
+ if (origin === "null") return;
89
+ iframeRef.current?.contentWindow?.postMessage(message, origin);
90
+ }
57
91
  function sendTheme(theme) {
58
- iframeRef.current?.contentWindow?.postMessage(
59
- { type: MSG_SET_THEME, theme },
60
- "*"
61
- );
92
+ post({ type: MSG_SET_THEME, v: PROTOCOL_VERSION, theme });
62
93
  }
94
+ const committedSrcRef = useRef(src);
95
+ useLayoutEffect(() => {
96
+ if (committedSrcRef.current === src) return;
97
+ committedSrcRef.current = src;
98
+ readyRef.current = false;
99
+ setHeight(INITIAL_FRAME_HEIGHT);
100
+ }, [src]);
63
101
  function syncTheme() {
64
102
  if (!readyRef.current) return;
65
103
  const mode = themeModeRef.current;
104
+ if (mode === "none") return;
66
105
  const theme = mode === "follow" ? readCatalogTheme() : mode;
67
106
  if (theme) sendTheme(theme);
68
107
  }
69
108
  useEffect(() => {
70
109
  function onMessage(e) {
110
+ if (e.origin !== window.location.origin) return;
71
111
  if (e.source !== iframeRef.current?.contentWindow) return;
72
112
  if (isReadyMessage(e.data)) {
113
+ if (!matchesPreviewIdentity(e.data, identityRef.current)) return;
73
114
  readyRef.current = true;
74
115
  syncTheme();
75
116
  return;
76
117
  }
77
118
  if (isHeightMessage(e.data)) {
119
+ if (!matchesPreviewIdentity(e.data, identityRef.current)) return;
120
+ if (fixedHeightRef.current !== void 0) return;
78
121
  setHeight(Math.max(80, Math.ceil(e.data.height)));
79
122
  }
80
123
  }
81
124
  window.addEventListener("message", onMessage);
82
- iframeRef.current?.contentWindow?.postMessage(
83
- { type: MSG_REQUEST_READY },
84
- "*"
85
- );
125
+ post({ type: MSG_REQUEST_READY, v: PROTOCOL_VERSION });
86
126
  return () => window.removeEventListener("message", onMessage);
87
127
  }, []);
88
128
  useEffect(() => {
@@ -113,10 +153,7 @@ function VariantFrame(props) {
113
153
  return () => unregisterPreviewIframe(iframe);
114
154
  }, []);
115
155
  function sendProps(props2) {
116
- iframeRef.current?.contentWindow?.postMessage(
117
- { type: MSG_UPDATE_PROPS, props: props2 },
118
- "*"
119
- );
156
+ post({ type: MSG_UPDATE_PROPS, v: PROTOCOL_VERSION, props: props2 });
120
157
  }
121
158
  return /* @__PURE__ */ jsxs("section", { class: "border border-[color:var(--sg-border)] rounded-md overflow-hidden bg-[var(--sg-surface)]", children: [
122
159
  /* @__PURE__ */ jsx("div", { class: "px-hsp-md py-vsp-2xs border-b border-[color:var(--sg-border)] bg-[var(--sg-surface-2)]", children: /* @__PURE__ */ jsx("span", { class: "text-caption leading-normal font-medium text-[color:var(--sg-fg)]", children: name }) }),
@@ -134,10 +171,11 @@ function VariantFrame(props) {
134
171
  src,
135
172
  title: `${slug} \u2014 ${name}`,
136
173
  loading: "lazy",
137
- sandbox: "allow-same-origin allow-scripts allow-forms",
174
+ sandbox: frameSandbox.join(" "),
175
+ allow: frameAllow ? frameAllow.join("; ") : void 0,
138
176
  style: {
139
177
  width: "100%",
140
- height: `${height}px`,
178
+ height: `${fixedHeight ?? height}px`,
141
179
  // An iframe's layout viewport is its content box. Keep the
142
180
  // border at zero so a 1280px preset reaches the 1280px
143
181
  // breakpoint; a visible border belongs on the wrapper.
@@ -148,7 +186,7 @@ function VariantFrame(props) {
148
186
  ) })
149
187
  }
150
188
  ),
151
- controls && controls.length > 0 && /* @__PURE__ */ jsx("div", { class: "border-t border-[color:var(--sg-border)] px-hsp-md py-vsp-xs", children: /* @__PURE__ */ jsx(ControlsPanel, { controls, onChange: sendProps }) })
189
+ controls && controls.length > 0 && /* @__PURE__ */ jsx("div", { class: "border-t border-[color:var(--sg-border)] px-hsp-md py-vsp-xs", children: /* @__PURE__ */ jsx(ControlsPanel, { controls, onChange: sendProps }, src) })
152
190
  ] });
153
191
  }
154
192
  function seedState(controls) {
@@ -281,9 +319,12 @@ function ControlsPanel({
281
319
  VariantFrame.displayName = "VariantFrame";
282
320
  var variant_frame_default = VariantFrame;
283
321
  export {
322
+ DEFAULT_FRAME_SANDBOX,
284
323
  DEFAULT_THEME_MODE,
285
324
  DEFAULT_VIEWPORT_ID,
325
+ RESERVED_PREVIEW_PARAMS,
286
326
  THEME_OPTIONS,
287
327
  VIEWPORTS,
328
+ buildPreviewSrc,
288
329
  variant_frame_default as default
289
330
  };
@@ -0,0 +1,64 @@
1
+ import type { StoryControl } from "../stories/types.js";
2
+ import type { StoryDescriptor, ThumbnailDescriptor } from "./descriptors.js";
3
+ import { type Registry, type StoryEntry } from "./registry.js";
4
+ /** One variant as the catalog sees it — no render function. */
5
+ export interface CatalogVariant {
6
+ exportName: string;
7
+ name: string;
8
+ controls?: StoryControl[];
9
+ }
10
+ interface CatalogEntryBase {
11
+ /** URL slug. Unique. */
12
+ slug: string;
13
+ /** Stable identity: the registry path key in module mode, the descriptor `id` in descriptor mode. */
14
+ id: string;
15
+ /** Registry path key (module mode) or the descriptor's `sourcePath`. */
16
+ path?: string;
17
+ title: string;
18
+ /** Always a string; `""` when a descriptor omits it. */
19
+ description: string;
20
+ category: string;
21
+ order?: number;
22
+ /** Variants in authored order; `variants[0]` is the default selection. */
23
+ variants: CatalogVariant[];
24
+ thumbnail?: ThumbnailDescriptor;
25
+ }
26
+ /** Built from a `createRegistry()` entry; keeps the original for the SSR thumbnail and code panel. */
27
+ export interface ModuleCatalogEntry extends CatalogEntryBase {
28
+ source: "module";
29
+ storyEntry: StoryEntry;
30
+ }
31
+ /** Built from a validated `StoryDescriptor`. */
32
+ export interface DescriptorCatalogEntry extends CatalogEntryBase {
33
+ source: "descriptor";
34
+ }
35
+ export type CatalogEntry = ModuleCatalogEntry | DescriptorCatalogEntry;
36
+ export interface CatalogCategoryGroup {
37
+ category: string;
38
+ stories: CatalogEntry[];
39
+ }
40
+ export interface CreateCatalogOptions {
41
+ /** Host-declared category order; unlisted used categories append alphabetically. */
42
+ categoryOrder?: readonly string[];
43
+ }
44
+ /** Same query surface as `Registry`, over `CatalogEntry`. */
45
+ export interface Catalog {
46
+ /** Full group order: `categoryOrder` (deduped) + unlisted used categories, alphabetical. */
47
+ categoryOrder: string[];
48
+ /** All entries, in input order. */
49
+ entries: CatalogEntry[];
50
+ getStoryBySlug(slug: string): CatalogEntry | undefined;
51
+ getAllSlugs(): string[];
52
+ /** Entries grouped by category in `categoryOrder`, sorted by `order` then title. Empty categories are omitted. */
53
+ getCategoryGroups(): CatalogCategoryGroup[];
54
+ }
55
+ /** Module-mode entries. Pass `registry.categoryOrder` to `createCatalog` for exact `createRegistry` parity. */
56
+ export declare function catalogEntriesFromRegistry(registry: Pick<Registry, "storyEntries">): ModuleCatalogEntry[];
57
+ /** Descriptor-mode entries. Expects the output of `validateStoryDescriptors`; slugs are kept verbatim. */
58
+ export declare function catalogEntriesFromDescriptors(descriptors: readonly StoryDescriptor[]): DescriptorCatalogEntry[];
59
+ /**
60
+ * Builds the slug-addressable catalog. Ordering matches `createRegistry`. The
61
+ * returned functions do not rely on `this`, so they can be destructured.
62
+ */
63
+ export declare function createCatalog(entries: readonly CatalogEntry[], options?: CreateCatalogOptions): Catalog;
64
+ export {};
@@ -0,0 +1,79 @@
1
+ import { compareByOrderThenTitle, orderCategories } from "./registry.js";
2
+ function catalogEntriesFromRegistry(registry) {
3
+ return registry.storyEntries.map((entry) => ({
4
+ slug: entry.slug,
5
+ id: entry.path,
6
+ path: entry.path,
7
+ title: entry.meta.title,
8
+ description: entry.meta.description ?? "",
9
+ category: entry.meta.category,
10
+ ...entry.meta.order !== void 0 && { order: entry.meta.order },
11
+ variants: entry.variants.map((v) => ({
12
+ exportName: v.exportName,
13
+ name: v.name,
14
+ ...v.story.controls !== void 0 && { controls: v.story.controls }
15
+ })),
16
+ source: "module",
17
+ storyEntry: entry
18
+ }));
19
+ }
20
+ function catalogEntriesFromDescriptors(descriptors) {
21
+ return descriptors.map((d) => ({
22
+ slug: d.slug,
23
+ id: d.id,
24
+ ...d.sourcePath !== void 0 && { path: d.sourcePath },
25
+ title: d.title,
26
+ description: d.description ?? "",
27
+ category: d.category,
28
+ ...d.order !== void 0 && { order: d.order },
29
+ variants: d.variants.map((v) => ({
30
+ exportName: v.exportName,
31
+ name: v.name,
32
+ ...v.controls !== void 0 && { controls: v.controls }
33
+ })),
34
+ ...d.thumbnail !== void 0 && { thumbnail: d.thumbnail },
35
+ source: "descriptor"
36
+ }));
37
+ }
38
+ function createCatalog(entries, options = {}) {
39
+ const list = [...entries];
40
+ const categoryOrder = orderCategories(
41
+ list.map((e) => e.category),
42
+ options.categoryOrder
43
+ );
44
+ const entryBySlug = /* @__PURE__ */ new Map();
45
+ for (const entry of list) {
46
+ if (entryBySlug.has(entry.slug)) {
47
+ throw new Error(`[zudo-sg] createCatalog: duplicate slug ${JSON.stringify(entry.slug)} (id ${JSON.stringify(entry.id)})`);
48
+ }
49
+ entryBySlug.set(entry.slug, entry);
50
+ }
51
+ function getCategoryGroups() {
52
+ const byCategory = /* @__PURE__ */ new Map();
53
+ for (const entry of list) {
54
+ const bucket = byCategory.get(entry.category) ?? [];
55
+ bucket.push(entry);
56
+ byCategory.set(entry.category, bucket);
57
+ }
58
+ const groups = [];
59
+ for (const category of categoryOrder) {
60
+ const stories = byCategory.get(category);
61
+ if (!stories || stories.length === 0) continue;
62
+ stories.sort(compareByOrderThenTitle);
63
+ groups.push({ category, stories });
64
+ }
65
+ return groups;
66
+ }
67
+ return {
68
+ categoryOrder,
69
+ entries: list,
70
+ getStoryBySlug: (slug) => entryBySlug.get(slug),
71
+ getAllSlugs: () => list.map((e) => e.slug),
72
+ getCategoryGroups
73
+ };
74
+ }
75
+ export {
76
+ catalogEntriesFromDescriptors,
77
+ catalogEntriesFromRegistry,
78
+ createCatalog
79
+ };
@@ -0,0 +1,46 @@
1
+ import type { StoryControl } from "../stories/types.js";
2
+ import { type SgRoutes } from "../sg-routes.js";
3
+ /** One variant of a descriptor story. `exportName` is the stable preview-URL id. */
4
+ export interface VariantDescriptor {
5
+ exportName: string;
6
+ name: string;
7
+ controls?: StoryControl[];
8
+ }
9
+ /** A pre-captured catalog tile image, or a labelled placeholder note. */
10
+ export type ThumbnailDescriptor = {
11
+ kind: "image";
12
+ src: string;
13
+ width: number;
14
+ height: number;
15
+ alt?: string;
16
+ } | {
17
+ kind: "placeholder";
18
+ note: string;
19
+ };
20
+ /** Plain-data description of one story. No functions allowed. */
21
+ export interface StoryDescriptor {
22
+ /** Host-stable identity. Unique. */
23
+ id: string;
24
+ /** URL slug, honored verbatim (never re-slugified from `title`). Unique and URL-safe. */
25
+ slug: string;
26
+ category: string;
27
+ title: string;
28
+ description?: string;
29
+ /** Source file path, informational only. */
30
+ sourcePath?: string;
31
+ /** Ordering hint within the category (lower = earlier). */
32
+ order?: number;
33
+ variants: VariantDescriptor[];
34
+ thumbnail?: ThumbnailDescriptor;
35
+ }
36
+ export interface ValidateStoryDescriptorsOptions {
37
+ /** The same route overrides passed to `withZudoSg()`; used to reject a slug the preview endpoint occupies. */
38
+ routes?: Partial<SgRoutes>;
39
+ }
40
+ /**
41
+ * Validates host-supplied story descriptors and returns normalized copies
42
+ * (unknown keys dropped). Throws a `[zudo-sg]` error naming the offending
43
+ * entry's index and id. Slugs are kept verbatim; reserved nav slugs and the
44
+ * slug the preview endpoint occupies are rejected rather than auto-suffixed.
45
+ */
46
+ export declare function validateStoryDescriptors(input: unknown, options?: ValidateStoryDescriptorsOptions): StoryDescriptor[];
@@ -0,0 +1,148 @@
1
+ import { previewCollisionSlug } from "../sg-routes.js";
2
+ import { RESERVED_NAV_SLUGS } from "./registry.js";
3
+ const UNSAFE_SLUG = /[\s/\\?#%]/;
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function isNonEmptyString(value) {
8
+ return typeof value === "string" && value.trim() !== "";
9
+ }
10
+ function describeEntry(index, raw) {
11
+ const id = isRecord(raw) && typeof raw.id === "string" && raw.id !== "" ? JSON.stringify(raw.id) : "(missing)";
12
+ return `storyDescriptors[${index}] (id ${id})`;
13
+ }
14
+ function findFunction(value, path, seen) {
15
+ if (typeof value === "function") return path;
16
+ if (typeof value !== "object" || value === null || seen.has(value)) return null;
17
+ seen.add(value);
18
+ for (const [key, child] of Object.entries(value)) {
19
+ const found = findFunction(child, Array.isArray(value) ? `${path}[${key}]` : `${path}.${key}`, seen);
20
+ if (found) return found;
21
+ }
22
+ return null;
23
+ }
24
+ function validateThumbnail(value) {
25
+ if (!isRecord(value)) return "thumbnail must be an object";
26
+ if (value.kind === "image") {
27
+ if (!isNonEmptyString(value.src)) return 'image thumbnail needs a non-empty "src"';
28
+ for (const dim of ["width", "height"]) {
29
+ const n = value[dim];
30
+ if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) {
31
+ return `image thumbnail needs a positive finite "${dim}"`;
32
+ }
33
+ }
34
+ if (value.alt !== void 0 && typeof value.alt !== "string") return 'image thumbnail "alt" must be a string';
35
+ return null;
36
+ }
37
+ if (value.kind === "placeholder") {
38
+ return isNonEmptyString(value.note) ? null : 'placeholder thumbnail needs a non-empty "note"';
39
+ }
40
+ return `thumbnail.kind must be "image" or "placeholder" (got ${JSON.stringify(value.kind)})`;
41
+ }
42
+ function validateControls(value) {
43
+ if (!Array.isArray(value)) return "controls must be an array";
44
+ for (const [i, control] of value.entries()) {
45
+ if (!isRecord(control) || !isNonEmptyString(control.type) || !isNonEmptyString(control.prop)) {
46
+ return `controls[${i}] needs string "type" and "prop"`;
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ function copyThumbnail(t) {
52
+ if (t.kind === "placeholder") return { kind: "placeholder", note: t.note };
53
+ return {
54
+ kind: "image",
55
+ src: t.src,
56
+ width: t.width,
57
+ height: t.height,
58
+ ...t.alt !== void 0 && { alt: t.alt }
59
+ };
60
+ }
61
+ function validateStoryDescriptors(input, options = {}) {
62
+ if (!Array.isArray(input)) {
63
+ throw new Error(
64
+ `[zudo-sg] storyDescriptors must be an array of story descriptors (got ${input === null ? "null" : typeof input})`
65
+ );
66
+ }
67
+ const reserved = new Set(RESERVED_NAV_SLUGS);
68
+ const previewSlug = previewCollisionSlug(options.routes);
69
+ if (previewSlug !== null) reserved.add(previewSlug);
70
+ const idIndex = /* @__PURE__ */ new Map();
71
+ const slugIndex = /* @__PURE__ */ new Map();
72
+ const result = [];
73
+ input.forEach((raw, index) => {
74
+ const where = describeEntry(index, raw);
75
+ const fail = (problem) => {
76
+ throw new Error(`[zudo-sg] ${where}: ${problem}`);
77
+ };
78
+ if (!isRecord(raw)) fail("must be an object");
79
+ const entry = raw;
80
+ const fn = findFunction(entry, "descriptor", /* @__PURE__ */ new Set());
81
+ if (fn) fail(`${fn} is a function; descriptors must be plain data`);
82
+ for (const key of ["id", "slug", "title", "category"]) {
83
+ if (!isNonEmptyString(entry[key])) fail(`"${key}" must be a non-empty string`);
84
+ }
85
+ const id = entry.id;
86
+ const slug = entry.slug;
87
+ if (UNSAFE_SLUG.test(slug) || slug === "." || slug === "..") {
88
+ fail(`slug ${JSON.stringify(slug)} is not URL-safe (no "/", "\\", "?", "#", "%" or whitespace)`);
89
+ }
90
+ if (reserved.has(slug)) {
91
+ fail(`slug ${JSON.stringify(slug)} is reserved by the styleguide routes`);
92
+ }
93
+ const prevId = idIndex.get(id);
94
+ if (prevId !== void 0) fail(`duplicate id ${JSON.stringify(id)} (also used by storyDescriptors[${prevId}])`);
95
+ idIndex.set(id, index);
96
+ const prevSlug = slugIndex.get(slug);
97
+ if (prevSlug !== void 0) {
98
+ fail(`duplicate slug ${JSON.stringify(slug)} (also used by storyDescriptors[${prevSlug}])`);
99
+ }
100
+ slugIndex.set(slug, index);
101
+ for (const key of ["description", "sourcePath"]) {
102
+ if (entry[key] !== void 0 && typeof entry[key] !== "string") fail(`"${key}" must be a string`);
103
+ }
104
+ if (entry.order !== void 0 && (typeof entry.order !== "number" || !Number.isFinite(entry.order))) {
105
+ fail('"order" must be a finite number');
106
+ }
107
+ if (!Array.isArray(entry.variants) || entry.variants.length === 0) {
108
+ fail('"variants" must be a non-empty array');
109
+ }
110
+ const exportNames = /* @__PURE__ */ new Set();
111
+ const variants = entry.variants.map((v, vi) => {
112
+ const at = `variants[${vi}]`;
113
+ if (!isRecord(v)) return fail(`${at} must be an object`);
114
+ if (!isNonEmptyString(v.exportName)) return fail(`${at}.exportName must be a non-empty string`);
115
+ if (exportNames.has(v.exportName)) return fail(`${at}: duplicate exportName ${JSON.stringify(v.exportName)}`);
116
+ exportNames.add(v.exportName);
117
+ if (!isNonEmptyString(v.name)) return fail(`${at}.name must be a non-empty string`);
118
+ if (v.controls !== void 0) {
119
+ const problem = validateControls(v.controls);
120
+ if (problem) return fail(`${at}.${problem}`);
121
+ }
122
+ return {
123
+ exportName: v.exportName,
124
+ name: v.name,
125
+ ...v.controls !== void 0 && { controls: v.controls }
126
+ };
127
+ });
128
+ if (entry.thumbnail !== void 0) {
129
+ const problem = validateThumbnail(entry.thumbnail);
130
+ if (problem) fail(`malformed thumbnail: ${problem}`);
131
+ }
132
+ result.push({
133
+ id,
134
+ slug,
135
+ category: entry.category,
136
+ title: entry.title,
137
+ ...entry.description !== void 0 && { description: entry.description },
138
+ ...entry.sourcePath !== void 0 && { sourcePath: entry.sourcePath },
139
+ ...entry.order !== void 0 && { order: entry.order },
140
+ variants,
141
+ ...entry.thumbnail !== void 0 && { thumbnail: copyThumbnail(entry.thumbnail) }
142
+ });
143
+ });
144
+ return result;
145
+ }
146
+ export {
147
+ validateStoryDescriptors
148
+ };
@@ -1,6 +1,10 @@
1
1
  export { computeCategoryOrder, createRegistry, OVERVIEW_SLUG, slugify, TOKENS_SLUG, } from "./registry.js";
2
2
  export type { CategoryGroup, CreateRegistryOptions, Registry, StoryEntry, VariantEntry, } from "./registry.js";
3
3
  export { buildNavNodes } from "./nav-nodes.js";
4
- export type { BuildNavNodesOptions, NavNode } from "./nav-nodes.js";
4
+ export type { BuildNavNodesOptions, NavNode, NavNodesSource } from "./nav-nodes.js";
5
+ export { validateStoryDescriptors } from "./descriptors.js";
6
+ export type { StoryDescriptor, ThumbnailDescriptor, ValidateStoryDescriptorsOptions, VariantDescriptor, } from "./descriptors.js";
7
+ export { catalogEntriesFromDescriptors, catalogEntriesFromRegistry, createCatalog } from "./catalog.js";
8
+ export type { Catalog, CatalogCategoryGroup, CatalogEntry, CatalogVariant, CreateCatalogOptions, DescriptorCatalogEntry, ModuleCatalogEntry, } from "./catalog.js";
5
9
  export { COMPONENT_DOCS_COLLECTION, componentDocsCollectionName, componentDocsRoots, deriveMapKeyPrefix, resolveComponentDoc, } from "./component-docs.js";
6
10
  export type { ComponentDocRef, ComponentDocsRoot } from "./component-docs.js";
@@ -6,6 +6,8 @@ import {
6
6
  TOKENS_SLUG
7
7
  } from "./registry.js";
8
8
  import { buildNavNodes } from "./nav-nodes.js";
9
+ import { validateStoryDescriptors } from "./descriptors.js";
10
+ import { catalogEntriesFromDescriptors, catalogEntriesFromRegistry, createCatalog } from "./catalog.js";
9
11
  import {
10
12
  COMPONENT_DOCS_COLLECTION,
11
13
  componentDocsCollectionName,
@@ -18,11 +20,15 @@ export {
18
20
  OVERVIEW_SLUG,
19
21
  TOKENS_SLUG,
20
22
  buildNavNodes,
23
+ catalogEntriesFromDescriptors,
24
+ catalogEntriesFromRegistry,
21
25
  componentDocsCollectionName,
22
26
  componentDocsRoots,
23
27
  computeCategoryOrder,
28
+ createCatalog,
24
29
  createRegistry,
25
30
  deriveMapKeyPrefix,
26
31
  resolveComponentDoc,
27
- slugify
32
+ slugify,
33
+ validateStoryDescriptors
28
34
  };
@@ -1,4 +1,5 @@
1
1
  import { type SgRoutes } from "../sg-routes.js";
2
+ import type { Catalog } from "./catalog.js";
2
3
  import { type Registry } from "./registry.js";
3
4
  /** Structural copy of zudo-doc's sidebar `NavNode`. */
4
5
  export interface NavNode {
@@ -19,4 +20,6 @@ export interface BuildNavNodesOptions {
19
20
  /** Label of the leading index leaf. Default `"Overview"`. */
20
21
  overviewLabel?: string;
21
22
  }
22
- export declare function buildNavNodes(registry: Pick<Registry, "getCategoryGroups">, options: BuildNavNodesOptions): NavNode[];
23
+ /** Anything with the registry's grouping query: a module `Registry` or a mode-neutral `Catalog`. */
24
+ export type NavNodesSource = Pick<Registry, "getCategoryGroups"> | Pick<Catalog, "getCategoryGroups">;
25
+ export declare function buildNavNodes(registry: NavNodesSource, options: BuildNavNodesOptions): NavNode[];
@@ -1,5 +1,8 @@
1
1
  import { componentHref, resolveSgRoutes } from "../sg-routes.js";
2
2
  import { OVERVIEW_SLUG } from "./registry.js";
3
+ function storyLabel(story) {
4
+ return "meta" in story ? story.meta.title : story.title;
5
+ }
3
6
  function buildNavNodes(registry, options) {
4
7
  const { withBase } = options;
5
8
  const routes = resolveSgRoutes(options.routes);
@@ -22,7 +25,7 @@ function buildNavNodes(registry, options) {
22
25
  hasPage: false,
23
26
  children: group.stories.map((story) => ({
24
27
  slug: story.slug,
25
- label: story.meta.title,
28
+ label: storyLabel(story),
26
29
  position: next(),
27
30
  href: withBase(componentHref(routes, story.slug)),
28
31
  hasPage: true,
@@ -8,6 +8,7 @@ import { type SgRoutes } from "../sg-routes.js";
8
8
  */
9
9
  export declare const OVERVIEW_SLUG = "";
10
10
  export declare const TOKENS_SLUG = "tokens";
11
+ export declare const RESERVED_NAV_SLUGS: readonly string[];
11
12
  /** One discovered story file, normalised. */
12
13
  export interface StoryEntry {
13
14
  /** URL slug, derived from meta.title (kebab-cased). Unique. */
@@ -62,6 +63,20 @@ export interface Registry {
62
63
  getCategoryGroups(): CategoryGroup[];
63
64
  }
64
65
  export declare function slugify(input: string): string;
66
+ /**
67
+ * Shared category-order rule for the module registry and the descriptor
68
+ * catalog: `declared` (deduped) first, then every unlisted used category
69
+ * alphabetically (never dropped).
70
+ */
71
+ export declare function orderCategories(used: Iterable<string | undefined>, declared?: readonly string[]): string[];
72
+ /** Shared within-category sort: `order` ascending (unset last), then title. */
73
+ export declare function compareByOrderThenTitle(a: {
74
+ order?: number;
75
+ title: string;
76
+ }, b: {
77
+ order?: number;
78
+ title: string;
79
+ }): number;
65
80
  export declare function computeCategoryOrder(storyModules: Readonly<Record<string, StoryModule>>, declared?: readonly string[]): string[];
66
81
  /**
67
82
  * Builds a registry from the host's generated story-modules map. Call once
@@ -12,16 +12,27 @@ function readMeta(mod) {
12
12
  const meta = mod.default;
13
13
  return meta && typeof meta.title === "string" ? meta : void 0;
14
14
  }
15
- function computeCategoryOrder(storyModules, declared = []) {
15
+ function orderCategories(used, declared = []) {
16
16
  const listed = [...new Set(declared)];
17
17
  const listedSet = new Set(listed);
18
18
  const unlisted = /* @__PURE__ */ new Set();
19
- for (const mod of Object.values(storyModules)) {
20
- const category = readMeta(mod)?.category;
19
+ for (const category of used) {
21
20
  if (typeof category === "string" && !listedSet.has(category)) unlisted.add(category);
22
21
  }
23
22
  return [...listed, ...[...unlisted].sort((a, b) => a.localeCompare(b))];
24
23
  }
24
+ function compareByOrderThenTitle(a, b) {
25
+ const oa = a.order ?? Number.POSITIVE_INFINITY;
26
+ const ob = b.order ?? Number.POSITIVE_INFINITY;
27
+ if (oa !== ob) return oa - ob;
28
+ return a.title.localeCompare(b.title);
29
+ }
30
+ function computeCategoryOrder(storyModules, declared = []) {
31
+ return orderCategories(
32
+ Object.values(storyModules).map((mod) => readMeta(mod)?.category),
33
+ declared
34
+ );
35
+ }
25
36
  function buildEntries(storyModules, storyExportOrder, previewSlug) {
26
37
  const entries = [];
27
38
  const seenSlugs = new Set(RESERVED_NAV_SLUGS);
@@ -66,12 +77,7 @@ function createRegistry(storyModules, options = {}) {
66
77
  for (const category of categoryOrder) {
67
78
  const stories = byCategory.get(category);
68
79
  if (!stories || stories.length === 0) continue;
69
- stories.sort((a, b) => {
70
- const oa = a.meta.order ?? Number.POSITIVE_INFINITY;
71
- const ob = b.meta.order ?? Number.POSITIVE_INFINITY;
72
- if (oa !== ob) return oa - ob;
73
- return a.meta.title.localeCompare(b.meta.title);
74
- });
80
+ stories.sort((a, b) => compareByOrderThenTitle(a.meta, b.meta));
75
81
  groups.push({ category, stories });
76
82
  }
77
83
  return groups;
@@ -86,8 +92,11 @@ function createRegistry(storyModules, options = {}) {
86
92
  }
87
93
  export {
88
94
  OVERVIEW_SLUG,
95
+ RESERVED_NAV_SLUGS,
89
96
  TOKENS_SLUG,
97
+ compareByOrderThenTitle,
90
98
  computeCategoryOrder,
91
99
  createRegistry,
100
+ orderCategories,
92
101
  slugify
93
102
  };