@takazudo/zudo-sg 0.5.0 → 0.5.1

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 +42 -0
  2. package/README.md +233 -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 +21 -5
  35. package/routes-src/components-slug.tsx +12 -9
package/CHANGELOG.md CHANGED
@@ -4,6 +4,48 @@ All notable changes to `@takazudo/zudo-sg` are documented in this file.
4
4
 
5
5
  The format is based on Keep a Changelog, and release notes are generated from the changelog MDX pages.
6
6
 
7
+ ## [0.5.1] - 2026-10-12
8
+
9
+ This release adds an opt-in, same-origin external preview runtime contract with
10
+ stricter catalog checks, so a host can render React 19 fixtures in its own
11
+ external document. It also fixes preview lifecycle bugs and updates the engine's
12
+ dependencies after a security audit. Existing module stories and
13
+ framework-free descriptors keep their current behavior.
14
+
15
+ ### Features
16
+
17
+ - New `@takazudo/zudo-sg/preview/external-runtime`, `preview/runtime`,
18
+ `registry/external-catalog`, and `registry/external-catalog-node` exports
19
+ define a strict external preview and catalog contract: fixture identity,
20
+ serializable controls, ready/request-ready replay, height, theme, the token
21
+ bridge, live CSS, visible errors, and deterministic cleanup. React and
22
+ ReactDOM stay inside the host's external fixture document; the engine does not
23
+ depend on them.
24
+ - External fixtures keep their root, hooks, focus, and editor state through
25
+ props updates and ordinary prop Reset. A separate full fixture reset remounts
26
+ fixture resources but keeps the current controls, theme, token edits, and
27
+ live CSS.
28
+ - External catalog generation checks descriptor slugs and variant IDs, loader
29
+ keys, displayed-source keys, and thumbnail keys against each other. Thumbnails
30
+ must be real captures of the named fixture or carry an explicit placeholder
31
+ or failed-capture state. Descriptor sources can be shown in the real code
32
+ panel.
33
+
34
+ ### Bug Fixes
35
+
36
+ - Reject sparse or malformed external catalog manifests, and messages from the
37
+ wrong origin or window or with stale document or variant identity.
38
+ - Keep owner-scoped live CSS when an iframe becomes ready again, recover
39
+ external fixtures with the current preview state, and keep render errors
40
+ reported during fixture updates visible.
41
+ - Keep mixed-property batches together when the preview token panel resets.
42
+ - Restore code-panel syntax highlighting with a CodeMirror/Lezer update that
43
+ resolves one shared Lezer identity (`@codemirror/language` 6.13.1,
44
+ `@codemirror/state` 6.7.6, `@codemirror/commands` 6.11.1). Hosts that keep
45
+ an older `@lezer/common` in their own lockfile should run `pnpm dedupe`.
46
+ - Fix security advisories in development and test dependencies, including the
47
+ move from Happy DOM 16 to 20.
48
+
7
49
  ## [0.5.0] - 2026-10-12
8
50
 
9
51
  This release ports the styleguide engine to zfb 4.3.1 and zudo-doc 6.0.0.
package/README.md CHANGED
@@ -283,6 +283,239 @@ source changes refresh without a restart. Host config or imported token-config
283
283
  changes require zfb config reload/restart so the snapshot contains fresh data.
284
284
  This token precedence rule does not isolate every host stylesheet selector.
285
285
 
