@takazudo/zudo-sg 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +266 -0
  3. package/dist/code-panel/code-panel.js +15 -5
  4. package/dist/code-panel/css-injection.d.ts +11 -5
  5. package/dist/code-panel/css-injection.js +179 -25
  6. package/dist/config/index.d.ts +1 -0
  7. package/dist/plugins/routes.d.ts +2 -0
  8. package/dist/plugins/routes.js +7 -3
  9. package/dist/preview/detail-workbench.d.ts +2 -1
  10. package/dist/preview/detail-workbench.js +3 -0
  11. package/dist/preview/external-runtime.d.ts +117 -0
  12. package/dist/preview/external-runtime.js +121 -0
  13. package/dist/preview/runtime-controller.d.ts +34 -0
  14. package/dist/preview/runtime-controller.js +302 -0
  15. package/dist/preview/variant-frame.d.ts +3 -0
  16. package/dist/preview/variant-frame.js +161 -15
  17. package/dist/registry/catalog.d.ts +2 -0
  18. package/dist/registry/catalog.js +2 -1
  19. package/dist/registry/descriptors.d.ts +3 -0
  20. package/dist/registry/descriptors.js +6 -1
  21. package/dist/registry/external-catalog-node.d.ts +65 -0
  22. package/dist/registry/external-catalog-node.js +220 -0
  23. package/dist/registry/external-catalog.d.ts +44 -0
  24. package/dist/registry/external-catalog.js +72 -0
  25. package/dist/registry/index.d.ts +2 -0
  26. package/dist/registry/index.js +4 -0
  27. package/dist/sg-context.d.ts +2 -0
  28. package/dist/token-tweak/iframe-css-vars-bridge.d.ts +14 -6
  29. package/dist/token-tweak/iframe-css-vars-bridge.js +46 -17
  30. package/dist/token-tweak/index.d.ts +1 -1
  31. package/dist/token-tweak/index.js +2 -0
  32. package/dist/token-tweak/preview-iframe-registry.d.ts +10 -1
  33. package/dist/token-tweak/preview-iframe-registry.js +48 -7
  34. package/package.json +27 -10
  35. package/routes-src/components-slug.tsx +12 -9
@@ -3,6 +3,8 @@ import { jsx, jsxs } from "@takazudo/zfb/zudo-react/jsx-runtime";
3
3
  import { onAfterNavigate } from "@takazudo/zudo-doc/transitions";
