@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
package/CHANGELOG.md CHANGED
@@ -4,6 +4,66 @@ 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.2] - 2026-10-12
8
+
9
+ This maintenance release raises the minimum versions of the engine's CodeMirror
10
+ and Lezer runtime dependencies and documents how hosts recover from a stale
11
+ Lezer lockfile. The public API is unchanged.
12
+
13
+ ### Other Changes
14
+
15
+ - Raise the runtime dependency minimums to `@codemirror/view` ^6.43.14 and
16
+ `@lezer/highlight` ^1.2.5, so fresh installs resolve the versions the code
17
+ panel is tested against.
18
+ - The README now explains how a host lockfile that keeps an older
19
+ `@lezer/common` breaks code-panel highlighting, and how `pnpm dedupe`
20
+ fixes it.
21
+ - Development tooling only: TypeScript checks now run on the native
22
+ TypeScript 7 compiler through the TypeScript 6 API, and test dependencies
23
+ were updated (`@testing-library/jest-dom` 7, `@types/node` 22.20.5).
24
+
25
+ ## [0.5.1] - 2026-10-12
26
+
27
+ This release adds an opt-in, same-origin external preview runtime contract with
28
+ stricter catalog checks, so a host can render React 19 fixtures in its own
29
+ external document. It also fixes preview lifecycle bugs and updates the engine's
30
+ dependencies after a security audit. Existing module stories and
31
+ framework-free descriptors keep their current behavior.
32
+
33
+ ### Features
34
+
35
+ - New `@takazudo/zudo-sg/preview/external-runtime`, `preview/runtime`,
36
+ `registry/external-catalog`, and `registry/external-catalog-node` exports
37
+ define a strict external preview and catalog contract: fixture identity,
38
+ serializable controls, ready/request-ready replay, height, theme, the token
39
+ bridge, live CSS, visible errors, and deterministic cleanup. React and
40
+ ReactDOM stay inside the host's external fixture document; the engine does not
41
+ depend on them.
42
+ - External fixtures keep their root, hooks, focus, and editor state through
43
+ props updates and ordinary prop Reset. A separate full fixture reset remounts
44
+ fixture resources but keeps the current controls, theme, token edits, and
45
+ live CSS.
46
+ - External catalog generation checks descriptor slugs and variant IDs, loader
47
+ keys, displayed-source keys, and thumbnail keys against each other. Thumbnails
48
+ must be real captures of the named fixture or carry an explicit placeholder
49
+ or failed-capture state. Descriptor sources can be shown in the real code
50
+ panel.
51
+
52
+ ### Bug Fixes
53
+
54
+ - Reject sparse or malformed external catalog manifests, and messages from the
55
+ wrong origin or window or with stale document or variant identity.
56
+ - Keep owner-scoped live CSS when an iframe becomes ready again, recover
57
+ external fixtures with the current preview state, and keep render errors
58
+ reported during fixture updates visible.
59
+ - Keep mixed-property batches together when the preview token panel resets.
60
+ - Restore code-panel syntax highlighting with a CodeMirror/Lezer update that
61
+ resolves one shared Lezer identity (`@codemirror/language` 6.13.1,
62
+ `@codemirror/state` 6.7.6, `@codemirror/commands` 6.11.1). Hosts that keep
63
+ an older `@lezer/common` in their own lockfile should run `pnpm dedupe`.
64
+ - Fix security advisories in development and test dependencies, including the
65
+ move from Happy DOM 16 to 20.
66
+
7
67
  ## [0.5.0] - 2026-10-12
8
68
 
9
69
  This release ports the styleguide engine to zfb 4.3.1 and zudo-doc 6.0.0.
package/README.md CHANGED
@@ -153,6 +153,39 @@ and `manifestOut` to populate the `/tokens` dashboards. Manual adopters should
153
153
  also retain `@takazudo/zdtp`, `diff`, and `katex`; they are required host
154
154
  dependencies, not optional extras.
155
155
 