286
+ ## External runtime contracts
287
+
288
+ The public leaf modules `@takazudo/zudo-sg/preview/external-runtime` and
289
+ `@takazudo/zudo-sg/registry/external-catalog` contain renderer-free types and
290
+ validators. They can be imported in Node/SSR without a browser. React,
291
+ ReactDOM, fixture loaders and component closures belong only in the host's
292
+ separately built same-origin preview document. The engine shell and catalog
293
+ stay zudo-react; the opaque Preact/zdtp adapter remains independent.
294
+
295
+ These contracts are additive. `preview/messages` remains import-free and
296
+ continues accepting legacy messages with no `v` and current `v: 1` messages.
297
+ The strict extension uses **both** `v: 1` and `runtimeVersion: 1`; it does not
298
+ reinterpret legacy messages. `ExternalRuntimeMode` is `"legacy" |
299
+ "external-v1"`. Select strict mode at the parent boundary before the first
300
+ message: a strict frame must never fall back to an identity-less legacy ready,
301
+ including during startup. `hasExternalRuntimeMarker()` also lets a legacy
302
+ receiver identify and reject malformed extension traffic instead of treating
303
+ it as legacy. Configure `externalPreview: { url: "/frame/", runtime:
304
+ "external-v1" }` to select strict mode in the injected detail route. Direct
305
+ `VariantFrame` and `DetailWorkbench` users pass `runtime="external-v1"`.
306
+ Omitting it preserves legacy module/vanilla behavior.
307
+
308
+ Import `createExternalPreviewRuntime` from `@takazudo/zudo-sg/preview/runtime`
309
+ inside your external document's entrypoint. Pass `mount` (the renderer-owned
310
+ `ExternalFixtureMount`), optional `initialProps`, and `fullReset: true` when
311
+ that fixture supports disposal/remount. Optional `target`, `identity`,
312
+ `onTheme` and `measureHeight` customize the document, query identity, host
313
+ theme side effects and height measurement. The function installs the strict
314
+ receiver and token receiver, mounts the fixture, and returns a controller;
315
+ importing the module alone installs nothing.
316
+
317
+ `controller.getSnapshot()` returns copied `{identity, ready, error}` state.
318
+ `controller.whenStable()` waits for the committed mount, queued prop updates
319
+ and optional fixture stability barrier, then returns the actual runtime
320
+ identity. It rejects errors, disposal/reset or props changes during the wait;
321
+ capture adapters can retry a changed fixture explicitly. Standalone top-level
322
+ capture documents receive a local session identity and emit no parent
323
+ messages. A host may expose its controller to its own capture adapter; the
324
+ engine installs no global capture object. `reportError`, `reportHeight` and
325
+ idempotent asynchronous `dispose` complete the controller API.
326
+ Explicit `dispose()` rejects if fixture cleanup fails. Cleanup failures also
327
+ reach the optional `onCleanupError` callback (default: `console.error`),
328
+ including late cancelled mounts and page unload; they never replace a newer
329
+ fixture's error state. Page unload consumes the already reported rejection.
330
+ Returning to a disposed document from the browser back/forward cache reloads
331
+ that document once to create fresh resources and identity. Explicit disposal
332
+ removes this restoration listener as well.
333
+
334
+ ### Identity, readiness and ordering
335
+
336
+ The parent sends `sg:requestReady` with `slug`, `variant`, and a fresh
337
+ `sessionId` challenge, plus the two version fields. Create a new unpredictable
338
+ session on iframe load and variant navigation, invalidate previous readiness,
339
+ height, document binding and errors, and retain the latest host state. A
340
+ same-URL reload requires this transition too: `contentWindow` can retain the
341
+ same WindowProxy after its document changes.
342
+
343
+ The document creates its own unpredictable `documentId`. Its committed
344
+ `sg:ready` echoes the challenge and adds `generation: 0`, `sequence`, and
345
+ `capabilities: { fullReset: boolean }`. A ready means the fixture mounted and
346
+ committed successfully, not merely that message listeners exist. A repeated
347
+ request re-announces the same committed document without remounting it. A
348
+ mount/import failure sends `sg:runtimeError` instead of successful ready.
349
+
350
+ All document-bound messages carry the exact
351
+ `{slug, variant, sessionId, documentId, generation}` identity and a
352
+ nonnegative safe-integer `sequence`. Sequence counters are independent per
353
+ sender and per session/generation. Validate the complete message, exact
354
+ same-origin and source window, current identity, and then monotonically
355
+ increasing sequence **before** mutating state or advancing the receive
356
+ watermark. `isExternalRuntimeMessageEvent()`,
357
+ `matchesExternalRuntimeIdentity()` and `isNewExternalRuntimeSequence()` are
358
+ separate pure checks; none maintains hidden state. Initialize a receive
359
+ watermark to `-1`. Reject opaque `"null"` origins and unknown/null sources.
360
+
361
+ A parent may initially bind a document from a valid ready or error answering
362
+ its current challenge and expected generation. Once bound, another document
363
+ cannot replace it without a new host session. Only an acknowledged full
364
+ reset can advance generation. A stale ready/error/height or malformed
365
+ high-sequence message must not affect the active document or its watermark.
366
+ Duplicate readiness may replay current snapshots, but cannot reset a fixture.
367
+
368
+ ### Updates, resets, errors and resource ownership
369
+
370
+ `sg:updateProps` contains a complete `SerializableProps` snapshot that replaces
371
+ previous control overrides. `isSerializableProps()` accepts finite JSON values,
372
+ rejecting callbacks/elements, undefined, cycles, accessors, symbols, prototype
373
+ keys, sparse arrays, and nesting beyond 32 object/array levels. Merge fixture
374
+ base props, declared control defaults and this current snapshot in that order.
375
+ Ordinary prop edits and the controls' **Reset** update the existing renderer
376
+ root and preserve hooks, focus and editor state. Existing module stories
377
+ continue their deliberate remount-on-args behavior.
378
+
379
+ Only runtimes advertising `fullReset: true` receive `sg:resetFixture`. It
380
+ targets the current identity and supplies `nextGeneration: generation + 1`.
381
+ The runtime disposes the current fixture, advances generation, clears its
382
+ per-generation sequence counters and mounts a fresh fixture with the retained
383
+ props. Ready/error then identifies the new generation. Reset replay is rejected
384
+ by identity/sequence checks. The parent retains controls, resolved theme,
385
+ token overrides and live CSS; it replays current state after accepted ready.
386
+ Changing variant seeds that variant's controls; reloading the same variant
387
+ retains its edited values.
388
+
389
+ `ExternalFixtureMount(context)` resolves only after a committed mount and
390
+ returns an `ExternalFixtureInstance` with `update(props)` and `dispose()`.
391
+ Its optional `whenStable()` is a fixture-specific capture barrier after
392
+ commit, for fonts, editor initialization or other async resources. The mount
393
+ context supplies current identity/props, an abort signal and `reportError()`.
394
+ Abort on reset/disposal; check identity after every awaited operation and
395
+ dispose any late instance rather than installing it. Serialize asynchronous
396
+ updates and resets so an older update cannot overwrite newer props.
397
+
398
+ The renderer owns its roots, hooks, portals, editors, workers and fixture
399
+ subscriptions. The runtime owns its message listeners, observers and timers;
400
+ final disposal removes them deterministically. Full fixture reset must not
401
+ erase host-owned theme, token overrides or the live-CSS style element.
402
+
403
+ Errors use `sg:runtimeError` and `{code, message, recoverable}`. Codes are
404
+ `unknown-fixture`, `import`, `render`, and `asset`; display messages as text,
405
+ never HTML or an empty successful tile. React error boundaries must report
406
+ render failures. An initial failure can bind the current document without
407
+ claiming readiness; show a reload/retry action. A successful recovery clears
408
+ only errors for its accepted identity, never another document's error.
409
+
410
+ Tokens retain their separate `zudo-sg-token-tweak-bridge` apply/clear/ready
411
+ envelopes, with exact parent/source and validated custom-property payloads.
412
+ Live CSS retains direct same-origin `contentDocument` injection into
413
+ `style[data-sg-injected-css]`. They are not new runtime message types. Keep
414
+ their snapshots at the parent, retain edits before readiness, replay on
415
+ reload/reset and tear down listeners/styles when their owning scope ends.
416
+
417
+ ### Source and canonical capture metadata
418
+
419
+ Descriptors may opt into `variant.source = { key, code }`. Obtain `key` from
420
+ `externalCatalogKey(slug, exportName)`; it encodes a JSON tuple, avoiding
421
+ delimiter collisions. `code` is verbatim text, including JSX or characters
422
+ that resemble HTML; never evaluate or inject it as markup. Existing
423
+ descriptors without source remain valid. Sourced variants mount the existing
424
+ accessible CodePanel, including source tabs/copy and isolated Live CSS. Variants
425
+ without source have no Source tab; a completely source-less descriptor has no
426
+ panel or panel toggle. `sourcePath` remains informational.
427
+
428
+ `validateExternalCatalogManifest(input)` validates and normalizes an array of
429
+ `ExternalCatalogEntry` rows, each containing `slug`, `variant`,
430
+ `loader: {key, module, exportName}`, `source: {key, code}`, and `capture`.
431
+ Loader modules are project-root-relative paths; generated loader functions
432
+ stay in the external bundle. All three keys must equal the canonical tuple
433
+ key, and row identities and captured asset ownership must be unique.
434
+
435
+ A capture is either `{kind: "image", key, fixture: {module, exportName}, src,
436
+ width, height}` matching the loader, or `{kind: "placeholder" | "failed", key,
437
+ note}` with an explicit nonempty explanation. Image paths are root-absolute
438
+ emitted URLs before adding the site base, with positive integer pixel
439
+ dimensions. Existing descriptor image/placeholder/no-thumbnail behavior is
440
+ unchanged unless the host opts into this canonical manifest.
441
+
442
+ This validator checks data, not files or screenshots. An image declaration
443
+ promises a real capture of the named external runtime: capture after committed
444
+ readiness and its stability barrier, then verify the emitted file, actual
445
+ dimensions and fixture/source/loader key agreement before claiming success.
446
+ Missing or invalid promised images fail the build/capture check; explicit
447
+ failed dispositions throw with their recorded note. Compare exact generated key sets,
448
+ source contents and loader references, including extra entries, before build.
449
+ The packed React proof is maintained separately. Never substitute engine React
450
+ SSR, decorative fake screenshots, or a
451
+ host route shadow for this boundary.
452
+
453
+ ### Node prebuild and capture API
454
+
455
+ Import these Node-only helpers from
456
+ `@takazudo/zudo-sg/registry/external-catalog-node` in a host build script.
457
+ Do not import them from `zfb.config` (its graph must remain node-free) or from
458
+ the browser bundle. The engine does not install a browser or import React.
459
+
460
+ - `validateExternalCatalogOutputs({manifest, descriptors, loaders, sources})`
461
+ compares complete generated arrays: missing/extra/duplicate keys, actual
462
+ source text and loader module/export references. Generate browser loaders and
463
+ their metadata from the same canonical manifest. The first authored variant
464
+ owns the story's catalog tile; use
465
+ `thumbnailFromExternalCapture(first.capture)` for its thumbnail. Every
466
+ variant's image promise is checked, including those not used for that tile.
467
+ - `captureExternalCatalogImages({manifest, projectRoot, assetRoot, origin,
468
+ base, previewUrl, page})` visits the actual external document with canonical
469
+ slug/variant query parameters. `origin` is an HTTP(S) origin without a
470
+ trailing slash, `base` defaults to `/`, and `previewUrl` is the root-absolute
471
+ document path before adding the base.
472
+ - `validateExternalCatalogAssets({manifest, projectRoot, assetRoot, captures})`
473
+ checks capture receipts against files. Missing images, stale loader/source
474
+ hashes, wrong image hash/dimensions/fixture identity, and `failed` dispositions
475
+ throw. Intentional placeholders remain labelled. Paths reject symlinks,
476
+ including parents, before reading/writing. Captures must be complete,
477
+ noninterlaced 8-bit PNGs of at most 16,777,216 pixels, matching the declared
478
+ viewport dimensions. Only IHDR/IDAT/IEND critical chunks are supported;
479
+ palette chunks are outside this browser screenshot format. Legacy descriptor
480
+ SVG/remote image semantics are unchanged.
481
+
482
+ `loaders` and `sources` are arrays of `ExternalCatalogLoader` and
483
+ `DescriptorSource`. Pass actual generated outputs rather than reconstructing
484
+ expected copies inside the check. Receipts record actual runtime identity and
485
+ SHA-256 hashes of the loader entry file, displayed source and PNG. The loader
486
+ hash covers the entry file, not its transitive imports: rerun captures after
487
+ fixture dependency or asset changes. Receipts establish capture consistency,
488
+ not independent attestation of arbitrary host-supplied metadata.
489
+
490
+ The caller-owned `page` adapter implements `goto(url)`,
491
+ `setViewportSize({width,height})`, `screenshot({type: "png", scale: "css"})`,
492
+ `whenStable()` and `getSnapshot()`. The latter two invoke the actual
493
+ `createExternalPreviewRuntime()` controller in the loaded document. Wait for
494
+ the host-exposed controller property to exist before calling `whenStable()`;
495
+ apply the browser runner's normal timeout. The helper checks committed
496
+ readiness, errors and identity before and after the screenshot. The host must
497
+ surface browser console errors and close its browser/server in `finally`.
498
+
499
+ Run this sequence from a Node script in the host's build command:
500
+
501
+ 1. Generate descriptors/source/loader metadata from the canonical manifest and
502
+ call `validateExternalCatalogOutputs`.
503
+ 2. Build the independent external preview, serve it under the intended base,
504
+ and capture into `public/`. Missing promised images cannot represent a
505
+ successful catalog build.
506
+ 3. Save the returned serializable receipts, validate assets in `public/`, then
507
+ run the final `zfb build` to copy those assets into `dist/`.
508
+ 4. Validate the same receipts against the emitted asset directory and verify
509
+ built browser loads. Use `assetRoot: "dist"` at the root base; zfb 4 copies
510
+ public assets under the base, so `/styleguide/` uses
511
+ `assetRoot: "dist/styleguide"`. Capture `src` stays `/captures/example.png`;
512
+ the helper resolves it beneath `assetRoot` without adding the URL base.
513
+
514
+ Adding source text alone neither runs captures nor makes thumbnails mandatory
515
+ for existing catalogs. Source-less legacy descriptors do not use this opt-in
516
+ manifest check. The focused helper tests cover framework-independent capture
517
+ orchestration; the separately installed React consumer supplies real screenshots.
518
+
286
519
  ## Release scheme