4
4
  import {
5
5
  MSG_REQUEST_READY,
6
+ MSG_READY,
7
+ MSG_HEIGHT,
6
8
  MSG_SET_THEME,
7
9
  MSG_UPDATE_PROPS,
8
10
  PROTOCOL_VERSION,
@@ -13,8 +15,20 @@ import {
13
15
  import { PREVIEW_ROUTE_PATH } from "./route.js";
14
16
  import {
15
17
  registerPreviewIframe,
16
- unregisterPreviewIframe
18
+ unregisterPreviewIframe,
19
+ replayPreviewVars
17
20
  } from "../token-tweak/preview-iframe-registry.js";
21
+ import { registerCssPreview, replayCssToPreview } from "../code-panel/css-injection.js";
22
+ import {
23
+ EXTERNAL_RUNTIME_VERSION,
24
+ MSG_RESET_FIXTURE,
25
+ MSG_RUNTIME_ERROR,
26
+ hasExternalRuntimeMarker,
27
+ isExternalRuntimeMessageEvent,
28
+ isNewExternalRuntimeSequence,
29
+ isSerializableProps,
30
+ matchesExternalRuntimeIdentity
31
+ } from "./external-runtime.js";
18
32
  import {
19
33
  buildPreviewSrc,
20
34
  DEFAULT_FRAME_SANDBOX,
@@ -41,6 +55,7 @@ function VariantFrame(props) {
41
55
  themeMode,
42
56
  viewportId,
43
57
  previewUrl = PREVIEW_ROUTE_PATH,
58
+ runtime = "legacy",
44
59
  frameSandbox = DEFAULT_FRAME_SANDBOX,
45
60
  frameAllow,
46
61
  previewParams,
@@ -49,6 +64,16 @@ function VariantFrame(props) {
49
64
  const scope = getScope();
50
65
  const iframeRef = { current: null };
51
66
  let ready = false;
67
+ let readyDocument = null;
68
+ const values = signal(seedState(read(controls) ?? []));
69
+ const canResetFixture = signal(false);
70
+ const previewError = signal(null);
71
+ let sessionId = "";
72
+ let identity = null;
73
+ let expectedGeneration = 0;
74
+ let incoming = -1;
75
+ let outgoing = -1;
76
+ let lastProps = "";
52
77
  const height = signal(INITIAL_FRAME_HEIGHT);
53
78
  const src = computed(
54
79
  () => buildPreviewSrc(previewUrl, slug, read(exportName), previewParams)
@@ -58,8 +83,9 @@ function VariantFrame(props) {
58
83
  const next = src.value;
59
84
  if (next === committedSrc) return;
60
85
  committedSrc = next;
61
- ready = false;
62
- height.value = INITIAL_FRAME_HEIGHT;
86
+ values.value = seedState(read(controls) ?? []);
87
+ resetDocument();
88
+ requestReady();
63
89
  });
64
90
  function post(message) {
65
91
  const origin = window.location.origin;
@@ -67,10 +93,73 @@ function VariantFrame(props) {
67
93
  iframeRef.current?.contentWindow?.postMessage(message, origin);
68
94
  }
69
95
  function sendTheme(theme) {
70
- post({ type: MSG_SET_THEME, v: PROTOCOL_VERSION, theme });
96
+ if (runtime === "external-v1") {
97
+ if (identity) post({ type: MSG_SET_THEME, v: PROTOCOL_VERSION, runtimeVersion: EXTERNAL_RUNTIME_VERSION, ...identity, sequence: ++outgoing, theme });
98
+ } else post({ type: MSG_SET_THEME, v: PROTOCOL_VERSION, theme });
99
+ }
100
+ function resetDocument() {
101
+ ready = false;
102
+ readyDocument = null;
103
+ identity = null;
104
+ expectedGeneration = 0;
105
+ sessionId = runtime === "external-v1" ? window.crypto.randomUUID() : "";
106
+ incoming = -1;
107
+ outgoing = -1;
108
+ lastProps = "";
109
+ height.value = INITIAL_FRAME_HEIGHT;
110
+ canResetFixture.value = false;
111
+ previewError.value = null;
112
+ }
113
+ function requestReady() {
114
+ if (runtime === "external-v1") {
115
+ post({ type: MSG_REQUEST_READY, v: PROTOCOL_VERSION, runtimeVersion: EXTERNAL_RUNTIME_VERSION, slug, variant: read(exportName), sessionId });
116
+ } else post({ type: MSG_REQUEST_READY, v: PROTOCOL_VERSION });
117
+ }
118
+ function syncProps(force = false) {
119
+ if (!ready && !(runtime === "external-v1" && identity) || !read(controls)?.length && Object.keys(values.value).length === 0) return;
120
+ const serialized = JSON.stringify(values.value);
121
+ if (!force && serialized === lastProps) return;
122
+ if (runtime === "external-v1") {
123
+ if (!identity || !isSerializableProps(values.value)) return;
124
+ post({ type: MSG_UPDATE_PROPS, v: PROTOCOL_VERSION, runtimeVersion: EXTERNAL_RUNTIME_VERSION, ...identity, sequence: ++outgoing, props: values.value });
125
+ } else post({ type: MSG_UPDATE_PROPS, v: PROTOCOL_VERSION, props: values.value });
126
+ lastProps = serialized;
127
+ }
128
+ function replay() {
129
+ syncProps();
130
+ syncTheme();
131
+ const iframe = iframeRef.current;
132
+ if (iframe) {
133
+ replayPreviewVars(iframe);
134
+ replayCssToPreview(iframe);
135
+ }
136
+ }
137
+ function resetFixture() {
138
+ if (!identity || !canResetFixture.value) return;
139
+ syncProps(true);
140
+ syncTheme();
141
+ const iframe = iframeRef.current;
142
+ if (iframe) {
143
+ replayPreviewVars(iframe);
144
+ replayCssToPreview(iframe);
145
+ }
146
+ const message = { type: MSG_RESET_FIXTURE, v: PROTOCOL_VERSION, runtimeVersion: EXTERNAL_RUNTIME_VERSION, ...identity, sequence: ++outgoing, nextGeneration: identity.generation + 1 };
147
+ identity = { ...identity, generation: message.nextGeneration };
148
+ incoming = -1;
149
+ outgoing = -1;
150
+ ready = false;
151
+ lastProps = "";
152
+ previewError.value = null;
153
+ height.value = INITIAL_FRAME_HEIGHT;
154
+ post(message);
155
+ }
156
+ function reloadFixture() {
157
+ resetDocument();
158
+ const iframe = iframeRef.current;
159
+ if (iframe) iframe.src = src.value;
71
160
  }
72
161
  function syncTheme() {
73
- if (!ready) return;
162
+ if (!ready && !(runtime === "external-v1" && identity)) return;
74
163
  const mode = read(themeMode);
75
164
  if (mode === "none") return;
76
165
  const theme = mode === "follow" ? readCatalogTheme() : mode;
@@ -80,23 +169,63 @@ function VariantFrame(props) {
80
169
  function onMessage(e) {
81
170
  if (e.origin !== window.location.origin) return;
82
171
  if (e.source !== iframeRef.current?.contentWindow) return;
172
+ if (runtime === "external-v1") {
173
+ if (!isExternalRuntimeMessageEvent(e, { origin: window.location.origin, source: iframeRef.current?.contentWindow })) return;
174
+ const data = e.data;
175
+ if (data.type !== MSG_READY && data.type !== MSG_HEIGHT && data.type !== MSG_RUNTIME_ERROR) return;
176
+ if (data.slug !== slug || data.variant !== read(exportName) || data.sessionId !== sessionId) return;
177
+ if (!identity) {
178
+ if (data.type !== MSG_READY && data.type !== MSG_RUNTIME_ERROR || data.generation !== expectedGeneration) return;
179
+ } else if (!matchesExternalRuntimeIdentity(data, identity)) return;
180
+ if (data.type === MSG_HEIGHT && !ready) return;
181
+ if (!isNewExternalRuntimeSequence(data.sequence, incoming)) return;
182
+ identity = { slug, variant: read(exportName), sessionId, documentId: data.documentId, generation: data.generation };
183
+ readyDocument = iframeRef.current?.contentDocument ?? null;
184
+ incoming = data.sequence;
185
+ if (data.type === MSG_READY) {
186
+ ready = true;
187
+ canResetFixture.value = data.capabilities.fullReset;
188
+ previewError.value = null;
189
+ replay();
190
+ } else if (data.type === MSG_RUNTIME_ERROR) {
191
+ ready = false;
192
+ previewError.value = data.error.message;
193
+ syncProps();
194
+ } else if (fixedHeight === void 0) height.value = Math.max(80, Math.ceil(data.height));
195
+ return;
196
+ }
197
+ if (hasExternalRuntimeMarker(e.data)) return;
83
198
  if (isReadyMessage(e.data)) {
84
199
  if (!matchesPreviewIdentity(e.data, { slug, variant: read(exportName) }))
85
200
  return;
86
201
  ready = true;
87
- syncTheme();
202
+ readyDocument = iframeRef.current?.contentDocument ?? null;
203
+ replay();
88
204
  return;
89
205
  }
90
206
  if (isHeightMessage(e.data)) {
91
207
  if (!matchesPreviewIdentity(e.data, { slug, variant: read(exportName) }))
92
208
  return;
93
- if (fixedHeight !== void 0) return;
209
+ if (fixedHeight !== void 0 || !Number.isFinite(e.data.height) || e.data.height < 0) return;
94
210
  height.value = Math.max(80, Math.ceil(e.data.height));
95
211
  }
96
212
  }
97
213
  window.addEventListener("message", onMessage);
98
- post({ type: MSG_REQUEST_READY, v: PROTOCOL_VERSION });
99
- return () => window.removeEventListener("message", onMessage);
214
+ const iframe = iframeRef.current;
215
+ const onLoad = () => {
216
+ if (runtime === "legacy" && ready && readyDocument === iframe?.contentDocument) return;
217
+ const generation = readyDocument === iframe?.contentDocument ? identity?.generation ?? 0 : 0;
218
+ resetDocument();
219
+ expectedGeneration = generation;
220
+ requestReady();
221
+ };
222
+ iframe?.addEventListener("load", onLoad);
223
+ resetDocument();
224
+ requestReady();
225
+ return () => {
226
+ window.removeEventListener("message", onMessage);
227
+ iframe?.removeEventListener("load", onLoad);
228
+ };
100
229
  });
101
230
  let previousThemeMode = read(themeMode);
102
231
  scope.effect(() => {
@@ -126,14 +255,30 @@ function VariantFrame(props) {
126
255
  scope.onActivate(() => {
127
256
  const iframe = iframeRef.current;
128
257
  if (!iframe) return;
129
- registerPreviewIframe(iframe);
130
- return () => unregisterPreviewIframe(iframe);
258
+ registerPreviewIframe(iframe, runtime === "external-v1" ? { identity: () => identity } : {});
259
+ const removeCss = registerCssPreview(iframe);
260
+ if (ready) {
261
+ replayPreviewVars(iframe);
262
+ replayCssToPreview(iframe);
263
+ }
264
+ return () => {
265
+ unregisterPreviewIframe(iframe);
266
+ removeCss();
267
+ };
131
268
  });
132
269
  function sendProps(props2) {
133
- post({ type: MSG_UPDATE_PROPS, v: PROTOCOL_VERSION, props: props2 });
270
+ values.value = props2;
271
+ syncProps(runtime === "legacy");
134
272
  }
135
273
  return /* @__PURE__ */ jsxs("section", { class: "border border-sg-border rounded-md overflow-hidden bg-sg-surface", children: [
136
- /* @__PURE__ */ jsx("div", { class: "px-hsp-md py-vsp-2xs border-b border-sg-border bg-sg-surface-2", children: /* @__PURE__ */ jsx("span", { class: "text-caption leading-normal font-medium text-sg-fg", children: computed(() => read(name)) }) }),
274
+ /* @__PURE__ */ jsxs("div", { class: "px-hsp-md py-vsp-2xs border-b border-sg-border bg-sg-surface-2", children: [
275
+ /* @__PURE__ */ jsx("span", { class: "text-caption leading-normal font-medium text-sg-fg", children: computed(() => read(name)) }),
276
+ /* @__PURE__ */ jsx(Show, { when: canResetFixture, children: () => /* @__PURE__ */ jsx("button", { type: "button", "on:click": resetFixture, "aria-label": `Reset fixture ${slug}`, class: "text-small", children: "Reset fixture" }) })
277
+ ] }),
278
+ /* @__PURE__ */ jsx(Show, { when: computed(() => previewError.value !== null), children: () => /* @__PURE__ */ jsxs("div", { role: "alert", class: "p-hsp-md text-small", children: [
279
+ /* @__PURE__ */ jsx("p", { children: computed(() => `Preview failed: ${previewError.value ?? ""}`) }),
280
+ /* @__PURE__ */ jsx("button", { type: "button", "on:click": reloadFixture, children: "Reload preview" })
281
+ ] }) }),
137
282
  /* @__PURE__ */ jsx(
138
283
  "div",
139
284
  {
@@ -174,6 +319,7 @@ function VariantFrame(props) {
174
319
  ControlsPanel,
175
320
  {
176
321
  controls: read(controls) ?? [],
322
+ values,
177
323
  onChange: sendProps
178
324
  }
179
325
  ) }) }) })
@@ -186,7 +332,7 @@ function seedState(controls) {
186
332
  }
187
333
  function coerceNumber(raw, control) {
188
334
  const n = Number(raw);
189
- if (Number.isNaN(n)) return control.defaultValue;
335
+ if (!Number.isFinite(n)) return control.defaultValue;
190
336
  let v = n;
191
337
  if (control.min !== void 0) v = Math.max(control.min, v);
192
338
  if (control.max !== void 0) v = Math.min(control.max, v);
@@ -194,9 +340,9 @@ function coerceNumber(raw, control) {
194
340
  }
195
341
  function ControlsPanel({
196
342
  controls,
343
+ values,
197
344
  onChange
198
345
  }) {
199
- const values = signal(seedState(controls));
200
346
  const open = signal(true);
201
347
  const fields = Object.fromEntries(
202
348
  controls.map((control) => [
@@ -1,11 +1,13 @@
1
1
  import type { StoryControl } from "../stories/types.js";
2
2
  import type { StoryDescriptor, ThumbnailDescriptor } from "./descriptors.js";
3
+ import type { DescriptorSource } from "./external-catalog.js";
3
4
  import { type Registry, type StoryEntry } from "./registry.js";
4
5
  /** One variant as the catalog sees it — no render function. */
5
6
  export interface CatalogVariant {
6
7
  exportName: string;
7
8
  name: string;
8
9
  controls?: StoryControl[];
10
+ source?: DescriptorSource;
9
11
  }
10
12
  interface CatalogEntryBase {
11
13
  /** URL slug. Unique. */
@@ -29,7 +29,8 @@ function catalogEntriesFromDescriptors(descriptors) {
29
29
  variants: d.variants.map((v) => ({
30
30
  exportName: v.exportName,
31
31
  name: v.name,
32
- ...v.controls !== void 0 && { controls: v.controls }
32
+ ...v.controls !== void 0 && { controls: v.controls },
33
+ ...v.source !== void 0 && { source: { ...v.source } }
33
34
  })),
34
35
  ...d.thumbnail !== void 0 && { thumbnail: d.thumbnail },
35
36
  source: "descriptor"
@@ -1,10 +1,13 @@
1
1
  import type { StoryControl } from "../stories/types.js";
2
2
  import { type SgRoutes } from "../sg-routes.js";
3
+ import { type DescriptorSource } from "./external-catalog.js";
3
4
  /** One variant of a descriptor story. `exportName` is the stable preview-URL id. */
4
5
  export interface VariantDescriptor {
5
6
  exportName: string;
6
7
  name: string;
7
8
  controls?: StoryControl[];
9
+ /** Opt-in verbatim code text, keyed to this exact slug/variant. */
10
+ source?: DescriptorSource;
8
11
  }
9
12
  /** A pre-captured catalog tile image, or a labelled placeholder note. */
10
13
  export type ThumbnailDescriptor = {
@@ -1,5 +1,6 @@
1
1
  import { previewCollisionSlug } from "../sg-routes.js";
2
2
  import { RESERVED_NAV_SLUGS } from "./registry.js";
3
+ import { externalCatalogKey, isDescriptorSource } from "./external-catalog.js";
3
4
  const UNSAFE_SLUG = /[\s/\\?#%]/;
4
5
  function isRecord(value) {
5
6
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -119,10 +120,14 @@ function validateStoryDescriptors(input, options = {}) {
119
120
  const problem = validateControls(v.controls);
120
121
  if (problem) return fail(`${at}.${problem}`);
121
122
  }
123
+ if (v.source !== void 0 && (!isDescriptorSource(v.source) || v.source.key !== externalCatalogKey(slug, v.exportName))) {
124
+ return fail(`${at}.source must provide code text with key ${externalCatalogKey(slug, v.exportName)}`);
125
+ }
122
126
  return {
123
127
  exportName: v.exportName,
124
128
  name: v.name,
125
- ...v.controls !== void 0 && { controls: v.controls }
129
+ ...v.controls !== void 0 && { controls: v.controls },
130
+ ...v.source !== void 0 && { source: { key: v.source.key, code: v.source.code } }
126
131
  };
127
132
  });
128
133
  if (entry.thumbnail !== void 0) {
@@ -0,0 +1,65 @@
1
+ import { type ExternalRuntimeIdentity } from "../preview/external-runtime.js";
2
+ import type { ExternalRuntimeSnapshot } from "../preview/runtime-controller.js";
3
+ import { type ThumbnailDescriptor } from "./descriptors.js";
4
+ import { type DescriptorSource, type ExternalCatalogEntry, type ExternalCatalogLoader, type ExternalCaptureDisposition } from "./external-catalog.js";
5
+ /** A failed promise is an error, never an intentional placeholder. */
6
+ export declare function thumbnailFromExternalCapture(capture: ExternalCaptureDisposition): ThumbnailDescriptor;
7
+ export interface ExternalCatalogOutputs {
8
+ manifest: unknown;
9
+ descriptors: unknown;
10
+ /** Actual metadata emitted beside the external bundle's generated loader functions. */
11
+ loaders: readonly ExternalCatalogLoader[];
12
+ /** Actual displayed-source output; compare content as well as identity. */
13
+ sources: readonly DescriptorSource[];
14
+ }
15
+ /** Compare the entire generated catalog, including extras and duplicate identities. */
16
+ export declare function validateExternalCatalogOutputs(input: ExternalCatalogOutputs): ExternalCatalogEntry[];
17
+ export interface ExternalCaptureReceipt {
18
+ key: string;
19
+ fixture: {
20
+ module: string;
21
+ exportName: string;
22
+ };
23
+ src: string;
24
+ width: number;
25
+ height: number;
26
+ imageSha256: string;
27
+ loaderSha256: string;
28
+ sourceSha256: string;
29
+ runtime: ExternalRuntimeIdentity;
30
+ stability: "runtime.whenStable";
31
+ }
32
+ export interface ExternalCatalogAssetsOptions {
33
+ manifest: unknown;
34
+ projectRoot: string;
35
+ /** Directory containing capture paths: public/ before build; dist/ or dist/<base>/ after build. */
36
+ assetRoot: string;
37
+ captures: readonly ExternalCaptureReceipt[];
38
+ }
39
+ export declare function validateExternalCatalogAssets(options: ExternalCatalogAssetsOptions): void;
40
+ /** Wrap a caller-owned browser page and its fixture-exposed runtime controller. */
41
+ export interface ExternalCapturePage {
42
+ goto(url: string): Promise<unknown>;
43
+ setViewportSize(size: {
44
+ width: number;
45
+ height: number;
46
+ }): Promise<unknown>;
47
+ whenStable(): Promise<ExternalRuntimeIdentity>;
48
+ getSnapshot(): Promise<ExternalRuntimeSnapshot>;
49
+ screenshot(options: {
50
+ type: "png";
51
+ scale: "css";
52
+ }): Promise<Uint8Array>;
53
+ }
54
+ export interface CaptureExternalCatalogOptions {
55
+ manifest: unknown;
56
+ projectRoot: string;
57
+ assetRoot: string;
58
+ origin: string;
59
+ base?: string;
60
+ /** Root-absolute external document path, before the site base. */
61
+ previewUrl: string;
62
+ page: ExternalCapturePage;
63
+ }
64
+ /** Capture the actual external document; this never renders a fixture in Node. */
65
+ export declare function captureExternalCatalogImages(options: CaptureExternalCatalogOptions): Promise<ExternalCaptureReceipt[]>;
@@ -0,0 +1,220 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { inflateSync } from "node:zlib";
5
+ import { isExternalRuntimeIdentity, isJsonValue, matchesExternalRuntimeIdentity } from "../preview/external-runtime.js";
6
+ import { validateStoryDescriptors } from "./descriptors.js";
7
+ import { externalCatalogKey, validateExternalCatalogManifest } from "./external-catalog.js";
8
+ function fail(message) {
9
+ throw new Error(`[zudo-sg] external catalog: ${message}`);
10
+ }
11
+ function hash(bytes) {
12
+ return createHash("sha256").update(bytes).digest("hex");
13
+ }
14
+ function keyed(values, label) {
15
+ if (!Array.isArray(values) || !isJsonValue(values)) fail(`${label} must be a dense serializable array`);
16
+ const result = /* @__PURE__ */ new Map();
17
+ for (const value of values) {
18
+ if (!value || typeof value.key !== "string" || result.has(value.key)) fail(`${label} has a missing or duplicate key`);
19
+ result.set(value.key, value);
20
+ }
21
+ return result;
22
+ }
23
+ function sameKeys(expected, actual, label) {
24
+ const missing = expected.filter((key) => !actual.has(key));
25
+ const wanted = new Set(expected);
26
+ const extra = [...actual.keys()].filter((key) => !wanted.has(key));
27
+ if (missing.length || extra.length) fail(`${label} key mismatch; missing: ${missing.join(", ")}; extra: ${extra.join(", ")}`);
28
+ }
29
+ function thumbnailFromExternalCapture(capture) {
30
+ if (capture.kind === "failed") fail(`capture failed for ${capture.key}: ${capture.note}`);
31
+ if (capture.kind !== "image") return { kind: "placeholder", note: capture.note };
32
+ if (!/\.png$/i.test(capture.src)) fail(`captured image must use a .png emitted path: ${capture.src}`);
33
+ return { kind: "image", src: capture.src, width: capture.width, height: capture.height };
34
+ }
35
+ function validateExternalCatalogOutputs(input) {
36
+ const manifest = validateExternalCatalogManifest(input.manifest);
37
+ if (!isJsonValue(input.descriptors)) fail("descriptors must be dense serializable data");
38
+ const descriptors = validateStoryDescriptors(input.descriptors);
39
+ const variants = keyed(descriptors.flatMap((d) => d.variants.map((v) => ({
40
+ key: externalCatalogKey(d.slug, v.exportName),
41
+ source: v.source ?? null
42
+ }))), "descriptors");
43
+ const loaders = keyed(input.loaders, "loaders");
44
+ const sources = keyed(input.sources, "sources");
45
+ const keys = manifest.map((row) => row.loader.key);
46
+ sameKeys(keys, variants, "descriptors");
47
+ sameKeys(keys, loaders, "loaders");
48
+ sameKeys(keys, sources, "sources");
49
+ for (const row of manifest) {
50
+ const key = row.loader.key;
51
+ const actual = loaders.get(key);
52
+ if (actual.module !== row.loader.module || actual.exportName !== row.loader.exportName) fail(`loader differs for ${key}`);
53
+ if (sources.get(key)?.code !== row.source.code || variants.get(key)?.source?.code !== row.source.code || variants.get(key)?.source?.key !== key) fail(`displayed source differs for ${key}`);
54
+ thumbnailFromExternalCapture(row.capture);
55
+ }
56
+ const byKey = new Map(manifest.map((row) => [row.loader.key, row]));
57
+ for (const descriptor of descriptors) {
58
+ const row = byKey.get(externalCatalogKey(descriptor.slug, descriptor.variants[0].exportName));
59
+ const expected = thumbnailFromExternalCapture(row.capture);
60
+ const actual = descriptor.thumbnail;
61
+ if (!actual || actual.kind !== expected.kind || (actual.kind === "image" && expected.kind === "image" ? actual.src !== expected.src || actual.width !== expected.width || actual.height !== expected.height : actual.kind === "placeholder" && expected.kind === "placeholder" && actual.note !== expected.note)) {
62
+ fail(`catalog thumbnail differs for ${descriptor.slug}`);
63
+ }
64
+ }
65
+ return manifest;
66
+ }
67
+ function containedPath(root, path, createParents = false) {
68
+ const boundary = resolve(root);
69
+ const candidate = resolve(boundary, path);
70
+ const rel = relative(boundary, candidate);
71
+ if (!rel || isAbsolute(rel) || rel === ".." || rel.startsWith(`..${sep}`)) fail(`path escapes asset/project root: ${path}`);
72
+ let cursor = boundary;
73
+ const ancestors = [];
74
+ for (; ; ) {
75
+ ancestors.unshift(cursor);
76
+ const parent = dirname(cursor);
77
+ if (parent === cursor) break;
78
+ cursor = parent;
79
+ }
80
+ const paths = [...ancestors, ...rel.split(sep).map((_, i, parts) => resolve(boundary, ...parts.slice(0, i + 1)))];
81
+ for (const part of paths) {
82
+ try {
83
+ if (lstatSync(part).isSymbolicLink()) fail(`symlink is not allowed: ${part}`);
84
+ } catch (error) {
85
+ if (error.code !== "ENOENT") throw error;
86
+ }
87
+ }
88
+ if (createParents) mkdirSync(dirname(candidate), { recursive: true });
89
+ return candidate;
90
+ }
91
+ function loaderHash(projectRoot, row) {
92
+ const path = containedPath(projectRoot, row.loader.module);
93
+ try {
94
+ return hash(readFileSync(path));
95
+ } catch {
96
+ return fail(`loader module is missing or unreadable: ${row.loader.module}`);
97
+ }
98
+ }
99
+ function pngDimensions(bytes) {
100
+ const data = Buffer.from(bytes);
101
+ if (data.length < 45 || data.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a") fail("invalid PNG signature/body");
102
+ let at = 8, width = 0, height = 0, channels = 0, ended = false;
103
+ const compressed = [];
104
+ while (at < data.length) {
105
+ if (at + 12 > data.length) fail("truncated PNG chunk");
106
+ const size = data.readUInt32BE(at), type = data.toString("latin1", at + 4, at + 8), end = at + 12 + size;
107
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type)) fail("invalid PNG chunk type");
108
+ if (/^[A-Z]/.test(type) && !["IHDR", "IDAT", "IEND"].includes(type)) fail("unsupported PNG critical chunk");
109
+ if (end > data.length) fail("truncated PNG data");
110
+ let crc = 4294967295;
111
+ for (const byte of data.subarray(at + 4, end - 4)) {
112
+ crc ^= byte;
113
+ for (let bit = 0; bit < 8; bit++) crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
114
+ }
115
+ if ((crc ^ 4294967295) >>> 0 !== data.readUInt32BE(end - 4)) fail("invalid PNG checksum");
116
+ if (at === 8) {
117
+ if (type !== "IHDR" || size !== 13) fail("missing PNG IHDR");
118
+ width = data.readUInt32BE(at + 8);
119
+ height = data.readUInt32BE(at + 12);
120
+ channels = { 0: 1, 2: 3, 4: 2, 6: 4 }[data[at + 17]] ?? 0;
121
+ if (!width || !height || width * height > 16777216 || data[at + 16] !== 8 || !channels || data[at + 18] !== 0 || data[at + 19] !== 0 || data[at + 20] !== 0) fail("unsupported PNG dimensions/encoding (8-bit, noninterlaced; at most 16M pixels)");
122
+ } else if (type === "IHDR") fail("duplicate PNG IHDR");
123
+ if (type === "IDAT") compressed.push(data.subarray(at + 8, end - 4));
124
+ at = end;
125
+ if (type === "IEND") {
126
+ if (size !== 0 || at !== data.length) fail("invalid PNG end");
127
+ ended = true;
128
+ break;
129
+ }
130
+ }
131
+ if (!ended || !compressed.length) fail("incomplete PNG");
132
+ const stride = width * channels + 1;
133
+ let raw;
134
+ try {
135
+ raw = inflateSync(Buffer.concat(compressed), { maxOutputLength: stride * height });
136
+ } catch {
137
+ return fail("invalid PNG compressed data");
138
+ }
139
+ if (raw.length !== stride * height) fail("invalid PNG pixel data length");
140
+ for (let y = 0; y < height; y++) if (raw[y * stride] > 4) fail("invalid PNG row filter");
141
+ return { width, height };
142
+ }
143
+ function validateExternalCatalogAssets(options) {
144
+ const manifest = validateExternalCatalogManifest(options.manifest);
145
+ const receipts = keyed(options.captures, "capture receipts");
146
+ sameKeys(manifest.filter((row) => row.capture.kind === "image").map((row) => row.loader.key), receipts, "capture receipts");
147
+ for (const row of manifest) {
148
+ thumbnailFromExternalCapture(row.capture);
149
+ const currentLoaderHash = loaderHash(options.projectRoot, row);
150
+ if (row.capture.kind !== "image") continue;
151
+ const capture = row.capture, receipt = receipts.get(capture.key);
152
+ if (!isExternalRuntimeIdentity(receipt.runtime) || receipt.runtime.slug !== row.slug || receipt.runtime.variant !== row.variant || receipt.stability !== "runtime.whenStable" || receipt.fixture?.module !== row.loader.module || receipt.fixture.exportName !== row.loader.exportName || receipt.src !== capture.src || receipt.width !== capture.width || receipt.height !== capture.height || receipt.loaderSha256 !== currentLoaderHash || receipt.sourceSha256 !== hash(row.source.code)) fail(`stale/mismatched capture receipt for ${capture.key}`);
153
+ const path = containedPath(options.assetRoot, `.${capture.src}`);
154
+ let image;
155
+ try {
156
+ image = readFileSync(path);
157
+ } catch {
158
+ return fail(`promised image is missing: ${capture.src}`);
159
+ }
160
+ const dimensions = pngDimensions(image);
161
+ if (dimensions.width !== capture.width || dimensions.height !== capture.height || hash(image) !== receipt.imageSha256) fail(`image bytes/dimensions differ for ${capture.key}`);
162
+ }
163
+ }
164
+ async function captureExternalCatalogImages(options) {
165
+ const manifest = validateExternalCatalogManifest(options.manifest);
166
+ const origin = new URL(options.origin);
167
+ if (!["http:", "https:"].includes(origin.protocol) || origin.origin !== options.origin || origin.username || origin.password) fail("origin must be an HTTP(S) origin without path or credentials");
168
+ const base = options.base ?? "/";
169
+ const portable = (path) => path.startsWith("/") && !path.startsWith("//") && !/[\\?#%\s]/u.test(path) && !path.split("/").some((part) => part === "." || part === "..");
170
+ if (!portable(base) || !portable(options.previewUrl)) fail("base/previewUrl must be root-absolute portable paths");
171
+ const receipts = [];
172
+ for (const row of manifest) {
173
+ thumbnailFromExternalCapture(row.capture);
174
+ loaderHash(options.projectRoot, row);
175
+ if (row.capture.kind === "image") containedPath(options.assetRoot, `.${row.capture.src}`);
176
+ }
177
+ for (const row of manifest) {
178
+ const capture = row.capture;
179
+ if (capture.kind !== "image") continue;
180
+ const initialLoaderHash = loaderHash(options.projectRoot, row);
181
+ const url = new URL(base.replace(/\/$/, "") + options.previewUrl, origin);
182
+ url.searchParams.set("slug", row.slug);
183
+ url.searchParams.set("variant", row.variant);
184
+ await options.page.setViewportSize({ width: capture.width, height: capture.height });
185
+ await options.page.goto(url.href);
186
+ const runtime = await options.page.whenStable();
187
+ const check = async () => {
188
+ const state = await options.page.getSnapshot();
189
+ if (!isExternalRuntimeIdentity(runtime) || runtime.slug !== row.slug || runtime.variant !== row.variant || !state.ready || state.error || !isExternalRuntimeIdentity(state.identity) || !matchesExternalRuntimeIdentity(state.identity, runtime)) fail(`runtime changed or failed during capture: ${capture.key}`);
190
+ };
191
+ await check();
192
+ const image = await options.page.screenshot({ type: "png", scale: "css" });
193
+ await check();
194
+ const dimensions = pngDimensions(image);
195
+ if (dimensions.width !== capture.width || dimensions.height !== capture.height) fail(`capture dimensions differ for ${capture.key}`);
196
+ if (loaderHash(options.projectRoot, row) !== initialLoaderHash) fail(`loader changed during capture: ${capture.key}`);
197
+ const path = containedPath(options.assetRoot, `.${capture.src}`, true);
198
+ containedPath(options.assetRoot, `.${capture.src}`);
199
+ writeFileSync(path, image, { flag: "w" });
200
+ receipts.push({
201
+ key: capture.key,
202
+ fixture: { ...capture.fixture },
203
+ src: capture.src,
204
+ ...dimensions,
205
+ imageSha256: hash(image),
206
+ loaderSha256: initialLoaderHash,
207
+ sourceSha256: hash(row.source.code),
208
+ runtime: { ...runtime },
209
+ stability: "runtime.whenStable"
210
+ });
211
+ }
212
+ validateExternalCatalogAssets({ ...options, captures: receipts });
213
+ return receipts;
214
+ }
215
+ export {
216
+ captureExternalCatalogImages,
217
+ thumbnailFromExternalCapture,
218
+ validateExternalCatalogAssets,
219
+ validateExternalCatalogOutputs
220
+ };
@@ -0,0 +1,44 @@
1
+ /** Tuple encoding avoids collisions even when an authored variant contains '/'. */
2
+ export declare function externalCatalogKey(slug: string, variant: string): string;
3
+ /** Verbatim source text, never an HTML fragment, filesystem include or render function. */
4
+ export interface DescriptorSource {
5
+ key: string;
6
+ code: string;
7
+ }
8
+ export interface ExternalFixtureReference {
9
+ /** Project-root-relative module path used by the host's generated loader. */
10
+ module: string;
11
+ exportName: string;
12
+ }
13
+ export interface ExternalCatalogLoader extends ExternalFixtureReference {
14
+ key: string;
15
+ }
16
+ /** An image declaration promises a real capture; shape validation is not capture evidence. */
17
+ export type ExternalCaptureDisposition = {
18
+ kind: "image";
19
+ key: string;
20
+ fixture: ExternalFixtureReference;
21
+ /** Root-absolute emitted asset URL, before adding the site's base. */
22
+ src: string;
23
+ width: number;
24
+ height: number;
25
+ } | {
26
+ kind: "placeholder" | "failed";
27
+ key: string;
28
+ note: string;
29
+ };
30
+ export interface ExternalCatalogEntry {
31
+ slug: string;
32
+ variant: string;
33
+ loader: ExternalCatalogLoader;
34
+ source: DescriptorSource;
35
+ capture: ExternalCaptureDisposition;
36
+ }
37
+ export declare function isDescriptorSource(value: unknown): value is DescriptorSource;
38
+ /**
39
+ * Validate one canonical generator input and return normalized copies. Every
40
+ * row owns exactly one descriptor/loader/source/capture identity. Runtimes
41
+ * import generated loader code separately; this manifest never imports it.
42
+ * This does NOT inspect files or claim that a promised capture has succeeded.
43
+ */
44
+ export declare function validateExternalCatalogManifest(input: unknown): ExternalCatalogEntry[];