An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): blog posts run tsx live blocks in the playground preview frame (#9436)
Cindy Zhang3b42f85e09e6
diff --git a/apps/docsite/e2e/blog-live-examples.spec.ts b/apps/docsite/e2e/blog-live-examples.spec.tsnew file mode 100644index 0000000000..f5169e8ba3--- /dev/null+++ b/apps/docsite/e2e/blog-live-examples.spec.ts@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file blog-live-examples.spec.ts+ * @input The built Docsite (canary target), its live-example fixture post+ * (`src/content/blog/fixtures/live-example-sample.md`), that post's+ * plain-text route, the RSS feed, the sitemap, and the blog index.+ * @output Real-browser proof of spec:AST-033 FR22: each `tsx live` block runs+ * in its own sandboxed preview frame (opaque origin, `allow-scripts` only);+ * an example imports a published package and a post-local asset; a block+ * that throws or fails to compile shows its error inside its frame while the+ * post renders on; the plain-text route shows the source as an ordinary code+ * block; and the fixture is never listed.+ * @position Docsite browser contracts (`pnpm test:docsite-browser`).+ */++import {expect, test, type Frame, type Page} from '@playwright/test';++const POST = '/blog/live-example-sample';++// The frame loads the TypeScript compiler before it renders anything.+const POLL = {timeout: 45_000};++/** The live-example frames of the post, in document order. */+async function liveFrames(page: Page): Promise<Frame[]> {+ const figures = page.locator('figure[data-live-example]');+ await expect(figures).toHaveCount(4);+ const frames: Frame[] = [];+ for (let index = 0; index < 4; index += 1) {+ const iframe = figures.nth(index).locator('iframe');+ await expect(iframe).toHaveAttribute('sandbox', 'allow-scripts');+ const handle = await iframe.elementHandle();+ const frame = await handle?.contentFrame();+ if (frame == null) {+ throw new Error(`live example ${index} has no frame`);+ }+ frames.push(frame);+ }+ return frames;+}++test('runs each tsx live block in its own sandboxed frame and contains failures', async ({+ page,+}) => {+ const pageErrors: string[] = [];+ page.on('pageerror', error => pageErrors.push(error.message));+ await page.setViewportSize({width: 1280, height: 900});+ await page.goto(POST);+ const [counter, asset, broken, uncompilable] = await liveFrames(page);++ // A running example, importing a published package: it renders and it runs.+ const count = counter.getByTestId('count');+ await expect(count).toHaveText('Clicked 0 times', POLL);+ await counter.getByRole('button', {name: 'Add one'}).click();+ await expect(count).toHaveText('Clicked 1 times');++ // An example importing its post's own asset.+ await expect(asset.getByTestId('sample-card')).toContainText(+ 'The Star',+ POLL,+ );++ // A runtime error and a compile error each stay inside their own frame.+ await expect(broken.locator('body')).toContainText(+ 'This example fails on purpose',+ POLL,+ );+ // The compiler transpiles without diagnostics, so a syntax error surfaces+ // when the frame evaluates the output.+ await expect(uncompilable.locator('body')).toContainText(+ 'Unexpected token',+ POLL,+ );++ // The frame has an opaque origin: the example cannot reach the post.+ expect(+ await counter.evaluate(() => {+ try {+ return window.parent.document == null;+ } catch {+ return 'blocked';+ }+ }),+ ).toBe('blocked');++ // The post around the examples keeps rendering, and nothing the examples+ // did reached it as an error.+ await expect(+ page.getByText('The post keeps rendering after every example above.'),+ ).toBeVisible();+ await expect(+ page.locator('pre, code').filter({hasText: 'NotLive'}).first(),+ ).toBeVisible();+ expect(pageErrors).toEqual([]);+});++test('shows each live block as its source in the plain-text route', async ({+ request,+}) => {+ const response = await request.get(`${POST}.txt`);+ expect(response.ok()).toBe(true);+ const text = await response.text();+ expect(text).not.toMatch(/^\s*(`{3,}|~{3,})\s*tsx\s+live/m);+ expect(text).toContain('```tsx\nimport {SampleCard}');+ expect(text).toContain("throw new Error('This example fails on purpose');");+});++test('never lists the fixture in the blog index, the feed, or the sitemap', async ({+ page,+ request,+}) => {+ for (const path of ['/rss.xml', '/sitemap.xml']) {+ const body = await (await request.get(path)).text();+ expect(body, path).not.toContain('live-example-sample');+ }+ await page.goto('/blog');+ await expect(page.locator('a[href*="live-example-sample"]')).toHaveCount(0);+ // The fixture page itself asks search engines not to index it.+ await page.goto(POST);+ await expect(page.locator('meta[name="robots"]')).toHaveAttribute(+ 'content',+ /noindex/,+ );+});diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjsindex 10abc6875a..1d51adfd87 100644--- a/apps/docsite/scripts/generate-data.mjs+++ b/apps/docsite/scripts/generate-data.mjs@@ -17,6 +17,8 @@* - templateRegistry.ts — page templates including playground source* - templateMetadataRegistry.ts — lightweight page-template metadata* - docsRegistry.ts — long-form documentation topics from CLI docs/+ * - blogRegistry.ts — blog posts (plus canary-only test fixtures)+ * - blogExampleAssets.ts — each post's live-example assets, loaded on demand* - searchLinks.json — search destinations and document presentation metadata*/@@ -2480,14 +2482,34 @@ async function generateBlogRegistry() {const POSTS_DIR = path.join(DOCSITE_ROOT, 'src', 'content', 'blog', 'posts');// Single source of truth for discovery + validation (shared with tests).- const {discoverPosts, collectTypes, collectTags} = await import(- pathToFileURL(path.join(DOCSITE_ROOT, 'src', 'lib', 'blog', 'posts.mjs'))- .href- );+ const {discoverPosts, collectTypes, collectTags, collectExampleAssets} =+ await import(+ pathToFileURL(path.join(DOCSITE_ROOT, 'src', 'lib', 'blog', 'posts.mjs'))+ .href+ );// Local development and every draft/preview deployment use the canary target.const includeDrafts = DOCSITE_TARGET === 'canary';const posts = discoverPosts(POSTS_DIR, {includeDrafts});+ // Test fixtures (spec:AST-033 FR22): canary-only posts that the post and+ // plain-text routes serve but the index, feed and sitemap never list.+ const FIXTURES_DIR = path.join(+ DOCSITE_ROOT,+ 'src',+ 'content',+ 'blog',+ 'fixtures',+ );+ const fixturePosts = includeDrafts+ ? discoverPosts(FIXTURES_DIR, {includeDrafts: true})+ : [];+ for (const fixture of fixturePosts) {+ if (posts.some(p => p.slug === fixture.slug)) {+ throw new Error(+ `Blog fixture "${fixture.slug}" has the same slug as a post`,+ );+ }+ }const types = collectTypes(posts);const tags = collectTags(posts);@@ -2511,6 +2533,12 @@ export const blogTags: string[] = ${JSON.stringify(tags)};export const blogPostCount = ${posts.length};+/**+ * Test fixture posts (canary only): the post and plain-text routes serve them,+ * but the index, feed and sitemap read only blogPosts.+ */+export const blogFixturePosts: BlogPost[] = ${JSON.stringify(fixturePosts, null, 2)};+/*** Site-absolute paths of every dark-mode image variant found under* public/blog (files named "<name>.dark.<ext>"). ThemedImage consults this to@@ -2529,6 +2557,42 @@ export const blogImageSizes: Record<string, {width: number; height: number}> =${JSON.stringify(imageSizes, null, 2)};`;writeRegistry('blogRegistry.ts', content);++ // Each post's example assets, loaded on demand inside the preview frame+ // that runs that post's live examples (spec:AST-033 FR22).+ const assetEntries = [+ ...posts.map(p => ({slug: p.slug, dir: POSTS_DIR})),+ ...fixturePosts.map(p => ({slug: p.slug, dir: FIXTURES_DIR})),+ ]+ .map(({slug, dir}) => ({slug, assets: collectExampleAssets(dir, slug)}))+ .filter(({assets}) => assets.length > 0);+ const assetLines = assetEntries.map(({slug, assets}) => {+ const loaders = assets.map(({specifier, file}) => {+ const target = path+ .relative(OUT_DIR, file)+ .replace(/\\/g, '/')+ .replace(/\.(tsx?|jsx?)$/, '');+ return ` ${JSON.stringify(specifier)}: () => import(${JSON.stringify(target)}),`;+ });+ return ` ${JSON.stringify(slug)}: {\n${loaders.join('\n')}\n },`;+ });+ writeRegistry(+ 'blogExampleAssets.ts',+ `// Auto-generated by scripts/generate-data.mjs — do not edit++/**+ * Each blog post's example assets, by post slug and then by the relative+ * specifier its live examples import (spec:AST-033 FR22).+ */+export const blogExampleAssets: Record<+ string,+ Record<string, () => Promise<unknown>>+> = {+${assetLines.join('\n')}+};+`,+ );+return {blogPostCount: posts.length, blogTypeCount: types.length};}diff --git a/apps/docsite/src/__tests__/blog-live-examples.test.tsx b/apps/docsite/src/__tests__/blog-live-examples.test.tsxnew file mode 100644index 0000000000..f7e43a74ee--- /dev/null+++ b/apps/docsite/src/__tests__/blog-live-examples.test.tsx@@ -0,0 +1,245 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Blog live examples (spec:AST-033 FR22).+ *+ * A `tsx live` fence in a post renders as a sandboxed live-example frame, any+ * other fence stays code, the plain-text route shows the source as an+ * ordinary code block, a post's example assets resolve only for that post,+ * and the test fixture post is never a listed post.+ */++import * as path from 'node:path';+import * as React from 'react';+import {renderToStaticMarkup} from 'react-dom/server';+import {describe, expect, it, vi} from 'vitest';+import * as ts from 'typescript';+import type {BlogPost} from '../lib/blog/schema';+import {collectExampleAssets, discoverPosts} from '../lib/blog/posts.mjs';+import {isLiveBlockMeta, toStaticLiveBlocks} from '../lib/blog/liveBlocks.mjs';++// The docsite's own StyleX is compiled by its Babel build, not by Vitest.+vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+ firstThatWorks: <T,>(...values: T[]) => values[0],+ defineMarker: () => ({}),+ defineConsts: <T,>(values: T) => values,+ defineVars: <T,>(values: T) => values,+ keyframes: () => 'keyframes',+ when: {ancestor: () => ':hover', descendant: () => ':hover'},+}));++// The runner resolves imports against the generated preview scope; a small+// stand-in keeps this test independent of `pnpm generate`.+vi.mock('@/generated/playground-scope', () => ({+ scope: {react: {default: React, useState: React.useState}},+}));++// The site's color mode; the real provider pulls in the built site theme.+vi.mock('../app/providers', () => ({+ useThemeMode: () => ({mode: 'light', setMode: () => {}}),+}));++const POSTS_DIR = path.resolve(__dirname, '../content/blog/posts');+const FIXTURES_DIR = path.resolve(__dirname, '../content/blog/fixtures');+const FIXTURE_SLUG = 'live-example-sample';++function fixturePost(): BlogPost {+ const post = (+ discoverPosts(FIXTURES_DIR, {includeDrafts: true}) as BlogPost[]+ ).find(p => p.slug === FIXTURE_SLUG);+ if (post == null) {+ throw new Error(`missing fixture ${FIXTURE_SLUG}`);+ }+ return post;+}++describe('the tsx live fence rule', () => {+ it('marks only an info string of exactly "live" after tsx', () => {+ expect(isLiveBlockMeta('live')).toBe(true);+ expect(isLiveBlockMeta(' live ')).toBe(true);+ expect(isLiveBlockMeta(undefined)).toBe(false);+ expect(isLiveBlockMeta('title="x"')).toBe(false);+ expect(isLiveBlockMeta('live title="x"')).toBe(false);+ });++ it('shows every live block as an ordinary tsx code block in the static fallback', () => {+ const body = [+ '```tsx live',+ 'export default function A() { return null; }',+ '```',+ '',+ ' ~~~~ tsx live ',+ 'export default function B() { return null; }',+ ' ~~~~',+ '',+ '```tsx',+ 'const unchanged = true;',+ '```',+ '',+ '```tsx title="live"',+ '```',+ ].join('\n');+ expect(toStaticLiveBlocks(body)).toBe(+ [+ '```tsx',+ 'export default function A() { return null; }',+ '```',+ '',+ ' ~~~~tsx',+ 'export default function B() { return null; }',+ ' ~~~~',+ '',+ '```tsx',+ 'const unchanged = true;',+ '```',+ '',+ '```tsx title="live"',+ '```',+ ].join('\n'),+ );+ });++ it('rewrites exactly the fences the page runs: in blockquotes and list items, nested, after an unclosed quoted fence, and never inside another block', () => {+ const body = [+ '> ```tsx live',+ '> export default function Quoted() { return null; }',+ '> ```',+ '',+ '- ```tsx live',+ ' export default function Listed() { return null; }',+ ' ```',+ '',+ '````md',+ '```tsx live',+ 'quoted syntax stays as written',+ '```',+ '````',+ '',+ '- > ```tsx live',+ ' > export default function ListQuote() { return null; }',+ ' > ```',+ '',+ '- - ```tsx live',+ ' export default function Nested() { return null; }',+ ' ```',+ '',+ '> ```tsx',+ '> an unclosed fence ends with its quote',+ '',+ '```tsx live',+ 'export default function AfterQuote() { return null; }',+ '```',+ '',+ ' ```tsx live',+ ' quoted inside an indented code block',+ ' ```',+ ].join('\n');+ expect(toStaticLiveBlocks(body)).toBe(+ [+ '> ```tsx',+ '> export default function Quoted() { return null; }',+ '> ```',+ '',+ '- ```tsx',+ ' export default function Listed() { return null; }',+ ' ```',+ '',+ '````md',+ '```tsx live',+ 'quoted syntax stays as written',+ '```',+ '````',+ '',+ '- > ```tsx',+ ' > export default function ListQuote() { return null; }',+ ' > ```',+ '',+ '- - ```tsx',+ ' export default function Nested() { return null; }',+ ' ```',+ '',+ '> ```tsx',+ '> an unclosed fence ends with its quote',+ '',+ '```tsx',+ 'export default function AfterQuote() { return null; }',+ '```',+ '',+ ' ```tsx live',+ ' quoted inside an indented code block',+ ' ```',+ ].join('\n'),+ );+ });++ it('leaves no live fence in the fixture plain-text body', () => {+ const fallback = toStaticLiveBlocks(fixturePost().body);+ expect(fallback).not.toMatch(/^\s*(`{3,}|~{3,})\s*tsx\s+live/m);+ expect(fallback).toContain(+ "throw new Error('This example fails on purpose');",+ );+ });+});++describe('the live example fixture post', () => {+ it('is a fixture, never a listed post', () => {+ const listed = discoverPosts(POSTS_DIR, {+ includeDrafts: true,+ }) as BlogPost[];+ expect(listed.map(p => p.slug)).not.toContain(FIXTURE_SLUG);+ expect(fixturePost().title).toBe('Live example sample');+ });++ it('has its own example asset, importable as ./SampleCard', () => {+ expect(+ collectExampleAssets(FIXTURES_DIR, FIXTURE_SLUG).map(a => a.specifier),+ ).toEqual(['./SampleCard']);+ // A post without an asset folder has none.+ expect(collectExampleAssets(POSTS_DIR, 'how-astryx-works')).toEqual([]);+ });++ it(+ 'renders each tsx live block as a live-example frame and keeps other fences as code',+ {timeout: 30_000},+ async () => {+ const {BlogPostBody} = await import('../components/blog/BlogPostBody');+ const html = renderToStaticMarkup(+ <BlogPostBody body={fixturePost().body} slug={FIXTURE_SLUG} />,+ );+ expect(html.match(/data-live-example=""/g)).toHaveLength(4);+ // The ordinary tsx block is still a code block...+ expect(html).toContain('NotLive');+ // ...and no live block's source is printed as code on the page.+ expect(html).not.toContain('This example fails on purpose');+ expect(html).not.toContain('SampleCard');+ },+ );+});++describe('post-local modules in the preview runner', () => {+ it('resolves a relative import only from the modules it is given', async () => {+ const {runCode, setTypeScript} =+ await import('../app/playground/preview/runner');+ setTypeScript(ts);+ const code = [+ "import {Greeting} from './Greeting';",+ 'export default function Example() { return Greeting(); }',+ ].join('\n');++ const withAsset = runCode(code, {+ './Greeting': {Greeting: () => 'hello from the post'},+ });+ expect(withAsset.error).toBeUndefined();+ const Component = withAsset.Component as () => unknown;+ expect(Component()).toBe('hello from the post');++ // Without the post's modules (the playground, another post) the import+ // resolves to the scope's render-nothing placeholder.+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const withoutAsset = runCode(code);+ const Unresolved = withoutAsset.Component as () => unknown;+ expect(Unresolved()).toBeNull();+ });+});diff --git a/apps/docsite/src/app/blog/[slug]/page.tsx b/apps/docsite/src/app/blog/[slug]/page.tsxindex 1a9b149e2d..0d699d5d45 100644--- a/apps/docsite/src/app/blog/[slug]/page.tsx+++ b/apps/docsite/src/app/blog/[slug]/page.tsx@@ -8,11 +8,21 @@import type {Metadata} from 'next';import {notFound} from 'next/navigation';-import {blogPosts} from '../../../generated/blogRegistry';+import {blogFixturePosts, blogPosts} from '../../../generated/blogRegistry';import {BlogArticle} from '../../../components/blog/BlogArticle';export function generateStaticParams() {- return blogPosts.map(p => ({slug: p.slug}));+ return [...blogPosts, ...blogFixturePosts].map(p => ({slug: p.slug}));+}++/** A post, or a canary-only test fixture (never listed, never indexed). */+function findPost(slug: string) {+ const post = blogPosts.find(p => p.slug === slug);+ if (post) {+ return {post, isFixture: false};+ }+ const fixture = blogFixturePosts.find(p => p.slug === slug);+ return fixture ? {post: fixture, isFixture: true} : null;}export async function generateMetadata({@@ -21,24 +31,24 @@ export async function generateMetadata({params: Promise<{slug: string}>;}): Promise<Metadata> {const {slug} = await params;- const post = blogPosts.find(p => p.slug === slug);- if (!post) {+ const found = findPost(slug);+ if (!found) {return {title: 'Blog'};}+ const {post, isFixture} = found;// Use the post's cover image for the social card when present; otherwise// fall back to the branded default card. Next.js shallow-merges metadata —// a route that sets `openGraph`/`twitter` replaces the root object wholesale// (images are not inherited), so the fallback must be explicit here.- const ogImage =- post.coverImage ??- '/images/Astryx-Banner.png';+ const ogImage = post.coverImage ?? '/images/Astryx-Banner.png';const ogAlt = post.coverImage ? (post.coverAlt ?? post.title) : post.title;return {// Renders as "<post title> · Astryx" via the root layout title template.title: post.title,description: post.description,+ ...(isFixture ? {robots: {index: false, follow: false}} : {}),openGraph: {type: 'article',title: post.title,@@ -63,10 +73,10 @@ export default async function BlogPostPage({params: Promise<{slug: string}>;}) {const {slug} = await params;- const post = blogPosts.find(p => p.slug === slug);- if (!post) {+ const found = findPost(slug);+ if (!found) {notFound();}- return <BlogArticle post={post} />;+ return <BlogArticle post={found.post} />;}diff --git a/apps/docsite/src/app/blog/txt/[slug]/route.ts b/apps/docsite/src/app/blog/txt/[slug]/route.tsindex 896d0e85e5..b9f292c882 100644--- a/apps/docsite/src/app/blog/txt/[slug]/route.ts+++ b/apps/docsite/src/app/blog/txt/[slug]/route.ts@@ -14,10 +14,11 @@* @output text/plain (the post's Markdown body) or 404*/-import {blogPosts} from '../../../../generated/blogRegistry';+import {blogFixturePosts, blogPosts} from '../../../../generated/blogRegistry';+import {toStaticLiveBlocks} from '../../../../lib/blog/liveBlocks.mjs';export function generateStaticParams() {- return blogPosts.map(p => ({slug: p.slug}));+ return [...blogPosts, ...blogFixturePosts].map(p => ({slug: p.slug}));}export async function GET(@@ -25,7 +26,9 @@ export async function GET({params}: {params: Promise<{slug: string}>},) {const {slug} = await params;- const post = blogPosts.find(p => p.slug === slug);+ const post =+ blogPosts.find(p => p.slug === slug) ??+ blogFixturePosts.find(p => p.slug === slug);if (!post) {return new Response('Not found\n', {status: 404,@@ -48,7 +51,9 @@ export async function GET('',].join('\n');- return new Response(header + post.body + '\n', {+ // A live example cannot run here: its source shows as an ordinary code+ // block instead (spec:AST-033 FR22).+ return new Response(header + toStaticLiveBlocks(post.body) + '\n', {headers: {'content-type': 'text/plain; charset=utf-8'},});}diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex 3f127b1848..9d9524299e 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -40,8 +40,7 @@ import * as stylex from '@stylexjs/stylex';import {AppShell} from '@astryxdesign/core/AppShell';import {DocsBanner} from '../../components/InternalDocsPrompt';import {compressCode, decompressCode} from '../../lib/compress';-import {createPreviewConnector, previewSrc} from './previewChannel';-import type {PreviewConnector} from './previewChannel';+import {usePreviewFrame} from './usePreviewFrame';import {Button} from '@astryxdesign/core/Button';import {Link} from '@astryxdesign/core/Link';import {HStack, VStack} from '@astryxdesign/core/Layout';@@ -332,17 +331,8 @@ export function PlaygroundClient() {const previewStartupTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null,);- const restartPreviewRef = useRef<() => void>(() => {});- // The preview frame generation: a fresh iframe element (key) navigated to- // the preview URL with a fresh nonce (src). Issued on the client only, and- // re-issued whenever the attested preview document is replaced — see- // previewChannel.ts for the trust model.- const [frame, setFrame] = useState<{key: number; src: string} | null>(null);- const frameGenerationRef = useRef(0);- // The channel's trust state machine (see previewChannel.ts) and the current- // port message handler — refs so the connector's port always dispatches- // into the latest closure.- const connectorRef = useRef<PreviewConnector | null>(null);+ // The current port message handler — a ref so the preview frame's port+ // always dispatches into the latest closure.const portHandlerRef = useRef<((e: MessageEvent) => void) | null>(null);const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);const editorRef = useRef<MonacoTypes.editor.IStandaloneCodeEditor | null>(@@ -406,10 +396,54 @@ export function PlaygroundClient() {}}, [themeParam]);- // Single channel to the preview iframe; no-ops until the handshake lands.- const postToPreview = useCallback((message: unknown) => {- connectorRef.current?.post(message);+ // The preview frame (usePreviewFrame.tsx, previewChannel.ts): a fresh+ // iframe per generation, navigated with a nonce only this page knows, and a+ // port only for the document it navigated to. Each generation arms a+ // startup timer that marks the build failed if the document, then its+ // compiler, never comes up.+ const clearStartupTimer = useCallback(() => {+ if (previewStartupTimerRef.current != null) {+ clearTimeout(previewStartupTimerRef.current);+ previewStartupTimerRef.current = null;+ }+ }, []);+ const armStartupTimer = useCallback(+ (timeout: number) => {+ clearStartupTimer();+ previewStartupTimerRef.current = setTimeout(() => {+ if (!readyRef.current) {+ setBuildStatus('error');+ }+ }, timeout);+ },+ [clearStartupTimer],+ );+ // A new document is coming: queue the current code so it picks up exactly+ // where the old one was — the preview-ready handler flushes it and the+ // theme effect re-sends on the previewReady flip.+ const resetForNewDocument = useCallback(() => {+ readyRef.current = false;+ setPreviewReady(false);+ pendingRef.current = codeRef.current;}, []);+ const previewFrame = usePreviewFrame({+ onMessage: e => portHandlerRef.current?.(e),+ onIssue: () => armStartupTimer(PREVIEW_DOCUMENT_STARTUP_TIMEOUT_MS),+ onAttested: () => armStartupTimer(PREVIEW_COMPILER_STARTUP_TIMEOUT_MS),+ onReplaced: resetForNewDocument,+ });+ const {frame, attachFrame, handleFrameLoad} = previewFrame;+ const restartPreview = useCallback(() => {+ resetForNewDocument();+ previewFrame.restart();+ }, [resetForNewDocument, previewFrame.restart]);+ useEffect(() => clearStartupTimer, [clearStartupTimer]);++ // Single channel to the preview iframe; no-ops until the handshake lands.+ const postToPreview = useCallback(+ (message: unknown) => previewFrame.post(message),+ [previewFrame.post],+ );const send = useCallback((c: string, source?: string) => {@@ -500,80 +534,6 @@ export function PlaygroundClient() {};}, [postCode, postToPreview]);- // Handshake (previewChannel.ts): mount a fresh iframe navigated to the- // preview URL with a nonce only this page knows; the preview document echoes- // it from its own URL, and the connector answers that one hello with a port.- // The window listener goes up BEFORE the frame is issued so the hello cannot- // arrive unheard.- useEffect(() => {- const clearStartupTimer = () => {- if (previewStartupTimerRef.current != null) {- clearTimeout(previewStartupTimerRef.current);- previewStartupTimerRef.current = null;- }- };- const armStartupTimer = (timeout: number) => {- clearStartupTimer();- previewStartupTimerRef.current = setTimeout(() => {- if (!readyRef.current) {- setBuildStatus('error');- }- }, timeout);- };- const issueFrame = () => {- frameGenerationRef.current += 1;- setFrame({- key: frameGenerationRef.current,- src: previewSrc(connector.issue()),- });- armStartupTimer(PREVIEW_DOCUMENT_STARTUP_TIMEOUT_MS);- };- const connector = createPreviewConnector({- onMessage: e => portHandlerRef.current?.(e),- onAttested: () => armStartupTimer(PREVIEW_COMPILER_STARTUP_TIMEOUT_MS),- // The attested preview document is gone (previewed code navigated or- // reloaded its frame). Its port and nonce are already discarded; start- // a new generation and queue the current code so the fresh document- // picks up exactly where the old one was — the preview-ready handler- // flushes it and the theme effect re-sends on the previewReady flip.- onReplaced: () => restartPreviewRef.current(),- });- restartPreviewRef.current = () => {- readyRef.current = false;- setPreviewReady(false);- pendingRef.current = codeRef.current;- issueFrame();- };- connectorRef.current = connector;- const onWindowMessage = (e: MessageEvent) =>- connector.handleWindowMessage(e);- window.addEventListener('message', onWindowMessage);- issueFrame();- return () => {- clearStartupTimer();- restartPreviewRef.current = () => {};- window.removeEventListener('message', onWindowMessage);- connector.stop();- connectorRef.current = null;- };- }, []);-- // The iframe element of the current generation, once React has mounted it:- // only its window can earn a port. React clears the old element's ref before- // attaching the new one's, and the connector forgets its window on every- // issue() anyway, so the null on unmount carries nothing it needs.- const attachFrame = useCallback((element: HTMLIFrameElement | null) => {- if (element?.contentWindow) {- connectorRef.current?.attachFrame(element.contentWindow);- }- }, []);-- // Every load of the iframe goes to the connector: the first in a generation- // is the document we navigated to arriving, any later one is a replacement.- const handleFrameLoad = useCallback(() => {- connectorRef.current?.handleFrameLoad();- }, []);-// Debounced push of code → preview + URL hashuseEffect(() => {if (debounceRef.current) {@@ -659,9 +619,9 @@ export function PlaygroundClient() {postCode(code);} else {pendingRef.current = code;- restartPreviewRef.current();+ restartPreview();}- }, [postCode, code]);+ }, [postCode, code, restartPreview]);// "Format code" — delegate to Monaco's own format-document action rather than// rewriting `code` state directly: the action is what Shift+Alt+F is bound to,diff --git a/apps/docsite/src/app/playground/PreviewStage.tsx b/apps/docsite/src/app/playground/PreviewStage.tsxindex 9100e11593..51dd0299e9 100644--- a/apps/docsite/src/app/playground/PreviewStage.tsx+++ b/apps/docsite/src/app/playground/PreviewStage.tsx@@ -23,17 +23,11 @@ import {Card} from '@astryxdesign/core/Card';import {Center} from '@astryxdesign/core/Center';import {Button} from '@astryxdesign/core/Button';import {Minimize2} from 'lucide-react';+import {PreviewFrame, type PreviewFrameGeneration} from './usePreviewFrame';-export type Viewport = 'desktop' | 'phone';+const noop = () => {};-// Under `next dev` the preview frame keeps the site origin (the sandbox the-// preview always had before isolation): the dev server serves its /_next-// assets only to requests that name an allowlisted host in Origin or Referer,-// and a document with an opaque origin sends neither, so an isolated preview-// cannot load its own scripts there. Production builds, which is where-// untrusted code meets real users, get the opaque origin — see the iframe-// below. `process.env.NODE_ENV` is inlined at build time.-const PREVIEW_KEEPS_SITE_ORIGIN = process.env.NODE_ENV === 'development';+export type Viewport = 'desktop' | 'phone';// iPhone 17 logical viewport (402 × 874 CSS px, ~9:19.5).const PHONE_WIDTH = 402;@@ -129,7 +123,7 @@ interface PreviewStageProps {* the playground has issued one on the client — the nonce must never be* baked into server-rendered HTML.*/- frame: {key: number; src: string} | null;+ frame: PreviewFrameGeneration | null;/*** Fires on every load of the preview document — including a replaced one* (previewed code navigating or reloading its own frame), which is what@@ -185,41 +179,15 @@ export function PreviewStage({isFullBleed && !isFullscreen && s.cardFullBleed,dynamic.size(width, height),]}>- {frame != null &&- // Two elements rather than one with a computed `sandbox`: the lint- // rule guarding iframes wants the attribute spelled out, and so does- // a reader auditing the boundary.- (PREVIEW_KEEPS_SITE_ORIGIN ? (- <iframe- key={frame.key}- ref={frameRef}- onLoad={onFrameLoad}- src={frame.src}- sandbox="allow-scripts allow-same-origin"- title="Preview"- {...stylex.props(- s.iframe,- isInteractionDisabled && s.iframeInert,- )}- />- ) : (- // No allow-same-origin: the preview document gets an opaque- // origin, so the code it compiles and runs holds no cookies, no- // storage, and no reach into this page — see previewChannel.ts- // for how the two ends talk without a nameable origin.- <iframe- key={frame.key}- ref={frameRef}- onLoad={onFrameLoad}- src={frame.src}- sandbox="allow-scripts"- title="Preview"- {...stylex.props(- s.iframe,- isInteractionDisabled && s.iframeInert,- )}- />- ))}+ {frame != null && (+ <PreviewFrame+ frame={frame}+ frameRef={frameRef}+ onLoad={onFrameLoad ?? noop}+ title="Preview"+ {...stylex.props(s.iframe, isInteractionDisabled && s.iframeInert)}+ />+ )}</Card></Center>);diff --git a/apps/docsite/src/app/playground/preview/page.tsx b/apps/docsite/src/app/playground/preview/page.tsxindex c5346938dd..740033a54c 100644--- a/apps/docsite/src/app/playground/preview/page.tsx+++ b/apps/docsite/src/app/playground/preview/page.tsx@@ -30,7 +30,8 @@ import {setCleanSource,setPostToParent,} from '../propertyEditor/targetingOverlay';-import {runCode, setTypeScript} from './runner';+import {runCode, setTypeScript, type LocalModules} from './runner';+import {loadPostModules} from './postModules';import {acceptPreviewConnect,announcePreview,@@ -63,7 +64,14 @@ const useIsomorphicLayoutEffect =typeof window !== 'undefined' ? useLayoutEffect : useEffect;type PreviewMessage =- | {type: 'preview-code'; code: string; source: string}+ | {+ type: 'preview-code';+ code: string;+ source: string;+ // A blog post's live example (spec:AST-033 FR22): the post whose+ // post-local example assets the code may import by relative path.+ post?: string;+ }| {type: 'preview-clear'}| {type: 'preview-theme';@@ -132,6 +140,9 @@ export default function PreviewPage() {const readyRef = useRef<MessagePort | null>(null);const stageRef = useRef<HTMLDivElement>(null);const contentRef = useRef<HTMLDivElement>(null);+ // Counts code messages, so a run that waits on a post's example assets+ // never lands after a newer message.+ const codeRunRef = useRef(0);// Load the TypeScript compiler from public/vendor — self-hosted because// corpnet blocks external CDNs. The UMD sets window.ts in the browser@@ -172,8 +183,8 @@ export default function PreviewPage() {}const handleCode = useCallback(- (code: string) => {- const result = runCode(code);+ (code: string, localModules?: LocalModules) => {+ const result = runCode(code, localModules);if (result.Component) {setComponent(() => result.Component);setError(null);@@ -313,9 +324,39 @@ export default function PreviewPage() {// any live badges so an open popover re-parses against it.setCleanSource(event.data.source ?? event.data.code);refreshTargetLabels();- handleCode(event.data.code);+ {+ const {code, post} = event.data;+ const run = ++codeRunRef.current;+ if (typeof post === 'string') {+ // Load the post's own example assets first; a newer code+ // message supersedes this run.+ void loadPostModules(post).then(+ modules => {+ if (run === codeRunRef.current) {+ handleCode(code, modules);+ }+ },+ (err: unknown) => {+ if (run === codeRunRef.current) {+ const message =+ err instanceof Error ? err.message : String(err);+ setComponent(null);+ setError(`[compile] ${message}`);+ postToParent({+ type: 'preview-error',+ error: message,+ phase: 'compile',+ });+ }+ },+ );+ } else {+ handleCode(code);+ }+ }break;case 'preview-clear':+ codeRunRef.current += 1;handleClear();break;case 'preview-theme':diff --git a/apps/docsite/src/app/playground/preview/postModules.ts b/apps/docsite/src/app/playground/preview/postModules.tsnew file mode 100644index 0000000000..60f83216ec--- /dev/null+++ b/apps/docsite/src/app/playground/preview/postModules.ts@@ -0,0 +1,30 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file postModules.ts+ * @input A blog post slug, and the generated `blogExampleAssets` loaders.+ * @output The post's own example assets as modules keyed by the relative+ * specifier a live example imports them with (`./TarotCard`).+ * @position Preview frame only. A blog post's `tsx live` block+ * (spec:AST-033 FR22) may import the demo material beside its Markdown file;+ * each asset loads on demand, and a post resolves only its own assets.+ */++import {blogExampleAssets} from '@/generated/blogExampleAssets';+import type {LocalModules} from './runner';++export async function loadPostModules(post: string): Promise<LocalModules> {+ const loaders = Object.hasOwn(blogExampleAssets, post)+ ? blogExampleAssets[post]+ : undefined;+ if (loaders == null) {+ return {};+ }+ const entries = await Promise.all(+ Object.entries(loaders).map(+ async ([specifier, load]) =>+ [specifier, (await load()) as Record<string, unknown>] as const,+ ),+ );+ return Object.fromEntries(entries);+}diff --git a/apps/docsite/src/app/playground/preview/runner.ts b/apps/docsite/src/app/playground/preview/runner.tsindex 489aad4f83..48f0c6fed9 100644--- a/apps/docsite/src/app/playground/preview/runner.ts+++ b/apps/docsite/src/app/playground/preview/runner.ts@@ -59,12 +59,23 @@ function warnUnresolved(id: string): void {);}+/**+ * Modules a blog post's live example may import by relative path (`./Name`):+ * the post-local example assets beside that post's Markdown file+ * (spec:AST-033 FR22). Only the post's own frame receives them.+ */+export type LocalModules = Readonly<Record<string, Record<string, unknown>>>;+/** A CommonJS-style require resolving against the preview scope. */-function makeRequire(): (id: string) => unknown {+function makeRequire(localModules?: LocalModules): (id: string) => unknown {return (id: string) => {if (ASSET_RE.test(id)) {return {default: '', __esModule: true};}+ const local = localModules?.[id];+ if (local) {+ return local.__esModule ? local : {...local, __esModule: true};+ }const mod = scopeLookup.get(id.toLowerCase());if (mod) {// Mark as an ES module so TS esModuleInterop uses `.default` correctly.@@ -205,7 +216,10 @@ function findDeclaredIdentifiers(compiled: string): Set<string> {return names;}-function evaluate(compiled: string): React.ComponentType {+function evaluate(+ compiled: string,+ localModules?: LocalModules,+): React.ComponentType {const exportsObj: Record<string, unknown> = {};const moduleObj = {exports: exportsObj};const globals = getGlobalScope();@@ -225,7 +239,7 @@ function evaluate(compiled: string): React.ComponentType {const values = [moduleObj,exportsObj,- sharedRequire,+ localModules == null ? sharedRequire : makeRequire(localModules),...globalNames.map(name => globals[name]),];@@ -245,7 +259,7 @@ function evaluate(compiled: string): React.ComponentType {return defaultExport as React.ComponentType;}-export function runCode(code: string): RunResult {+export function runCode(code: string, localModules?: LocalModules): RunResult {if (!ts) {return {error: 'TypeScript compiler not loaded yet', phase: 'compile'};}@@ -261,7 +275,7 @@ export function runCode(code: string): RunResult {}try {- const Component = evaluate(compiled);+ const Component = evaluate(compiled, localModules);return {Component};} catch (e: unknown) {return {diff --git a/apps/docsite/src/app/playground/usePreviewFrame.tsx b/apps/docsite/src/app/playground/usePreviewFrame.tsxnew file mode 100644index 0000000000..516743fa07--- /dev/null+++ b/apps/docsite/src/app/playground/usePreviewFrame.tsx@@ -0,0 +1,190 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file usePreviewFrame.tsx+ * @input A message handler for the attested preview document, plus optional+ * lifecycle callbacks (a frame issued, a document attested, a document+ * replaced).+ * @output `usePreviewFrame`, the playground preview channel's lifecycle for+ * one frame, and `PreviewFrame`, the sandboxed iframe it drives.+ * @position The one embedding of the preview frame: the playground stage and+ * a blog post's live examples (spec:AST-033 FR16, FR22) both use it, so the+ * sandbox boundary and its recovery live in one place. The trust model is+ * previewChannel.ts: a fresh frame per generation, a nonce in its URL, and+ * a MessagePort only for the document the frame navigated to.+ */++import {+ useCallback,+ useEffect,+ useEffectEvent,+ useRef,+ useState,+ type ComponentPropsWithoutRef,+ type Ref,+} from 'react';+import {createPreviewConnector, previewSrc} from './previewChannel';+import type {PreviewConnector} from './previewChannel';++// Under `next dev` the preview frame keeps the site origin (the sandbox the+// preview always had before isolation): the dev server serves its /_next+// assets only to requests that name an allowlisted host in Origin or Referer,+// and a document with an opaque origin sends neither, so an isolated preview+// cannot load its own scripts there. Production builds, which is where+// untrusted code meets real users, get the opaque origin — see the iframe+// below. `process.env.NODE_ENV` is inlined at build time.+const PREVIEW_KEEPS_SITE_ORIGIN = process.env.NODE_ENV === 'development';++/** One frame generation: a fresh iframe element (key) and its URL (src). */+export interface PreviewFrameGeneration {+ key: number;+ src: string;+}++export interface UsePreviewFrameOptions {+ /** Receives every message the attested document sends on its port. */+ onMessage: (event: MessageEvent) => void;+ /** A new frame generation was issued (the first one, or a restart). */+ onIssue?: () => void;+ /** The current frame proved it loaded the issued preview URL. */+ onAttested?: () => void;+ /**+ * The attested document is gone (previewed code navigated or reloaded its+ * frame). Its port and nonce are already discarded, and a fresh frame is+ * issued right after this returns.+ */+ onReplaced?: () => void;+}++export interface PreviewFrameHandle {+ /** The current generation; null until issued on the client. */+ frame: PreviewFrameGeneration | null;+ /** The iframe ref: only the current element's window can earn a port. */+ attachFrame: (element: HTMLIFrameElement | null) => void;+ /** The iframe's `load` handler. */+ handleFrameLoad: () => void;+ /** Send to the attested document; a no-op while there is none. */+ post: (message: unknown) => void;+ /** Start a new generation in a fresh frame. */+ restart: () => void;+}++/**+ * The preview channel's lifecycle for one frame. The window listener goes up+ * before the first frame is issued, so the hello cannot arrive unheard; the+ * nonce exists only on the client, never in server-rendered HTML.+ */+export function usePreviewFrame(+ options: UsePreviewFrameOptions,+): PreviewFrameHandle {+ // The connector fires these long after the Effect that wires it ran, so+ // each reads the latest callbacks.+ const onMessage = useEffectEvent((event: MessageEvent) =>+ options.onMessage(event),+ );+ const onIssue = useEffectEvent(() => options.onIssue?.());+ const onAttested = useEffectEvent(() => options.onAttested?.());+ const onReplaced = useEffectEvent(() => options.onReplaced?.());+ const [frame, setFrame] = useState<PreviewFrameGeneration | null>(null);+ const connectorRef = useRef<PreviewConnector | null>(null);+ const restartRef = useRef<() => void>(() => {});++ useEffect(() => {+ let generation = 0;+ const issue = () => {+ generation += 1;+ setFrame({key: generation, src: previewSrc(connector.issue())});+ onIssue();+ };+ const connector = createPreviewConnector({+ onMessage,+ onAttested,+ onReplaced: () => {+ onReplaced();+ issue();+ },+ });+ connectorRef.current = connector;+ restartRef.current = issue;+ const onWindowMessage = (event: MessageEvent) =>+ connector.handleWindowMessage(event);+ window.addEventListener('message', onWindowMessage);+ issue();+ return () => {+ restartRef.current = () => {};+ window.removeEventListener('message', onWindowMessage);+ connector.stop();+ connectorRef.current = null;+ };+ }, []);++ // React clears the old element's ref before attaching the new one's, and+ // the connector forgets its window on every issue() anyway, so the null on+ // unmount carries nothing it needs.+ const attachFrame = useCallback((element: HTMLIFrameElement | null) => {+ if (element?.contentWindow) {+ connectorRef.current?.attachFrame(element.contentWindow);+ }+ }, []);+ // The first load in a generation is the document we navigated to arriving;+ // any later one is a replacement.+ const handleFrameLoad = useCallback(() => {+ connectorRef.current?.handleFrameLoad();+ }, []);+ const post = useCallback((message: unknown) => {+ connectorRef.current?.post(message);+ }, []);+ const restart = useCallback(() => restartRef.current(), []);++ return {frame, attachFrame, handleFrameLoad, post, restart};+}++export interface PreviewFrameProps extends Omit<+ ComponentPropsWithoutRef<'iframe'>,+ 'src' | 'sandbox' | 'onLoad' | 'ref'+> {+ frame: PreviewFrameGeneration;+ frameRef: Ref<HTMLIFrameElement>;+ onLoad: () => void;+ title: string;+}++/** The sandboxed preview iframe of one generation. */+export function PreviewFrame({+ frame,+ frameRef,+ onLoad,+ title,+ ...rest+}: PreviewFrameProps) {+ // Two elements rather than one with a computed `sandbox`: the lint rule+ // guarding iframes wants the attribute spelled out, and so does a reader+ // auditing the boundary.+ return PREVIEW_KEEPS_SITE_ORIGIN ? (+ <iframe+ {...rest}+ key={frame.key}+ ref={frameRef}+ onLoad={onLoad}+ src={frame.src}+ sandbox="allow-scripts allow-same-origin"+ title={title}+ />+ ) : (+ // No allow-same-origin: the preview document gets an opaque origin, so+ // the code it compiles and runs holds no cookies, no storage, and no+ // reach into this page — see previewChannel.ts for how the two ends talk+ // without a nameable origin.+ <iframe+ {...rest}+ key={frame.key}+ ref={frameRef}+ onLoad={onLoad}+ src={frame.src}+ sandbox="allow-scripts"+ title={title}+ />+ );+}diff --git a/apps/docsite/src/components/blog/BlogArticle.tsx b/apps/docsite/src/components/blog/BlogArticle.tsxindex d50cf173c7..f1f97bfb09 100644--- a/apps/docsite/src/components/blog/BlogArticle.tsx+++ b/apps/docsite/src/components/blog/BlogArticle.tsx@@ -107,7 +107,7 @@ export function BlogArticle({post}: BlogArticleProps) {</AspectRatio>) : null}- <BlogPostBody body={post.body} />+ <BlogPostBody body={post.body} slug={post.slug} />{post.tags.length > 0 ? (<HStack gap={1} xstyle={styles.tagRow}>diff --git a/apps/docsite/src/components/blog/BlogPostBody.tsx b/apps/docsite/src/components/blog/BlogPostBody.tsxindex 2902e3d992..01ab0b32bc 100644--- a/apps/docsite/src/components/blog/BlogPostBody.tsx+++ b/apps/docsite/src/components/blog/BlogPostBody.tsx@@ -5,7 +5,8 @@/*** @file BlogPostBody.tsx* A blog post's Markdown body. Every heading gets a stable id and the- * hover-revealed copy-link control (createMarkdownHeadingLinks).+ * hover-revealed copy-link control (createMarkdownHeadingLinks), and every+ * `tsx live` fence runs as a sandboxed live example (spec:AST-033 FR22).** The plugin list is created here, in the client module, because a Markdown* plugin is a registered handle: passed from the server-rendered BlogArticle@@ -13,27 +14,84 @@* recognizes, and the plugin would silently not run.*/+import {useMemo} from 'react';import {Markdown} from '@astryxdesign/core/Markdown';-import {createMarkdownHeadingLinks} from '@astryxdesign/core/Markdown/plugins';+import {+ createMarkdownFenceTransform,+ createMarkdownHeadingLinks,+ createMarkdownPlugin,+ type MarkdownExtensionNode,+} from '@astryxdesign/core/Markdown/plugins';import {MarkdownImage} from './ThemedImage';+import {LiveExampleFrame} from './LiveExampleFrame';+import {+ isLiveBlockMeta,+ LIVE_BLOCK_LANGUAGE,+} from '../../lib/blog/liveBlocks.mjs';import css from './BlogPostBody.module.css';// One post per page, so ids are unprefixed and match each heading's own text.-const POST_MARKDOWN_PLUGINS = [createMarkdownHeadingLinks()];+const headingLinks = createMarkdownHeadingLinks();++type LiveExampleNode = MarkdownExtensionNode<+ 'live-examples',+ 'live-example',+ {readonly code: string},+ 'block'+>;++/**+ * Claims each `tsx live` fence; any other `tsx` fence keeps Markdown's+ * ordinary code block. Its text form is the source, so copy and plain-text+ * projections show the example's code.+ */+function createLiveExamples(post: string) {+ return createMarkdownPlugin<'live-examples', LiveExampleNode>({+ name: 'live-examples',+ apiVersion: 1,+ transform: createMarkdownFenceTransform({+ languages: [LIVE_BLOCK_LANGUAGE],+ createNode: ({code, meta}) =>+ isLiveBlockMeta(meta)+ ? {+ type: 'extension',+ plugin: 'live-examples',+ name: 'live-example',+ display: 'block',+ data: {code},+ }+ : null,+ }),+ renderers: {+ 'live-example': {+ render: ({node}) => (+ <LiveExampleFrame code={node.data.code} post={post} />+ ),+ toText: node => node.data.code,+ },+ },+ });+}export interface BlogPostBodyProps {/** Markdown body (frontmatter stripped). */body: string;+ /** The post's slug: its live examples resolve only its own assets. */+ slug: string;}-export function BlogPostBody({body}: BlogPostBodyProps) {+export function BlogPostBody({body, slug}: BlogPostBodyProps) {+ const plugins = useMemo(+ () => [headingLinks, createLiveExamples(slug)],+ [slug],+ );return (<div className={css.body}><MarkdownheadingLevelStart={2}contentWidth="100%"components={{image: MarkdownImage}}- plugins={POST_MARKDOWN_PLUGINS}>+ plugins={plugins}>{body}</Markdown></div>diff --git a/apps/docsite/src/components/blog/LiveExampleFrame.module.css b/apps/docsite/src/components/blog/LiveExampleFrame.module.cssnew file mode 100644index 0000000000..f76f34c9bf--- /dev/null+++ b/apps/docsite/src/components/blog/LiveExampleFrame.module.css@@ -0,0 +1,19 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/* A live example's frame in a blog post: a bordered stage at a fixed height,+ so the post never reflows when the example compiles or fails. */+.frame {+ margin: var(--spacing-6) 0;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-container, 12px);+ overflow: hidden;+ background: var(--color-background-surface);+}++.iframe {+ display: block;+ width: 100%;+ height: 360px;+ border: 0;+ background: transparent;+}diff --git a/apps/docsite/src/components/blog/LiveExampleFrame.tsx b/apps/docsite/src/components/blog/LiveExampleFrame.tsxnew file mode 100644index 0000000000..c875ef4487--- /dev/null+++ b/apps/docsite/src/components/blog/LiveExampleFrame.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file LiveExampleFrame.tsx+ * @input One `tsx live` block from a blog post: its source and the post slug.+ * @output The example running in its own playground preview frame+ * (`/playground/preview`), sandboxed with an opaque origin.+ * @position Blog post body (spec:AST-033 FR22, DEC-9). The post shares the+ * playground's renderer, its frame element and its channel lifecycle+ * (usePreviewFrame.tsx), so the FR16 sandbox boundary and its recovery live+ * in one place. The frame compiles the source, resolves its imports against+ * the preview scope plus this post's own example assets, and shows a+ * compile or runtime error inside itself, so a broken example never breaks+ * the post around it.+ */++import {useEffect, useEffectEvent, useRef} from 'react';+import {+ PreviewFrame,+ usePreviewFrame,+} from '../../app/playground/usePreviewFrame';+import {useThemeMode} from '../../app/providers';+import css from './LiveExampleFrame.module.css';++export interface LiveExampleFrameProps {+ /** The block's TSX source, with a default-exported component. */+ code: string;+ /** The post's slug: the only post whose example assets this frame resolves. */+ post: string;+}++export function LiveExampleFrame({code, post}: LiveExampleFrameProps) {+ const {mode} = useThemeMode();+ // Whether the current frame's document has said it is ready for code.+ const readyRef = useRef(false);++ const {+ frame,+ attachFrame,+ handleFrameLoad,+ post: postToFrame,+ } = usePreviewFrame({+ onMessage: event => {+ if ((event.data as {type?: unknown} | null)?.type === 'preview-ready') {+ readyRef.current = true;+ sendExample();+ }+ },+ // A new frame is coming (the first, or after the example navigated or+ // reloaded its own frame): wait for its ready signal again.+ onIssue: () => {+ readyRef.current = false;+ },+ });++ // Sends this render's theme and source; a no-op until the frame is ready.+ const sendExample = useEffectEvent(() => {+ if (!readyRef.current) {+ return;+ }+ postToFrame({type: 'preview-theme', mode});+ postToFrame({type: 'preview-code', code, source: code, post});+ });++ // A new source, post or site color mode re-sends once the frame is ready;+ // any other render leaves the running example alone.+ useEffect(() => {+ sendExample();+ }, [code, post, mode]);++ return (+ <figure className={css.frame} data-live-example="">+ {frame == null ? null : (+ <PreviewFrame+ frame={frame}+ frameRef={attachFrame}+ onLoad={handleFrameLoad}+ title="Live example"+ className={css.iframe}+ />+ )}+ </figure>+ );+}diff --git a/apps/docsite/src/content/blog/README.md b/apps/docsite/src/content/blog/README.mdindex 123ea41b3f..2d20c0ef30 100644--- a/apps/docsite/src/content/blog/README.md+++ b/apps/docsite/src/content/blog/README.md@@ -184,6 +184,34 @@ How it works: the same build-time scan records the natural size of everyof it. The dark variant takes the light image's width, so the theme togglenever shifts the layout. Images without the suffix are unchanged.+## 5a. Live examples++A fenced block whose info string is `tsx live` runs as a live example instead+of showing as code:++````md+```tsx live+import {Button} from '@astryxdesign/core/Button';++export default function Example() {+ return <Button label="Try me" />;+}+```+````++- The block needs a default-exported component. It runs in the playground's+ preview frame: sandboxed, with its own origin, so a compile or runtime error+ shows inside the frame and the rest of the post still renders.+- It can import published Astryx packages, plus demo material that lives+ beside the post: put `.tsx` modules in a folder named after the post+ (`posts/<slug>/TarotCard.tsx` next to `posts/<slug>.md`) and import them as+ `./TarotCard`. They are not Astryx components, no package exports them, and+ only this post's examples can import them.+- The plain-text route (`/blog/<slug>.txt`) shows the block's source as an+ ordinary `tsx` code block.+- `src/content/blog/fixtures/` holds test posts: the canary serves them at+ `/blog/<slug>`, but the index, feed and sitemap never list them.+## 6. Preview locally```bashdiff --git a/apps/docsite/src/content/blog/fixtures/live-example-sample.md b/apps/docsite/src/content/blog/fixtures/live-example-sample.mdnew file mode 100644index 0000000000..7ef2ea625a--- /dev/null+++ b/apps/docsite/src/content/blog/fixtures/live-example-sample.md@@ -0,0 +1,69 @@+---+title: 'Live example sample'+description: 'Test fixture for runnable tsx live blocks in blog posts. Never listed.'+date: '2026-11-01'+type: 'engineering'+authors:+ - 'cixzhang'+tags:+ - 'Docs'+draft: true+---++This fixture exercises every case of a `tsx live` block. It is served on the+canary only, and the blog index, feed and sitemap never list it.++## A running example++```tsx live+import {useState} from 'react';+import {Button} from '@astryxdesign/core/Button';+import {HStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++export default function Counter() {+ const [count, setCount] = useState(0);+ return (+ <HStack gap={3} style={{alignItems: 'center'}}>+ <Button label="Add one" onClick={() => setCount(c => c + 1)} />+ <Text type="body" data-testid="count">+ Clicked {count} times+ </Text>+ </HStack>+ );+}+```++## An example that imports a post-local asset++```tsx live+import {SampleCard} from './SampleCard';++export default function Spread() {+ return <SampleCard title="The Star" detail="Hope, renewal, calm" />;+}+```++## A broken example stays inside its frame++```tsx live+export default function Broken() {+ throw new Error('This example fails on purpose');+}+```++```tsx live+export default function DoesNotCompile( {+ return <div>never</div>;+}+```++## An ordinary code block++```tsx+export default function NotLive() {+ return null;+}+```++The post keeps rendering after every example above.diff --git a/apps/docsite/src/content/blog/fixtures/live-example-sample/SampleCard.tsx b/apps/docsite/src/content/blog/fixtures/live-example-sample/SampleCard.tsxnew file mode 100644index 0000000000..58c0ab089c--- /dev/null+++ b/apps/docsite/src/content/blog/fixtures/live-example-sample/SampleCard.tsx@@ -0,0 +1,27 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file SampleCard.tsx+ * @input A title and a one-line detail.+ * @output A demo card built from Astryx components.+ * @position Post-local example asset for the live-example-sample fixture+ * (spec:AST-033 FR22): not an Astryx component, exported from no package,+ * listed in no catalog, and resolvable only by this post's live examples.+ */++import {Card} from '@astryxdesign/core/Card';+import {VStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++export function SampleCard({title, detail}: {title: string; detail: string}) {+ return (+ <Card padding={4} data-testid="sample-card" style={{width: 220}}>+ <VStack gap={2}>+ <Text type="large" weight="bold">+ {title}+ </Text>+ <Text type="body">{detail}</Text>+ </VStack>+ </Card>+ );+}diff --git a/apps/docsite/src/lib/blog/liveBlocks.mjs b/apps/docsite/src/lib/blog/liveBlocks.mjsnew file mode 100644index 0000000000..2805685dee--- /dev/null+++ b/apps/docsite/src/lib/blog/liveBlocks.mjs@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file liveBlocks.mjs+ * @input A blog post's Markdown body.+ * @output The `tsx live` fence rule (spec:AST-033 FR22) and the static+ * fallback the plain-text route serves in place of a running example.+ * @position Shared by BlogPostBody (which runs the blocks), the plain-text+ * post route, and their tests.+ */++import {markdownSourceLinesPlugin} from '@astryxdesign/core/Markdown/plugins';+import {parseMarkdownAst} from '@astryxdesign/core/Markdown/parser';+import {visitMarkdownNodes} from '@astryxdesign/core/Markdown/utils';++/** The fenced-code language a live block declares. */+export const LIVE_BLOCK_LANGUAGE = 'tsx';++/** Whether a `tsx` fence's info string, after the language, marks it live. */+export function isLiveBlockMeta(meta) {+ return typeof meta === 'string' && meta.trim() === 'live';+}++/**+ * The body with every `tsx live` block shown as its source in an ordinary+ * `tsx` code block: the static fallback where nothing can run it. The blocks+ * are found by the same Markdown parser the page renders with, so the+ * fallback rewrites exactly the fences the page runs: inside blockquotes and+ * list items too, and never a fence quoted inside another block.+ *+ * @param {string} body+ * @returns {string}+ */+export function toStaticLiveBlocks(body) {+ const root = parseMarkdownAst(body, {plugins: [markdownSourceLinesPlugin]});+ /** 1-based source lines that open a live block. */+ const openers = new Set();+ visitMarkdownNodes(root, 'code', node => {+ if (+ node.lang === LIVE_BLOCK_LANGUAGE &&+ isLiveBlockMeta(node.meta) &&+ node.position?.start.line != null+ ) {+ openers.add(node.position.start.line);+ }+ });+ if (openers.size === 0) {+ return body;+ }+ return body+ .split('\n')+ .map((line, index) =>+ openers.has(index + 1)+ ? line.replace(/(`{3,}|~{3,})[ \t]*tsx[ \t]+live[ \t]*$/, '$1tsx')+ : line,+ )+ .join('\n');+}diff --git a/apps/docsite/src/lib/blog/posts.mjs b/apps/docsite/src/lib/blog/posts.mjsindex 8a7bdcd8b2..261fda03d4 100644--- a/apps/docsite/src/lib/blog/posts.mjs+++ b/apps/docsite/src/lib/blog/posts.mjs@@ -32,7 +32,14 @@ import * as path from 'node:path';* The small, stable set of editorial post types used for primary filtering.* Keep this in sync with the proposal in issue #2896.*/-export const POST_TYPES = ['update', 'guide', 'design', 'story', 'perspective', 'engineering'];+export const POST_TYPES = [+ 'update',+ 'guide',+ 'design',+ 'story',+ 'perspective',+ 'engineering',+];/** Maximum number of tags allowed per post (keeps the index calm and scannable). */export const MAX_TAGS = 4;@@ -48,7 +55,10 @@ function unquote(value) {if ((first === '"' && last === '"') || (first === "'" && last === "'")) {const inner = trimmed.slice(1, -1);if (first === '"') {- return inner.replace(/\\"/g, '"').replace(/\\n/g, '\n').replace(/\\\\/g, '\\');+ return inner+ .replace(/\\"/g, '"')+ .replace(/\\n/g, '\n')+ .replace(/\\\\/g, '\\');}return inner;}@@ -165,7 +175,9 @@ export function parseYamlFrontmatter(text) {const bLine = block[j];const trimmed = bLine.trim();if (!trimmed.startsWith('- ')) {- throw new Error(`Expected a "- " sequence item under "${key}", got: "${bLine}"`);+ throw new Error(+ `Expected a "- " sequence item under "${key}", got: "${bLine}"`,+ );}const afterDash = trimmed.slice(2);const mapField = afterDash.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);@@ -181,7 +193,9 @@ export function parseYamlFrontmatter(text) {) {const fld = block[j].trim().match(/^([A-Za-z0-9_-]+):\s*(.*)$/);if (!fld) {- throw new Error(`Malformed map field under "${key}": "${block[j]}"`);+ throw new Error(+ `Malformed map field under "${key}": "${block[j]}"`,+ );}obj[fld[1]] = coerceScalar(fld[2]);j += 1;@@ -218,7 +232,8 @@ export function parseFrontmatter(raw) {// ── Validation ─────────────────────────────────────────────────────────function isValidDate(value) {- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value))+ return false;const d = new Date(value + 'T00:00:00Z');return !Number.isNaN(d.getTime()) && d.toISOString().startsWith(value);}@@ -279,7 +294,8 @@ export function validatePostFrontmatter(slug, data) {if (data.releasePackage != null &&- (typeof data.releasePackage !== 'string' || data.releasePackage.trim() === '')+ (typeof data.releasePackage !== 'string' ||+ data.releasePackage.trim() === '')) {err('"releasePackage" must be a non-empty string when provided');}@@ -290,7 +306,9 @@ export function validatePostFrontmatter(slug, data) {}if (data.updatedAt != null && !isValidDate(data.updatedAt)) {- err(`"updatedAt" must be an ISO date (YYYY-MM-DD), got "${data.updatedAt}"`);+ err(+ `"updatedAt" must be an ISO date (YYYY-MM-DD), got "${data.updatedAt}"`,+ );}if (@@ -409,6 +427,31 @@ export function discoverPosts(postsDir, options = {}) {return visible;}+/**+ * A post's example assets (spec:AST-033 FR22): the modules in the directory+ * named after the post, beside its Markdown file (`posts/<slug>/TarotCard.tsx`+ * next to `posts/<slug>.md`). A `tsx live` block in that post imports one as+ * `./TarotCard`. They are docs-only demo material: no package exports them and+ * no catalog lists them, and only their own post's examples can resolve them.+ *+ * @param {string} postsDir Absolute path to the directory holding the post.+ * @param {string} slug The post's slug.+ * @returns {{specifier: string, file: string}[]} Sorted by specifier; `file`+ * is the absolute path of the module.+ */+export function collectExampleAssets(postsDir, slug) {+ const dir = path.join(postsDir, slug);+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return [];+ return fs+ .readdirSync(dir)+ .filter(f => /\.(tsx?|jsx?)$/.test(f) && !/\.(test|spec)\./.test(f))+ .sort()+ .map(f => ({+ specifier: `./${f.replace(/\.(tsx?|jsx?)$/, '')}`,+ file: path.join(dir, f),+ }));+}+/** Distinct post types present in the given posts (ordered by POST_TYPES). */export function collectTypes(posts) {const present = new Set(posts.map(p => p.type));diff --git a/docs/specs/AST-033/spec.md b/docs/specs/AST-033/spec.mdindex a4514fc99e..4f07c6fd94 100644--- a/docs/specs/AST-033/spec.md+++ b/docs/specs/AST-033/spec.md@@ -266,9 +266,14 @@ for each bug.example assets that live beside the post's Markdown file, such as docs-onlydemo components like tarot cards; those assets are not Astryx components,are not exported from any package, enter no catalog, and resolve only for- their own post. The plain-text post route and the RSS feed show a static- fallback in place of the running example: the block's source as an ordinary- code block. Implementation gap: not built (Current-state impact).+ their own post. The plain-text post route shows a static fallback in place+ of the running example: the block's source as an ordinary code block, read+ the way the page reads fences (inside blockquotes and list items too, and+ never inside another fenced block). RSS items carry the post's description+ and no body, so no example reaches the feed. A post's example assets live in a folder named after the post,+ beside its Markdown file, and load only in the frames of that post's live+ examples. Test fixture posts under `src/content/blog/fixtures/` are served+ on the canary only and never listed in the blog index, feed, or sitemap.### Authority routing@@ -320,10 +325,7 @@ Known conformance gaps remain implementation work:source, type, tab, view, and toggle-value fields, and nested template-previewactivation can reach the same semantic action twice;- existing interaction tests do not yet cover the complete primary-selection,- Back/Forward, close, cancellation, and supersession matrix; and-- blog posts render every fenced code block as static code: no `tsx live`- block runs an example, the preview scope holds no post-local assets, and the- plain-text route and RSS feed have no live-block fallback (FR22).+ Back/Forward, close, cancellation, and supersession matrix.Stable Storybook and Sandbox currently use a split deployment: pull-requestpreviews are staged inside the Vercel Docsite, while stable main is rebuilt and@@ -338,16 +340,16 @@ exact source already serving those public surfaces.## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| --------- | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |-| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |-| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |-| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |-| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |-| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |-| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |-| FR22 | real-browser blog post checks plus plain-text route and RSS feed checks | a post with a `tsx live` block; that post's plain-text route and RSS item; a block importing a post-local asset; a block that fails to compile or throws | the live block does not run in the browser, the text route or feed shows anything but the source fallback, a post-local import fails to resolve, or a broken example breaks the page outside its frame |+| Contract | Verification | Representative states | Mutation or failure expectation |+| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR3 | generator/data-extraction tests plus cross-projection inventory; search endpoint parity with `astryx search --json` | package, component, template, theme; gallery, sidebar, search, direct route, preview, playground | a local map changes membership or a canonical item fact, or availability and visibility collapse into one projection |+| FR4–FR6 | latest/canary generation and projection tests | stable package, canary-only package, ready/unready item, overview-hidden item, invalid integration metadata | latest exposes canary package docs, workspace-backed content is called release-pinned, a second readiness state appears, or projections disagree |+| FR7–FR9 | navigation-family checks plus real-browser navigation/history tests | direct link, modified click, new tab, deep link, primary selection, secondary tab/filter, canonicalization, Back/Forward | Docsite misclassifies a destination, canonical identity diverges, primary selections replace one another, or secondary state clutters history |+| FR10–FR12 | selection/transition tests plus real-browser visible-content checks | initial open, reopen, deep link, direct selection, pending previous/next, close, supersede, reject, unmount | header/body/actions disagree, stale content paints without its owning pending state, or obsolete selection work commits after supersession |+| FR13–FR15 | analytics schema and interaction tests with transport spies | navigation intent, successful/failed copy, cancel, URL restoration, render/effect, duplicate activation | event names/properties drift, free-form/high-cardinality data is logged, a passive lifecycle emits, success logs on failure, or one action emits twice |+| FR16 | production-browser playground isolation and recovery tests | direct load, reload, hostile navigation, storage and parent-DOM denial | preview code reaches parent/storage or trusted recovery restores stale source/theme |+| FR17–FR21 | exact-head Vercel build, route/asset probes, metadata checks, and Pages landing contract | production and PR Preview; Storybook manager/frame; Sandbox route/embed; old root/deep path; desktop/mobile; light/dark | one app is absent or stale, a direct asset/route fails, metadata claims the wrong owner, identity drifts, or Pages hosts more than the compatibility page |+| FR22 | `e2e/blog-live-examples.spec.ts` (real-browser post, plain-text route, feed, sitemap, and index checks) and `blog-live-examples.test.tsx` (fence rule, static fallback, fixture listing, runner) | a post with a `tsx live` block; that post's plain-text route; a block importing a post-local asset; a block that fails to compile or throws; live fences in a blockquote, a list item, and quoted inside a longer fence | the live block does not run in the browser, the text route shows anything but the source fallback for a fence the page runs, a post-local import fails to resolve, a broken example breaks the page outside its frame, or the feed, sitemap, or index lists the fixture |## Decision log