287
520
 
288
521
  Stable only. `v*.*.*` tags publish to the npm `latest` dist-tag — there is no
@@ -3,7 +3,7 @@ import { jsx, jsxs } from "@takazudo/zfb/zudo-react/jsx-runtime";
3
3
  import { computed, For, getScope, signal } from "@takazudo/zfb/zudo-react";
4
4
  import SourceEditor from "./source-editor.js";
5
5
  import CopyButton from "./copy-button.js";
6
- import { injectCssToAllPreviews } from "./css-injection.js";
6
+ import { createPreviewCssOwner } from "./css-injection.js";
7
7
  import { handleTablistKeyDown } from "../shared/tablist-keyboard.js";
8
8
  const STARTER_CSS = `/* Live CSS \u2014 edits inject into every preview above.
9
9
  Try overriding a component utility, e.g.:
@@ -20,15 +20,25 @@ function CodePanel({
20
20
  const active = computed(() => variants[activeIndex.value]);
21
21
  const activeItems = computed(() => active.value ? [active.value] : []);
22
22
  let debounce;
23
- getScope().onActivate(() => () => window.clearTimeout(debounce));
23
+ let cssOwner;
24
+ getScope().onActivate(() => {
25
+ const owner = createPreviewCssOwner(previewUrl);
26
+ cssOwner = owner;
27
+ return () => {
28
+ window.clearTimeout(debounce);
29
+ owner.dispose();
30
+ if (cssOwner === owner) cssOwner = void 0;
31
+ };
32
+ });
24
33
  const tabsId = `sg-code-panel-${slug ?? encodeURIComponent(storyTitle)}`;
25
34
  const tabId = (index) => `${tabsId}-tab-${index}`;
26
35
  const panelId = `${tabsId}-panel`;
27
36
  function handleCssChange(css) {
37
+ const owner = cssOwner;
38
+ if (!owner) return;
39
+ owner.set("live", css);
28
40
  window.clearTimeout(debounce);
29
- debounce = window.setTimeout(() => {
30
- injectCssToAllPreviews("live", css, previewUrl);
31
- }, 250);
41
+ debounce = window.setTimeout(() => owner.apply(), 250);
32
42
  }
33
43
  function onTabKeyDown(e, index) {
34
44
  handleTablistKeyDown(
@@ -1,6 +1,12 @@
1
- /**
2
- * Inject `css` (keyed by `cssKey`, e.g. a filename) into all preview iframes.
3
- * Re-injecting with the same key replaces the prior buffer. `previewUrl` is the
4
- * (base-prefixed) preview route the iframes load; defaults to PREVIEW_ROUTE_PATH.
5
- */
1
+ /** VariantFrame owns readiness; registering alone never styles an about:blank document. */
2
+ export declare function registerCssPreview(iframe: HTMLIFrameElement): () => void;
3
+ /** Call only after VariantFrame accepts ready; always reads the latest retained buffers. */
4
+ export declare function replayCssToPreview(iframe: HTMLIFrameElement): void;
5
+ /** Own a code panel's buffers. Retention is synchronous; only apply() should be debounced. */
6
+ export declare function createPreviewCssOwner(previewUrl?: string): {
7
+ set(cssKey: string, css: string): void;
8
+ apply(): void;
9
+ dispose(): void;
10
+ };
11
+ /** Selector-compatible direct injection, with current-value replay on later loads. */
6
12
  export declare function injectCssToAllPreviews(cssKey: string, css: string, previewUrl?: string): void;
@@ -1,37 +1,191 @@
1
1
  import { PREVIEW_ROUTE_PATH } from "../preview/route.js";
2
2
  const INJECTED_STYLE_ATTR = "data-sg-injected-css";
3
- function previewIframes(previewUrl) {
4
- if (typeof document === "undefined") return [];
5
- return Array.from(
6
- document.querySelectorAll(`iframe[src*="${previewUrl}"]`)
7
- );
8
- }
9
- function injectInto(iframe, cssKey, css) {
10
- const doc = iframe.contentDocument;
11
- if (!doc) return;
12
- const id = `sg-injected-${cssKey}`;
13
- let style = doc.querySelector(
14
- `style[${INJECTED_STYLE_ATTR}="${CSS.escape(cssKey)}"]`
15
- );
3
+ const buffers = /* @__PURE__ */ new Map();
4
+ const registrations = /* @__PURE__ */ new Map();
5
+ const legacyLoads = /* @__PURE__ */ new Map();
6
+ const styleOwners = /* @__PURE__ */ new WeakMap();
7
+ const owners = /* @__PURE__ */ new Set();
8
+ function normalizedPath(url) {
9
+ return url.pathname.replace(/\/$/u, "") || "/";
10
+ }
11
+ function bufferId(previewUrl, cssKey) {
12
+ let target = previewUrl;
13
+ if (typeof document !== "undefined") {
14
+ try {
15
+ const url = new URL(previewUrl, document.baseURI);
16
+ target = `${url.origin}${normalizedPath(url)}`;
17
+ } catch {
18
+ }
19
+ }
20
+ return JSON.stringify([target, cssKey]);
21
+ }
22
+ function matches(iframe, previewUrl) {
23
+ try {
24
+ const base = new URL(iframe.ownerDocument.baseURI);
25
+ const source = new URL(iframe.getAttribute("src") ?? "", base);
26
+ const target = new URL(previewUrl, base);
27
+ const origin = new URL(iframe.ownerDocument.URL).origin;
28
+ return source.origin === origin && target.origin === origin && normalizedPath(source) === normalizedPath(target);
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+ function forgetStyle(owner, iframe, cssKey) {
34
+ const styles = owner.styles.get(iframe);
35
+ styles?.delete(cssKey);
36
+ if (!styles?.size) owner.styles.delete(iframe);
37
+ }
38
+ function releaseFrameStyles(iframe, currentDocument) {
39
+ for (const owner of owners) {
40
+ for (const [cssKey, style] of owner.styles.get(iframe) ?? []) {
41
+ if (currentDocument && style.ownerDocument === currentDocument) continue;
42
+ if (styleOwners.get(style) === owner) style.remove();
43
+ forgetStyle(owner, iframe, cssKey);
44
+ }
45
+ }
46
+ }
47
+ function frameDocument(iframe) {
48
+ try {
49
+ return iframe.contentDocument;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ function stylesFor(doc, cssKey) {
55
+ return Array.from(doc.querySelectorAll(`style[${INJECTED_STYLE_ATTR}]`)).filter((style) => style.getAttribute(INJECTED_STYLE_ATTR) === cssKey);
56
+ }
57
+ function injectInto(iframe, buffer) {
58
+ const doc = frameDocument(iframe);
59
+ if (!doc?.head) return;
60
+ const registration = registrations.get(iframe);
61
+ if (registration && registration.readyDocument !== doc) return;
62
+ const existing = stylesFor(doc, buffer.cssKey);
63
+ if (!buffer.css) {
64
+ for (const style2 of existing) {
65
+ const previousOwner2 = styleOwners.get(style2);
66
+ if (previousOwner2) forgetStyle(previousOwner2, iframe, buffer.cssKey);
67
+ style2.remove();
68
+ styleOwners.delete(style2);
69
+ }
70
+ return;
71
+ }
72
+ let style = existing[0];
16
73
  if (!style) {
17
74
  style = doc.createElement("style");
18
- style.setAttribute(INJECTED_STYLE_ATTR, cssKey);
19
- style.id = id;
75
+ style.setAttribute(INJECTED_STYLE_ATTR, buffer.cssKey);
76
+ style.id = `sg-injected-${buffer.cssKey}`;
20
77
  doc.head.appendChild(style);
21
78
  }
22
- style.textContent = css;
79
+ style.textContent = buffer.css;
80
+ const previousOwner = styleOwners.get(style);
81
+ if (previousOwner) forgetStyle(previousOwner, iframe, buffer.cssKey);
82
+ styleOwners.set(style, buffer.owner);
83
+ const ownedStyles = buffer.owner.styles.get(iframe) ?? /* @__PURE__ */ new Map();
84
+ ownedStyles.set(buffer.cssKey, style);
85
+ buffer.owner.styles.set(iframe, ownedStyles);
23
86
  }
24
- function injectCssToAllPreviews(cssKey, css, previewUrl = PREVIEW_ROUTE_PATH) {
25
- for (const iframe of previewIframes(previewUrl)) {
26
- if (iframe.contentDocument?.head) {
27
- injectInto(iframe, cssKey, css);
28
- } else {
29
- iframe.addEventListener("load", () => injectInto(iframe, cssKey, css), {
30
- once: true
31
- });
87
+ function pruneLegacyLoads() {
88
+ for (const [iframe, listener] of legacyLoads) {
89
+ if (!iframe.isConnected || registrations.has(iframe) || !Array.from(buffers.values()).some((buffer) => buffer.css && matches(iframe, buffer.previewUrl))) {
90
+ iframe.removeEventListener("load", listener);
91
+ legacyLoads.delete(iframe);
32
92
  }
33
93
  }
34
94
  }
95
+ function ensureLegacyLoad(iframe) {
96
+ if (registrations.has(iframe) || legacyLoads.has(iframe)) return;
97
+ const listener = () => replayCssToPreview(iframe);
98
+ iframe.addEventListener("load", listener);
99
+ legacyLoads.set(iframe, listener);
100
+ }
101
+ function registerCssPreview(iframe) {
102
+ let registration = registrations.get(iframe);
103
+ if (!registration) {
104
+ registration = { tokens: /* @__PURE__ */ new Set(), readyDocument: null };
105
+ registrations.set(iframe, registration);
106
+ }
107
+ const token = /* @__PURE__ */ Symbol("preview registration");
108
+ registration.tokens.add(token);
109
+ pruneLegacyLoads();
110
+ return () => {
111
+ const current = registrations.get(iframe);
112
+ if (!current?.tokens.delete(token) || current.tokens.size) return;
113
+ registrations.delete(iframe);
114
+ releaseFrameStyles(iframe);
115
+ };
116
+ }
117
+ function replayCssToPreview(iframe) {
118
+ const registration = registrations.get(iframe);
119
+ const doc = frameDocument(iframe);
120
+ releaseFrameStyles(iframe, doc);
121
+ if (registration) registration.readyDocument = doc;
122
+ for (const buffer of buffers.values()) {
123
+ if (matches(iframe, buffer.previewUrl)) injectInto(iframe, buffer);
124
+ }
125
+ }
126
+ function createPreviewCssOwner(previewUrl = PREVIEW_ROUTE_PATH) {
127
+ const owner = { styles: /* @__PURE__ */ new Map() };
128
+ owners.add(owner);
129
+ const keys = /* @__PURE__ */ new Set();
130
+ let disposed = false;
131
+ return {
132
+ set(cssKey, css) {
133
+ if (disposed) return;
134
+ const id = bufferId(previewUrl, cssKey);
135
+ if (keys.has(id) && buffers.get(id)?.owner !== owner) return;
136
+ keys.add(id);
137
+ buffers.set(id, { owner, cssKey, css, previewUrl });
138
+ },
139
+ apply() {
140
+ if (disposed || typeof document === "undefined") return;
141
+ const frames = /* @__PURE__ */ new Set([
142
+ ...registrations.keys(),
143
+ ...document.querySelectorAll("iframe[src]")
144
+ ]);
145
+ for (const id of keys) {
146
+ const buffer = buffers.get(id);
147
+ if (buffer?.owner !== owner) continue;
148
+ for (const iframe of frames) {
149
+ if (!matches(iframe, previewUrl)) continue;
150
+ if (buffer.css) ensureLegacyLoad(iframe);
151
+ injectInto(iframe, buffer);
152
+ }
153
+ }
154
+ pruneLegacyLoads();
155
+ },
156
+ dispose() {
157
+ if (disposed) return;
158
+ disposed = true;
159
+ for (const id of keys) {
160
+ if (buffers.get(id)?.owner === owner) buffers.delete(id);
161
+ }
162
+ for (const styles of owner.styles.values()) {
163
+ for (const style of styles.values()) {
164
+ if (styleOwners.get(style) === owner) style.remove();
165
+ }
166
+ }
167
+ owner.styles.clear();
168
+ owners.delete(owner);
169
+ pruneLegacyLoads();
170
+ }
171
+ };
172
+ }
173
+ const legacyOwners = /* @__PURE__ */ new Map();
174
+ function injectCssToAllPreviews(cssKey, css, previewUrl = PREVIEW_ROUTE_PATH) {
175
+ const id = bufferId(previewUrl, cssKey);
176
+ legacyOwners.get(id)?.dispose();
177
+ const owner = createPreviewCssOwner(previewUrl);
178
+ legacyOwners.set(id, owner);
179
+ owner.set(cssKey, css);
180
+ owner.apply();
181
+ if (!css) {
182
+ owner.dispose();
183
+ legacyOwners.delete(id);
184
+ }
185
+ }
35
186
  export {
36
- injectCssToAllPreviews
187
+ createPreviewCssOwner,
188
+ injectCssToAllPreviews,
189
+ registerCssPreview,
190
+ replayCssToPreview
37
191
  };
@@ -72,6 +72,7 @@ export interface ZudoSgComposeBaseOptions {
72
72
  externalPreview?: {
73
73
  url: string;
74
74
  trailingSlash?: "never" | "always";
75
+ runtime?: "legacy" | "external-v1";
75
76
  };
76
77
  catalog?: {
77
78
  title?: string;
@@ -39,6 +39,7 @@ export interface RoutesPluginOptions {
39
39
  externalPreview?: {
40
40
  url: string;
41
41
  trailingSlash?: "never" | "always";
42
+ runtime?: "legacy" | "external-v1";
42
43
  };
43
44
  categoryOrder?: string[];
44
45
  uiPackageName?: string;
@@ -83,6 +84,7 @@ export interface ResolvedRoutesPluginOptions {
83
84
  disabledRoutes: Array<keyof SgRoutes>;
84
85
  /** Root-absolute URL of the host preview document, or `null` — see `RoutesPluginOptions.externalPreview`. */
85
86
  externalPreviewUrl: string | null;
87
+ externalPreviewRuntime: "legacy" | "external-v1";
86
88
  categoryOrder: string[];
87
89
  uiPackageName: string | null;
88
90
  previewCssUrl: string;
@@ -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;