156
+ ## Recover highlighting in an existing consumer lock
157
+
158
+ An existing lock can retain two `@lezer/common` module identities even after
159
+ installing compatible engine/editor versions. The visible symptom is missing
160
+ TSX or editable CSS highlighting with a CodeMirror plugin error
161
+ `tags is not iterable` (the variable name can differ in a minified bundle);
162
+ successful editor construction or typing does not
163
+ establish that highlighting works.
164
+
165
+ From the affected host, diagnose and deduplicate its own graph:
166
+
167
+ ```sh
168
+ pnpm dedupe --check
169
+ pnpm dedupe --ignore-scripts
170
+ pnpm install --frozen-lockfile
171
+ ```
172
+
173
+ The first command is diagnostic and exits nonzero when deduplication is needed.
174
+ Review the resulting lock diff. Rebuild the host's generated output from scratch
175
+ (the packed proof removes only `dist` and `.zfb-build` before `pnpm exec zfb build`),
176
+ then verify TSX source tokens, editable CSS tokens, Live CSS application and
177
+ clearing, preview isolation, and absence of plugin/browser errors.
178
+ An ordinary or frozen install alone can preserve the split.
179
+
180
+ This recovery is scoped to pnpm **11.5.2**; other package managers need their own
181
+ resolution proof. It is consumer remediation, not a universal package-side fix.
182
+ Published compatible Lezer ranges still admit older common modules; direct
183
+ floors or a root-workspace dedupe check do not guarantee every retained consumer
184
+ lock. The separate packed diagnostic `pnpm verify:retained-lezer-lock` in the
185
+ engine repository preserves a clean control and treats the pre-recovery failure
186
+ as expected evidence. Track the remaining compatibility requirement in
187
+ [zudo-sg#963](https://github.com/Takazudo/zudo-sg/issues/963).
188
+
156
189
  ## Composing it into a host
157
190
 
158
191
  ```ts
@@ -283,6 +316,239 @@ source changes refresh without a restart. Host config or imported token-config
283
316
  changes require zfb config reload/restart so the snapshot contains fresh data.
284
317
  This token precedence rule does not isolate every host stylesheet selector.
285
318
 
319
+ ## External runtime contracts
320
+
321
+ The public leaf modules `@takazudo/zudo-sg/preview/external-runtime` and
322
+ `@takazudo/zudo-sg/registry/external-catalog` contain renderer-free types and
323
+ validators. They can be imported in Node/SSR without a browser. React,
324
+ ReactDOM, fixture loaders and component closures belong only in the host's
325
+ separately built same-origin preview document. The engine shell and catalog
326
+ stay zudo-react; the opaque Preact/zdtp adapter remains independent.
327
+
328
+ These contracts are additive. `preview/messages` remains import-free and
329
+ continues accepting legacy messages with no `v` and current `v: 1` messages.
330
+ The strict extension uses **both** `v: 1` and `runtimeVersion: 1`; it does not
331
+ reinterpret legacy messages. `ExternalRuntimeMode` is `"legacy" |
332
+ "external-v1"`. Select strict mode at the parent boundary before the first
333
+ message: a strict frame must never fall back to an identity-less legacy ready,
334
+ including during startup. `hasExternalRuntimeMarker()` also lets a legacy
335
+ receiver identify and reject malformed extension traffic instead of treating
336
+ it as legacy. Configure `externalPreview: { url: "/frame/", runtime:
337
+ "external-v1" }` to select strict mode in the injected detail route. Direct
338
+ `VariantFrame` and `DetailWorkbench` users pass `runtime="external-v1"`.
339
+ Omitting it preserves legacy module/vanilla behavior.
340
+
341
+ Import `createExternalPreviewRuntime` from `@takazudo/zudo-sg/preview/runtime`
342
+ inside your external document's entrypoint. Pass `mount` (the renderer-owned
343
+ `ExternalFixtureMount`), optional `initialProps`, and `fullReset: true` when
344
+ that fixture supports disposal/remount. Optional `target`, `identity`,
345
+ `onTheme` and `measureHeight` customize the document, query identity, host
346
+ theme side effects and height measurement. The function installs the strict
347
+ receiver and token receiver, mounts the fixture, and returns a controller;
348
+ importing the module alone installs nothing.
349
+
350
+ `controller.getSnapshot()` returns copied `{identity, ready, error}` state.
351
+ `controller.whenStable()` waits for the committed mount, queued prop updates
352
+ and optional fixture stability barrier, then returns the actual runtime
353
+ identity. It rejects errors, disposal/reset or props changes during the wait;
354
+ capture adapters can retry a changed fixture explicitly. Standalone top-level
355
+ capture documents receive a local session identity and emit no parent
356
+ messages. A host may expose its controller to its own capture adapter; the
357
+ engine installs no global capture object. `reportError`, `reportHeight` and
358
+ idempotent asynchronous `dispose` complete the controller API.
359
+ Explicit `dispose()` rejects if fixture cleanup fails. Cleanup failures also
360
+ reach the optional `onCleanupError` callback (default: `console.error`),
361
+ including late cancelled mounts and page unload; they never replace a newer
362
+ fixture's error state. Page unload consumes the already reported rejection.
363
+ Returning to a disposed document from the browser back/forward cache reloads
364
+ that document once to create fresh resources and identity. Explicit disposal
365
+ removes this restoration listener as well.
366
+
367
+ ### Identity, readiness and ordering
368
+
369
+ The parent sends `sg:requestReady` with `slug`, `variant`, and a fresh
370
+ `sessionId` challenge, plus the two version fields. Create a new unpredictable
371
+ session on iframe load and variant navigation, invalidate previous readiness,
372
+ height, document binding and errors, and retain the latest host state. A
373
+ same-URL reload requires this transition too: `contentWindow` can retain the
374
+ same WindowProxy after its document changes.
375
+
376
+ The document creates its own unpredictable `documentId`. Its committed
377
+ `sg:ready` echoes the challenge and adds `generation: 0`, `sequence`, and
378
+ `capabilities: { fullReset: boolean }`. A ready means the fixture mounted and
379
+ committed successfully, not merely that message listeners exist. A repeated
380
+ request re-announces the same committed document without remounting it. A
381
+ mount/import failure sends `sg:runtimeError` instead of successful ready.
382
+
383
+ All document-bound messages carry the exact
384
+ `{slug, variant, sessionId, documentId, generation}` identity and a
385
+ nonnegative safe-integer `sequence`. Sequence counters are independent per
386
+ sender and per session/generation. Validate the complete message, exact
387
+ same-origin and source window, current identity, and then monotonically
388
+ increasing sequence **before** mutating state or advancing the receive
389
+ watermark. `isExternalRuntimeMessageEvent()`,
390
+ `matchesExternalRuntimeIdentity()` and `isNewExternalRuntimeSequence()` are
391
+ separate pure checks; none maintains hidden state. Initialize a receive
392
+ watermark to `-1`. Reject opaque `"null"` origins and unknown/null sources.
393
+
394
+ A parent may initially bind a document from a valid ready or error answering
395
+ its current challenge and expected generation. Once bound, another document
396
+ cannot replace it without a new host session. Only an acknowledged full
397
+ reset can advance generation. A stale ready/error/height or malformed
398
+ high-sequence message must not affect the active document or its watermark.
399
+ Duplicate readiness may replay current snapshots, but cannot reset a fixture.
400
+
401
+ ### Updates, resets, errors and resource ownership
402
+
403
+ `sg:updateProps` contains a complete `SerializableProps` snapshot that replaces
404
+ previous control overrides. `isSerializableProps()` accepts finite JSON values,
405
+ rejecting callbacks/elements, undefined, cycles, accessors, symbols, prototype
406
+ keys, sparse arrays, and nesting beyond 32 object/array levels. Merge fixture
407
+ base props, declared control defaults and this current snapshot in that order.
408
+ Ordinary prop edits and the controls' **Reset** update the existing renderer
409
+ root and preserve hooks, focus and editor state. Existing module stories
410
+ continue their deliberate remount-on-args behavior.
411
+
412
+ Only runtimes advertising `fullReset: true` receive `sg:resetFixture`. It
413
+ targets the current identity and supplies `nextGeneration: generation + 1`.
414
+ The runtime disposes the current fixture, advances generation, clears its
415
+ per-generation sequence counters and mounts a fresh fixture with the retained
416
+ props. Ready/error then identifies the new generation. Reset replay is rejected
417
+ by identity/sequence checks. The parent retains controls, resolved theme,
418
+ token overrides and live CSS; it replays current state after accepted ready.
419
+ Changing variant seeds that variant's controls; reloading the same variant
420
+ retains its edited values.
421
+
422
+ `ExternalFixtureMount(context)` resolves only after a committed mount and
423
+ returns an `ExternalFixtureInstance` with `update(props)` and `dispose()`.
424
+ Its optional `whenStable()` is a fixture-specific capture barrier after
425
+ commit, for fonts, editor initialization or other async resources. The mount
426
+ context supplies current identity/props, an abort signal and `reportError()`.
427
+ Abort on reset/disposal; check identity after every awaited operation and
428
+ dispose any late instance rather than installing it. Serialize asynchronous
429
+ updates and resets so an older update cannot overwrite newer props.
430
+
431
+ The renderer owns its roots, hooks, portals, editors, workers and fixture
432
+ subscriptions. The runtime owns its message listeners, observers and timers;
433
+ final disposal removes them deterministically. Full fixture reset must not
434
+ erase host-owned theme, token overrides or the live-CSS style element.
435
+
436
+ Errors use `sg:runtimeError` and `{code, message, recoverable}`. Codes are
437
+ `unknown-fixture`, `import`, `render`, and `asset`; display messages as text,
438
+ never HTML or an empty successful tile. React error boundaries must report
439
+ render failures. An initial failure can bind the current document without
440
+ claiming readiness; show a reload/retry action. A successful recovery clears
441
+ only errors for its accepted identity, never another document's error.
442
+
443
+ Tokens retain their separate `zudo-sg-token-tweak-bridge` apply/clear/ready
444
+ envelopes, with exact parent/source and validated custom-property payloads.
445
+ Live CSS retains direct same-origin `contentDocument` injection into
446
+ `style[data-sg-injected-css]`. They are not new runtime message types. Keep
447
+ their snapshots at the parent, retain edits before readiness, replay on
448
+ reload/reset and tear down listeners/styles when their owning scope ends.
449
+
450
+ ### Source and canonical capture metadata
451
+
452
+ Descriptors may opt into `variant.source = { key, code }`. Obtain `key` from
453
+ `externalCatalogKey(slug, exportName)`; it encodes a JSON tuple, avoiding
454
+ delimiter collisions. `code` is verbatim text, including JSX or characters
455
+ that resemble HTML; never evaluate or inject it as markup. Existing
456
+ descriptors without source remain valid. Sourced variants mount the existing
457
+ accessible CodePanel, including source tabs/copy and isolated Live CSS. Variants
458
+ without source have no Source tab; a completely source-less descriptor has no
459
+ panel or panel toggle. `sourcePath` remains informational.
460
+
461
+ `validateExternalCatalogManifest(input)` validates and normalizes an array of
462
+ `ExternalCatalogEntry` rows, each containing `slug`, `variant`,
463
+ `loader: {key, module, exportName}`, `source: {key, code}`, and `capture`.
464
+ Loader modules are project-root-relative paths; generated loader functions
465
+ stay in the external bundle. All three keys must equal the canonical tuple
466
+ key, and row identities and captured asset ownership must be unique.
467
+
468
+ A capture is either `{kind: "image", key, fixture: {module, exportName}, src,
469
+ width, height}` matching the loader, or `{kind: "placeholder" | "failed", key,
470
+ note}` with an explicit nonempty explanation. Image paths are root-absolute
471
+ emitted URLs before adding the site base, with positive integer pixel
472
+ dimensions. Existing descriptor image/placeholder/no-thumbnail behavior is
473
+ unchanged unless the host opts into this canonical manifest.
474
+
475
+ This validator checks data, not files or screenshots. An image declaration
476
+ promises a real capture of the named external runtime: capture after committed
477
+ readiness and its stability barrier, then verify the emitted file, actual
478
+ dimensions and fixture/source/loader key agreement before claiming success.
479
+ Missing or invalid promised images fail the build/capture check; explicit
480
+ failed dispositions throw with their recorded note. Compare exact generated key sets,
481
+ source contents and loader references, including extra entries, before build.
482
+ The packed React proof is maintained separately. Never substitute engine React
483
+ SSR, decorative fake screenshots, or a
484
+ host route shadow for this boundary.
485
+
486
+ ### Node prebuild and capture API
487
+
488
+ Import these Node-only helpers from
489
+ `@takazudo/zudo-sg/registry/external-catalog-node` in a host build script.
490
+ Do not import them from `zfb.config` (its graph must remain node-free) or from
491
+ the browser bundle. The engine does not install a browser or import React.
492
+
493
+ - `validateExternalCatalogOutputs({manifest, descriptors, loaders, sources})`
494
+ compares complete generated arrays: missing/extra/duplicate keys, actual
495
+ source text and loader module/export references. Generate browser loaders and
496
+ their metadata from the same canonical manifest. The first authored variant
497
+ owns the story's catalog tile; use
498
+ `thumbnailFromExternalCapture(first.capture)` for its thumbnail. Every
499
+ variant's image promise is checked, including those not used for that tile.
500
+ - `captureExternalCatalogImages({manifest, projectRoot, assetRoot, origin,
501
+ base, previewUrl, page})` visits the actual external document with canonical
502
+ slug/variant query parameters. `origin` is an HTTP(S) origin without a
503
+ trailing slash, `base` defaults to `/`, and `previewUrl` is the root-absolute
504
+ document path before adding the base.
505
+ - `validateExternalCatalogAssets({manifest, projectRoot, assetRoot, captures})`
506
+ checks capture receipts against files. Missing images, stale loader/source
507
+ hashes, wrong image hash/dimensions/fixture identity, and `failed` dispositions
508
+ throw. Intentional placeholders remain labelled. Paths reject symlinks,
509
+ including parents, before reading/writing. Captures must be complete,
510
+ noninterlaced 8-bit PNGs of at most 16,777,216 pixels, matching the declared
511
+ viewport dimensions. Only IHDR/IDAT/IEND critical chunks are supported;
512
+ palette chunks are outside this browser screenshot format. Legacy descriptor
513
+ SVG/remote image semantics are unchanged.
514
+
515
+ `loaders` and `sources` are arrays of `ExternalCatalogLoader` and
516
+ `DescriptorSource`. Pass actual generated outputs rather than reconstructing
517
+ expected copies inside the check. Receipts record actual runtime identity and
518
+ SHA-256 hashes of the loader entry file, displayed source and PNG. The loader
519
+ hash covers the entry file, not its transitive imports: rerun captures after
520
+ fixture dependency or asset changes. Receipts establish capture consistency,
521
+ not independent attestation of arbitrary host-supplied metadata.
522
+
523
+ The caller-owned `page` adapter implements `goto(url)`,
524
+ `setViewportSize({width,height})`, `screenshot({type: "png", scale: "css"})`,
525
+ `whenStable()` and `getSnapshot()`. The latter two invoke the actual
526
+ `createExternalPreviewRuntime()` controller in the loaded document. Wait for
527
+ the host-exposed controller property to exist before calling `whenStable()`;
528
+ apply the browser runner's normal timeout. The helper checks committed
529
+ readiness, errors and identity before and after the screenshot. The host must
530
+ surface browser console errors and close its browser/server in `finally`.
531
+
532
+ Run this sequence from a Node script in the host's build command:
533
+
534
+ 1. Generate descriptors/source/loader metadata from the canonical manifest and
535
+ call `validateExternalCatalogOutputs`.
536
+ 2. Build the independent external preview, serve it under the intended base,
537
+ and capture into `public/`. Missing promised images cannot represent a
538
+ successful catalog build.
539
+ 3. Save the returned serializable receipts, validate assets in `public/`, then
540
+ run the final `zfb build` to copy those assets into `dist/`.
541
+ 4. Validate the same receipts against the emitted asset directory and verify
542
+ built browser loads. Use `assetRoot: "dist"` at the root base; zfb 4 copies
543
+ public assets under the base, so `/styleguide/` uses
544
+ `assetRoot: "dist/styleguide"`. Capture `src` stays `/captures/example.png`;
545
+ the helper resolves it beneath `assetRoot` without adding the URL base.
546
+
547
+ Adding source text alone neither runs captures nor makes thumbnails mandatory
548
+ for existing catalogs. Source-less legacy descriptors do not use this opt-in
549
+ manifest check. The focused helper tests cover framework-independent capture
550
+ orchestration; the separately installed React consumer supplies real screenshots.
551
+
286
552
  ## Release scheme
287
553
 
288
554
  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;