@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
@@ -103,8 +103,8 @@ function normalizeExternalPreview(value) {
103
103
  if (value === void 0 || value === null) return null;
104
104
  if (!isPlainObject(value)) fail(`option "externalPreview" must be an object ({ url, trailingSlash? })`);
105
105
  for (const key of Object.keys(value)) {
106
- if (key !== "url" && key !== "trailingSlash") {
107
- fail(`option "externalPreview.${key}" is not supported (expected url, trailingSlash)`);
106
+ if (key !== "url" && key !== "trailingSlash" && key !== "runtime") {
107
+ fail(`option "externalPreview.${key}" is not supported (expected url, trailingSlash, runtime)`);
108
108
  }
109
109
  }
110
110
  const rawUrl = value.url;
@@ -113,13 +113,15 @@ function normalizeExternalPreview(value) {
113
113
  fail(`option "externalPreview.url" = "${rawUrl}" must be a root-absolute path starting with a single "/" (no scheme, no "//")`);
114
114
  }
115
115
  const trailingSlash = value.trailingSlash;
116
+ const runtime = value.runtime ?? "legacy";
117
+ if (runtime !== "legacy" && runtime !== "external-v1") fail('option "externalPreview.runtime" must be "legacy" or "external-v1"');
116
118
  if (trailingSlash !== void 0 && trailingSlash !== "never" && trailingSlash !== "always") {
117
119
  fail(`option "externalPreview.trailingSlash" must be "never" or "always"`);
118
120
  }
119
121
  let url = rawUrl;
120
122
  if (trailingSlash === "never") url = url.length > 1 ? url.replace(/\/+$/, "") : url;
121
123
  if (trailingSlash === "always" && !url.endsWith("/")) url = `${url}/`;
122
- return { url };
124
+ return { url, runtime };
123
125
  }
124
126
  function normalizeCategoryOrder(value) {
125
127
  if (value === void 0 || value === null) return [];
@@ -236,6 +238,7 @@ function resolveRoutesPluginOptions(projectRoot, options) {
236
238
  routes,
237
239
  disabledRoutes: [...disabledRoutes],
238
240
  externalPreviewUrl: externalPreview?.url ?? null,
241
+ externalPreviewRuntime: externalPreview?.runtime ?? "legacy",
239
242
  categoryOrder: normalizeCategoryOrder(options.categoryOrder),
240
243
  uiPackageName: optionalString("uiPackageName", options.uiPackageName) ?? null,
241
244
  previewCssUrl: previewCssUrl === void 0 ? DEFAULT_PREVIEW_CSS_URL : urlPath("previewCssUrl", previewCssUrl),
@@ -264,6 +267,7 @@ function buildSgContext(base, resolved) {
264
267
  componentDocs: resolved.componentDocs,
265
268
  disabledRoutes: resolved.disabledRoutes,
266
269
  externalPreviewUrl: resolved.externalPreviewUrl,
270
+ externalPreviewRuntime: resolved.externalPreviewRuntime,
267
271
  previewTokenPanel: resolved.previewTokenPanel
268
272
  };
269
273
  }
@@ -59,6 +59,7 @@ export interface DetailWorkbenchProps {
59
59
  variants: WorkbenchVariant[];
60
60
  /** Base-prefixed preview route URL, forwarded to every stage (see VariantFrame). */
61
61
  previewUrl?: string;
62
+ runtime?: "legacy" | "external-v1";
62
63
  /** Iframe `sandbox` tokens, forwarded to every stage (see VariantFrame). */
63
64
  frameSandbox?: readonly string[];
64
65
  /** Iframe `allow` directives, forwarded to every stage (see VariantFrame). */
@@ -77,4 +78,4 @@ export interface DetailWorkbenchProps {
77
78
  /** Which toolbar groups render. */
78
79
  toolbar?: WorkbenchToolbar;
79
80
  }
80
- export default function DetailWorkbench({ slug, variants, previewUrl, frameSandbox, frameAllow, selection, theme, previewParams, sizing, toolbar, }: DetailWorkbenchProps): Description;
81
+ export default function DetailWorkbench({ slug, variants, previewUrl, runtime, frameSandbox, frameAllow, selection, theme, previewParams, sizing, toolbar, }: DetailWorkbenchProps): Description;
@@ -46,6 +46,7 @@ function DetailWorkbench({
46
46
  slug,
47
47
  variants,
48
48
  previewUrl,
49
+ runtime = "legacy",
49
50
  frameSandbox,
50
51
  frameAllow,
51
52
  selection = { mode: "all" },
@@ -123,6 +124,7 @@ function DetailWorkbench({
123
124
  themeMode: frameThemeMode,
124
125
  viewportId,
125
126
  previewUrl,
127
+ runtime,
126
128
  frameSandbox,
127
129
  frameAllow,
128
130
  previewParams,
@@ -289,6 +291,7 @@ function DetailWorkbench({
289
291
  themeMode: frameThemeMode,
290
292
  viewportId,
291
293
  previewUrl,
294
+ runtime,
292
295
  frameSandbox,
293
296
  frameAllow,
294
297
  previewParams,
@@ -0,0 +1,117 @@
1
+ import { MSG_HEIGHT, MSG_READY, MSG_REQUEST_READY, MSG_SET_THEME, MSG_UPDATE_PROPS, PROTOCOL_VERSION, type PreviewTheme } from "./messages.js";
2
+ /** Extension revision; the underlying legacy protocol remains v1. */
3
+ export declare const EXTERNAL_RUNTIME_VERSION: 1;
4
+ export declare const MSG_RESET_FIXTURE: "sg:resetFixture";
5
+ export declare const MSG_RUNTIME_ERROR: "sg:runtimeError";
6
+ /** The parent must select strict mode before accepting the first message. */
7
+ export type ExternalRuntimeMode = "legacy" | "external-v1";
8
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
9
+ [key: string]: JsonValue;
10
+ };
11
+ export type SerializableProps = Record<string, JsonValue>;
12
+ /** JSON data only; no accessors, cycles, prototype keys or lossy values. */
13
+ export declare function isJsonValue(value: unknown): value is JsonValue;
14
+ export declare function isSerializableProps(value: unknown): value is SerializableProps;
15
+ export interface ExternalFixtureIdentity {
16
+ slug: string;
17
+ variant: string;
18
+ }
19
+ /** A host challenge changes on load/navigation; a document nonce changes on reload. */
20
+ export interface ExternalRuntimeIdentity extends ExternalFixtureIdentity {
21
+ sessionId: string;
22
+ documentId: string;
23
+ /** Starts at zero, advances only for an accepted full fixture reset. */
24
+ generation: number;
25
+ }
26
+ export interface ExternalRuntimeCapabilities {
27
+ fullReset: boolean;
28
+ }
29
+ interface ExternalEnvelope extends ExternalFixtureIdentity {
30
+ v: typeof PROTOCOL_VERSION;
31
+ runtimeVersion: typeof EXTERNAL_RUNTIME_VERSION;
32
+ sessionId: string;
33
+ }
34
+ /** The frame answers this challenge even when its initial ready was missed. */
35
+ export interface ExternalRequestReadyMessage extends ExternalEnvelope {
36
+ type: typeof MSG_REQUEST_READY;
37
+ }
38
+ interface ExternalDocumentMessage extends ExternalEnvelope, ExternalRuntimeIdentity {
39
+ /** Monotonic per sender/session/generation. Receivers ignore repeats and older values. */
40
+ sequence: number;
41
+ }
42
+ export interface ExternalReadyMessage extends ExternalDocumentMessage {
43
+ type: typeof MSG_READY;
44
+ capabilities: ExternalRuntimeCapabilities;
45
+ }
46
+ export interface ExternalHeightMessage extends ExternalDocumentMessage {
47
+ type: typeof MSG_HEIGHT;
48
+ height: number;
49
+ }
50
+ export interface ExternalUpdatePropsMessage extends ExternalDocumentMessage {
51
+ type: typeof MSG_UPDATE_PROPS;
52
+ /** Complete control snapshot, replacing previous overrides; never remounts by itself. */
53
+ props: SerializableProps;
54
+ }
55
+ export interface ExternalSetThemeMessage extends ExternalDocumentMessage {
56
+ type: typeof MSG_SET_THEME;
57
+ theme: PreviewTheme;
58
+ }
59
+ export interface ExternalResetFixtureMessage extends ExternalDocumentMessage {
60
+ type: typeof MSG_RESET_FIXTURE;
61
+ /** Exactly generation + 1; the next ready/error must identify this generation. */
62
+ nextGeneration: number;
63
+ }
64
+ export type ExternalRuntimeErrorCode = "unknown-fixture" | "import" | "render" | "asset";
65
+ export interface ExternalRuntimeError {
66
+ code: ExternalRuntimeErrorCode;
67
+ /** Display as text, never HTML. Do not send stacks or nonserializable Error objects. */
68
+ message: string;
69
+ recoverable: boolean;
70
+ }
71
+ export interface ExternalRuntimeErrorMessage extends ExternalDocumentMessage {
72
+ type: typeof MSG_RUNTIME_ERROR;
73
+ error: ExternalRuntimeError;
74
+ }
75
+ export type ExternalParentMessage = ExternalRequestReadyMessage | ExternalUpdatePropsMessage | ExternalSetThemeMessage | ExternalResetFixtureMessage;
76
+ export type ExternalPreviewMessage = ExternalReadyMessage | ExternalHeightMessage | ExternalRuntimeErrorMessage;
77
+ export type ExternalRuntimeMessage = ExternalParentMessage | ExternalPreviewMessage;
78
+ export declare function isExternalRuntimeIdentity(value: unknown): value is ExternalRuntimeIdentity;
79
+ export declare function isExternalRuntimeCapabilities(value: unknown): value is ExternalRuntimeCapabilities;
80
+ export declare function isExternalRuntimeError(value: unknown): value is ExternalRuntimeError;
81
+ /** Check this before legacy guards: malformed extensions must not fall back to legacy mode. */
82
+ export declare function hasExternalRuntimeMarker(value: unknown): boolean;
83
+ /** Shape validation only; pair with transport, identity and sequence checks before applying. */
84
+ export declare function isExternalRuntimeMessage(value: unknown): value is ExternalRuntimeMessage;
85
+ export declare function matchesExternalRuntimeIdentity(actual: ExternalRuntimeIdentity, expected: ExternalRuntimeIdentity): boolean;
86
+ /** Start lastSequence at -1; advance it only after every other check passes. */
87
+ export declare function isNewExternalRuntimeSequence(sequence: unknown, lastSequence: number): sequence is number;
88
+ /** Pure transport check. Null/opaque origins and unknown source windows never qualify. */
89
+ export declare function isExternalRuntimeMessageEvent(event: {
90
+ origin: string;
91
+ source: unknown;
92
+ data: unknown;
93
+ }, expected: {
94
+ origin: string;
95
+ source: unknown;
96
+ }): event is {
97
+ origin: string;
98
+ source: unknown;
99
+ data: ExternalRuntimeMessage;
100
+ };
101
+ /** Renderer-owned instance. Update retains hooks/editor state; dispose releases all fixture resources. */
102
+ export interface ExternalFixtureInstance {
103
+ update(props: SerializableProps): void | Promise<void>;
104
+ dispose(): void | Promise<void>;
105
+ /** Optional fixture-specific stability barrier for captures, beyond the initial committed mount. */
106
+ whenStable?(): Promise<void>;
107
+ }
108
+ export interface ExternalFixtureMountContext {
109
+ identity: ExternalRuntimeIdentity;
110
+ props: SerializableProps;
111
+ /** Aborted on reset/disposal. A late instance must be disposed instead of installed. */
112
+ signal: AbortSignal;
113
+ reportError(error: ExternalRuntimeError): void;
114
+ }
115
+ /** Resolve only after the renderer commits; React closures remain in the host's external bundle. */
116
+ export type ExternalFixtureMount = (context: ExternalFixtureMountContext) => ExternalFixtureInstance | Promise<ExternalFixtureInstance>;
117
+ export {};
@@ -0,0 +1,121 @@
1
+ import {
2
+ MSG_HEIGHT,
3
+ MSG_READY,
4
+ MSG_REQUEST_READY,
5
+ MSG_SET_THEME,
6
+ MSG_UPDATE_PROPS,
7
+ PROTOCOL_VERSION
8
+ } from "./messages.js";
9
+ const EXTERNAL_RUNTIME_VERSION = 1;
10
+ const MSG_RESET_FIXTURE = "sg:resetFixture";
11
+ const MSG_RUNTIME_ERROR = "sg:runtimeError";
12
+ const MAX_JSON_DEPTH = 32;
13
+ const RESERVED_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
14
+ function isRecord(value) {
15
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
16
+ const prototype = Object.getPrototypeOf(value);
17
+ return prototype === Object.prototype || prototype === null;
18
+ }
19
+ function isJson(value, ancestors, depth) {
20
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
21
+ if (typeof value === "number") return Number.isFinite(value);
22
+ if (typeof value !== "object" || depth > MAX_JSON_DEPTH || ancestors.has(value)) return false;
23
+ if (!Array.isArray(value) && !isRecord(value)) return false;
24
+ if (Object.getOwnPropertySymbols(value).length > 0) return false;
25
+ ancestors.add(value);
26
+ try {
27
+ const descriptors = Object.getOwnPropertyDescriptors(value);
28
+ if (Array.isArray(value)) {
29
+ if (Object.keys(descriptors).length !== value.length + 1) return false;
30
+ for (let index = 0; index < value.length; index++) {
31
+ const property = descriptors[String(index)];
32
+ if (!property || !("value" in property) || !isJson(property.value, ancestors, depth + 1)) return false;
33
+ }
34
+ return true;
35
+ }
36
+ return Object.entries(descriptors).every(
37
+ ([key, property]) => !RESERVED_KEYS.has(key) && property.enumerable && "value" in property && isJson(property.value, ancestors, depth + 1)
38
+ );
39
+ } finally {
40
+ ancestors.delete(value);
41
+ }
42
+ }
43
+ function isJsonValue(value) {
44
+ try {
45
+ return isJson(value, /* @__PURE__ */ new Set(), 0);
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+ function isSerializableProps(value) {
51
+ try {
52
+ return isRecord(value) && isJsonValue(value);
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+ function isNonEmptyString(value) {
58
+ return typeof value === "string" && value.trim().length > 0;
59
+ }
60
+ function isCounter(value) {
61
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
62
+ }
63
+ function isExternalRuntimeIdentity(value) {
64
+ return isSerializableProps(value) && isNonEmptyString(value.slug) && isNonEmptyString(value.variant) && isNonEmptyString(value.sessionId) && isNonEmptyString(value.documentId) && isCounter(value.generation);
65
+ }
66
+ function isExternalRuntimeCapabilities(value) {
67
+ return isSerializableProps(value) && Object.keys(value).length === 1 && typeof value.fullReset === "boolean";
68
+ }
69
+ function isExternalRuntimeError(value) {
70
+ return isSerializableProps(value) && Object.keys(value).every((key) => ["code", "message", "recoverable"].includes(key)) && ["unknown-fixture", "import", "render", "asset"].includes(value.code) && isNonEmptyString(value.message) && typeof value.recoverable === "boolean";
71
+ }
72
+ function hasExternalRuntimeMarker(value) {
73
+ return typeof value === "object" && value !== null && Object.hasOwn(value, "runtimeVersion");
74
+ }
75
+ function isExternalRuntimeMessage(value) {
76
+ if (!isSerializableProps(value) || value.v !== PROTOCOL_VERSION || value.runtimeVersion !== EXTERNAL_RUNTIME_VERSION || !isNonEmptyString(value.slug) || !isNonEmptyString(value.variant) || !isNonEmptyString(value.sessionId)) return false;
77
+ if (value.type === MSG_REQUEST_READY) {
78
+ return value.documentId === void 0 && value.generation === void 0 && value.sequence === void 0;
79
+ }
80
+ if (!isExternalRuntimeIdentity(value) || !isCounter(value.sequence)) return false;
81
+ switch (value.type) {
82
+ case MSG_READY:
83
+ return isExternalRuntimeCapabilities(value.capabilities);
84
+ case MSG_HEIGHT:
85
+ return typeof value.height === "number" && Number.isFinite(value.height) && value.height >= 0;
86
+ case MSG_UPDATE_PROPS:
87
+ return isSerializableProps(value.props);
88
+ case MSG_SET_THEME:
89
+ return value.theme === "light" || value.theme === "dark";
90
+ case MSG_RESET_FIXTURE:
91
+ return isCounter(value.nextGeneration) && value.nextGeneration === value.generation + 1;
92
+ case MSG_RUNTIME_ERROR:
93
+ return isExternalRuntimeError(value.error);
94
+ default:
95
+ return false;
96
+ }
97
+ }
98
+ function matchesExternalRuntimeIdentity(actual, expected) {
99
+ return actual.slug === expected.slug && actual.variant === expected.variant && actual.sessionId === expected.sessionId && actual.documentId === expected.documentId && actual.generation === expected.generation;
100
+ }
101
+ function isNewExternalRuntimeSequence(sequence, lastSequence) {
102
+ return isCounter(sequence) && Number.isSafeInteger(lastSequence) && lastSequence >= -1 && sequence > lastSequence;
103
+ }
104
+ function isExternalRuntimeMessageEvent(event, expected) {
105
+ return expected.origin !== "" && expected.origin !== "null" && expected.source != null && event.origin === expected.origin && event.source === expected.source && isExternalRuntimeMessage(event.data);
106
+ }
107
+ export {
108
+ EXTERNAL_RUNTIME_VERSION,
109
+ MSG_RESET_FIXTURE,
110
+ MSG_RUNTIME_ERROR,
111
+ hasExternalRuntimeMarker,
112
+ isExternalRuntimeCapabilities,
113
+ isExternalRuntimeError,
114
+ isExternalRuntimeIdentity,
115
+ isExternalRuntimeMessage,
116
+ isExternalRuntimeMessageEvent,
117
+ isJsonValue,
118
+ isNewExternalRuntimeSequence,
119
+ isSerializableProps,
120
+ matchesExternalRuntimeIdentity
121
+ };
@@ -0,0 +1,34 @@
1
+ import { type ExternalFixtureIdentity, type ExternalFixtureMount, type ExternalRuntimeError, type ExternalRuntimeIdentity, type SerializableProps } from "./external-runtime.js";
2
+ import { type PreviewTheme } from "./messages.js";
3
+ export interface ExternalPreviewRuntimeOptions {
4
+ target?: Window;
5
+ /** Defaults to the document's slug/variant query parameters. */
6
+ identity?: ExternalFixtureIdentity;
7
+ initialProps?: SerializableProps;
8
+ mount: ExternalFixtureMount;
9
+ fullReset?: boolean;
10
+ onTheme?(theme: PreviewTheme): void | Promise<void>;
11
+ measureHeight?(): number;
12
+ /** Background/final cleanup failures; defaults to console.error. */
13
+ onCleanupError?(error: ExternalRuntimeError): void;
14
+ }
15
+ export interface ExternalRuntimeSnapshot {
16
+ identity: ExternalRuntimeIdentity;
17
+ ready: boolean;
18
+ error: ExternalRuntimeError | null;
19
+ }
20
+ export interface ExternalPreviewRuntime {
21
+ getSnapshot(): ExternalRuntimeSnapshot;
22
+ /** Await the committed current fixture, pending updates, and its stability barrier. */
23
+ whenStable(): Promise<ExternalRuntimeIdentity>;
24
+ reportError(error: ExternalRuntimeError): void;
25
+ reportHeight(): void;
26
+ dispose(): Promise<void>;
27
+ }
28
+ /** Throw from a host loader to distinguish a missing fixture from a failed import. */
29
+ export declare class ExternalPreviewError extends Error {
30
+ readonly code: ExternalRuntimeError["code"];
31
+ readonly recoverable: boolean;
32
+ constructor(code: ExternalRuntimeError["code"], message: string, recoverable?: boolean);
33
+ }
34
+ export declare function createExternalPreviewRuntime(options: ExternalPreviewRuntimeOptions): ExternalPreviewRuntime;
@@ -0,0 +1,302 @@
1
+ import {
2
+ EXTERNAL_RUNTIME_VERSION,
3
+ MSG_RESET_FIXTURE,
4
+ MSG_RUNTIME_ERROR,
5
+ isExternalRuntimeMessageEvent,
6
+ isNewExternalRuntimeSequence,
7
+ isSerializableProps,
8
+ matchesExternalRuntimeIdentity
9
+ } from "./external-runtime.js";
10
+ import { MSG_HEIGHT, MSG_READY, MSG_REQUEST_READY, MSG_SET_THEME, MSG_UPDATE_PROPS, PROTOCOL_VERSION } from "./messages.js";
11
+ import { installIframeReceiver } from "../token-tweak/iframe-css-vars-bridge.js";
12
+ class ExternalPreviewError extends Error {
13
+ constructor(code, message, recoverable = true) {
14
+ super(message);
15
+ this.code = code;
16
+ this.recoverable = recoverable;
17
+ this.name = "ExternalPreviewError";
18
+ }
19
+ code;
20
+ recoverable;
21
+ }
22
+ function runtimeError(error, fallback) {
23
+ return {
24
+ code: error instanceof ExternalPreviewError ? error.code : fallback,
25
+ message: error instanceof Error ? error.message || error.name : String(error),
26
+ recoverable: error instanceof ExternalPreviewError ? error.recoverable : true
27
+ };
28
+ }
29
+ function createExternalPreviewRuntime(options) {
30
+ const target = options.target ?? window;
31
+ const params = new URLSearchParams(target.location.search);
32
+ const fixture = options.identity ?? { slug: params.get("slug") ?? "", variant: params.get("variant") ?? "" };
33
+ const documentId = target.crypto.randomUUID();
34
+ let identity = { ...fixture, documentId, sessionId: `standalone-${documentId}`, generation: 0 };
35
+ let props = options.initialProps ?? {};
36
+ if (!isSerializableProps(props)) throw new TypeError("External runtime initialProps must be serializable props");
37
+ let propsRevision = 0;
38
+ let ready = false;
39
+ let error = null;
40
+ let errorRevision = 0;
41
+ let errorNode = null;
42
+ let disposed = false;
43
+ let epoch = 0;
44
+ let outgoing = -1;
45
+ let incoming = -1;
46
+ let instance = null;
47
+ let abort = new AbortController();
48
+ let operations = Promise.resolve();
49
+ let mounting = Promise.resolve();
50
+ let pendingMountOwner = null;
51
+ let disposeResult;
52
+ let restoreListener = null;
53
+ const retiredSessions = /* @__PURE__ */ new Set();
54
+ const fullReset = options.fullReset === true;
55
+ const current = (owner) => !disposed && owner === epoch;
56
+ function post(message) {
57
+ if (disposed || target.parent === target || target.location.origin === "null") return;
58
+ target.parent.postMessage({ ...message, ...identity, v: PROTOCOL_VERSION, runtimeVersion: EXTERNAL_RUNTIME_VERSION, sequence: ++outgoing }, target.location.origin);
59
+ }
60
+ function clearError() {
61
+ error = null;
62
+ errorNode?.remove();
63
+ errorNode = null;
64
+ }
65
+ function reportError(value) {
66
+ if (disposed) return;
67
+ errorRevision++;
68
+ error = { ...value };
69
+ ready = false;
70
+ if (!errorNode) {
71
+ errorNode = target.document.createElement("pre");
72
+ errorNode.setAttribute("role", "alert");
73
+ errorNode.setAttribute("data-sg-runtime-error", "");
74
+ target.document.body.appendChild(errorNode);
75
+ }
76
+ errorNode.textContent = `Preview failed: ${value.message}`;
77
+ post({ type: MSG_RUNTIME_ERROR, error });
78
+ }
79
+ function reportHeight() {
80
+ if (!ready || disposed) return;
81
+ try {
82
+ const height = options.measureHeight?.() ?? Math.ceil(target.document.body.getBoundingClientRect().bottom + target.scrollY);
83
+ if (Number.isFinite(height) && height >= 0) post({ type: MSG_HEIGHT, height });
84
+ } catch (failure) {
85
+ reportError(runtimeError(failure, "render"));
86
+ }
87
+ }
88
+ function announce() {
89
+ if (error) post({ type: MSG_RUNTIME_ERROR, error });
90
+ else if (ready) {
91
+ post({ type: MSG_READY, capabilities: { fullReset } });
92
+ reportHeight();
93
+ }
94
+ }
95
+ async function disposeInstance(value, owner, propagate = false) {
96
+ try {
97
+ await value.dispose();
98
+ } catch (failure) {
99
+ const diagnostic = runtimeError(failure, "render");
100
+ if (current(owner)) reportError(diagnostic);
101
+ try {
102
+ if (options.onCleanupError) options.onCleanupError(diagnostic);
103
+ else console.error("External fixture cleanup failed:", failure);
104
+ } catch (callbackFailure) {
105
+ console.error("External fixture cleanup reporter failed:", callbackFailure);
106
+ }
107
+ if (propagate) throw failure;
108
+ }
109
+ }
110
+ function queue(work, owner = epoch) {
111
+ operations = operations.then(async () => {
112
+ if (!current(owner)) return;
113
+ try {
114
+ await work();
115
+ } catch (failure) {
116
+ if (current(owner)) reportError(runtimeError(failure, "render"));
117
+ }
118
+ });
119
+ }
120
+ function mount() {
121
+ const owner = epoch;
122
+ pendingMountOwner = owner;
123
+ const revision = propsRevision;
124
+ const initial = props;
125
+ const signal = abort.signal;
126
+ const cancelled = /* @__PURE__ */ Symbol("cancelled mount");
127
+ mounting = Promise.resolve().then(() => {
128
+ if (!current(owner)) return cancelled;
129
+ return options.mount({
130
+ identity: { ...identity },
131
+ props: initial,
132
+ signal,
133
+ reportError: (failure) => {
134
+ if (current(owner)) reportError(failure);
135
+ }
136
+ });
137
+ }).then(async (mounted) => {
138
+ if (mounted === cancelled) return;
139
+ if (!mounted || typeof mounted.update !== "function" || typeof mounted.dispose !== "function" || mounted.whenStable !== void 0 && typeof mounted.whenStable !== "function") {
140
+ throw new ExternalPreviewError("render", "External fixture mount must return an instance with update() and dispose() methods");
141
+ }
142
+ if (!current(owner)) {
143
+ await disposeInstance(mounted, owner);
144
+ return;
145
+ }
146
+ operations = operations.then(async () => {
147
+ let applied = revision;
148
+ try {
149
+ while (current(owner) && applied !== propsRevision) {
150
+ applied = propsRevision;
151
+ await mounted.update(props);
152
+ }
153
+ if (!current(owner)) {
154
+ await disposeInstance(mounted, owner);
155
+ return;
156
+ }
157
+ instance = mounted;
158
+ if (!error) {
159
+ ready = true;
160
+ announce();
161
+ }
162
+ } catch (failure) {
163
+ await disposeInstance(mounted, owner);
164
+ if (current(owner)) reportError(runtimeError(failure, "render"));
165
+ }
166
+ });
167
+ await operations;
168
+ }).catch((failure) => {
169
+ if (current(owner)) reportError(runtimeError(failure, "import"));
170
+ }).finally(() => {
171
+ if (pendingMountOwner === owner) pendingMountOwner = null;
172
+ if (current(owner) && !instance && error && propsRevision !== revision) retryFailedMount();
173
+ });
174
+ }
175
+ function retryFailedMount() {
176
+ if (pendingMountOwner !== null || instance || !error) return;
177
+ abort.abort();
178
+ abort = new AbortController();
179
+ epoch++;
180
+ ready = false;
181
+ clearError();
182
+ mount();
183
+ }
184
+ function reset(nextGeneration) {
185
+ const old = instance;
186
+ instance = null;
187
+ abort.abort();
188
+ abort = new AbortController();
189
+ const owner = ++epoch;
190
+ identity = { ...identity, generation: nextGeneration };
191
+ incoming = -1;
192
+ outgoing = -1;
193
+ ready = false;
194
+ clearError();
195
+ operations = operations.then(async () => {
196
+ if (old) await disposeInstance(old, owner);
197
+ if (current(owner)) mount();
198
+ });
199
+ }
200
+ function receive(event) {
201
+ if (!isExternalRuntimeMessageEvent(event, { origin: target.location.origin, source: target.parent })) return;
202
+ const message = event.data;
203
+ if (message.slug !== fixture.slug || message.variant !== fixture.variant) return;
204
+ if (message.type === MSG_REQUEST_READY) {
205
+ if (retiredSessions.has(message.sessionId)) return;
206
+ if (message.sessionId !== identity.sessionId) {
207
+ retiredSessions.add(identity.sessionId);
208
+ identity = { ...identity, sessionId: message.sessionId };
209
+ incoming = -1;
210
+ outgoing = -1;
211
+ }
212
+ announce();
213
+ return;
214
+ }
215
+ if (!matchesExternalRuntimeIdentity(message, identity) || !isNewExternalRuntimeSequence(message.sequence, incoming)) return;
216
+ if (message.type !== MSG_UPDATE_PROPS && message.type !== MSG_SET_THEME && message.type !== MSG_RESET_FIXTURE) return;
217
+ if (message.type === MSG_RESET_FIXTURE && !fullReset) return;
218
+ incoming = message.sequence;
219
+ if (message.type === MSG_UPDATE_PROPS) {
220
+ props = message.props;
221
+ propsRevision++;
222
+ const mounted = instance;
223
+ if (mounted) {
224
+ const snapshot = props;
225
+ const owner = epoch;
226
+ queue(async () => {
227
+ const previousErrorRevision = errorRevision;
228
+ await mounted.update(snapshot);
229
+ if (!current(owner) || previousErrorRevision !== errorRevision) return;
230
+ const recovering = !!error;
231
+ clearError();
232
+ ready = true;
233
+ if (recovering) announce();
234
+ else reportHeight();
235
+ }, owner);
236
+ } else retryFailedMount();
237
+ } else if (message.type === MSG_SET_THEME) {
238
+ target.document.documentElement.dataset.theme = message.theme;
239
+ queue(() => options.onTheme?.(message.theme));
240
+ } else reset(message.nextGeneration);
241
+ }
242
+ target.addEventListener("message", receive);
243
+ const removeTokens = installIframeReceiver(target, { identity: () => identity });
244
+ const observer = new target.ResizeObserver(reportHeight);
245
+ observer.observe(target.document.body);
246
+ const pagehide = (event) => {
247
+ void dispose().catch(() => {
248
+ });
249
+ if (event.persisted) {
250
+ restoreListener = (shown) => {
251
+ if (restoreListener) target.removeEventListener("pageshow", restoreListener);
252
+ restoreListener = null;
253
+ if (shown.persisted) target.location.reload();
254
+ };
255
+ target.addEventListener("pageshow", restoreListener);
256
+ }
257
+ };
258
+ target.addEventListener("pagehide", pagehide);
259
+ mount();
260
+ function dispose() {
261
+ if (restoreListener) target.removeEventListener("pageshow", restoreListener);
262
+ restoreListener = null;
263
+ if (disposeResult) return disposeResult;
264
+ disposed = true;
265
+ epoch++;
266
+ abort.abort();
267
+ target.removeEventListener("message", receive);
268
+ target.removeEventListener("pagehide", pagehide);
269
+ observer.disconnect();
270
+ removeTokens();
271
+ errorNode?.remove();
272
+ const old = instance;
273
+ instance = null;
274
+ ready = false;
275
+ disposeResult = operations.then(async () => {
276
+ if (old) await disposeInstance(old, epoch, true);
277
+ });
278
+ return disposeResult;
279
+ }
280
+ return {
281
+ getSnapshot: () => ({ identity: { ...identity }, ready, error: error ? { ...error } : null }),
282
+ async whenStable() {
283
+ const owner = epoch;
284
+ const revision = propsRevision;
285
+ await operations;
286
+ await mounting;
287
+ await operations;
288
+ const mounted = instance;
289
+ if (!current(owner) || !mounted || !ready || error) throw new Error(error?.message ?? "External fixture is not ready");
290
+ await mounted.whenStable?.();
291
+ if (!current(owner) || !ready || error || revision !== propsRevision) throw new Error("External fixture changed while waiting for stability");
292
+ return { ...identity };
293
+ },
294
+ reportError,
295
+ reportHeight,
296
+ dispose
297
+ };
298
+ }
299
+ export {
300
+ ExternalPreviewError,
301
+ createExternalPreviewRuntime
302
+ };
@@ -1,4 +1,5 @@
1
1
  import type { StoryControl } from "../stories/index.js";
2
+ import { type ExternalRuntimeMode } from "./external-runtime.js";
2
3
  import { type FrameThemeMode, type ViewportId } from "./variant-frame-config.js";
3
4
  import { type ReadonlySignal, type Description } from "@takazudo/zfb/zudo-react";
4
5
  type Live<T> = T | ReadonlySignal<T>;
@@ -22,6 +23,8 @@ export interface VariantFrameProps {
22
23
  * `routes.componentsPreview`). Defaults to the unprefixed PREVIEW_ROUTE_PATH.
23
24
  */
24
25
  previewUrl?: string;
26
+ /** Explicit strict mode; never negotiate down to legacy identity-less traffic. */
27
+ runtime?: ExternalRuntimeMode;
25
28
  /**
26
29
  * Iframe `sandbox` tokens. Defaults to DEFAULT_FRAME_SANDBOX. Dropping
27
30
  * `allow-same-origin` gives the frame an opaque origin, which the protocol's