An open source design system that's fully customizable and agent ready
TypeScript
feat(docsite): offer internal docs after network reachability check (#6785)
Xinzi Zhou43d9b88c30f8
diff --git a/apps/docsite/e2e/header-offset.spec.ts b/apps/docsite/e2e/header-offset.spec.tsindex 42cec06db4..beaeb53329 100644--- a/apps/docsite/e2e/header-offset.spec.ts+++ b/apps/docsite/e2e/header-offset.spec.ts@@ -28,9 +28,7 @@ test('the canary banner does not leave the hero and nav backdrop behind it', asyawait page.setViewportSize({width: 1440, height: 900});await page.goto('/');- const banner = page- .getByRole('alert')- .filter({hasText: "You're viewing unreleased docs"});+ const banner = page.getByRole('region', {name: 'Documentation notice'});test.skip((await banner.count()) === 0, 'Only canary builds show the banner');const header = page.locator('.astryx-app-shell-header').first();diff --git a/apps/docsite/e2e/internal-docs-prompt.spec.ts b/apps/docsite/e2e/internal-docs-prompt.spec.tsnew file mode 100644index 0000000000..b921989cf9--- /dev/null+++ b/apps/docsite/e2e/internal-docs-prompt.spec.ts@@ -0,0 +1,305 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @input A production docsite build and exact-origin reachability fixtures+ * @output Browser evidence of unified banner CTAs and page-view-only dismissal+ * @position Docsite integration tests; run against both latest and canary builds+ */++import {expect, test, type Page} from '@playwright/test';++const deployments = [+ {name: 'production', origin: 'https://astryx.atmeta.com'},+ {+ name: 'preview',+ origin:+ 'https://astryx-git-feat-docs-internal-network-prompt-fbopensource.vercel.app',+ },+ {name: 'canary', origin: 'https://astryx-canary.vercel.app'},+];+const isCanary = process.env.DOCSITE_TEST_TARGET !== 'latest';+const target = isCanary ? 'canary' : 'latest';+const internalOrigin = 'https://astryx.internalmeta.com';+const probeOrigin = 'https://codebunny.internalmeta.com';+const noticeName = 'Documentation notice';+const dismissName = 'Dismiss documentation notice for this page view';++test.afterEach(async ({page}) => {+ await page.waitForLoadState('networkidle');+});++async function servePublicOrigin(+ page: Page,+ baseURL: string | undefined,+ origin: string,+) {+ if (!baseURL) {+ throw new Error('A local docsite baseURL is required');+ }+ await page.route(`${origin}/**`, async route => {+ const url = new URL(route.request().url());+ const response = await route.fetch({+ url: `${baseURL}${url.pathname}${url.search}`,+ });+ await route.fulfill({response});+ });+}++async function serveReachability(page: Page, origin: string) {+ let requests = 0;+ let allowReply = () => {};+ const gate = new Promise<void>(resolve => {+ allowReply = resolve;+ });+ await page.route(`${probeOrigin}/embed/access-check?**`, async route => {+ requests++;+ expect(+ new URL(route.request().url()).searchParams.get('parent_origin'),+ ).toBe(origin);+ await gate;+ await route.fulfill({+ contentType: 'text/html; charset=utf-8',+ headers: {+ 'Cache-Control': 'private, no-store',+ 'Content-Security-Policy': `frame-ancestors ${origin}`,+ 'Cross-Origin-Resource-Policy': 'cross-origin',+ 'Referrer-Policy': 'no-referrer',+ 'X-Content-Type-Options': 'nosniff',+ },+ body: `<!doctype html><html><body><script>window.parent.postMessage({type:'codebunny:access-check:v1',reachable:true},${JSON.stringify(origin)});</script></body></html>`,+ });+ });+ return {requests: () => requests, allowReply};+}++for (const {name, origin} of deployments) {+ for (const width of [1440, 390]) {+ for (const colorScheme of ['light', 'dark'] as const) {+ test(`${target} ${name}: one info banner at ${width}px in ${colorScheme}`, async ({+ page,+ baseURL,+ }, testInfo) => {+ await page.setViewportSize({width, height: 900});+ await page.emulateMedia({colorScheme});+ await servePublicOrigin(page, baseURL, origin);+ const probe = await serveReachability(page, origin);+ const documentResponse = await page.goto(+ `${origin}/docs/getting-started?source=test`,+ {+ waitUntil: 'domcontentloaded',+ },+ );+ if (!documentResponse) {+ throw new Error('The documentation response is required');+ }+ expect(await documentResponse.text()).not.toMatch(+ /Meta internal|Meta-specific components/,+ );+ const heading = page.getByRole('heading', {+ name: 'Getting Started',+ exact: true,+ });+ await expect(heading).toBeVisible();+ await page.evaluate(() => document.fonts.ready);+ const notice = page.getByRole('region', {name: noticeName});+ const internal = notice.getByRole('link', {+ name: 'Meta internal docs',+ exact: true,+ });+ const production = notice.getByRole('link', {+ name: 'View production',+ exact: true,+ });+ await expect(notice).toHaveCount(isCanary ? 1 : 0);+ await expect(internal).toHaveCount(0);+ if (isCanary) {+ await expect(production).toHaveAttribute(+ 'href',+ 'https://astryx.atmeta.com/docs/getting-started?source=test',+ );+ await expect(notice).toContainText("You're viewing Canary docs");+ await expect(notice.locator('[data-status="warning"]')).toHaveCount(+ 2,+ );+ await page.screenshot({+ path: testInfo.outputPath(+ `docs-banner-canary-default-${name}-${width}-${colorScheme}.png`,+ ),+ });+ await expect(notice).toContainText(+ 'These docs may include unreleased components and props. View production docs for the latest stable release.',+ );+ await expect(notice).not.toContainText(+ /Meta internal|Meta-specific components/,+ );+ }+ await expect(+ page.locator(+ 'iframe[title="Astryx documentation reachability check"]',+ ),+ ).toHaveAttribute('sandbox', 'allow-scripts allow-same-origin');+ probe.allowReply();+ await expect(notice).toHaveCount(1);+ await expect(notice).toContainText('Working on Meta internal tools?');+ await expect(notice).not.toContainText("You're viewing Canary docs");+ if (isCanary) {+ await expect(notice).toContainText(+ 'These docs may include unreleased components and props. View production docs for the latest stable release.',+ );+ } else {+ await expect(notice).not.toContainText('Canary');+ }+ await expect(notice).toContainText(+ 'Meta-specific components and guidance',+ );+ await expect(internal).toBeVisible();+ await expect(internal).toHaveAttribute(+ 'href',+ `${internalOrigin}/docs/getting-started?source=test`,+ );+ expect(await internal.getAttribute('target')).toBeNull();+ await expect(internal).not.toContainText('opens in');+ await expect(production).toHaveCount(isCanary ? 1 : 0);+ await expect(notice.getByRole('link')).toHaveCount(isCanary ? 2 : 1);+ await expect(page.locator('[data-status="warning"]')).toHaveCount(0);+ await expect(notice.locator('[data-status="info"]')).toHaveCount(2);+ await expect(page.getByRole('banner')).toHaveCount(1);+ await expect(+ page.getByRole('banner').getByRole('complementary'),+ ).toHaveCount(0);+ const box = await notice.boundingBox();+ if (!box) {+ throw new Error('The info banner must have a visible box');+ }+ expect(box.x).toBeGreaterThanOrEqual(0);+ expect(box.x + box.width).toBeLessThanOrEqual(width);+ expect(box.width).toBeGreaterThan(width * 0.9);+ expect(box.y).toBeLessThan(1);+ await expect(notice).not.toHaveCSS('position', 'fixed');+ await expect(+ page.locator(+ 'iframe[title="Astryx documentation reachability check"]',+ ),+ ).toHaveCount(0);+ expect(probe.requests()).toBe(1);+ await page.keyboard.press('Tab');+ await expect(+ page.getByRole('link', {name: 'Skip to content', exact: true}),+ ).toBeFocused();+ await page.keyboard.press('Tab');+ await expect(internal).toBeFocused();+ await page.screenshot({+ path: testInfo.outputPath(+ `docs-banner-focus-${target}-${name}-${width}-${colorScheme}.png`,+ ),+ });+ if (isCanary) {+ await page.keyboard.press('Tab');+ await expect(production).toBeFocused();+ }+ await page.keyboard.press('Tab');+ const dismiss = notice.getByRole('button', {name: dismissName});+ await expect(dismiss).toBeFocused();+ await heading.click();+ await expect(page.getByRole('tooltip')).toHaveCount(0);+ await page.screenshot({+ path: testInfo.outputPath(+ `docs-banner-${target}-${name}-${width}-${colorScheme}.png`,+ ),+ });+ const storageBefore = await page.evaluate(() => ({+ session: {...sessionStorage},+ local: {...localStorage},+ cookie: document.cookie,+ }));+ await dismiss.click();+ await expect(notice).toHaveCount(0);+ expect(+ await page.evaluate(() => ({+ session: {...sessionStorage},+ local: {...localStorage},+ cookie: document.cookie,+ })),+ ).toEqual(storageBefore);+ await page.evaluate(() =>+ window.history.pushState(null, '', '?source=after-dismiss'),+ );+ await expect(notice).toHaveCount(1);+ await expect(internal).toHaveAttribute(+ 'href',+ `${internalOrigin}/docs/getting-started?source=after-dismiss`,+ );+ if (isCanary) {+ await expect(production).toHaveAttribute(+ 'href',+ 'https://astryx.atmeta.com/docs/getting-started?source=after-dismiss',+ );+ }+ expect(probe.requests()).toBe(1);+ await dismiss.click();+ await page.reload();+ await expect(heading).toBeVisible();+ await expect(internal).toBeVisible();+ expect(probe.requests()).toBe(2);+ await page.route(`${internalOrigin}/**`, route =>+ route.fulfill({+ contentType: 'text/html',+ body: '<h1>Internal destination fixture</h1>',+ }),+ );+ await internal.click();+ await expect(page).toHaveURL(+ `${internalOrigin}/docs/getting-started?source=after-dismiss`,+ );+ await expect(+ page.getByRole('heading', {name: 'Internal destination fixture'}),+ ).toBeVisible();+ expect(page.context().pages()).toHaveLength(1);+ });+ }+ }+}++for (const width of [1440, 390]) {+ test(`${target}: failed reachability exposes no internal wording at ${width}px`, async ({+ page,+ baseURL,+ }, testInfo) => {+ await page.setViewportSize({width, height: 900});+ const origin = deployments[0].origin;+ await servePublicOrigin(page, baseURL, origin);+ await page.route(`${probeOrigin}/**`, route => route.abort());+ await page.goto(`${origin}/docs/getting-started`);+ await expect(+ page.getByRole('heading', {name: 'Getting Started', exact: true}),+ ).toBeVisible();+ await expect(+ page.locator('iframe[title="Astryx documentation reachability check"]'),+ ).toHaveCount(0, {timeout: 10_000});+ const notice = page.getByRole('region', {name: noticeName});+ await expect(notice).toHaveCount(isCanary ? 1 : 0);+ await expect(+ page.getByRole('link', {+ name: 'Meta internal docs',+ exact: true,+ }),+ ).toHaveCount(0);+ if (isCanary) {+ await expect(notice.locator('[data-status="warning"]')).toHaveCount(2);+ await expect(notice).not.toContainText(+ /Meta internal|Meta-specific components/,+ );+ expect(await notice.evaluate(element => element.outerHTML)).not.toMatch(+ /Meta internal|Meta-specific components/,+ );+ await expect(+ notice.getByRole('link', {name: 'View production', exact: true}),+ ).toBeVisible();+ }+ await page.screenshot({+ path: testInfo.outputPath(+ `docs-banner-${target}-no-internal-access-${width}.png`,+ ),+ });+ });+}diff --git a/apps/docsite/e2e/mobile-navigation.spec.ts b/apps/docsite/e2e/mobile-navigation.spec.tsindex e189105521..2fb5eb5ec0 100644--- a/apps/docsite/e2e/mobile-navigation.spec.ts+++ b/apps/docsite/e2e/mobile-navigation.spec.ts@@ -139,7 +139,7 @@ test('desktop search stays exposed across hydration at exactly 768px', async ({);expect(await search.boundingBox()).toEqual(initialBox);- const banner = page.getByRole('alert').filter({hasText: 'unreleased docs'});+ const banner = page.getByRole('region', {name: 'Documentation notice'});if (await banner.count()) {await banner.getByRole('button', {name: /^Dismiss/}).click();await expect(banner).toHaveCount(0);diff --git a/apps/docsite/src/__tests__/internal-docs-prompt.test.tsx b/apps/docsite/src/__tests__/internal-docs-prompt.test.tsxnew file mode 100644index 0000000000..a6f8f2c72d--- /dev/null+++ b/apps/docsite/src/__tests__/internal-docs-prompt.test.tsx@@ -0,0 +1,563 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++// @vitest-environment jsdom+// @vitest-environment-options {"url":"https://astryx.atmeta.com/components/Button?tab=props"}++import {StrictMode} from 'react';+import {renderToString} from 'react-dom/server';+import {readFileSync} from 'node:fs';+import {join} from 'node:path';+import {act, cleanup, fireEvent, render, screen} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import type {+ InternalDocsPrompt,+ internalDocsHref,+} from '../components/InternalDocsPrompt';++const route = vi.hoisted(() => ({+ pathname: '/components/Button',+ search: 'tab=props',+ suspendSearch: false,+}));+vi.mock('next/navigation', () => ({+ usePathname: () => route.pathname,+ useSearchParams: () => {+ if (route.suspendSearch) {+ throw new Promise(() => {});+ }+ return new URLSearchParams(route.search);+ },+}));+vi.mock('@stylexjs/stylex', () => ({+ create: <T,>(styles: T) => styles,+ props: () => ({}),+}));++const allowedOrigins = [+ 'https://astryx.atmeta.com',+ 'https://astryx-git-feat-docs-internal-network-prompt-fbopensource.vercel.app',+ 'https://astryx-canary.vercel.app',+];+declare const jsdom: {reconfigure(options: {url: string}): void};++let Prompt: typeof InternalDocsPrompt;+let href: typeof internalDocsHref;+const internalOrigin = 'https://astryx.internalmeta.com';+const probeOrigin = 'https://codebunny.internalmeta.com';+const message = {type: 'codebunny:access-check:v1', reachable: true};++beforeEach(async () => {+ vi.resetModules();+ vi.useFakeTimers();+ vi.stubEnv('NEXT_PUBLIC_DOCS_TARGET', 'latest');+ jsdom.reconfigure({+ url: 'https://astryx.atmeta.com/components/Button?tab=props',+ });+ route.pathname = '/components/Button';+ route.search = 'tab=props';+ route.suspendSearch = false;+ await loadPrompt();+});++async function loadPrompt() {+ vi.resetModules();+ const module = await import('../components/InternalDocsPrompt');+ Prompt = () => (+ <module.InternalDocsReachabilityProvider>+ <module.InternalDocsPrompt />+ </module.InternalDocsReachabilityProvider>+ );+ href = module.internalDocsHref;+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.useRealTimers();+ vi.unstubAllEnvs();+});++async function mount() {+ const view = render(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ await act(async () => {});+ return view;+}++function frame() {+ const result = document.querySelector('iframe');+ expect(result).not.toBeNull();+ return result!;+}++function send(+ target: HTMLIFrameElement,+ data: unknown = message,+ origin = probeOrigin,+ source: MessageEventSource | null = target.contentWindow,+) {+ act(() => {+ window.dispatchEvent(new MessageEvent('message', {data, origin, source}));+ });+}++function showPrompt() {+ const target = frame();+ fireEvent.load(target);+ send(target);+}++function prompt() {+ return screen.queryByRole('region', {+ name: 'Documentation notice',+ });+}++describe('InternalDocsPrompt', () => {+ it('keeps detection at the server root without making the layout URL-aware', () => {+ const layout = readFileSync(join(__dirname, '../app/layout.tsx'), 'utf8');+ expect(layout).not.toContain("'use client'");+ expect(layout.match(/<InternalDocsReachabilityProvider>/g)).toHaveLength(1);+ expect(layout).toMatch(+ /<InternalDocsReachabilityProvider>\s*\{children\}\s*<\/InternalDocsReachabilityProvider>/,+ );+ expect(layout).not.toContain('<InternalDocsPrompt');+ });++ it('does not start another probe inside an embedded document', async () => {+ const parentFrame = document.createElement('iframe');+ document.body.append(parentFrame);+ vi.stubGlobal('top', parentFrame.contentWindow);+ try {+ expect(window.top).not.toBe(window);+ await mount();+ expect(+ document.querySelector(+ 'iframe[title="Astryx documentation reachability check"]',+ ),+ ).toBeNull();+ expect(prompt()).toBeNull();+ } finally {+ vi.unstubAllGlobals();+ parentFrame.remove();+ }+ });++ it('renders nothing before a loaded iframe sends a valid message', async () => {+ await mount();+ expect(prompt()).toBeNull();+ const target = frame();+ expect(target.hidden).toBe(true);+ expect(target.tabIndex).toBe(-1);+ expect(target.getAttribute('aria-hidden')).toBe('true');+ expect(target.getAttribute('sandbox')).toBe(+ 'allow-scripts allow-same-origin',+ );+ expect(target.referrerPolicy).toBe('no-referrer');+ expect(target.src).toBe(+ `${probeOrigin}/embed/access-check?parent_origin=https%3A%2F%2Fastryx.atmeta.com`,+ );+ fireEvent.load(target);+ expect(prompt()).toBeNull();+ send(target);+ expect(prompt()).not.toBeNull();+ const link = screen.getByRole('link', {+ name: /Meta internal docs/,+ });+ expect(screen.getByText('Meta internal docs', {exact: true})).toBeTruthy();+ expect(prompt()?.textContent).not.toContain("On Meta's network?");+ expect(prompt()?.textContent).toContain(+ 'Meta-specific components and guidance',+ );+ expect(prompt()?.querySelectorAll('a')).toHaveLength(1);+ expect(prompt()?.querySelectorAll('button')).toHaveLength(1);+ expect(link.getAttribute('aria-label')).toBeNull();+ expect(link.getAttribute('href')).toBe(+ `${internalOrigin}/components/Button?tab=props`,+ );+ expect(link.getAttribute('target')).toBeNull();+ expect(link.textContent).not.toContain('opens in');+ expect(document.querySelector('iframe')).toBeNull();+ });++ it.each(allowedOrigins)(+ 'sends the actual allowlisted parent origin: %s',+ async origin => {+ const {ALLOWED_PARENT_ORIGINS} =+ await import('../lib/useInternalDocsPrompt');+ expect(ALLOWED_PARENT_ORIGINS).toEqual(allowedOrigins);+ jsdom.reconfigure({url: `${origin}/docs/tokens?mode=dark`});+ await mount();+ const target = frame();+ expect(new URL(target.src).searchParams.get('parent_origin')).toBe(+ origin,+ );+ fireEvent.load(target);+ send(target);+ expect(prompt()).not.toBeNull();+ },+ );++ it.each([+ 'https://astryx-canary.vercel.app.evil.example',+ 'https://astryx-git-feat-docs-internal-network-prompt-fbopensource.vercel.app.evil.example',+ 'http://astryx-canary.vercel.app',+ 'https://astryx-f3fuc1mqg-fbopensource.vercel.app',+ 'https://astryx-git-unapproved-fbopensource.vercel.app',+ 'https://astryx-canary-otherteam.vercel.app',+ 'http://localhost:3233',+ ])('does not probe on an unallowlisted parent: %s', async origin => {+ jsdom.reconfigure({url: `${origin}/docs/tokens`});+ await mount();+ expect(document.querySelector('iframe')).toBeNull();+ expect(prompt()).toBeNull();+ });++ it('also accepts the message before the iframe load event', async () => {+ await mount();+ const target = frame();+ send(target);+ expect(prompt()).toBeNull();+ fireEvent.load(target);+ expect(prompt()).not.toBeNull();+ });++ it.each([+ 'https://evil.example',+ 'https://codebunny.internalmeta.com.evil.example',+ 'http://codebunny.internalmeta.com',+ 'https://astryx.internalmeta.com',+ 'null',+ ])('ignores messages from the wrong origin: %s', async origin => {+ await mount();+ const target = frame();+ fireEvent.load(target);+ send(target, message, origin);+ expect(prompt()).toBeNull();+ send(target);+ expect(prompt()).not.toBeNull();+ });++ it.each([+ null,+ {},+ {type: 'wrong', reachable: true},+ {type: 'astryx:access-check:v1', reachable: true},+ {type: message.type, reachable: false},+ {type: message.type, reachable: 'true'},+ {type: message.type, reachable: 1},+ ])('ignores wrong types or non-boolean reachability: %j', async data => {+ await mount();+ const target = frame();+ fireEvent.load(target);+ send(target, data);+ expect(prompt()).toBeNull();+ });++ it('ignores the right payload from another window', async () => {+ await mount();+ const target = frame();+ fireEvent.load(target);+ send(target, message, probeOrigin, window);+ expect(prompt()).toBeNull();+ });++ it('times out silently and cleans up the iframe and listener', async () => {+ const removeListener = vi.spyOn(window, 'removeEventListener');+ await mount();+ const target = frame();+ fireEvent.load(target);+ act(() => vi.advanceTimersByTime(4000));+ expect(prompt()).toBeNull();+ expect(document.querySelector('iframe')).toBeNull();+ expect(removeListener).toHaveBeenCalledWith(+ 'message',+ expect.any(Function),+ );+ send(target);+ expect(prompt()).toBeNull();+ });++ it('runs at most once under StrictMode and after remounting', async () => {+ const append = vi.spyOn(document.body, 'append');+ const view = await mount();+ expect(append).toHaveBeenCalledTimes(1);+ showPrompt();+ view.unmount();+ await mount();+ expect(append).toHaveBeenCalledTimes(1);+ expect(prompt()).not.toBeNull();+ });++ it('cancels on unmount and does not restart an abandoned probe', async () => {+ const removeListener = vi.spyOn(window, 'removeEventListener');+ const view = await mount();+ view.unmount();+ expect(document.querySelector('iframe')).toBeNull();+ expect(removeListener).toHaveBeenCalledWith(+ 'message',+ expect.any(Function),+ );+ await mount();+ expect(document.querySelector('iframe')).toBeNull();+ expect(prompt()).toBeNull();+ });++ it('dismisses only the mounted view without writing storage or cookies', async () => {+ for (const path of [+ 'components/InternalDocsPrompt.tsx',+ 'lib/useInternalDocsPrompt.ts',+ ]) {+ const source = readFileSync(join(__dirname, '..', path), 'utf8');+ expect(source).not.toMatch(+ /sessionStorage|localStorage|document\.cookie/,+ );+ }+ const view = await mount();+ showPrompt();+ const before = {+ session: {...window.sessionStorage},+ local: {...window.localStorage},+ cookie: document.cookie,+ };+ const close = screen.getByRole('button', {+ name: 'Dismiss documentation notice for this page view',+ });+ expect(close.getAttribute('tabindex')).not.toBe('-1');+ fireEvent.click(close);+ expect(prompt()).toBeNull();+ view.rerender(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ expect(prompt()).toBeNull();+ expect({+ session: {...window.sessionStorage},+ local: {...window.localStorage},+ cookie: document.cookie,+ }).toEqual(before);+ view.unmount();+ await mount();+ expect(prompt()).not.toBeNull();+ expect(document.querySelector('iframe')).toBeNull();+ });++ it('resets dismissal on pathname and query navigation, including returning to a dismissed URL', async () => {+ const view = await mount();+ showPrompt();+ for (const [pathname, search] of [+ ['/docs/tokens', ''],+ ['/docs/tokens', 'mode=dark'],+ ['/components/Button', 'tab=props'],+ ]) {+ fireEvent.click(+ screen.getByRole('button', {+ name: 'Dismiss documentation notice for this page view',+ }),+ );+ expect(prompt()).toBeNull();+ route.pathname = pathname;+ route.search = search;+ view.rerender(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ expect(prompt()).not.toBeNull();+ expect(document.querySelector('iframe')).toBeNull();+ }+ });++ it('keeps an in-flight probe alive across client navigation', async () => {+ const view = await mount();+ const target = frame();+ route.pathname = '/docs/tokens';+ view.rerender(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ expect(frame()).toBe(target);+ fireEvent.load(target);+ send(target);+ expect(prompt()).not.toBeNull();+ });++ it('shows one canary notice before reachability, with only the production CTA', async () => {+ vi.stubEnv('NEXT_PUBLIC_DOCS_TARGET', 'canary');+ await loadPrompt();+ await mount();+ expect(prompt()?.textContent).toContain("You're viewing Canary docs");+ expect(+ prompt()?.querySelector('.astryx-banner')?.getAttribute('data-status'),+ ).toBe('warning');+ expect(prompt()?.textContent).toContain(+ 'These docs may include unreleased components and props. View production docs for the latest stable release.',+ );+ expect(prompt()?.textContent).not.toMatch(+ /Meta internal|Meta-specific components/,+ );+ expect(+ screen.getByRole('link', {name: 'View production'}).getAttribute('href'),+ ).toBe('https://astryx.atmeta.com/components/Button?tab=props');+ expect(+ screen.queryByRole('link', {+ name: 'Meta internal docs',+ }),+ ).toBeNull();+ await act(async () => vi.advanceTimersByTime(5000));+ expect(prompt()).not.toBeNull();+ expect(+ prompt()?.querySelector('.astryx-banner')?.getAttribute('data-status'),+ ).toBe('warning');+ expect(prompt()?.outerHTML).not.toMatch(+ /Meta internal|Meta-specific components/,+ );+ expect(+ screen.queryByRole('link', {+ name: 'Meta internal docs',+ }),+ ).toBeNull();+ });++ it.each([false, true])(+ 'does not expose internal wording in Canary SSR (Suspense fallback: %s)',+ async suspendSearch => {+ vi.stubEnv('NEXT_PUBLIC_DOCS_TARGET', 'canary');+ await loadPrompt();+ const module = await import('../components/InternalDocsPrompt');+ route.suspendSearch = suspendSearch;+ const html = renderToString(+ <module.InternalDocsReachabilityProvider>+ <module.DocsBanner />+ </module.InternalDocsReachabilityProvider>,+ );+ expect(html).toContain(+ 'These docs may include unreleased components and props. View production docs for the latest stable release.',+ );+ expect(html).toContain('View production');+ expect(html).toContain('data-status="warning"');+ expect(html).not.toMatch(/Meta internal|Meta-specific components/);+ },+ );++ it('switches the Canary notice to the internal banner’s Canary variant after a valid probe', async () => {+ vi.stubEnv('NEXT_PUBLIC_DOCS_TARGET', 'canary');+ await loadPrompt();+ await mount();+ expect(prompt()?.textContent).not.toMatch(+ /Meta internal|Meta-specific components/,+ );+ showPrompt();+ expect(prompt()?.textContent).toContain('Working on Meta internal tools?');+ expect(+ prompt()?.querySelector('.astryx-banner')?.getAttribute('data-status'),+ ).toBe('info');+ expect(prompt()?.textContent).not.toContain("You're viewing Canary docs");+ expect(prompt()?.textContent).toContain(+ 'These docs may include unreleased components and props. View production docs for the latest stable release.',+ );+ expect(prompt()?.textContent).toContain(+ 'Meta-specific components and guidance',+ );+ expect(+ screen.getAllByRole('region', {name: 'Documentation notice'}),+ ).toHaveLength(1);+ expect(screen.getAllByRole('link')).toHaveLength(2);+ expect(+ screen+ .getByRole('link', {name: 'Meta internal docs'})+ .getAttribute('href'),+ ).toBe(`${internalOrigin}/components/Button?tab=props`);+ expect(+ screen.getByRole('link', {name: 'View production'}).getAttribute('href'),+ ).toBe('https://astryx.atmeta.com/components/Button?tab=props');+ });++ it('does not revive a dismissed canary notice when the probe finishes', async () => {+ vi.stubEnv('NEXT_PUBLIC_DOCS_TARGET', 'canary');+ await loadPrompt();+ const view = await mount();+ fireEvent.click(+ screen.getByRole('button', {+ name: 'Dismiss documentation notice for this page view',+ }),+ );+ expect(prompt()).toBeNull();+ showPrompt();+ expect(prompt()).toBeNull();+ route.search = 'tab=examples';+ view.rerender(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ expect(prompt()).not.toBeNull();+ expect(+ screen+ .getByRole('link', {name: 'Meta internal docs'})+ .getAttribute('href'),+ ).toBe(`${internalOrigin}/components/Button?tab=examples`);+ });++ it('offers only internal docs on a reachable production view', async () => {+ await mount();+ showPrompt();+ expect(prompt()?.textContent).toContain('Working on Meta internal tools?');+ expect(prompt()?.textContent).not.toContain('Canary');+ expect(screen.queryByRole('link', {name: 'View production'})).toBeNull();+ expect(screen.getAllByRole('link')).toHaveLength(1);+ });++ it('updates the link on client navigation without probing again', async () => {+ const view = await mount();+ showPrompt();+ route.pathname = '/docs/tokens';+ route.search = 'mode=dark&query=a%26b';+ view.rerender(+ <StrictMode>+ <Prompt />+ </StrictMode>,+ );+ expect(+ screen+ .getByRole('link', {name: /Meta internal docs/})+ .getAttribute('href'),+ ).toBe(`${internalOrigin}/docs/tokens?mode=dark&query=a%26b`);+ expect(document.querySelector('iframe')).toBeNull();+ });+});++describe('internalDocsHref', () => {+ it.each([+ '/',+ '/docs',+ '/docs/tokens',+ '/components/Button',+ '/templates/example',+ '/themes',+ '/playground',+ ])('preserves shared route %s and its query', pathname => {+ expect(href(pathname, 'a=1&a=2')).toBe(+ `${internalOrigin}${pathname}?a=1&a=2`,+ );+ });+ it.each([+ '/blog',+ '/blog/launch',+ '/community',+ '/changelog',+ '/playground/preview',+ '//evil.example',+ '/docs/a/b',+ ])(+ 'falls back to the home page for public-only or unknown route %s',+ pathname => {+ expect(href(pathname, 'a=1')).toBe(`${internalOrigin}/`);+ },+ );+});diff --git a/apps/docsite/src/app/(site)/layout.tsx b/apps/docsite/src/app/(site)/layout.tsxindex b56f541884..c1bf0fb5d7 100644--- a/apps/docsite/src/app/(site)/layout.tsx+++ b/apps/docsite/src/app/(site)/layout.tsx@@ -2,8 +2,7 @@import {AppShell} from '@astryxdesign/core/AppShell';import {SharedTopNav} from '../../components/SharedTopNav';-import {CanaryBanner} from '../../components/CanaryBanner';-import {CURRENT_TARGET} from '../../lib/docsVersions';+import {DocsBanner} from '../../components/InternalDocsPrompt';import {SiteFooter} from '../../components/SiteFooter';import {getCopyrightYear} from '../../lib/copyrightYear';import styles from './layout.module.css';@@ -20,7 +19,7 @@ export default async function MarketingLayout({variant="surface"height="auto"mobileNav={false}- banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}+ banner={<DocsBanner />}topNav={<SharedTopNav />}><div className={styles.shell}><div className={styles.main}>{children}</div>diff --git a/apps/docsite/src/app/blog/layout.tsx b/apps/docsite/src/app/blog/layout.tsxindex b5f2e82e87..f2d7c8c08e 100644--- a/apps/docsite/src/app/blog/layout.tsx+++ b/apps/docsite/src/app/blog/layout.tsx@@ -8,8 +8,7 @@import {AppShell} from '@astryxdesign/core/AppShell';import {SharedTopNav} from '../../components/SharedTopNav';-import {CanaryBanner} from '../../components/CanaryBanner';-import {CURRENT_TARGET} from '../../lib/docsVersions';+import {DocsBanner} from '../../components/InternalDocsPrompt';import {SiteFooter} from '../../components/SiteFooter';import {getCopyrightYear} from '../../lib/copyrightYear';@@ -25,7 +24,7 @@ export default async function BlogLayout({variant="surface"height="auto"mobileNav={false}- banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}+ banner={<DocsBanner />}topNav={<SharedTopNav />}>{children}<SiteFooter year={year} />diff --git a/apps/docsite/src/app/layout.tsx b/apps/docsite/src/app/layout.tsxindex 3973909c28..0a63201800 100644--- a/apps/docsite/src/app/layout.tsx+++ b/apps/docsite/src/app/layout.tsx@@ -1,6 +1,13 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @input Page content and site-wide metadata+ * @output Server-rendered document with root-owned optional reachability+ * @position Docsite root; page shells own the URL-aware info banner+ */+import type {Metadata} from 'next';+import {InternalDocsReachabilityProvider} from '../components/InternalDocsPrompt';import {Analytics} from '@vercel/analytics/next';import {SpeedInsights} from '@vercel/speed-insights/next';import './globals.css';@@ -26,8 +33,7 @@ import {// Default social card image: the launch banner that the announcement blog post// uses for its cover. Reusing the same branded banner keeps the shared-link// preview consistent with the launch creative across the site and the post.-const OG_IMAGE =- '/images/Astryx-Banner.png';+const OG_IMAGE = '/images/Astryx-Banner.png';export const metadata: Metadata = {metadataBase: new URL(SITE_URL),@@ -94,7 +100,11 @@ export default function RootLayout({children}: {children: React.ReactNode}) {<body><Analytics /><SpeedInsights />- <Providers>{children}</Providers>+ <Providers>+ <InternalDocsReachabilityProvider>+ {children}+ </InternalDocsReachabilityProvider>+ </Providers></body></html>);diff --git a/apps/docsite/src/app/not-found.tsx b/apps/docsite/src/app/not-found.tsxindex 38e4c472cc..573c74d9c6 100644--- a/apps/docsite/src/app/not-found.tsx+++ b/apps/docsite/src/app/not-found.tsx@@ -12,9 +12,8 @@ import {Center} from '@astryxdesign/core/Center';import {VStack} from '@astryxdesign/core/Layout';import {Heading, Text} from '@astryxdesign/core/Text';import {SharedTopNav} from '../components/SharedTopNav';-import {CanaryBanner} from '../components/CanaryBanner';+import {DocsBanner} from '../components/InternalDocsPrompt';import {DidYouMean} from '../components/DidYouMean';-import {CURRENT_TARGET} from '../lib/docsVersions';import {SiteFooter} from '../components/SiteFooter';import {getCopyrightYear} from '../lib/copyrightYear';import {getSitemapPages} from './sitemap';@@ -33,7 +32,7 @@ export default async function NotFound() {variant="surface"height="fill"mobileNav={false}- banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}+ banner={<DocsBanner />}topNav={<SharedTopNav />}><div className={styles.shell}><div className={styles.content}>diff --git a/apps/docsite/src/app/playground/PlaygroundClient.tsx b/apps/docsite/src/app/playground/PlaygroundClient.tsxindex bd6ced3b53..3f127b1848 100644--- a/apps/docsite/src/app/playground/PlaygroundClient.tsx+++ b/apps/docsite/src/app/playground/PlaygroundClient.tsx@@ -38,6 +38,7 @@ import {useSearchParams} from 'next/navigation';import dynamic from 'next/dynamic';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';@@ -954,6 +955,7 @@ export function PlaygroundClient() {variant="section"height="fill"contentPadding={0}+ banner={<DocsBanner />}mobileNav={isMobile ? false : {}}topNav={mobileTopNav}sideNav={playgroundSideNav}>diff --git a/apps/docsite/src/components/CanaryBanner.tsx b/apps/docsite/src/components/CanaryBanner.tsxdeleted file mode 100644index 2de7aa6c25..0000000000--- a/apps/docsite/src/components/CanaryBanner.tsx+++ /dev/null@@ -1,51 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--import {usePathname} from 'next/navigation';-import {Banner} from '@astryxdesign/core/Banner';-import {Button} from '@astryxdesign/core/Button';-import {CURRENT_TARGET, DOCS_VERSIONS, urlForTarget} from '../lib/docsVersions';--/**- * Full-width notice shown ONLY on canary builds (the `main` deploy and every PR- * preview), warning readers that they are viewing unreleased, work-in-progress- * documentation whose components and props may not exist in the published- * package yet. Links to the same page on the stable site, and can be dismissed- * for the lifetime of the mounted shell via Banner's internal state.- *- * Rendered via AppShell's `banner` slot; callers gate the slot on- * `CURRENT_TARGET === 'canary'` so production renders no banner region at all- * (AppShell keys the region off `isRenderable`, and a bare `<CanaryBanner />`- * element always counts as renderable even when it would return `null`). The- * internal target guard is a belt-and-suspenders fallback.- */-export function CanaryBanner() {- const pathname = usePathname();-- if (CURRENT_TARGET !== 'canary') {- return null;- }-- const stableHref = urlForTarget('latest', pathname);- const stableLabel = DOCS_VERSIONS.latest.label;-- return (- <Banner- container="section"- status="warning"- isDismissable- title="You're viewing unreleased docs (Canary)"- description="This documents the canary release from main. Some components and props shown here may not exist in the latest published package yet — they ship on the @canary npm tag until the next stable release."- endContent={- stableHref ? (- <Button- label={`View ${stableLabel}`}- variant="secondary"- href={stableHref}- />- ) : undefined- }- />- );-}diff --git a/apps/docsite/src/components/DocsShell.tsx b/apps/docsite/src/components/DocsShell.tsxindex e6a18f308a..7cf6bd452a 100644--- a/apps/docsite/src/components/DocsShell.tsx+++ b/apps/docsite/src/components/DocsShell.tsx@@ -18,8 +18,7 @@ import {SideNav, SideNavItem, SideNavSection} from '@astryxdesign/core/SideNav';import {TextInput} from '@astryxdesign/core/TextInput';import {Icon} from '@astryxdesign/core/Icon';import {SharedTopNav} from './SharedTopNav';-import {CanaryBanner} from './CanaryBanner';-import {CURRENT_TARGET} from '../lib/docsVersions';+import {DocsBanner} from './InternalDocsPrompt';import type {PackageMeta} from '../generated/packageRegistry';import type {DocTopic} from '../generated/docsRegistry';import {@@ -185,7 +184,7 @@ export function DocsShell({children, packages, docTopics}: DocsShellProps) {className="astryx-docs-shell"variant="surface"height="auto"- banner={CURRENT_TARGET === 'canary' ? <CanaryBanner /> : undefined}+ banner={<DocsBanner />}topNav={<><SharedTopNav />diff --git a/apps/docsite/src/components/DocsVersionFooterLink.tsx b/apps/docsite/src/components/DocsVersionFooterLink.tsxindex 599470784f..da5bbd698a 100644--- a/apps/docsite/src/components/DocsVersionFooterLink.tsx+++ b/apps/docsite/src/components/DocsVersionFooterLink.tsx@@ -10,8 +10,8 @@ import type {DocsTarget} from '../lib/docsVersions';/*** Footer link to the sibling content line: from the Latest (production) site* over to the Canary docs, or back again. This is the low-key, persistent way- * to reach Canary from production; on Canary the prominent CanaryBanner carries- * the primary link back to Latest.+ * to reach Canary from production; on Canary the docs info banner carries+ * the primary link back to production.** Renders nothing when there is no distinct sibling to link to (e.g. a local* build where the destination resolves to the current origin).diff --git a/apps/docsite/src/components/InternalDocsPrompt.tsx b/apps/docsite/src/components/InternalDocsPrompt.tsxnew file mode 100644index 0000000000..1b28b00666--- /dev/null+++ b/apps/docsite/src/components/InternalDocsPrompt.tsx@@ -0,0 +1,136 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @input Build target, exact-origin reachability, and the current docs view+ * @output The internal-docs banner after reachability, otherwise the public Canary banner+ * @position Root-owned detection; banner content lives in the page shell+ */++import {createContext, Suspense, useContext, type ReactNode} from 'react';+import {usePathname, useSearchParams} from 'next/navigation';+import {Banner} from '@astryxdesign/core/Banner';+import {Button} from '@astryxdesign/core/Button';+import {CURRENT_TARGET, urlForTarget} from '../lib/docsVersions';+import {+ INTERNAL_DOCS_ORIGIN,+ useInternalDocsPrompt,+} from '../lib/useInternalDocsPrompt';++const ReachabilityContext = createContext(false);++export function InternalDocsReachabilityProvider({+ children,+}: {+ children: ReactNode;+}) {+ const isReachable = useInternalDocsPrompt();+ return (+ <ReachabilityContext value={isReachable}>{children}</ReachabilityContext>+ );+}++export function internalDocsHref(pathname: string, search: string): string {+ // Shared route families use the same topic/name/slug semantics. Public-only+ // pages (blog, community, changelog, preview) have no same-path counterpart.+ const hasCounterpart =+ pathname === '/' ||+ /^\/(docs|components|templates)(\/[^/]+)?\/?$/.test(pathname) ||+ /^\/(themes|playground)\/?$/.test(pathname);+ const url = new URL(INTERNAL_DOCS_ORIGIN);+ if (hasCounterpart) {+ url.pathname = pathname;+ url.search = search;+ }+ return url.href;+}++export function DocsBanner() {+ return (+ <Suspense fallback={<CanaryNotice />}>+ <InternalDocsPrompt />+ </Suspense>+ );+}++function CanaryNotice() {+ const pathname = usePathname();+ return CURRENT_TARGET === 'canary' ? (+ <DocsInfoBanner productionHref={urlForTarget('latest', pathname)} />+ ) : null;+}++export function InternalDocsPrompt() {+ const isReachable = useContext(ReachabilityContext);+ const pathname = usePathname();+ const search = useSearchParams().toString();+ const isCanary = CURRENT_TARGET === 'canary';+ const view = `${pathname}${search ? `?${search}` : ''}`;++ return isCanary || isReachable ? (+ <DocsInfoBanner+ key={view}+ internalHref={+ isReachable ? internalDocsHref(pathname, search) : undefined+ }+ productionHref={isCanary ? urlForTarget('latest', view) : null}+ />+ ) : null;+}++function DocsInfoBanner({+ internalHref,+ productionHref,+}: {+ internalHref?: string;+ productionHref: string | null;+}) {+ const isCanary = CURRENT_TARGET === 'canary';+ return (+ <Banner+ role="region"+ aria-label="Documentation notice"+ container="section"+ status={internalHref ? 'info' : 'warning'}+ isDismissable+ dismissLabel="Dismiss documentation notice for this page view"+ title={+ internalHref+ ? 'Working on Meta internal tools?'+ : "You're viewing Canary docs"+ }+ description={+ <>+ {internalHref &&+ 'Meta internal docs include Meta-specific components and guidance.'}+ {isCanary && internalHref && <br />}+ {isCanary && (+ <>+ These docs may include unreleased components and props. View+ production docs for the latest stable release.+ </>+ )}+ </>+ }+ endContent={+ <>+ {internalHref && (+ <Button+ label="Meta internal docs"+ variant="secondary"+ href={internalHref}+ />+ )}+ {productionHref && (+ <Button+ label="View production"+ variant="secondary"+ href={productionHref}+ />+ )}+ </>+ }+ />+ );+}diff --git a/apps/docsite/src/lib/useInternalDocsPrompt.ts b/apps/docsite/src/lib/useInternalDocsPrompt.tsnew file mode 100644index 0000000000..3064f1c5e7--- /dev/null+++ b/apps/docsite/src/lib/useInternalDocsPrompt.ts@@ -0,0 +1,117 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @input A top-level page and an anonymous iframe's exact-origin reachability message+ * @output A fail-closed, once-per-page-load reachability result+ * @position Client-only detection shared across root-layout remounts+ */++import {useSyncExternalStore} from 'react';++export const ALLOWED_PARENT_ORIGINS: readonly string[] = [+ 'https://astryx.atmeta.com',+ 'https://astryx-git-feat-docs-internal-network-prompt-fbopensource.vercel.app',+ 'https://astryx-canary.vercel.app',+];+export const INTERNAL_DOCS_ORIGIN = 'https://astryx.internalmeta.com';+export const ACCESS_CHECK_ORIGIN = 'https://codebunny.internalmeta.com';+export const ACCESS_CHECK_MESSAGE_TYPE = 'codebunny:access-check:v1';++const listeners = new Set<() => void>();+let attempted = false;+let reachable = false;+let cancelCheck: (() => void) | undefined;++function publishReachability(next: boolean) {+ reachable = next;+ for (const listener of listeners) {+ listener();+ }+}++function startCheck() {+ attempted = true;++ // Embedded documents, including playground previews, must not probe again.+ if (window.top !== window) {+ return;+ }++ // The probe and docs destination are independent origins. Match only the+ // probe's exact parent allowlist, never arbitrary preview/hash domains.+ const parentOrigin = window.location.origin;+ if (!ALLOWED_PARENT_ORIGINS.includes(parentOrigin)) {+ return;+ }++ const frame = document.createElement('iframe');+ frame.hidden = true;+ frame.tabIndex = -1;+ frame.setAttribute('aria-hidden', 'true');+ frame.setAttribute('sandbox', 'allow-scripts allow-same-origin');+ frame.title = 'Astryx documentation reachability check';+ frame.referrerPolicy = 'no-referrer';+ frame.src = `${ACCESS_CHECK_ORIGIN}/embed/access-check?parent_origin=${encodeURIComponent(parentOrigin)}`;++ let loaded = false;+ let received = false;+ const finish = (reachable: boolean) => {+ window.clearTimeout(timeout);+ window.removeEventListener('message', onMessage);+ frame.removeEventListener('load', onLoad);+ frame.remove();+ cancelCheck = undefined;+ publishReachability(reachable);+ };+ const onLoad = () => {+ loaded = true;+ if (received) {+ finish(true);+ }+ };+ const onMessage = (event: MessageEvent) => {+ if (+ event.origin !== ACCESS_CHECK_ORIGIN ||+ event.source !== frame.contentWindow ||+ event.data?.type !== ACCESS_CHECK_MESSAGE_TYPE ||+ event.data?.reachable !== true+ ) {+ return;+ }+ received = true;+ if (loaded) {+ finish(true);+ }+ };+ const timeout = window.setTimeout(() => finish(false), 4000);+ cancelCheck = () => finish(false);+ window.addEventListener('message', onMessage);+ frame.addEventListener('load', onLoad);+ document.body.append(frame);+}++function subscribe(listener: () => void) {+ listeners.add(listener);+ // StrictMode's setup/cleanup/setup finishes before this microtask. It must+ // neither start two probes nor cancel the only probe during effect replay.+ queueMicrotask(() => {+ if (!attempted && listeners.size > 0) {+ startCheck();+ }+ });+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) {+ cancelCheck?.();+ }+ };+}++const getSnapshot = () => reachable;+const getServerSnapshot = () => false;++export function useInternalDocsPrompt() {+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);+}