Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(cli): experimental `astryx experimental render` — a page to one self-contained HTML file, and back (#7958)

Joey7b32a9306345
diff --git a/.changeset/cli-experimental-render.md b/.changeset/cli-experimental-render.md
new file mode 100644
index 0000000000..b4a99e4ebe
--- /dev/null
+++ b/.changeset/cli-experimental-render.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[experimental] New command `astryx experimental render <page>`: renders a page with your installed Astryx components to ONE self-contained HTML file. The file inlines only the Core CSS rules the page uses plus the page's own StyleX styles and local images, runs no script, loads nothing from the network, follows light and dark mode, and carries the page's source. `astryx experimental render --reverse <file.html>` writes that source back byte for byte, rebuilds a page from Astryx markup when the source was removed, and refuses other HTML. Warnings flag what may not look as meant, such as a `ListItem` given children instead of `label`. Experimental commands live under `astryx experimental`, are marked `[experimental]` in help and the manifest, and may change or be removed in any patch release. Guide: `astryx docs cli/experimental/render-pages`.
+
+@josephfarina
diff --git a/apps/docsite/src/__tests__/route-resolution.test.ts b/apps/docsite/src/__tests__/route-resolution.test.ts
index 88c8c0eb92..5e862ccf74 100644
--- a/apps/docsite/src/__tests__/route-resolution.test.ts
+++ b/apps/docsite/src/__tests__/route-resolution.test.ts
@@ -92,7 +92,8 @@ describe('route resolution', () => {
// other topics were split into short guides. `styling-overview` and
// `cli-host-entry` are topics added since; `global` is the Global mode
// page; `authoring` holds what CLI Integrations and Writing docs did;
- // `use-integrations` is the guide for apps that install one.
+ // `use-integrations` is the guide for apps that install one;
+ // `cli-experimental-render-pages` is the experimental render guide.
const sidebarGuides = docTopics
.filter(d => d.category === 'guide' && d.topic !== 'getting-started')
.map(d => d.topic)
@@ -104,6 +105,7 @@ describe('route resolution', () => {
'cli-component-lookups',
'cli-experimental-icon-set-files',
'cli-experimental-icon-sets',
+ 'cli-experimental-render-pages',
'cli-host-entry',
'global',
'internationalization',
diff --git a/packages/cli/api/experimental.mjs b/packages/cli/api/experimental.mjs
new file mode 100644
index 0000000000..c78db407ca
--- /dev/null
+++ b/packages/cli/api/experimental.mjs
@@ -0,0 +1,15 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `@astryxdesign/cli/api/experimental`: the CLI's experimental
+ * functions (spec:AST-017 FR21, FR27). Nothing here is part of the stable
+ * `@astryxdesign/cli/api`; each function and type may change or be removed in
+ * a patch release.
+ *
+ * @position api — the experimental entry beside api/index.mjs
+ */
+
+export {render} from './render/render.mjs';
+
+// Types (runtime no-ops; tsc carries them into api/experimental.d.mts).
+export * from './render/render.type.mjs';
diff --git a/packages/cli/api/render/_adapter.mjs b/packages/cli/api/render/_adapter.mjs
new file mode 100644
index 0000000000..75b706e098
--- /dev/null
+++ b/packages/cli/api/render/_adapter.mjs
@@ -0,0 +1,540 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The `render` subject's adapter: its only access to the environment.
+ * It reads the page or rendered file, runs the renderer, and writes results.
+ *
+ * @position api/render — adapter for api/render/render.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
+import {
+ PAGE_EXTENSIONS,
+ RenderError,
+ renderPage,
+} from '../../foundation/render/render-page.mjs';
+import {readSourceBlock} from '../../foundation/render/source-block.mjs';
+import {embeddedPathProblem, runnerPicksUp} from '../../foundation/render/embedded-files.mjs';
+import {isAssetBytes, isAssetPath} from '../../foundation/render/assets.mjs';
+import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
+import {reachableFiles, receivingAliases} from '../../foundation/render/embedded-imports.mjs';
+import {isAstryxMarkup} from '../../foundation/render/html-reader.mjs';
+import {rebuildPage} from '../../foundation/render/rebuild.mjs';
+import {cliVersion} from '../../foundation/integrations/cli-peer-version.mjs';
+import {assertWithin, PathSafetyError} from '../../foundation/fs/path-safety.mjs';
+
+export {PAGE_EXTENSIONS, embeddedPathProblem};
+
+/** @param {string} cwd @param {string} file */
+const shown = (cwd, file) => {
+ const rel = path.relative(cwd, file);
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel)
+ ? rel.split(path.sep).join('/')
+ : file;
+};
+
+/**
+ * Read a file the caller named, or throw ERR_FILE_NOT_FOUND.
+ * @param {string} file absolute
+ * @param {string} cwd
+ * @returns {Buffer}
+ */
+function readInput(file, cwd) {
+ try {
+ if (!fs.statSync(file).isFile()) throw new Error('not a file');
+ return fs.readFileSync(file);
+ } catch {
+ throw new AstryxError(
+ `${shown(cwd, file)} does not exist`,
+ [],
+ ERROR_CODES.ERR_FILE_NOT_FOUND,
+ );
+ }
+}
+
+/**
+ * Whether @astryxdesign/core resolves from a folder (or the nearest existing
+ * folder above it).
+ * @param {string} dir
+ */
+function resolvesCore(dir) {
+ let d = dir;
+ while (!fs.existsSync(d) && path.dirname(d) !== d) d = path.dirname(d);
+ try {
+ createRequire(path.join(d, 'noop.js')).resolve('@astryxdesign/core');
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Refuse a write outside the current folder, symlinks followed (cli-surface
+ * INV10).
+ * @param {string} file absolute
+ * @param {string} cwd
+ * @param {string} what
+ * @returns {string}
+ */
+function confined(file, cwd, what) {
+ try {
+ return assertWithin(file, cwd, {allowAbsolute: true, label: what});
+ } catch (e) {
+ if (e instanceof PathSafetyError) {
+ throw new AstryxError(
+ `${what} ${shown(cwd, file)} is outside the current folder; nothing was written. Write inside the folder you run the command from.`,
+ [],
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
+ }
+ throw e;
+ }
+}
+
+/**
+ * Refuse, before anything is written, a write that reaches through a
+ * symbolic link, and the replacement of an existing file the project
+ * protects (generated, vendored, ignored, a dependency or version-control
+ * metadata; spec:AST-040 FR2), even with --overwrite.
+ * @param {string[]} files absolute
+ * @param {string} cwd
+ */
+function refuseProtected(files, cwd) {
+ for (const file of files) {
+ let current = cwd;
+ for (const part of path.relative(cwd, file).split(path.sep)) {
+ current = path.join(current, part);
+ let stat;
+ try {
+ stat = fs.lstatSync(current);
+ } catch {
+ break;
+ }
+ if (stat.isSymbolicLink()) {
+ throw new AstryxError(
+ `${shown(cwd, file)} is reached through a symbolic link (${shown(cwd, current)}); nothing was written.`,
+ [],
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
+ }
+ }
+ }
+ const existing = files.filter(file => fs.existsSync(file));
+ if (existing.length === 0) return;
+ /** @type {ReturnType<typeof createFileProtectionResolver>} */
+ let resolver;
+ try {
+ resolver = createFileProtectionResolver(cwd);
+ } catch (e) {
+ throw new AstryxError(
+ `Could not read this project's file protection (${e instanceof Error ? e.message : String(e)}), so no existing file is replaced; nothing was written.`,
+ [],
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+ const blocked = existing.flatMap(file => {
+ const protection = resolver.classify(file)[0];
+ return protection ? [`${shown(cwd, file)} (${protection.declaration})`] : [];
+ });
+ if (blocked.length > 0) {
+ throw new AstryxError(
+ `${blocked.join(', ')} ${blocked.length === 1 ? 'is' : 'are'} protected, so never replaced, even with --overwrite; nothing was written. Choose another --out.`,
+ [],
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+}
+
+/**
+ * Write several files all or nothing: each goes to a temporary file beside
+ * its target first, and only when every one is written are they moved into
+ * place. On a failure, the temporary files and the folders this made are
+ * removed, so nothing is left behind.
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets
+ * @param {string} cwd
+ */
+function writeAll(writes, cwd) {
+ /** @type {string[]} */
+ const madeDirs = [];
+ /** @type {{temp: string, file: string}[]} */
+ const staged = [];
+ const undo = () => {
+ for (const {temp} of staged) fs.rmSync(temp, {force: true});
+ for (const dir of madeDirs.reverse()) {
+ try {
+ fs.rmdirSync(dir);
+ } catch {
+ // Not empty or already gone: leave it.
+ }
+ }
+ };
+ let current = '';
+ try {
+ for (const w of writes) {
+ current = w.file;
+ /** @type {string[]} */
+ const missing = [];
+ for (let d = path.dirname(w.file); !fs.existsSync(d); d = path.dirname(d)) missing.unshift(d);
+ for (const d of missing) {
+ fs.mkdirSync(d);
+ madeDirs.push(d);
+ }
+ const temp = `${w.file}.astryx-${process.pid}.tmp`;
+ fs.writeFileSync(temp, w.bytes, {flag: 'wx'});
+ staged.push({temp, file: w.file});
+ }
+ for (const {temp, file} of staged) {
+ current = file;
+ fs.renameSync(temp, file);
+ }
+ } catch (e) {
+ undo();
+ throw new AstryxError(
+ `Could not write ${shown(cwd, current)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
+ [],
+ ERROR_CODES.ERR_WRITE_FAILED,
+ );
+ }
+}
+
+/**
+ * Write one file, creating its folder.
+ * @param {string} file absolute
+ * @param {string | Buffer} content
+ * @param {string} cwd
+ */
+function writeOutput(file, content, cwd) {
+ try {
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, content);
+ } catch (e) {
+ throw new AstryxError(
+ `Could not write ${shown(cwd, file)}: ${/** @type {Error} */ (e).message}`,
+ [],
+ ERROR_CODES.ERR_WRITE_FAILED,
+ );
+ }
+}
+
+/** @param {unknown} e */
+function asAstryxError(e) {
+ if (e instanceof RenderError) {
+ const code = /** @type {import('../../foundation/response/error-codes.mjs').ErrorCode} */ (e.code);
+ /** @type {{name: string, reason: string}[]} */
+ const suggestions = [];
+ if (e.code === 'ERR_RENDER_MISSING_DEPENDENCY' && typeof e.detail?.package === 'string') {
+ suggestions.push({name: `npm install ${e.detail.package}`, reason: 'install the package the page imports'});
+ }
+ return new AstryxError(e.message, suggestions, code);
+ }
+ const err = /** @type {any} */ (e);
+ if (typeof err?.code === 'string' && err.code.startsWith('ERR_RENDER_')) {
+ return new AstryxError(err.message, [], err.code);
+ }
+ return e;
+}
+
+/**
+ * Render a page module to one HTML file and write it.
+ * @param {{cwd: string, input: string, output: string, title?: string}} args absolute paths
+ * @returns {Promise<import('./render.type.mjs').RenderPageResponse['data']>}
+ */
+export async function renderToFile({cwd, input, output, title}) {
+ readInput(input, cwd);
+ confined(output, cwd, 'The output');
+ /** @type {import('../../foundation/render/render-page.mjs').RenderedPage} */
+ let page;
+ try {
+ page = await renderPage(input, {title, version: cliVersion()});
+ } catch (e) {
+ throw asAstryxError(e);
+ }
+ refuseProtected([output], cwd);
+ // An existing file is replaced only when a render wrote it.
+ if (
+ fs.existsSync(output) &&
+ fs.statSync(output).isFile() &&
+ !/<meta name="generator" content="Astryx[ "]/.test(fs.readFileSync(output, 'utf8').slice(0, 4096))
+ ) {
+ throw new AstryxError(
+ `${shown(cwd, output)} already exists and was not written by a render, so it is not replaced; nothing was written. Choose another --out.`,
+ [],
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+ writeOutput(output, page.html, cwd);
+ return {
+ input: shown(cwd, input),
+ output: shown(cwd, output),
+ bytes: Buffer.byteLength(page.html),
+ files: page.files,
+ stylesheets: page.stylesheets,
+ classes: page.classes,
+ cssBytes: page.cssBytes,
+ images: page.images,
+ warnings: page.warnings,
+ };
+}
+
+/**
+ * Refuse files a test, story or benchmark runner would run where they land,
+ * judged from the repository root (every folder above the file up to it),
+ * else the topmost folder with a package.json, else the current folder.
+ * @param {string[]} files absolute
+ * @param {string} cwd
+ * @param {string} input
+ */
+function refuseRunnable(files, cwd, input) {
+ /** @param {string} marker */
+ const nearest = marker => {
+ for (let d = cwd; ; d = path.dirname(d)) {
+ if (fs.existsSync(path.join(d, marker))) return d;
+ if (path.dirname(d) === d) return null;
+ }
+ };
+ let topPackage = null;
+ for (let d = cwd; ; d = path.dirname(d)) {
+ if (fs.existsSync(path.join(d, 'package.json'))) topPackage = d;
+ if (path.dirname(d) === d) break;
+ }
+ const projectRoot = nearest('.git') ?? topPackage ?? cwd;
+ const runnable = files
+ .map(file => path.relative(projectRoot, file).split(path.sep))
+ .filter(segments => runnerPicksUp(segments))
+ .map(segments => segments.join('/'));
+ if (runnable.length > 0) {
+ throw new AstryxError(
+ `${shown(cwd, input)} would write ${runnable.join(', ')} (from the project root), where a test, story or benchmark runner would run it; nothing was written. Restore it somewhere else with --out.`,
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+}
+
+/**
+ * The new folder a restore without --out writes into: beside the HTML file,
+ * named after it (`report.html` gives `report-restored/`, then
+ * `report-restored-2/` when that exists).
+ * @param {string} input absolute
+ */
+function restoreFolder(input) {
+ const stem = path.basename(input).replace(/\.[^.]+$/, '');
+ let folder = path.join(path.dirname(input), `${stem}-restored`);
+ for (let n = 2; fs.existsSync(folder); n++) folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
+ return folder;
+}
+
+/**
+ * Turn a rendered HTML file back into a page module.
+ * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
+ * @returns {import('./render.type.mjs').RenderReverseResponse['data']}
+ */
+export function reverseToFile({cwd, input, output, overwrite}) {
+ const html = readInput(input, cwd).toString('utf8');
+ const block = readSourceBlock(html);
+ /** @param {string[]} files */
+ const refuseExisting = files => {
+ if (overwrite) return;
+ const existing = files.filter(file => fs.existsSync(file));
+ if (existing.length > 0) {
+ throw new AstryxError(
+ `${existing.map(file => shown(cwd, file)).join(', ')} already exist${existing.length === 1 ? 's' : ''}; nothing was written. Pass --overwrite to replace ${existing.length === 1 ? 'it' : 'them'}.`,
+ [],
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+ };
+ /** A page is never written as a configuration, test, spec or story file. @param {string} file */
+ const refuseConfigTarget = file => {
+ const rel = path.relative(cwd, file).split(path.sep).join('/');
+ const where = rel.startsWith('..') || path.isAbsolute(rel) ? path.basename(file) : rel;
+ // Where the page lands must be a page module, and a name no tool takes
+ // as its own (configuration, a runner's file): the same rules as any
+ // file a restore writes.
+ const problem = embeddedPathProblem(where, {page: true}) ?? embeddedPathProblem(where);
+ if (problem) {
+ throw new AstryxError(
+ `${shown(cwd, file)} is not a page module file name a reverse writes (${problem.reason}); nothing was written.`,
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ };
+ if (block.found && 'damaged' in block) {
+ throw new AstryxError(
+ `${shown(cwd, input)} carries an Astryx page source, but ${block.damaged}, so it cannot be given back exactly.`,
+ [],
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
+ );
+ }
+ if (block.found) {
+ const {source} = block;
+ // A file someone sends is untrusted: it may carry only what a render
+ // embeds (the page, and the stylesheets, JSON and images it imports).
+ source.files.forEach((f, i) => {
+ const problem = embeddedPathProblem(f.path, {page: i === 0});
+ if (problem) {
+ throw new AstryxError(
+ `${shown(cwd, input)} carries ${problem.reason}, which a render never embeds; nothing was written.`,
+ [],
+ ERROR_CODES[problem.code],
+ );
+ }
+ });
+ // Without --out, the page and the files it imports come back into a new
+ // folder beside the HTML file, named after it (`report.html` gives
+ // `report-restored/`), with the layout they were rendered in. Nothing in
+ // the received file decides where in your project anything goes.
+ const requested = output ?? path.join(restoreFolder(input), ...source.files[0].path.split('/'));
+ refuseConfigTarget(requested);
+ const seen = new Set();
+ for (const f of source.files) {
+ const key = f.path.toLowerCase();
+ if (seen.has(key)) {
+ throw new AstryxError(
+ `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
+ [],
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
+ );
+ }
+ seen.add(key);
+ }
+ // Modules, stylesheets and JSON are written only when the page reaches
+ // them through its own imports: one it never imports is not part of it,
+ // whatever its name.
+ const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(path.dirname(requested))});
+ // A carried image, font or media file needs no import to be part of the
+ // page (it may be named in markup, a stylesheet, JSON or a computed
+ // path): the render's own list is the authority, so it is kept when its
+ // bytes are a known image, font or media format (any, whatever the
+ // extension), and goes where the layout puts it.
+ for (const f of source.files) {
+ if (reached.has(f.path) || !isAssetPath(f.path)) continue;
+ if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
+ }
+ const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
+ if (stray.length > 0) {
+ throw new AstryxError(
+ `${shown(cwd, input)} carries ${stray.length === 1 ? 'a file' : 'files'} the page does not import, or that is not the image, font or media file its name says (${stray.join(', ')}), which a render never embeds; nothing was written. A file reached through a path alias needs the same alias in this project's tsconfig.json or jsconfig.json.`,
+ [],
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
+ );
+ }
+ // Each file the page reaches by a relative import goes where that import
+ // finds it from the page's new folder, so every relative import still
+ // resolves wherever the page lands; a file reached through an alias goes
+ // where this project's alias points. Every file but the page must land
+ // in a folder this restore creates: a received file never adds a file to
+ // a folder that already exists (a server hook at the project root, a
+ // middleware module), so a page with neighbours comes back into a new
+ // folder.
+ const entryDir = path.posix.dirname(source.files[0].path);
+ const anchor = path.dirname(requested);
+ /** @param {string} p */
+ const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
+ // A file beside the page or elsewhere goes only into a folder this
+ // restore creates: never into a folder that already exists.
+ // The one folder every file but the page must land in: the topmost
+ // folder on the page's path that this restore creates. When the page's
+ // folder already exists there is none, so a page with neighbours comes
+ // back only into a new folder.
+ /** @type {string | null} */
+ let home = null;
+ for (let d = anchor; !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) home = d;
+ const within = (/** @type {string} */ file) => {
+ if (!home) return false;
+ const rel = path.relative(home, file);
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
+ };
+ const target = path.join(anchor, path.basename(requested));
+ /** @type {{file: string, bytes: Buffer}[]} */
+ const writes = [];
+ const placed = new Set();
+ /** @type {string[]} */
+ const outside = [];
+ /** @type {string[]} */
+ const aliasedOutside = [];
+ source.files.forEach((f, i) => {
+ const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
+ const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
+ for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
+ if (placed.has(file)) continue;
+ placed.add(file);
+ if (i > 0 && !within(file)) (aliased ? aliasedOutside : outside).push(file);
+ writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
+ }
+ });
+ if (aliasedOutside.length > 0) {
+ throw new AstryxError(
+ `${shown(cwd, input)} imports ${aliasedOutside.map(file => shown(cwd, file)).join(', ')} through a path alias that points outside the folder the restore creates; nothing was written. A received page never adds files to your existing folders: change those imports to relative ones before rendering, or restore it in a project whose alias points somewhere new.`,
+ [],
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
+ }
+ if (outside.length > 0) {
+ const top = entryDir === '.' ? '' : `${entryDir}/`;
+ let fresh = 'restored';
+ for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
+ const suggestion = `--out ${fresh}/${top}${path.basename(requested)}`;
+ throw new AstryxError(
+ `${shown(cwd, input)} would add ${outside.map(file => shown(cwd, file)).join(', ')} outside the folder the restore creates; nothing was written. A received page writes the files it imports only inside one new folder: restore it into one, such as ${suggestion}.`,
+ [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
+ }
+ writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
+ refuseRunnable(writes.map(w => w.file), cwd, input);
+ refuseExisting(writes.map(w => w.file));
+ refuseProtected(writes.map(w => w.file), cwd);
+ writeAll(writes, cwd);
+ return {
+ input: shown(cwd, input),
+ mode: 'embedded',
+ output: shown(cwd, target),
+ files: writes.map(w => shown(cwd, w.file)),
+ // The page is byte for byte the one rendered; an import it makes that
+ // the file does not carry (a file a render never embeds) is named.
+ exact: missing.length === 0,
+ ...(missing.length > 0 ? {missing} : {}),
+ };
+ }
+ if (!isAstryxMarkup(html)) {
+ throw new AstryxError(
+ `${shown(cwd, input)} is not an Astryx page: it has no embedded source and no Astryx components to rebuild from. To start an Astryx page like it, run astryx build "<what the page is>".`,
+ [
+ {
+ name: 'astryx build "<what the page is>"',
+ reason: 'start an Astryx page from a description of it instead',
+ },
+ ],
+ ERROR_CODES.ERR_RENDER_NOT_ASTRYX,
+ );
+ }
+ const target = output ?? path.join(restoreFolder(input), 'page.tsx');
+ refuseConfigTarget(target);
+ confined(target, cwd, 'The page');
+ refuseRunnable([target], cwd, input);
+ refuseExisting([target]);
+ // Components resolve from where the page will live, then from the HTML
+ // file's folder, then from the current folder.
+ const from =
+ [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
+ const rebuilt = rebuildPage(html, from);
+ refuseProtected([target], cwd);
+ writeOutput(target, rebuilt.source, cwd);
+ return {
+ input: shown(cwd, input),
+ mode: 'rebuilt',
+ output: shown(cwd, target),
+ files: [shown(cwd, target)],
+ exact: false,
+ components: rebuilt.components,
+ elements: rebuilt.elements,
+ unknown: rebuilt.unknown,
+ omitted: rebuilt.omitted,
+ };
+}
diff --git a/packages/cli/api/render/render.doc.mjs b/packages/cli/api/render/render.doc.mjs
new file mode 100644
index 0000000000..00c4298390
--- /dev/null
+++ b/packages/cli/api/render/render.doc.mjs
@@ -0,0 +1,112 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `render()` / `astryx experimental render`.
+ * @position packages/cli/api/render — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'render',
+ namespace: 'cli/api',
+ stability: 'experimental',
+ displayName: 'render()',
+ summary:
+ 'Render a page to one self-contained HTML file, or turn a rendered file back into a page.',
+ description:
+ "Renders the page module's default export on the server with the project's own React and Astryx components, and writes ONE static HTML file that needs nothing beside it: the page's own StyleX styles are compiled, Core's stylesheets are cut to the rules the markup uses (layer order, custom properties and keyframes kept), local images become data: URIs, and the page's source is embedded so it can be given back exactly. The file runs no script and loads nothing from the network, so it works inside a sandboxed frame with a strict content security policy, and its colors follow the viewer's light or dark scheme. Warnings name anything that may differ from what the author meant, such as a component that did not render the text it was given. With `reverse`, it writes the embedded source back byte for byte, and only the files a render embeds: the page and the local modules, stylesheets, JSON files and images it imports, into a new folder; a file with Astryx markup but no embedded source is rebuilt from its component class names and data attributes (text and layout only); any other file is refused. Experimental: it may change or be removed in a patch release.",
+ importPath: '@astryxdesign/cli/api/experimental',
+ signature:
+ 'render(file: string, options?: RenderOptions): Promise<RenderPageResponse | RenderReverseResponse>',
+ keywords: [
+ 'render',
+ 'static',
+ 'html',
+ 'export',
+ 'artifact',
+ 'snapshot',
+ 'self-contained',
+ 'reverse',
+ ],
+ params: [
+ {
+ name: 'file',
+ type: 'string',
+ description:
+ 'The page module (.tsx, .jsx, .ts, .js or .mjs) with a default export, or with `reverse` the rendered .html file.',
+ },
+ {
+ name: 'options.out',
+ type: 'string',
+ description:
+ "The file to write. Rendering: an .html file (default: the page's name with .html). Reversing: a page module (default: inside a new folder beside the HTML file, named after it, such as `report-restored/`).",
+ },
+ {
+ name: 'options.reverse',
+ type: 'boolean',
+ description: 'Turn a rendered HTML file back into a page module.',
+ default: 'false',
+ },
+ {
+ name: 'options.title',
+ type: 'string',
+ description:
+ "The rendered page's title (default: its first top-level heading, else the file name). Rendering only.",
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description:
+ 'Replace the existing page module when reversing (never a protected file, and never a file other than the page, which always goes into a new folder). Rendering replaces an existing HTML file only when a render wrote it.',
+ default: 'false',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Folder relative paths resolve from (default: the current directory).',
+ },
+ ],
+ returns: [
+ {
+ type: 'render.page',
+ description:
+ 'The page and the HTML file written, its size, the local modules embedded, the stylesheets inlined, the class and image counts, the CSS size, and any warnings.',
+ },
+ {
+ type: 'render.reverse',
+ description:
+ "How the page came back (`embedded`, exact; or `rebuilt`, text and layout only), the files written, and for a rebuilt page the components it uses and what could not be rebuilt.",
+ },
+ ],
+ throws: [
+ {code: 'ERR_MISSING_ARGUMENT', when: 'no file is given'},
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'the file or `out` has the wrong kind of extension, `out` is the input itself, `title` is given with `reverse`, or `overwrite` without it; with `reverse`, the page would land under a configuration name (`vite.config.ts`) or where a test, story or benchmark runner would run it (judged from the repository root)',
+ },
+ {code: 'ERR_FILE_NOT_FOUND', when: 'the file, or a local file the page imports, does not exist'},
+ {code: 'ERR_FILE_EXISTS', when: 'rendering would replace an existing file a render did not write, reversing would replace an existing file and `overwrite` is not set, or an existing file the project protects (generated, vendored or ignored) would be replaced, which `overwrite` never does'},
+ {code: 'ERR_WRITE_FAILED', when: 'a file cannot be written, such as when `out` names a folder; with `reverse`, every file is written or none is'},
+ {code: 'ERR_RENDER_COMPILE', when: 'the page does not compile, or a stylesheet it imports is not valid CSS (the message names the file)'},
+ {code: 'ERR_RENDER_NO_DEFAULT_EXPORT', when: 'the page has no default export'},
+ {code: 'ERR_RENDER_MISSING_DEPENDENCY', when: 'the page imports a package that is not installed; the suggestion is its install line'},
+ {code: 'ERR_RENDER_BROWSER_API', when: 'the page reads a browser-only API, such as window or document, while rendering'},
+ {code: 'ERR_RENDER_ASSET_TOO_LARGE', when: 'a local file the page uses is over 8 MB'},
+ {code: 'ERR_RENDER_TIMEOUT', when: 'the page does not finish rendering within 60 seconds'},
+ {code: 'ERR_RENDER_FAILED', when: 'the page throws while rendering for any other reason'},
+ {
+ code: 'ERR_RENDER_NOT_ASTRYX',
+ when: 'reversing a file with no embedded source and no Astryx markup; the suggestion is `astryx build "<what the page is>"`',
+ },
+ {code: 'ERR_RENDER_SOURCE_DAMAGED', when: 'reversing a file whose embedded source is damaged, lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds (a dotfile or dot-folder, `node_modules`, a package manifest, lockfile or tool configuration, or any kind but a page module, stylesheet, JSON or image)'},
+ {code: 'ERR_PATH_TRAVERSAL', when: 'a file would be written outside the current folder (symlinks followed), or through a symbolic link: `out`, or with `reverse` the page or an embedded file; or, with `reverse`, a file other than the page would go into a folder that already exists'},
+ ],
+ examples: [
+ {label: 'Render a page', code: "const {data} = await render('src/app/page.tsx', {out: 'page.html'});"},
+ {label: 'Give it back', code: "await render('page.html', {reverse: true, out: 'page.tsx'});"},
+ ],
+ command: 'experimental render',
+ related: ['template', 'build'],
+};
diff --git a/packages/cli/api/render/render.mjs b/packages/cli/api/render/render.mjs
new file mode 100644
index 0000000000..b117ec5049
--- /dev/null
+++ b/packages/cli/api/render/render.mjs
@@ -0,0 +1,113 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Programmatic API for `astryx experimental render`: a page module to
+ * one self-contained HTML file, and back.
+ *
+ * render('page.tsx') render.page: write page.html
+ * render('page.html', {reverse: true}) render.reverse: write page.tsx
+ *
+ * @input a page module or a rendered HTML file, and options
+ * @output render.page | render.reverse envelope
+ * @position api/render — leaf; command wrapper in
+ * clients/cli/commands/experimental/render.mjs
+ */
+
+import * as path from 'node:path';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
+import {PAGE_EXTENSIONS, embeddedPathProblem, renderToFile, reverseToFile} from './_adapter.mjs';
+
+/**
+ * Render a page module to one self-contained HTML file, or turn a rendered
+ * file back into a page module.
+ *
+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch
+ * release.
+ * @experimental
+ * @param {string} file the page module, or with `reverse` the HTML file
+ * @param {import('./render.type.mjs').RenderOptions} [options]
+ * @returns {Promise<import('./render.type.mjs').RenderPageResponse | import('./render.type.mjs').RenderReverseResponse>}
+ */
+export async function render(file, options = {}) {
+ const {cwd = process.cwd(), reverse = false, overwrite = false, title} = options;
+ if (typeof file !== 'string' || !file.trim()) {
+ throw new AstryxError(
+ reverse ? 'A rendered HTML file is required' : 'A page file is required',
+ [
+ reverse
+ ? {name: 'astryx experimental render --reverse page.html', reason: 'turn a rendered file back into a page'}
+ : {name: 'astryx experimental render page.tsx', reason: 'render a page to one HTML file'},
+ ],
+ ERROR_CODES.ERR_MISSING_ARGUMENT,
+ );
+ }
+ const input = path.resolve(cwd, file);
+ const output = options.out ? path.resolve(cwd, options.out) : undefined;
+ if (output && output === input) {
+ throw new AstryxError(
+ '--out names the input file itself; choose another file',
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (reverse) {
+ if (title != null) {
+ throw new AstryxError('--title applies only to rendering, not to --reverse', [], ERROR_CODES.ERR_INVALID_ARGUMENT);
+ }
+ if (!/\.html?$/i.test(input)) {
+ throw new AstryxError(
+ `--reverse reads a rendered .html file; ${file} is not one`,
+ [{name: `astryx experimental render ${file}`, reason: 'render the page instead'}],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (output && !PAGE_EXTENSIONS.includes(path.extname(output).toLowerCase())) {
+ throw new AstryxError(
+ `--out for --reverse must be a page module (${PAGE_EXTENSIONS.join(', ')})`,
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ const outProblem = output
+ ? (embeddedPathProblem(path.basename(output), {page: true}) ?? embeddedPathProblem(path.basename(output)))
+ : null;
+ if (output && outProblem) {
+ throw new AstryxError(
+ `--out for --reverse must name a page module, not ${outProblem.reason}`,
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ return {
+ type: 'render.reverse',
+ data: reverseToFile({cwd, input, output, overwrite}),
+ };
+ }
+ if (!PAGE_EXTENSIONS.includes(path.extname(input).toLowerCase())) {
+ throw new AstryxError(
+ /\.html?$/i.test(input)
+ ? `${file} is already HTML; pass --reverse to turn it back into a page`
+ : `render reads a page module (${PAGE_EXTENSIONS.join(', ')}); ${file} is not one`,
+ /\.html?$/i.test(input)
+ ? [{name: `astryx experimental render --reverse ${file}`, reason: 'turn it back into a page'}]
+ : [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (overwrite) {
+ throw new AstryxError(
+ '--overwrite applies only to --reverse; rendering replaces an existing HTML file only when a render wrote it',
+ [],
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
+ );
+ }
+ if (output && !/\.html?$/i.test(output)) {
+ throw new AstryxError('--out must be an .html file', [], ERROR_CODES.ERR_INVALID_ARGUMENT);
+ }
+ const target = output ?? input.replace(/\.[^.]+$/, '.html');
+ return {
+ type: 'render.page',
+ data: await renderToFile({cwd, input, output: target, title}),
+ };
+}
diff --git a/packages/cli/api/render/render.test.mjs b/packages/cli/api/render/render.test.mjs
new file mode 100644
index 0000000000..5e9d24f353
--- /dev/null
+++ b/packages/cli/api/render/render.test.mjs
@@ -0,0 +1,1155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for render() (`astryx experimental render`): a page to one
+ * self-contained HTML file and back, each refusal, and the warnings.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+import {render} from './render.mjs';
+import {runCli} from '../../test-utils/run-cli.mjs';
+
+const CLI_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+
+/** @type {string} */
+let dir;
+
+/** @param {string} name @param {string | Buffer} content */
+const put = (name, content) => {
+ const file = path.join(dir, name);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, content);
+ return file;
+};
+
+/** @param {() => Promise<unknown>} fn */
+async function codeOf(fn) {
+ try {
+ await fn();
+ } catch (e) {
+ return /** @type {any} */ (e).code;
+ }
+ return 'no error';
+}
+
+// A 1×1 PNG.
+const PNG = Buffer.from(
+ '89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d4944415478da6364f8cf00000301010018dd8db40000000049454e44ae426082',
+ 'hex',
+);
+
+const PAGE = `import * as stylex from '@stylexjs/stylex';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {Button} from '@astryxdesign/core/Button';
+import dot from './dot.png';
+
+const styles = stylex.create({box: {padding: 12}});
+
+export default function Page() {
+ return (
+ <div {...stylex.props(styles.box)}>
+ <Heading level={1}>Café ✓ report</Heading>
+ <Text>{'</script><script>alert(1)</script>'}</Text>
+ <img src={dot} alt="" />
+ <List>
+ <ListItem>Dropped child text</ListItem>
+ <ListItem label="Kept label" />
+ </List>
+ <Button>Go</Button>
+ </div>
+ );
+}
+`;
+
+beforeAll(async () => {
+ dir = fs.mkdtempSync(path.join(CLI_DIR, '.astryx-render-test-'));
+ put('dot.png', PNG);
+ put('page.tsx', PAGE);
+ put('plain.html', '<!doctype html><html><body><h1>Hello</h1><p class="lead">Hi</p></body></html>');
+ // Every test can read the rendered page, whatever runs first.
+ await render('page.tsx', {cwd: dir});
+}, 60_000);
+
+afterAll(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+describe('render(): page to one HTML file', () => {
+ /** @type {import('./render.type.mjs').RenderPageResponse} */
+ let result;
+ /** @type {string} */
+ let html;
+
+ beforeAll(async () => {
+ result = /** @type {any} */ (await render('page.tsx', {cwd: dir}));
+ html = fs.readFileSync(path.join(dir, 'page.html'), 'utf8');
+ }, 60_000);
+
+ it('answers render.page and writes beside the page by default', () => {
+ expect(result.type).toBe('render.page');
+ expect(result.data.output).toBe('page.html');
+ expect(result.data.files).toEqual(['page.tsx', 'dot.png']);
+ expect(result.data.bytes).toBe(Buffer.byteLength(html));
+ expect(result.data.stylesheets).toContain('@astryxdesign/core/astryx.css');
+ });
+
+ it('is one static file: no external references, no running script', () => {
+ expect(html).not.toMatch(/<link\b/i);
+ expect(html).not.toMatch(/\ssrc="(?!data:)/);
+ const scripts = [...html.matchAll(/<script\b([^>]*)>/gi)].map(m => m[1]);
+ expect(scripts).toEqual([' type="application/x-astryx-source"']);
+ });
+
+ it('keeps text safe and the page title from its heading', () => {
+ expect(html).toContain('<title>Café ✓ report</title>');
+ expect(html).toContain('&lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt;');
+ });
+
+ it('inlines CSS for the classes it uses, its own StyleX, and the layer order once', () => {
+ const style = /<style>([\s\S]*?)<\/style>/.exec(html)?.[1] ?? '';
+ expect(style).toMatch(/^:root\{color-scheme:light dark\}/);
+ expect(style.match(/@layer reset, astryx-base, astryx-theme;/g)).toHaveLength(1);
+ expect(style).toContain('padding:12px');
+ const classes = new Set(
+ [...html.matchAll(/\sclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/)),
+ );
+ const astryx = [...classes].filter(c => c.startsWith('astryx-'));
+ expect(astryx.length).toBeGreaterThan(0);
+ // Core's stylesheet is cut: a component the page does not use is absent.
+ expect(style).not.toContain('.astryx-calendar');
+ });
+
+ it('inlines a local image as a data: URI', () => {
+ expect(result.data.images).toBe(1);
+ expect(html).toContain('src="data:image/png;base64,');
+ });
+
+ it('warns when a component drops the text it was given', () => {
+ const dropped = result.data.warnings.filter(w => w.code === 'dropped-children');
+ expect(dropped).toHaveLength(1);
+ expect(dropped[0].message).toContain('ListItem');
+ expect(dropped[0].message).toContain('label=');
+ });
+
+ it('gives the page back byte for byte', async () => {
+ const back = /** @type {any} */ (
+ await render('page.html', {cwd: dir, reverse: true, out: 'back/page.tsx'})
+ );
+ expect(back.type).toBe('render.reverse');
+ expect(back.data).toMatchObject({mode: 'embedded', exact: true, output: 'back/page.tsx'});
+ expect(fs.readFileSync(path.join(dir, 'back/page.tsx'))).toEqual(
+ fs.readFileSync(path.join(dir, 'page.tsx')),
+ );
+ });
+
+ it('refuses to replace a page without --overwrite, and never adds neighbours to a folder that exists', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('alone-page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [{path: 'page.tsx', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ await render('alone-page.html', {cwd: dir, reverse: true, out: 'twice/page.tsx'});
+ expect(await codeOf(() => render('alone-page.html', {cwd: dir, reverse: true, out: 'twice/page.tsx'}))).toBe(
+ 'ERR_FILE_EXISTS',
+ );
+ const again = /** @type {any} */ (
+ await render('alone-page.html', {cwd: dir, reverse: true, out: 'twice/page.tsx', overwrite: true})
+ );
+ expect(again.data.mode).toBe('embedded');
+ // A page with a neighbour (its image) comes back only into a new folder.
+ await render('page.html', {cwd: dir, reverse: true, out: 'twice-img/page.tsx'});
+ expect(
+ await codeOf(() => render('page.html', {cwd: dir, reverse: true, out: 'twice-img/page.tsx', overwrite: true})),
+ ).toBe('ERR_PATH_TRAVERSAL');
+ });
+
+
+ it('rebuilds a page from Astryx markup when there is no embedded source', async () => {
+ put('stripped.html', html.replace(/<script type="application\/x-astryx-source">[\s\S]*?<\/script>/, ''));
+ const rebuilt = /** @type {any} */ (await render('stripped.html', {cwd: dir, reverse: true}));
+ expect(rebuilt.data).toMatchObject({mode: 'rebuilt', exact: false, output: 'stripped-restored/page.tsx'});
+ expect(rebuilt.data.components).toEqual(expect.arrayContaining(['Button', 'Heading', 'List']));
+ const source = fs.readFileSync(path.join(dir, 'stripped-restored/page.tsx'), 'utf8');
+ expect(source).toContain("from '@astryxdesign/core/Button'");
+ expect(source).toContain('Café ✓ report');
+ // The rebuilt page renders.
+ const again = /** @type {any} */ (await render('stripped-restored/page.tsx', {cwd: dir}));
+ expect(again.type).toBe('render.page');
+ }, 60_000);
+
+ it('refuses HTML that is not an Astryx page, naming the next step', async () => {
+ put('plain.html', '<!doctype html><html><body><h1>Hello</h1><p class="lead">Hi</p></body></html>');
+ /** @type {any} */
+ let error;
+ try {
+ await render('plain.html', {cwd: dir, reverse: true});
+ } catch (e) {
+ error = e;
+ }
+ expect(error.code).toBe('ERR_RENDER_NOT_ASTRYX');
+ expect(error.suggestions[0].name).toBe('astryx build "<what the page is>"');
+ });
+
+ it('refuses a damaged embedded source', async () => {
+ put(
+ 'damaged.html',
+ html.replace(/"base64":"[^"]{4}/, '"base64":"AAAA'),
+ );
+ expect(await codeOf(() => render('damaged.html', {cwd: dir, reverse: true}))).toBe(
+ 'ERR_RENDER_SOURCE_DAMAGED',
+ );
+ });
+});
+
+describe('render(): embedded files stay inside the current folder', () => {
+ it('refuses an embedded path that climbs out', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put(
+ 'escape.html',
+ `<!doctype html><html><body><p class="astryx-text">x</p>${sourceBlock('p.tsx', [
+ {path: 'p.tsx', bytes: Buffer.from('export default () => null;')},
+ {path: '../../../escaped.tsx', bytes: Buffer.from('x')},
+ ])}</body></html>`,
+ );
+ expect(await codeOf(() => render('escape.html', {cwd: dir, reverse: true, out: 'esc/p.tsx'}))).toBe(
+ 'ERR_PATH_TRAVERSAL',
+ );
+ expect(fs.existsSync(path.join(dir, 'esc/p.tsx'))).toBe(false);
+ });
+});
+
+describe('render(): what a page imports', () => {
+ it('inlines an imported theme stylesheet, embeds local CSS, JSON and images, and gives them all back', async () => {
+ put('node_modules/@acme/theme/package.json', JSON.stringify({name: '@acme/theme', version: '1.0.0'}));
+ put('node_modules/@acme/theme/theme.css', ':root{--acme-brand:#123456}.acme-unused{color:red}');
+ put('site/local.css', '.site-title{letter-spacing:2px}');
+ put('site/data.json', JSON.stringify({title: 'From JSON'}));
+ put('site/dot.png', PNG);
+ put(
+ 'site/page.tsx',
+ `import '@acme/theme/theme.css';
+import './local.css';
+import data from './data.json';
+import dot from './dot.png';
+export default function Page() {
+ return (<main><h1 className="site-title">{data.title}</h1><img src={dot} alt="" /><a href="https://example.com/docs">Docs</a></main>);
+}
+`,
+ );
+ const result = /** @type {any} */ (await render('site/page.tsx', {cwd: dir}));
+ expect(result.data.stylesheets).toContain('@acme/theme/theme.css');
+ expect(result.data.files).toEqual(expect.arrayContaining(['page.tsx', 'local.css', 'data.json', 'dot.png']));
+ // A plain link loads nothing, so it is not a remote-asset warning.
+ expect(result.data.warnings.filter((/** @type {any} */ w) => w.code === 'remote-asset')).toEqual([]);
+ const html = fs.readFileSync(path.join(dir, 'site/page.html'), 'utf8');
+ expect(html).toContain('--acme-brand:#123456');
+ expect(html).not.toContain('.acme-unused');
+ expect(html).toContain('letter-spacing:2px');
+ expect(html).toContain('From JSON');
+ fs.copyFileSync(path.join(dir, 'site/page.html'), path.join(dir, 'moved.html'));
+ const back = /** @type {any} */ (await render('moved.html', {cwd: dir, reverse: true, out: 'moved/page.tsx'}));
+ expect(back.data.files.sort()).toEqual(
+ ['moved/data.json', 'moved/dot.png', 'moved/local.css', 'moved/page.tsx'].sort(),
+ );
+ for (const name of ['page.tsx', 'local.css', 'data.json', 'dot.png']) {
+ expect(fs.readFileSync(path.join(dir, 'moved', name))).toEqual(fs.readFileSync(path.join(dir, 'site', name)));
+ }
+ // The moved copy renders the same page again.
+ const again = /** @type {any} */ (await render('moved/page.tsx', {cwd: dir}));
+ expect(fs.readFileSync(path.join(dir, 'moved/page.html'), 'utf8')).toContain('From JSON');
+ expect(again.type).toBe('render.page');
+ }, 60_000);
+
+ it('uses an explicit --title', async () => {
+ const r = /** @type {any} */ (await render('page.tsx', {cwd: dir, out: 'titled.html', title: 'Q3 <report>'}));
+ expect(r.data.output).toBe('titled.html');
+ expect(fs.readFileSync(path.join(dir, 'titled.html'), 'utf8')).toContain('<title>Q3 &lt;report&gt;</title>');
+ }, 60_000);
+});
+
+describe('render(): every write stays inside the current folder', () => {
+ it('refuses an embedded entry path that climbs out', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ fs.mkdirSync(path.join(dir, 'inner'), {recursive: true});
+ put(
+ 'inner/entry.html',
+ `<body><p class="astryx-text">x</p>${sourceBlock('../../../outside.tsx', [
+ {path: '../../../outside.tsx', bytes: Buffer.from('export default () => null;')},
+ ])}</body>`,
+ );
+ expect(await codeOf(() => render('inner/entry.html', {cwd: dir, reverse: true}))).toBe('ERR_PATH_TRAVERSAL');
+ expect(fs.existsSync(path.join(dir, 'inner/outside.tsx'))).toBe(false);
+ });
+
+ it('gives back a page that imports from a parent folder, keeping the layout inside the current folder', async () => {
+ put('tree/src/components/Footer.tsx', 'export function Footer() { return <p>Parent footer</p>; }\n');
+ put(
+ 'tree/src/app/page.tsx',
+ "import {Footer} from '../components/Footer';\nexport default function Page() { return <main><h1>Tree</h1><Footer /></main>; }\n",
+ );
+ const cwd = path.join(dir, 'tree/src/app');
+ const r = /** @type {any} */ (await render('page.tsx', {cwd}));
+ expect(r.data.files).toEqual(['app/page.tsx', 'components/Footer.tsx']);
+ // From the page's own folder, the neighbour would land outside it, beside
+ // existing files: refused, naming a new folder to restore into.
+ /** @type {any} */
+ let refused;
+ try {
+ await render('page.html', {cwd, reverse: true, out: 'back.tsx'});
+ } catch (e) {
+ refused = e;
+ }
+ expect(refused?.code).toBe('ERR_PATH_TRAVERSAL');
+ expect(refused.message).toContain('--out restored/app/back.tsx');
+ expect(fs.existsSync(path.join(cwd, 'back.tsx'))).toBe(false);
+ const back = /** @type {any} */ (await render('page.html', {cwd, reverse: true, out: 'restored/app/back.tsx'}));
+ expect(back.data.files).toEqual(['restored/app/back.tsx', 'restored/components/Footer.tsx']);
+ const again = /** @type {any} */ (await render('restored/app/back.tsx', {cwd}));
+ expect(again.type).toBe('render.page');
+ // From a folder that holds the whole tree, the page lands where asked.
+ const up = path.join(dir, 'tree');
+ const back2 = /** @type {any} */ (await render('src/app/page.html', {cwd: up, reverse: true, out: 'copy/app/page.tsx'}));
+ expect(back2.data.output).toBe('copy/app/page.tsx');
+ expect(back2.data.files).toEqual(['copy/app/page.tsx', 'copy/components/Footer.tsx']);
+ // Into a folder with another name: each neighbour goes where the page's
+ // own imports find it from there, and the page renders again.
+ const renamed = /** @type {any} */ (
+ await render('src/app/page.html', {cwd: up, reverse: true, out: 'src/reports/today/page.tsx'})
+ );
+ expect(renamed.data.output).toBe('src/reports/today/page.tsx');
+ expect(renamed.data.files).toEqual(['src/reports/today/page.tsx', 'src/reports/components/Footer.tsx']);
+ const rerendered = /** @type {any} */ (await render('src/reports/today/page.tsx', {cwd: up}));
+ expect(rerendered.type).toBe('render.page');
+ }, 60_000);
+
+ it('resolves a tsconfig path alias', async () => {
+ put('aliased/tsconfig.json', '{\n // paths\n "compilerOptions": {"baseUrl": ".", "paths": {"@/*": ["./src/*"]}},\n}\n');
+ put('aliased/package.json', '{"name":"aliased","private":true}');
+ put('aliased/src/Header.tsx', 'export function Header() { return <p>Aliased header</p>; }\n');
+ put('aliased/src/page.tsx', "import {Header} from '@/Header';\nexport default function Page() { return <Header />; }\n");
+ put('aliased/src/bad.tsx', "import X from '@/nope';\nexport default function Page() { return <X />; }\n");
+ const r = /** @type {any} */ (await render('aliased/src/page.tsx', {cwd: dir}));
+ expect(fs.readFileSync(path.join(dir, 'aliased/src/page.html'), 'utf8')).toContain('Aliased header');
+ expect(r.data.files).toEqual(['page.tsx', 'Header.tsx']);
+ expect(await codeOf(() => render('aliased/src/bad.tsx', {cwd: dir}))).toBe('ERR_FILE_NOT_FOUND');
+ }, 60_000);
+
+ it('gives back a page that imports through an alias where this project\'s alias points', async () => {
+ put('aliased-src/tsconfig.json', '{"compilerOptions": {"baseUrl": ".", "paths": {"@/*": ["./src/*"]}}}\n');
+ put('aliased-src/package.json', '{"name":"aliased-src","private":true}');
+ put('aliased-src/src/components/Header.tsx', 'export function Header() { return <p>Alias header</p>; }\n');
+ put(
+ 'aliased-src/src/app/page.tsx',
+ "import {Header} from '@/components/Header';\nexport default function Page() { return <Header />; }\n",
+ );
+ await render('aliased-src/src/app/page.tsx', {cwd: dir});
+ // Another project with the same alias, and the guide's own command.
+ put('aliased-to/tsconfig.json', '{"compilerOptions": {"baseUrl": ".", "paths": {"@/*": ["./src/*"]}}}\n');
+ put('aliased-to/package.json', '{"name":"aliased-to","private":true}');
+ fs.copyFileSync(path.join(dir, 'aliased-src/src/app/page.html'), path.join(dir, 'aliased-to/page.html'));
+ const cwd = path.join(dir, 'aliased-to');
+ // Into the project's existing folders: refused, without a suggestion that cannot work.
+ put('aliased-to/src/keep.txt', 'existing\n');
+ /** @type {any} */
+ let refused;
+ try {
+ await render('page.html', {cwd, reverse: true, out: 'page.tsx'});
+ } catch (e) {
+ refused = e;
+ }
+ expect(refused?.code).toBe('ERR_PATH_TRAVERSAL');
+ expect(refused.message).toContain('path alias');
+ expect(refused.suggestions ?? []).toEqual([]);
+ fs.rmSync(path.join(cwd, 'src'), {recursive: true});
+ // Into a new folder the alias points into: the page and its import come back.
+ const back = /** @type {any} */ (await render('page.html', {cwd, reverse: true, out: 'src/app/page.tsx'}));
+ expect(back.data.files).toEqual(['src/app/page.tsx', 'src/components/Header.tsx']);
+ const again = /** @type {any} */ (await render('src/app/page.tsx', {cwd}));
+ expect(again.type).toBe('render.page');
+ expect(fs.readFileSync(path.join(cwd, 'src/app/page.html'), 'utf8')).toContain('Alias header');
+ // Without the alias, the file it names is refused, naming why.
+ put('no-alias/package.json', '{"name":"no-alias","private":true}');
+ fs.copyFileSync(path.join(dir, 'aliased-src/src/app/page.html'), path.join(dir, 'no-alias/page.html'));
+ expect(
+ await codeOf(() => render('page.html', {cwd: path.join(dir, 'no-alias'), reverse: true, out: 'page.tsx'})),
+ ).toBe('ERR_RENDER_SOURCE_DAMAGED');
+ }, 60_000);
+
+ it('never writes through a symbolic link or over a protected file, even with --overwrite', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ const page = {path: 'page.tsx', bytes: Buffer.from("import './styles.css';\nexport default () => null;\n")};
+ const css = {path: 'styles.css', bytes: Buffer.from('.a{}\n')};
+ put('prot/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, css])}</body>`);
+ const cwd = path.join(dir, 'prot');
+ // A symbolic link inside the folder, onto a file the refusal never named.
+ put('prot/real.css', 'original\n');
+ fs.mkdirSync(path.join(cwd, 'out'), {recursive: true});
+ fs.symlinkSync(path.join(cwd, 'real.css'), path.join(cwd, 'out/styles.css'));
+ expect(await codeOf(() => render('page.html', {cwd, reverse: true, out: 'out/page.tsx', overwrite: true}))).toBe(
+ 'ERR_PATH_TRAVERSAL',
+ );
+ expect(fs.readFileSync(path.join(cwd, 'real.css'), 'utf8')).toBe('original\n');
+ // A generated file and an ignored file are never replaced.
+ put('prot/alone.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [{path: 'page.tsx', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ put('prot/gen/page.tsx', '// @generated\nexport default () => null;\n');
+ expect(await codeOf(() => render('alone.html', {cwd, reverse: true, out: 'gen/page.tsx', overwrite: true}))).toBe(
+ 'ERR_FILE_EXISTS',
+ );
+ expect(fs.readFileSync(path.join(cwd, 'gen/page.tsx'), 'utf8')).toContain('@generated');
+ put('prot/.gitignore', 'ignored/\n');
+ put('prot/ignored/page.tsx', 'mine\n');
+ expect(await codeOf(() => render('alone.html', {cwd, reverse: true, out: 'ignored/page.tsx', overwrite: true}))).toBe(
+ 'ERR_FILE_EXISTS',
+ );
+ expect(fs.readFileSync(path.join(cwd, 'ignored/page.tsx'), 'utf8')).toBe('mine\n');
+ });
+
+ it('refuses a configuration file a received page imports from above it', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ for (const name of ['babel.config.json', 'jest.config.json', 'project.json']) {
+ const page = {path: 'src/app/page.tsx', bytes: Buffer.from(`import c from '../../${name}';\nexport default () => null;\n`)};
+ put('cfg-above.html', `<body><p class="astryx-text">x</p>${sourceBlock('src/app/page.tsx', [page, {path: name, bytes: Buffer.from('{}')}])}</body>`);
+ expect(await codeOf(() => render('cfg-above.html', {cwd: dir, reverse: true, out: 'cfg-above/src/app/page.tsx'}))).toBe(
+ 'ERR_RENDER_SOURCE_DAMAGED',
+ );
+ expect(fs.existsSync(path.join(dir, 'cfg-above', name))).toBe(false);
+ }
+ });
+
+ it('restores a short alias import to the file it names', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('short-alias/tsconfig.json', '{"compilerOptions": {"baseUrl": ".", "paths": {"@/*": ["./src/*"]}}}\n');
+ const page = {path: 'page.tsx', bytes: Buffer.from("import {t} from '@/t';\nexport default () => t;\n")};
+ put('short-alias/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, {path: 't.ts', bytes: Buffer.from("export const t = 'x';\n")}])}</body>`);
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'short-alias'), reverse: true, out: 'src/page.tsx'}));
+ expect(back.data.files).toEqual(['src/page.tsx', 'src/t.ts']);
+ });
+
+ it('writes a page rebuilt from markup into a new folder by default', async () => {
+ put('rebuilt-default/middleware.html', '<body><div class="astryx-stack"><p class="astryx-text">Hi</p></div></body>');
+ const cwd = path.join(dir, 'rebuilt-default');
+ const back = /** @type {any} */ (await render('middleware.html', {cwd, reverse: true}));
+ expect(back.data.mode).toBe('rebuilt');
+ expect(back.data.output).toBe('middleware-restored/page.tsx');
+ expect(fs.existsSync(path.join(cwd, 'middleware.tsx'))).toBe(false);
+ });
+
+ it('inlines a stylesheet\'s own url()s from the stylesheet\'s folder', async () => {
+ put('sheet-url/styles/bg.png', PNG);
+ put('sheet-url/styles/page.css', '.hero { background: url("./bg.png"); }\n');
+ put('sheet-url/page.tsx', "import './styles/page.css';\nexport default function Page() { return <div className=\"hero\">Hi</div>; }\n");
+ const r = /** @type {any} */ (await render('sheet-url/page.tsx', {cwd: dir}));
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('missing-asset');
+ expect(fs.readFileSync(path.join(dir, 'sheet-url/page.html'), 'utf8')).toContain('url("data:image/png;base64,');
+ }, 60_000);
+
+ it('carries images the page names by path, in markup and in a stylesheet, and gives them back', async () => {
+ put('by-path/logo.png', PNG);
+ put('by-path/styles/bg.png', PNG);
+ put('by-path/styles/page.css', '.hero { background: url("./bg.png"); }\n');
+ put('by-path/page.tsx', "import './styles/page.css';\nexport default function Page() { return <div className=\"hero\"><img src=\"./logo.png\" alt=\"\" /></div>; }\n");
+ const r = /** @type {any} */ (await render('by-path/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(expect.arrayContaining(['page.tsx', 'styles/page.css', 'logo.png', 'styles/bg.png']));
+ const back = /** @type {any} */ (await render('by-path/page.html', {cwd: dir, reverse: true, out: 'by-path-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ expect(back.data.files).toEqual(
+ expect.arrayContaining(['by-path-back/page.tsx', 'by-path-back/logo.png', 'by-path-back/styles/bg.png']),
+ );
+ const again = /** @type {any} */ (await render('by-path-back/page.tsx', {cwd: dir}));
+ expect(again.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('missing-asset');
+ }, 60_000);
+
+ it('gives back images named any way the render carried them', async () => {
+ put('spell/logo.png', PNG);
+ put('spell/images/bg.png', PNG);
+ put('spell/pic.png', PNG);
+ put('spell/tpl.png', PNG);
+ put('spell/card.png', PNG);
+ put('spell/styles.css', '.hero { background: url(images/bg.png); }\n');
+ put('spell/data.json', '{"img": "pic.png"}\n');
+ put('spell/components/Card.tsx', 'export function Card() { return <img src="card.png" alt="" />; }\n');
+ put(
+ 'spell/page.tsx',
+ [
+ "import './styles.css';",
+ "import data from './data.json';",
+ "import {Card} from './components/Card';",
+ "const name = 'tpl';",
+ 'export default function Page() {',
+ ' return <div className="hero"><img src="logo.png" alt="" /><img src={data.img} alt="" /><img src={`./${name}.png`} alt="" /><Card /></div>;',
+ '}',
+ '',
+ ].join('\n'),
+ );
+ const r = /** @type {any} */ (await render('spell/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(expect.arrayContaining(['logo.png', 'images/bg.png', 'pic.png', 'tpl.png', 'card.png']));
+ const back = /** @type {any} */ (await render('spell/page.html', {cwd: dir, reverse: true, out: 'spell-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ for (const f of ['logo.png', 'images/bg.png', 'pic.png', 'tpl.png', 'card.png']) {
+ expect(fs.existsSync(path.join(dir, 'spell-back', f))).toBe(true);
+ }
+ const again = /** @type {any} */ (await render('spell-back/page.tsx', {cwd: dir}));
+ expect(again.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('missing-asset');
+ }, 60_000);
+
+ it('round-trips an image or font whose bytes and extension disagree', async () => {
+ put('mismatch/photo.png', Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 74, 70, 73, 70, 0, 1]));
+ put('mismatch/fonts/face.otf', Buffer.from([0, 1, 0, 0, 0, 10, 0, 128, 0, 3]));
+ put('mismatch/styles.css', "@font-face { font-family: Face; src: url(fonts/face.otf); }\n.t { font-family: Face; }\n");
+ put('mismatch/page.tsx', "import './styles.css';\nexport default function Page() { return <p className=\"t\"><img src=\"photo.png\" alt=\"\" />Hi</p>; }\n");
+ const r = /** @type {any} */ (await render('mismatch/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(expect.arrayContaining(['photo.png', 'fonts/face.otf']));
+ const back = /** @type {any} */ (await render('mismatch/page.html', {cwd: dir, reverse: true, out: 'mismatch-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ expect(back.data.files).toEqual(expect.arrayContaining(['mismatch-back/photo.png', 'mismatch-back/fonts/face.otf']));
+ }, 60_000);
+
+ it('leaves out a path-named "image" whose bytes are not one, and says so', async () => {
+ put('notimg/fake.png', 'console.log(1)\n');
+ put('notimg/page.tsx', 'export default function Page() { return <img src="fake.png" alt="" />; }\n');
+ const r = /** @type {any} */ (await render('notimg/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(['page.tsx']);
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('not-embedded');
+ }, 60_000);
+
+ it('inlines style-attribute images in every url() form and keeps the element whole', async () => {
+ put('styleattr/a.png', PNG);
+ put('styleattr/b.png', PNG);
+ put(
+ 'styleattr/page.tsx',
+ [
+ 'export default function Page() {',
+ ' return (',
+ ' <div>',
+ ` <div id="q" style={{backgroundImage: 'url("./a.png")'}}>Q</div>`,
+ ` <div id="u" style={{backgroundImage: 'url(b.png)'}}>U</div>`,
+ ` <div id="r" style={{backgroundImage: "url('https://example.com/x.png')"}}>R</div>`,
+ ' </div>',
+ ' );',
+ '}',
+ '',
+ ].join('\n'),
+ );
+ const r = /** @type {any} */ (await render('styleattr/page.tsx', {cwd: dir}));
+ const html = fs.readFileSync(path.join(dir, 'styleattr/page.html'), 'utf8');
+ const {parseHtml} = await import('../../foundation/render/html-reader.mjs');
+ /** @param {any} n @param {string} id @returns {any} */
+ const byId = (n, id) => {
+ if (n.attrs?.id === id) return n;
+ for (const c of n.children ?? []) {
+ const f = byId(c, id);
+ if (f) return f;
+ }
+ return null;
+ };
+ const doc = parseHtml(html);
+ expect(byId(doc, 'q').attrs.style).toContain('url("data:image/png;base64,');
+ expect(byId(doc, 'u').attrs.style).toContain('url("data:image/png;base64,');
+ expect(byId(doc, 'q').children[0].text).toBe('Q');
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('remote-asset');
+ expect(r.data.files).toEqual(expect.arrayContaining(['a.png', 'b.png']));
+ }, 60_000);
+
+ it('carries a stylesheet pulled in by @import and gives it back, and says when one is missing', async () => {
+ put('imp/styles/main.css', "@import './parts/base.css';\n@import url('https://example.com/f.css');\n.m { color: red; }\n");
+ put('imp/styles/parts/base.css', '.b { color: blue; background: url(./dot.png); }\n');
+ put('imp/styles/parts/dot.png', PNG);
+ put('imp/page.tsx', "import './styles/main.css';\nexport default function Page() { return <p className=\"m b\">Hi</p>; }\n");
+ const r = /** @type {any} */ (await render('imp/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(expect.arrayContaining(['styles/main.css', 'styles/parts/base.css', 'styles/parts/dot.png']));
+ const html = fs.readFileSync(path.join(dir, 'imp/page.html'), 'utf8');
+ expect(html).toContain('color: blue');
+ expect(html).not.toContain('@import');
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('remote-asset');
+ const back = /** @type {any} */ (await render('imp/page.html', {cwd: dir, reverse: true, out: 'imp-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ expect(back.data.files).toEqual(expect.arrayContaining(['imp-back/styles/parts/base.css']));
+ // A file whose @import target it does not carry says so.
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('imp-missing.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [{path: 'page.tsx', bytes: Buffer.from("import './a.css';\nexport default () => null;\n")}, {path: 'a.css', bytes: Buffer.from("@import './gone.css';\n")}])}</body>`);
+ const partial = /** @type {any} */ (await render('imp-missing.html', {cwd: dir, reverse: true, out: 'imp-missing/page.tsx'}));
+ expect(partial.data.exact).toBe(false);
+ expect(partial.data.missing).toEqual(['gone.css']);
+ }, 60_000);
+
+ it('handles every kind of stylesheet import', async () => {
+ const themeFonts = fs.readFileSync(path.join(CLI_DIR, '../themes/butter/fonts.css'), 'utf8');
+ put('kinds/fonts.css', themeFonts);
+ put('kinds/legacy.css', '.legacy-btn { padding: 3px; }\n');
+ put('kinds/main.css', "@import './fonts.css';\n@import './legacy.css' layer(reset);\n@import './print.css' print;\n@import '@astryxdesign/core/astryx.css';\n.k { color: red; }\n");
+ put('kinds/print.css', '.p { color: black; }\n');
+ put('kinds/page.tsx', "import './main.css';\nexport default function Page() { return <p className=\"k legacy-btn p\">Hi</p>; }\n");
+ const r = /** @type {any} */ (await render('kinds/page.tsx', {cwd: dir}));
+ const html = fs.readFileSync(path.join(dir, 'kinds/page.html'), 'utf8');
+ expect(html).toMatch(/@layer reset\s*\{[^}]*\.legacy-btn/);
+ expect(html).toMatch(/@media print\s*\{[^}]*\.p/);
+ expect(html).not.toContain('@import');
+ const codes = r.data.warnings.map((/** @type {any} */ w) => w.code);
+ expect(codes).toContain('remote-asset');
+ expect(r.data.warnings.some((/** @type {any} */ w) => w.message.includes('astryx.css'))).toBe(false);
+ expect(r.data.files).not.toContain(expect.stringContaining('node_modules'));
+ // The package import is neither carried nor missing when given back.
+ const back = /** @type {any} */ (await render('kinds/page.html', {cwd: dir, reverse: true, out: 'kinds-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ // Sass is named, CSS Modules refused with a clear message.
+ put('kinds/sass.tsx', "import './x.scss';\nexport default function Page() { return <p>Hi</p>; }\n");
+ const sass = /** @type {any} */ (await render('kinds/sass.tsx', {cwd: dir}));
+ expect(sass.data.warnings.some((/** @type {any} */ w) => w.message.includes('x.scss'))).toBe(true);
+ put('kinds/x.module.css', '.a { color: red; }\n');
+ put('kinds/mod.tsx', "import styles from './x.module.css';\nexport default function Page() { return <p className={styles.a}>Hi</p>; }\n");
+ /** @type {any} */
+ let error;
+ try {
+ await render('kinds/mod.tsx', {cwd: dir});
+ } catch (e) {
+ error = e;
+ }
+ expect(error?.code).toBe('ERR_RENDER_FAILED');
+ expect(error.message).toContain('CSS Modules');
+ }, 90_000);
+
+ it('refuses any stylesheet imported as a value, inlines Core once, ignores commented imports, and names a broken stylesheet', async () => {
+ put('more/x.module.scss', '.a { color: red; }\n');
+ put('more/scssmod.tsx', "import styles from './x.module.scss';\nexport default function Page() { return <p className={styles.a}>Hi</p>; }\n");
+ /** @type {any} */
+ let error;
+ try {
+ await render('more/scssmod.tsx', {cwd: dir});
+ } catch (e) {
+ error = e;
+ }
+ expect(error?.code).toBe('ERR_RENDER_FAILED');
+ expect(error.message).toContain('x.module.scss');
+ // A globals.css that imports Core: Core's rules once, listed once.
+ put('more/plain.tsx', "export default function Page() { return <p className=\"astryx-text\">Hi</p>; }\n");
+ put('more/globals.css', "@import '@astryxdesign/core/astryx.css';\n");
+ put('more/withcore.tsx', "import './globals.css';\nexport default function Page() { return <p className=\"astryx-text\">Hi</p>; }\n");
+ const plain = /** @type {any} */ (await render('more/plain.tsx', {cwd: dir}));
+ const withCore = /** @type {any} */ (await render('more/withcore.tsx', {cwd: dir}));
+ // Within a few bytes (the emptied import line), not a second copy of Core.
+ expect(Math.abs(withCore.data.cssBytes - plain.data.cssBytes)).toBeLessThan(16);
+ expect(withCore.data.stylesheets.filter((/** @type {string} */ x) => x.endsWith('astryx.css'))).toHaveLength(1);
+ // A commented-out import does not make a full restore partial.
+ put('more/commented.css', "/* @import './gone.css'; */\n.c { color: red; }\n");
+ put('more/commented.tsx', "import './commented.css';\nexport default function Page() { return <p className=\"c\">Hi</p>; }\n");
+ await render('more/commented.tsx', {cwd: dir});
+ const back = /** @type {any} */ (await render('more/commented.html', {cwd: dir, reverse: true, out: 'more-back/page.tsx'}));
+ expect(back.data.exact).toBe(true);
+ // A stylesheet that is not CSS: a documented code, naming the file.
+ put('more/broken.css', '.b { color: red;\n');
+ put('more/broken.tsx', "import './broken.css';\nexport default function Page() { return <p className=\"b\">Hi</p>; }\n");
+ /** @type {any} */
+ let broken;
+ try {
+ await render('more/broken.tsx', {cwd: dir});
+ } catch (e) {
+ broken = e;
+ }
+ expect(broken?.code).toBe('ERR_RENDER_COMPILE');
+ expect(broken.message).toContain('broken.css');
+ }, 90_000);
+
+ it('resolves aliased stylesheets and images, inlines a shared sheet once in first-import order, and names a broken @import', async () => {
+ put('al/tsconfig.json', '{"compilerOptions": {"baseUrl": ".", "paths": {"@/*": ["./src/*"]}}}\n');
+ put('al/package.json', '{"name":"al","private":true}');
+ put('al/src/styles/site.css', '.site { color: red; }\n');
+ put('al/src/assets/logo.png', PNG);
+ put('al/src/page.tsx', "import '@/styles/site.css';\nimport logo from '@/assets/logo.png';\nexport default function Page() { return <p className=\"site\"><img src={logo} alt=\"\" />Hi</p>; }\n");
+ const r = /** @type {any} */ (await render('al/src/page.tsx', {cwd: dir}));
+ const html = fs.readFileSync(path.join(dir, 'al/src/page.html'), 'utf8');
+ expect(html).toContain('color: red');
+ expect(html).toContain('data:image/png;base64,');
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).not.toContain('missing-asset');
+ // One sheet shared by two modules, a third sheet between them.
+ put('order/shared.css', '.o { color: red; }\n');
+ put('order/middle.css', '.o { color: blue; }\n');
+ put('order/A.tsx', "import './shared.css';\nexport const A = () => null;\n");
+ put('order/B.tsx', "import './middle.css';\nimport './shared.css';\nexport const B = () => null;\n");
+ put('order/page.tsx', "import {A} from './A';\nimport {B} from './B';\nexport default function Page() { return <p className=\"o\"><A /><B />Hi</p>; }\n");
+ await render('order/page.tsx', {cwd: dir});
+ const orderHtml = fs.readFileSync(path.join(dir, 'order/page.html'), 'utf8');
+ expect(orderHtml.match(/color: red/g)).toHaveLength(1);
+ expect(orderHtml.indexOf('color: red')).toBeLessThan(orderHtml.indexOf('color: blue'));
+ // A broken @import target: the same documented code, naming both files.
+ put('bad-imp/inner.css', '.x { color: red;\n');
+ put('bad-imp/outer.css', "@import './inner.css';\n.y { color: blue; }\n");
+ put('bad-imp/page.tsx', "import './outer.css';\nexport default function Page() { return <p className=\"x y\">Hi</p>; }\n");
+ /** @type {any} */
+ let error;
+ try {
+ await render('bad-imp/page.tsx', {cwd: dir});
+ } catch (e) {
+ error = e;
+ }
+ expect(error?.code).toBe('ERR_RENDER_COMPILE');
+ expect(error.message).toContain('inner.css');
+ expect(error.message).toContain('outer.css');
+ // A stylesheet import naming a missing file, directly or through an alias.
+ for (const spec of ['./gone.css', '@/styles/gone.css']) {
+ put('al/src/missing.tsx', `import '${spec}';\nexport default function Page() { return <p>Hi</p>; }\n`);
+ /** @type {any} */
+ let missing;
+ try {
+ await render('al/src/missing.tsx', {cwd: dir});
+ } catch (e) {
+ missing = e;
+ }
+ expect(missing?.code).toBe('ERR_FILE_NOT_FOUND');
+ expect(missing.message).toContain('gone.css');
+ }
+ }, 90_000);
+
+ it('refuses a carried "image" whose bytes are not one', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('fake-img.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [{path: 'page.tsx', bytes: Buffer.from('export default () => null;\n')}, {path: 'hook.png', bytes: Buffer.from('process.exit(1)\n')}])}</body>`);
+ expect(await codeOf(() => render('fake-img.html', {cwd: dir, reverse: true, out: 'fake-img/page.tsx'}))).toBe(
+ 'ERR_RENDER_SOURCE_DAMAGED',
+ );
+ });
+
+ it('rebuilds a quoted attribute as JSX that compiles', async () => {
+ put(
+ 'quoted.html',
+ '<body><div class="astryx-stack"><img src="data:image/png;base64,iVBORw0KGgo=" alt="say &quot;hi&quot; {now}"><a class="astryx-link" href="/x?a=&quot;b&quot;">Go</a></div></body>',
+ );
+ const back = /** @type {any} */ (await render('quoted.html', {cwd: dir, reverse: true, out: 'quoted/page.tsx'}));
+ expect(back.data.mode).toBe('rebuilt');
+ const source = fs.readFileSync(path.join(dir, 'quoted/page.tsx'), 'utf8');
+ expect(source).toContain('alt={"say \\"hi\\" {now}"}');
+ const again = /** @type {any} */ (await render('quoted/page.tsx', {cwd: dir}));
+ expect(again.type).toBe('render.page');
+ }, 60_000);
+
+ it('never adds a file outside the page\'s own folder beside existing project files', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('plant/app/keep.txt', 'existing\n');
+ for (const [spec, name] of [
+ ['../../nodemon.json', 'nodemon.json'],
+ ['../../jsr.json', 'jsr.json'],
+ ['../../instrumentation', 'instrumentation.ts'],
+ ['../middleware', 'src/middleware.ts'],
+ ]) {
+ const page = {path: 'src/app/page.tsx', bytes: Buffer.from(`import x from '${spec}';\nexport default () => null;\n`)};
+ put('plant/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('src/app/page.tsx', [page, {path: name, bytes: Buffer.from('{}')}])}</body>`);
+ expect(
+ await codeOf(() => render('page.html', {cwd: path.join(dir, 'plant'), reverse: true, out: 'app/page.tsx', overwrite: true})),
+ ).toMatch(/ERR_PATH_TRAVERSAL|ERR_RENDER_SOURCE_DAMAGED/);
+ expect(fs.existsSync(path.join(dir, 'plant', path.basename(name)))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'plant/app/page.tsx'))).toBe(false);
+ }
+ });
+
+ it('writes all or nothing: a failure part-way leaves nothing behind', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ // The second file's name is longer than a file system allows, so its
+ // write fails after the page's has been staged.
+ const long = 'C'.repeat(300);
+ const page = {path: 'app/page.tsx', bytes: Buffer.from(`import {C} from './components/${long}';\nexport default () => <C />;\n`)};
+ const comp = {path: `app/components/${long}.tsx`, bytes: Buffer.from('export const C = () => null;\n')};
+ put('atomic/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('app/page.tsx', [page, comp])}</body>`);
+ expect(await codeOf(() => render('page.html', {cwd: path.join(dir, 'atomic'), reverse: true, out: 'out/page.tsx'}))).toBe(
+ 'ERR_WRITE_FAILED',
+ );
+ expect(fs.readdirSync(path.join(dir, 'atomic'))).toEqual(['page.html']);
+ });
+
+
+
+ it('restores an exact alias import to the file it names', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('exact-alias/tsconfig.json', '{"compilerOptions": {"baseUrl": ".", "paths": {"@theme": ["./src/theme.ts"]}}}\n');
+ const page = {path: 'page.tsx', bytes: Buffer.from("import {t} from '@theme';\nexport default () => t;\n")};
+ put('exact-alias/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, {path: 'theme.ts', bytes: Buffer.from("export const t = 'x';\n")}])}</body>`);
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'exact-alias'), reverse: true, out: 'src/page.tsx'}));
+ expect(back.data.files).toEqual(['src/page.tsx', 'src/theme.ts']);
+ });
+
+ it('keeps every neighbour inside the one folder the restore creates', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('depth/app/layout.tsx', 'existing\n');
+ const page = {path: 'restored/report.tsx', bytes: Buffer.from("import r from '../app/report-export/route';\nexport default () => null;\n")};
+ put('depth/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('restored/report.tsx', [page, {path: 'app/report-export/route.ts', bytes: Buffer.from('export {};\n')}])}</body>`);
+ /** @type {any} */
+ let refused;
+ try {
+ await render('page.html', {cwd: path.join(dir, 'depth'), reverse: true, out: 'restored/report.tsx'});
+ } catch (e) {
+ refused = e;
+ }
+ expect(refused?.code).toBe('ERR_PATH_TRAVERSAL');
+ expect(fs.existsSync(path.join(dir, 'depth/app/report-export'))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'depth/restored'))).toBe(false);
+ // The suggested folder works.
+ const suggestion = refused.suggestions[0].name.replace('--out ', '');
+ const back = /** @type {any} */ (await render('page.html', {cwd: path.join(dir, 'depth'), reverse: true, out: suggestion}));
+ expect(back.data.mode).toBe('embedded');
+ });
+
+ it('refuses test, spec and story files a received page imports', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ for (const name of [
+ 'report.test.ts',
+ 'report.spec.tsx',
+ 'Report.stories.tsx',
+ '__tests__/r.ts',
+ 'report-test.mjs',
+ 'report_test.mjs',
+ 'test-report.mjs',
+ 'test.mjs',
+ 'test/helper.mjs',
+ 'test-report.ts',
+ 'report_test.mts',
+ 'test.cts',
+ 'test/helper.ts',
+ 'spec.ts',
+ 'test.tsx',
+ 'report.benchmark.ts',
+ 'report_test.tsx',
+ 'tests/helper.js',
+ 'spectest.js',
+ 'testtest.ts',
+ ]) {
+ const page = {path: 'page.tsx', bytes: Buffer.from(`import './${name.replace(/\.(tsx?|[mc]?[jt]s)$/, '')}';\nexport default () => null;\n`)};
+ put('tests-in.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, {path: name, bytes: Buffer.from('export {};\n')}])}</body>`);
+ expect(await codeOf(() => render('tests-in.html', {cwd: dir, reverse: true, out: 'tests-in/page.tsx'}))).toBe(
+ 'ERR_RENDER_SOURCE_DAMAGED',
+ );
+ }
+ });
+
+ it('never names the page as a file a test runner picks up', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('runner/report.test.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.mjs', [{path: 'page.mjs', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ const cwd = path.join(dir, 'runner');
+ // The page's name never comes from the received file's name.
+ const back = /** @type {any} */ (await render('report.test.html', {cwd, reverse: true}));
+ expect(back.data.output).toBe('report.test-restored/page.mjs');
+ expect(await codeOf(() => render('report.test.html', {cwd, reverse: true, out: 'test/page.mjs'}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(await codeOf(() => render('report.test.html', {cwd, reverse: true, out: 'page.cy.mjs'}))).toBe('ERR_INVALID_ARGUMENT');
+ put('runner/spec.html', `<body><p class="astryx-text">x</p>${sourceBlock('report.cy.ts', [{path: 'report.cy.ts', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ expect(await codeOf(() => render('spec.html', {cwd, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ // Ordinary names that only contain such words still come back.
+ put('runner/results.html', `<body><p class="astryx-text">x</p>${sourceBlock('stories/test-results.tsx', [{path: 'stories/test-results.tsx', bytes: Buffer.from("import d from '../mock-data';\nexport default () => d;\n")}, {path: 'mock-data.ts', bytes: Buffer.from('export default 1;\n')}])}</body>`);
+ // Where a file lands counts, not only its name in the file.
+ expect(await codeOf(() => render('results.html', {cwd, reverse: true, out: 'tests/stories/test-results.tsx'}))).toMatch(
+ /ERR_INVALID_ARGUMENT|ERR_RENDER_SOURCE_DAMAGED/,
+ );
+ expect(fs.existsSync(path.join(cwd, 'tests'))).toBe(false);
+ const ok = /** @type {any} */ (await render('results.html', {cwd, reverse: true}));
+ expect(ok.data.files).toEqual(['results-restored/stories/test-results.tsx', 'results-restored/mock-data.ts']);
+ });
+
+
+ it('judges where a file lands from the project root, not the current folder', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('rooted-runner/package.json', '{"name":"rr","private":true}');
+ put('rooted-runner/test/fixtures/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.mjs', [{path: 'page.mjs', bytes: Buffer.from("import './helper.mjs';\nexport default () => null;\n")}, {path: 'helper.mjs', bytes: Buffer.from('export {};\n')}])}</body>`);
+ const cwd = path.join(dir, 'rooted-runner/test/fixtures');
+ expect(await codeOf(() => render('page.html', {cwd, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(fs.readdirSync(cwd)).toEqual(['page.html']);
+ });
+
+ it('judges a nested package under a test folder from the repository root', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ fs.mkdirSync(path.join(dir, 'repo-root/.git'), {recursive: true});
+ put('repo-root/package.json', '{"name":"repo","private":true}');
+ put('repo-root/test/fixtures/app/package.json', '{"name":"app","private":true}');
+ put('repo-root/test/fixtures/app/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.mjs', [{path: 'page.mjs', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ const cwd = path.join(dir, 'repo-root/test/fixtures/app');
+ expect(await codeOf(() => render('page.html', {cwd, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(fs.readdirSync(cwd).sort()).toEqual(['package.json', 'page.html']);
+ });
+
+ it('warns about a <script> or a loading <link> the page renders', async () => {
+ put('scripted/page.tsx', 'export default function Page() { return <main><link rel="stylesheet" href="https://example.com/x.css" /><script dangerouslySetInnerHTML={{__html: "1"}} /><p>Hi</p></main>; }\n');
+ const r = /** @type {any} */ (await render('scripted/page.tsx', {cwd: dir}));
+ const codes = r.data.warnings.map((/** @type {any} */ w) => w.code);
+ expect(codes).toContain('page-script');
+ expect(codes).toContain('remote-asset');
+ }, 60_000);
+
+ it('judges the page by where it lands, on both paths', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ fs.mkdirSync(path.join(dir, 'land/.git'), {recursive: true});
+ // A page saved as test.tsx comes back under another name with --out.
+ put('land/named.html', `<body><p class="astryx-text">x</p>${sourceBlock('test.tsx', [{path: 'test.tsx', bytes: Buffer.from('export default () => null;\n')}])}</body>`);
+ const cwd = path.join(dir, 'land');
+ expect(await codeOf(() => render('named.html', {cwd, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ const back = /** @type {any} */ (await render('named.html', {cwd, reverse: true, out: 'demo/page.tsx'}));
+ expect(back.data.output).toBe('demo/page.tsx');
+ // A page rebuilt from markup inside __tests__/ is refused too.
+ put('land/src/__tests__/stripped.html', '<body><div class="astryx-stack"><p class="astryx-text">Hi</p></div></body>');
+ expect(
+ await codeOf(() => render('stripped.html', {cwd: path.join(cwd, 'src/__tests__'), reverse: true})),
+ ).toBe('ERR_INVALID_ARGUMENT');
+ expect(fs.readdirSync(path.join(cwd, 'src/__tests__'))).toEqual(['stripped.html']);
+ });
+
+ it('refuses --title with --reverse', async () => {
+ expect(await codeOf(() => render('page.html', {cwd: dir, reverse: true, title: 'x'}))).toBe('ERR_INVALID_ARGUMENT');
+ });
+
+ it('keeps a received title out of the rebuilt code', async () => {
+ put('evil-title.html', '<html><head><title>x\rprocess.exit(7)\u2028//</title></head><body><div class="astryx-stack"><p class="astryx-text">Hi</p></div></body></html>');
+ await render('evil-title.html', {cwd: dir, reverse: true, out: 'evil-title/page.tsx'});
+ const first = fs.readFileSync(path.join(dir, 'evil-title/page.tsx'), 'utf8').split(/\r\n|\r|\n|\u2028|\u2029/)[0];
+ expect(first).toContain('process.exit(7)');
+ expect(first.startsWith('//')).toBe(true);
+ });
+
+ it('never adds a neighbour to an existing folder, a project root included', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put('rooted/package.json', '{"name":"rooted","private":true}');
+ for (const name of ['instrumentation.ts', 'middleware.ts', 'nodemon.json']) {
+ const spec = `./${name.replace(/\.ts$/, '')}`;
+ const page = {path: 'page.tsx', bytes: Buffer.from(`import x from '${spec}';\nexport default () => null;\n`)};
+ put('rooted/page.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, {path: name, bytes: Buffer.from('{}')}])}</body>`);
+ expect(
+ await codeOf(() => render('page.html', {cwd: path.join(dir, 'rooted'), reverse: true, out: 'page.tsx', overwrite: true})),
+ ).toMatch(/ERR_PATH_TRAVERSAL|ERR_RENDER_SOURCE_DAMAGED/);
+ expect(fs.existsSync(path.join(dir, 'rooted', name))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'rooted/page.tsx'))).toBe(false);
+ }
+ // Without --out, everything comes back into a new folder named after the file given.
+ put('rooted/shared.html', `<body><p class="astryx-text">x</p>${sourceBlock('instrumentation.ts', [{path: 'instrumentation.ts', bytes: Buffer.from('export function register() {}\n')}])}</body>`);
+ const back = /** @type {any} */ (await render('shared.html', {cwd: path.join(dir, 'rooted'), reverse: true}));
+ expect(back.data.output).toBe('shared-restored/instrumentation.ts');
+ });
+
+ it('replaces an existing output only when a render wrote it, and never an ignored one', async () => {
+ put('fwd/page.tsx', PAGE);
+ fs.copyFileSync(path.join(dir, 'dot.png'), path.join(dir, 'fwd/dot.png'));
+ put('fwd/mine.html', '<p>hand-written</p>\n');
+ const cwd = path.join(dir, 'fwd');
+ expect(await codeOf(() => render('page.tsx', {cwd, out: 'mine.html'}))).toBe('ERR_FILE_EXISTS');
+ expect(fs.readFileSync(path.join(cwd, 'mine.html'), 'utf8')).toBe('<p>hand-written</p>\n');
+ await render('page.tsx', {cwd});
+ const again = /** @type {any} */ (await render('page.tsx', {cwd}));
+ expect(again.type).toBe('render.page');
+ put('fwd/.gitignore', 'page.html\n');
+ expect(await codeOf(() => render('page.tsx', {cwd}))).toBe('ERR_FILE_EXISTS');
+ }, 60_000);
+
+ it('refuses a received file that lists one path twice', async () => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ const page = {path: 'page.tsx', bytes: Buffer.from('export default () => null;\n')};
+ put('twice.html', `<body><p class="astryx-text">x</p>${sourceBlock('page.tsx', [page, {path: 'page.tsx', bytes: Buffer.from("import './instrumentation';\n")}, {path: 'instrumentation.ts', bytes: Buffer.from('export {};\n')}])}</body>`);
+ expect(await codeOf(() => render('twice.html', {cwd: dir, reverse: true, out: 'twice-out/page.tsx'}))).toBe(
+ 'ERR_RENDER_SOURCE_DAMAGED',
+ );
+ expect(fs.existsSync(path.join(dir, 'twice-out'))).toBe(false);
+ });
+
+ it('reports ERR_WRITE_FAILED when the output cannot be written', async () => {
+ fs.mkdirSync(path.join(dir, 'a-folder.html'), {recursive: true});
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, out: 'a-folder.html'}))).toBe('ERR_WRITE_FAILED');
+ }, 60_000);
+
+ it('refuses --out outside the current folder, and a write through a symlink that leaves it', async () => {
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, out: '../escaped.html'}))).toBe('ERR_PATH_TRAVERSAL');
+ expect(await codeOf(() => render('page.html', {cwd: dir, reverse: true, out: '../escaped.tsx'}))).toBe(
+ 'ERR_PATH_TRAVERSAL',
+ );
+ const outside = fs.mkdtempSync(path.join(CLI_DIR, '.astryx-render-outside-'));
+ try {
+ fs.symlinkSync(outside, path.join(dir, 'link-out'));
+ expect(
+ await codeOf(() => render('page.html', {cwd: dir, reverse: true, out: 'link-out/page.tsx'})),
+ ).toBe('ERR_PATH_TRAVERSAL');
+ expect(fs.readdirSync(outside)).toEqual([]);
+ } finally {
+ fs.rmSync(outside, {recursive: true, force: true});
+ }
+ });
+});
+
+describe('render --reverse: a received file may carry only what a render embeds', () => {
+ /** @param {string} name @param {{path: string, text: string}[]} files */
+ const crafted = async (name, files) => {
+ const {sourceBlock} = await import('../../foundation/render/source-block.mjs');
+ put(
+ name,
+ `<body><p class="astryx-text">x</p>${sourceBlock(files[0].path, files.map(f => ({path: f.path, bytes: Buffer.from(f.text)})))}</body>`,
+ );
+ };
+ it.each([
+ ['a git hook', '.git/hooks/pre-commit', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a dotfile', '.env', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a tool configuration module', 'vite.config.ts', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['an rc module', '.eslintrc.js', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['the Astryx configuration', 'astryx.config.mjs', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['the package manifest', 'package.json', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a TypeScript configuration', 'tsconfig.json', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a package inside node_modules', 'node_modules/react/index.js', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a shell script', 'scripts/install.sh', 'ERR_RENDER_SOURCE_DAMAGED'],
+ ['a climbing path', '../escape.css', 'ERR_PATH_TRAVERSAL'],
+ ['an absolute path', '/tmp/escape.css', 'ERR_PATH_TRAVERSAL'],
+ ])('refuses %s, writing nothing', async (_, bad, code) => {
+ const name = `crafted-${bad.replace(/[^a-z0-9]/gi, '_')}.html`;
+ await crafted(name, [
+ {path: 'page.tsx', text: 'export default () => null;\n'},
+ {path: bad, text: 'echo pwned\n'},
+ ]);
+ const out = `crafted-out-${bad.replace(/[^a-z0-9]/gi, '_')}`;
+ expect(await codeOf(() => render(name, {cwd: dir, reverse: true, out: `${out}/page.tsx`}))).toBe(code);
+ expect(fs.existsSync(path.join(dir, out))).toBe(false);
+ });
+
+ it.each([
+ ['a framework hook file', 'instrumentation.ts'],
+ ['a middleware module', 'src/middleware.ts'],
+ ['a JSON tool configuration', 'babel.config.json'],
+ ['a module in a tools folder', 'tools/plugin.js'],
+ ['a stylesheet the page never imports', 'theme.css'],
+ ])('refuses %s the page does not import, writing nothing', async (_, extra) => {
+ const name = `stray-${extra.replace(/[^a-z0-9]/gi, '_')}.html`;
+ await crafted(name, [
+ {path: 'page.tsx', text: "import {Header} from './Header';\nexport default () => <Header />;\n"},
+ {path: 'Header.tsx', text: 'export const Header = () => <h1>Hi</h1>;\n'},
+ {path: extra, text: 'export default {};\n'},
+ ]);
+ const out = `stray-out-${extra.replace(/[^a-z0-9]/gi, '_')}`;
+ /** @type {any} */
+ let error;
+ try {
+ await render(name, {cwd: dir, reverse: true, out: `${out}/page.tsx`});
+ } catch (e) {
+ error = e;
+ }
+ expect(error?.code).toBe('ERR_RENDER_SOURCE_DAMAGED');
+ expect(error.message).toContain(extra);
+ expect(fs.existsSync(path.join(dir, out))).toBe(false);
+ });
+
+ it('writes every file the page reaches: re-exports, import(), require() and a folder index', async () => {
+ await crafted('reach.html', [
+ {
+ path: 'page.tsx',
+ text: "export {a} from './a';\nconst b = import('./b');\nconst c = require('./c.json');\nimport './parts';\nexport default () => null;\n",
+ },
+ {path: 'a.ts', text: "import './a.css';\nexport const a = 1;\n"},
+ {path: 'a.css', text: '.a{}\n'},
+ {path: 'b.tsx', text: 'export default 2;\n'},
+ {path: 'c.json', text: '{}\n'},
+ {path: 'parts/index.ts', text: 'export {};\n'},
+ ]);
+ const r = /** @type {any} */ (await render('reach.html', {cwd: dir, reverse: true, out: 'reach/page.tsx'}));
+ expect(r.data.files.length).toBe(6);
+ });
+
+ it('refuses a page entry that is not a page module, and an --out that names a configuration file', async () => {
+ await crafted('crafted-entry.html', [{path: 'vite.config.ts', text: 'export default {};\n'}]);
+ expect(await codeOf(() => render('crafted-entry.html', {cwd: dir, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ await crafted('crafted-good.html', [{path: 'page.tsx', text: 'export default () => null;\n'}]);
+ expect(await codeOf(() => render('crafted-good.html', {cwd: dir, reverse: true, out: 'vite.config.ts'}))).toBe(
+ 'ERR_INVALID_ARGUMENT',
+ );
+ // Refused before the input is read: a missing input gives the same answer.
+ expect(await codeOf(() => render('missing.html', {cwd: dir, reverse: true, out: 'vite.config.ts'}))).toBe(
+ 'ERR_INVALID_ARGUMENT',
+ );
+ expect(fs.existsSync(path.join(dir, 'vite.config.ts'))).toBe(false);
+ });
+
+ it('refuses neighbours into a folder that already exists, naming them, and writes nothing', async () => {
+ await crafted('crafted-exists.html', [
+ {path: 'page.tsx', text: "import './styles.css';\nexport default () => null;\n"},
+ {path: 'styles.css', text: '.a{}\n'},
+ ]);
+ put('exists/keep.txt', 'existing\n');
+ /** @type {any} */
+ let error;
+ try {
+ await render('crafted-exists.html', {cwd: dir, reverse: true, out: 'exists/page.tsx', overwrite: true});
+ } catch (e) {
+ error = e;
+ }
+ expect(error.code).toBe('ERR_PATH_TRAVERSAL');
+ expect(error.message).toContain('exists/styles.css');
+ expect(fs.readdirSync(path.join(dir, 'exists'))).toEqual(['keep.txt']);
+ });
+
+ it('never embeds a configuration file the page imports, and says so', async () => {
+ put('cfg/package.json', JSON.stringify({name: 'cfg', version: '1.2.3'}));
+ put('cfg/page.tsx', "import pkg from './package.json';\nexport default function Page() { return <p>v{pkg.version}</p>; }\n");
+ const r = /** @type {any} */ (await render('cfg/page.tsx', {cwd: dir}));
+ expect(r.data.files).toEqual(['page.tsx']);
+ expect(r.data.warnings.map((/** @type {any} */ w) => w.code)).toContain('not-embedded');
+ expect(fs.readFileSync(path.join(dir, 'cfg/page.html'), 'utf8')).toContain('v1.2.3');
+ // Given back, the page says what it imports that the file did not carry.
+ const back = /** @type {any} */ (await render('cfg/page.html', {cwd: dir, reverse: true}));
+ expect(back.data.exact).toBe(false);
+ expect(back.data.missing).toEqual(['package.json']);
+ }, 60_000);
+});
+
+describe('astryx experimental render (CLI)', () => {
+ it('refuses an unknown experimental subcommand with exit 1', async () => {
+ const r = await runCli(['--json', 'experimental', 'nope'], dir);
+ expect(r.status).toBe(1);
+ const out = JSON.parse(r.stdout);
+ expect(out.code).toBe('ERR_UNKNOWN_SUBCOMMAND');
+ expect(out.suggestions.map((/** @type {any} */ s) => s.name)).toContain('render');
+ });
+
+ it('fails with exit 1 and a readable message without --json', async () => {
+ const r = await runCli(['experimental', 'render', '--reverse', 'plain.html'], dir);
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('is not an Astryx page');
+ expect(r.stderr).toContain('astryx build');
+ });
+
+
+ it('answers --json with the render.page envelope and --title', async () => {
+ const r = await runCli(['--json', 'experimental', 'render', 'page.tsx', '--out', 'cli.html', '--title', 'From the CLI'], dir);
+ expect(r.status).toBe(0);
+ const json = JSON.parse(r.stdout);
+ expect(json.type).toBe('render.page');
+ expect(json.data.output).toBe('cli.html');
+ expect(fs.readFileSync(path.join(dir, 'cli.html'), 'utf8')).toContain('<title>From the CLI</title>');
+ }, 60_000);
+
+ it('fails with exit 1 and a JSON error envelope', async () => {
+ const r = await runCli(['--json', 'experimental', 'render', '--reverse', 'plain.html'], dir);
+ expect(r.status).toBe(1);
+ const json = JSON.parse(r.stdout);
+ expect(json.code).toBe('ERR_RENDER_NOT_ASTRYX');
+ expect(json.suggestions?.[0]?.name ?? '').toContain('astryx build');
+ });
+
+ it('marks itself experimental in help', async () => {
+ const r = await runCli(['experimental', '--help'], dir);
+ expect(r.stdout).toMatch(/render[^\n]*\[experimental\]/);
+ });
+});
+
+describe('render(): refusals', () => {
+ it.each([
+ ['syntax error', 'bad.tsx', 'export default function Page() { return <div>; }', 'ERR_RENDER_COMPILE'],
+ ['no default export', 'named.tsx', 'export function Page() { return null; }', 'ERR_RENDER_NO_DEFAULT_EXPORT'],
+ ['package not installed', 'dep.tsx', "import x from 'not-a-real-package-xyz';\nexport default () => <p>{String(x)}</p>;", 'ERR_RENDER_MISSING_DEPENDENCY'],
+ ['browser API while rendering', 'win.tsx', 'export default function Page() { return <p>{window.innerWidth}</p>; }', 'ERR_RENDER_BROWSER_API'],
+ ['missing local module', 'local.tsx', "import X from './nope';\nexport default () => <X />;", 'ERR_FILE_NOT_FOUND'],
+ ['a throw', 'throw.tsx', "export default function Page() { throw new Error('boom'); }", 'ERR_RENDER_FAILED'],
+ ])('%s', async (_, name, source, code) => {
+ put(name, source);
+ expect(await codeOf(() => render(name, {cwd: dir}))).toBe(code);
+ }, 30_000);
+
+ it('refuses wrong inputs and flags', async () => {
+ expect(await codeOf(() => render('', {cwd: dir}))).toBe('ERR_MISSING_ARGUMENT');
+ expect(await codeOf(() => render('missing.tsx', {cwd: dir}))).toBe('ERR_FILE_NOT_FOUND');
+ expect(await codeOf(() => render('page.html', {cwd: dir}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, reverse: true}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, out: 'page.txt'}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, overwrite: true}))).toBe('ERR_INVALID_ARGUMENT');
+ expect(await codeOf(() => render('page.tsx', {cwd: dir, out: 'page.tsx'}))).toBe('ERR_INVALID_ARGUMENT');
+ });
+
+ it('refuses an image too large to inline', async () => {
+ put('big.png', Buffer.alloc(9 * 1024 * 1024));
+ put('big.tsx', "import big from './big.png';\nexport default () => <img src={big} alt='' />;");
+ expect(await codeOf(() => render('big.tsx', {cwd: dir}))).toBe('ERR_RENDER_ASSET_TOO_LARGE');
+ }, 30_000);
+});
diff --git a/packages/cli/api/render/render.type.mjs b/packages/cli/api/render/render.type.mjs
new file mode 100644
index 0000000000..d0bb912c41
--- /dev/null
+++ b/packages/cli/api/render/render.type.mjs
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Colocated types for `astryx experimental render`: the source of truth
+ * for its response shapes.
+ *
+ * @position api/render — typedefs for api/render/render.mjs
+ */
+
+/**
+ * @experimental May change or be removed in a patch release.
+ * @typedef {object} RenderOptions
+ * @property {string} [cwd] - Folder relative paths resolve from (default: process.cwd()).
+ * @property {string} [out] - The file to write. Rendering: an .html file (default: the page's name with .html). Reversing: a page module (default: inside a new folder beside the HTML file, named after it, such as `report-restored/`).
+ * @property {boolean} [reverse] - Turn a rendered HTML file back into a page module.
+ * @property {string} [title] - The rendered page's title (default: its first heading, else the file name). Rendering only.
+ * @property {boolean} [overwrite] - Replace the existing page module when reversing (never a protected file, and never a file other than the page, which always goes into a new folder). Rendering replaces an existing HTML file only when a render wrote it.
+ */
+
+/**
+ * Something the render noticed that may make the page differ from what its
+ * author meant.
+ * @experimental May change or be removed in a patch release.
+ * @typedef {object} RenderWarning
+ * @property {'dropped-children' | 'remote-asset' | 'missing-asset' | 'page-output' | 'page-script' | 'no-astryx-styles' | 'chart-size' | 'not-embedded'} code - What kind of problem.
+ * @property {string} message - What happened and what to do, in one sentence.
+ */
+
+/**
+ * `astryx --json experimental render <page>`.
+ * @experimental May change or be removed in a patch release.
+ * @typedef {object} RenderPageResponse
+ * @property {'render.page'} type
+ * @property {object} data
+ * @property {string} data.input - The page module, relative to cwd when inside it.
+ * @property {string} data.output - The HTML file written.
+ * @property {number} data.bytes - Size of the HTML file.
+ * @property {string[]} data.files - Local files the page loaded (modules, stylesheets, images, JSON), relative to the folder that holds them all (the page's folder unless it imports from above it), page first; each is embedded so --reverse can give it back.
+ * @property {string[]} data.stylesheets - Package stylesheets that were cut to the rules the page uses and inlined.
+ * @property {number} data.classes - Distinct class names in the markup.
+ * @property {number} data.cssBytes - Size of the inlined CSS.
+ * @property {number} data.images - Local files inlined as data: URIs.
+ * @property {RenderWarning[]} data.warnings - Empty when nothing looked wrong.
+ */
+
+/**
+ * `astryx --json experimental render --reverse <file.html>`.
+ * @experimental May change or be removed in a patch release.
+ * @typedef {object} RenderReverseResponse
+ * @property {'render.reverse'} type
+ * @property {object} data
+ * @property {string} data.input - The HTML file read.
+ * @property {'embedded' | 'rebuilt'} data.mode - `embedded`: the file carried its source, written back byte for byte. `rebuilt`: rebuilt from Astryx markup (text and layout only).
+ * @property {string} data.output - The page module written: `out`, or by default inside a new folder beside the HTML file named after it (`report.html` gives `report-restored/`).
+ * @property {string[]} data.files - Every file written, page first.
+ * @property {boolean} data.exact - Whether the page and every file it imports came back exactly as rendered.
+ * @property {string[]} [data.missing] - Embedded only: relative imports the file did not carry (files a render never embeds), so the restored page needs them before it renders.
+ * @property {string[]} [data.components] - Rebuilt only: the components the page uses.
+ * @property {number} [data.elements] - Rebuilt only: how many component elements were rebuilt.
+ * @property {string[]} [data.unknown] - Rebuilt only: Astryx class names no installed component claims; their content is kept as plain elements.
+ * @property {string[]} [data.omitted] - Rebuilt only: component kinds left out because the markup cannot give them back (such as icons).
+ */
+
+export {};
diff --git a/packages/cli/assets/docs/tree/render-pages.doc.mjs b/packages/cli/assets/docs/tree/render-pages.doc.mjs
new file mode 100644
index 0000000000..d40c0621fe
--- /dev/null
+++ b/packages/cli/assets/docs/tree/render-pages.doc.mjs
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx docs cli/experimental/render-pages`: turn a page into one
+ * self-contained HTML file to share or embed, and turn that file back into
+ * the page.
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'render-pages',
+ placement: {parent: 'namespace:experimental', slot: 'guides', order: 20},
+ stability: 'experimental',
+ title: 'Pages as one HTML file',
+ category: 'guide',
+ keywords: [
+ 'render',
+ 'static html',
+ 'single file',
+ 'artifact',
+ 'share a page',
+ 'snapshot',
+ 'embed',
+ 'sandboxed iframe',
+ 'reverse',
+ ],
+ description:
+ 'Experimental. Render a page to one self-contained HTML file for sharing or embedding, and get the page back from it.',
+ sections: [
+ {
+ id: 'experimental',
+ title: 'Experimental',
+ content: [
+ {
+ type: 'prose',
+ text: 'This command is experimental, as everything under `astryx docs cli/experimental` is: its options, its output file and its JSON may still change. Nothing else in the CLI changes because it exists.',
+ },
+ ],
+ },
+ {
+ id: 'make-a-file',
+ title: 'Make a file to share',
+ content: [
+ {
+ type: 'prose',
+ text: 'Build the page with Astryx components as usual, then render it. The page module needs a default export; it renders on your machine with the React and Astryx packages your project installed.',
+ },
+ {
+ type: 'code',
+ lang: 'bash',
+ code: 'astryx experimental render src/app/page.tsx --out page.html',
+ },
+ {
+ type: 'prose',
+ text: 'The result is ONE file with nothing beside it: the markup, only the CSS rules the page uses (from Core and from any stylesheet it imports, such as a theme), the page\u2019s own StyleX styles, and local images as data: URIs. It runs no script and loads nothing from the network, so it opens from disk, attaches to a message, and displays inside a sandboxed frame that blocks network and script. Colors follow the viewer\u2019s light or dark setting, and a `data-theme` of `light` or `dark` on the root element picks one. The file also carries the source of the page and of every local module, stylesheet, JSON file and image it imports, so whoever you share it with can read that code; keep secrets out of what the page imports.',
+ },
+ {
+ type: 'prose',
+ text: 'What it cannot keep: anything that needs a browser while running. State, effects, click handlers and data loaded after the first paint are gone, and a chart sized by its container is empty, so give charts a fixed size. Read browser-only values such as window inside an effect, or the render stops with ERR_RENDER_BROWSER_API.',
+ },
+ ],
+ },
+ {
+ id: 'warnings',
+ title: 'Read the warnings',
+ content: [
+ {
+ type: 'prose',
+ text: 'Each warning names something that may look different from what you meant, and what to change. The most common is a component that ignores its children: `<ListItem>Save</ListItem>` renders an empty row because ListItem takes `label="Save"`. Others flag remote images (a sandboxed viewer cannot load them; save the image next to the page and import it), a `<script>`, `<link>` or `<iframe>` the page itself renders (the file promises to run and load nothing, so remove them), missing images, and output the page printed while rendering.',
+ },
+ ],
+ },
+ {
+ id: 'get-it-back',
+ title: 'Get the page back',
+ content: [
+ {
+ type: 'code',
+ lang: 'bash',
+ code: 'astryx experimental render --reverse page.html --out page.tsx',
+ },
+ {
+ type: 'prose',
+ text: 'Every rendered file carries its source, so this writes the page back byte for byte; edit it and render again. A file whose source block was removed but whose markup came from Astryx components is rebuilt from that markup instead: the components, their recorded props and the text come back, while styling, icons and behavior do not, so treat it as a starting point. HTML that was never an Astryx page is refused with ERR_RENDER_NOT_ASTRYX; describe the page to `astryx build` to start one.',
+ },
+ {
+ type: 'prose',
+ text: 'It writes the page, the modules, stylesheets and JSON files the page reaches through its own imports, and the images, fonts and media the render carried (however the page named them, as long as their bytes really are one): each goes where the page\'s relative imports find it from wherever you put the page, and a file the page imports through a path alias (`@/components/Header`) goes where your project\'s `tsconfig.json` or `jsconfig.json` alias points. Every file but the page goes inside the one new folder the restore creates (the topmost folder on the page\'s path that does not exist yet), never into a folder that already exists: a page that imports other files comes back into a new folder (`--out restored/app/page.tsx`), and a file it imports through a path alias comes back only when that alias points inside the new folder. Nor does it write a file that a test, story or benchmark runner would run by its default patterns (Jest, Vitest, Bun, AVA, Playwright, Storybook, Cypress and `node --test`: names such as `*.test.*`, `*.spec.*`, `*_test.*`, `*-test.*`, `*.bench.*`, `*.stories.*`, `*.cy.*`, and anything under `test/`, `tests/` or `__tests__/`), judged from the repository root (every folder above the file up to it), else the topmost folder with a package.json. Restored files are the sender\'s code: read them before you run or import them. Without `--out`, everything comes back into a new folder beside the HTML file, named after it (`page.html` comes back into `page-restored/`). A received file that carries anything else (a file the page never imports, a dotfile, `package.json`, a tool configuration, a path that leaves the folder) is refused with nothing written. An existing file is never replaced unless you pass `--overwrite`, and the refusal names every one; a generated, vendored or ignored file, and any path through a symbolic link, is not written even then. Add `--json` for the result as data: what was written, how big it is, and every warning.',
+ },
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/clients/cli/commands/experimental-render.doc.mjs b/packages/cli/clients/cli/commands/experimental-render.doc.mjs
new file mode 100644
index 0000000000..86db5dc734
--- /dev/null
+++ b/packages/cli/clients/cli/commands/experimental-render.doc.mjs
@@ -0,0 +1,60 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx experimental render`. The terminal binding of
+ * the `render()` function (referenced via `fn`).
+ * @position packages/cli/clients/cli/commands — command documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'experimental render',
+ displayName: 'astryx experimental render',
+ namespace: 'cli/commands',
+ stability: 'experimental',
+ summary:
+ 'Render a page to one self-contained HTML file, or turn one back into a page',
+ description:
+ "Renders the page's default export with the project's own Astryx components and writes ONE static HTML file that needs nothing beside it: no script runs and nothing loads from the network, so it opens anywhere, including a sandboxed frame with a strict content security policy, and follows the viewer's light or dark scheme. The page's own StyleX compiles, only the Core CSS rules the page uses are inlined, local images become data: URIs, and the page's source is embedded. Warnings name anything that may not look as meant, such as a component that did not render the text it was given (ListItem takes label=, not children). --reverse writes the embedded source back byte for byte; a file with Astryx markup but no embedded source is rebuilt from its components (text and layout only, as a starting point); any other HTML is refused. Experimental: it may change or be removed in a patch release.",
+ fn: 'render',
+ args: [{name: 'file', param: 'file', required: false}],
+ options: [
+ {
+ flag: '--out <file>',
+ param: 'options.out',
+ description:
+ "Where to write: an .html file, or with --reverse a page module (default: page.tsx gives page.html beside it; with --reverse, page.html comes back into a new folder page-restored/)",
+ },
+ {
+ flag: '--reverse',
+ param: 'options.reverse',
+ description: 'Turn a rendered HTML file back into a page module',
+ },
+ {
+ flag: '--title <text>',
+ param: 'options.title',
+ description:
+ "The page's title (default: its first top-level heading, else the file name)",
+ },
+ {
+ flag: '--overwrite',
+ param: 'options.overwrite',
+ description: 'With --reverse, replace the page module if it already exists (never a protected file; the files it imports always go into a new folder)',
+ },
+ ],
+ examples: [
+ {label: 'Render a page', cli: 'astryx experimental render src/app/page.tsx --out page.html'},
+ {label: 'Give it back', cli: 'astryx experimental render --reverse page.html --out page.tsx'},
+ {label: 'As JSON', cli: 'astryx --json experimental render page.tsx'},
+ ],
+ outsideProject: 'same',
+ exitCodes: [
+ {code: 0, when: 'the file was written (warnings included)'},
+ {
+ code: 1,
+ when: 'no file, a wrong extension, a missing file, a page that does not compile, has no default export, imports a package that is not installed, reads a browser API while rendering, throws, or takes over 60 seconds; a file to write outside the current folder; with --reverse, an existing output without --overwrite, a damaged embedded source, or HTML that is not an Astryx page',
+ },
+ ],
+ related: ['template', 'build'],
+};
diff --git a/packages/cli/clients/cli/commands/experimental.doc.mjs b/packages/cli/clients/cli/commands/experimental.doc.mjs
index b6e766c06e..8c7674cc6f 100644
--- a/packages/cli/clients/cli/commands/experimental.doc.mjs
+++ b/packages/cli/clients/cli/commands/experimental.doc.mjs
@@ -17,10 +17,11 @@ export const doc = {
'Try features that may change in a patch release: icon sets (find icons, build an icon-set package)',
description:
'The experimental command group. Every command under it is experimental: its arguments, options, output, and JSON may change or be removed in any patch release, with no deprecation period. A feature leaves this group when it becomes stable. Nothing here changes what any other command does unless you use it.',
- subcommands: ['icon'],
+ subcommands: ['icon', 'render'],
examples: [
{label: 'List the experiments', cli: 'astryx experimental'},
{label: 'Find an icon by meaning', cli: 'astryx experimental icon delete'},
+ {label: 'Render a page to one HTML file', cli: 'astryx experimental render page.tsx'},
],
exitCodes: [
{code: 0, when: 'help is shown or a subcommand succeeds'},
diff --git a/packages/cli/clients/cli/commands/experimental/index.mjs b/packages/cli/clients/cli/commands/experimental/index.mjs
index 6780ce39ef..6d691c794c 100644
--- a/packages/cli/clients/cli/commands/experimental/index.mjs
+++ b/packages/cli/clients/cli/commands/experimental/index.mjs
@@ -13,6 +13,7 @@ import {cliError} from '../../lib/cli-error.mjs';
import {defineCommand} from '../../lib/define-command.mjs';
import {doc as experimentalGroup} from '../experimental.doc.mjs';
import {registerExperimentalIcon} from './icon.mjs';
+import {registerExperimentalRender} from './render.mjs';
/** @param {import('commander').Command} program */
export function registerExperimental(program) {
@@ -40,4 +41,5 @@ export function registerExperimental(program) {
},
});
registerExperimentalIcon(experimental, program);
+ registerExperimentalRender(experimental, program);
}
diff --git a/packages/cli/clients/cli/commands/experimental/render.mjs b/packages/cli/clients/cli/commands/experimental/render.mjs
new file mode 100644
index 0000000000..f1150b5e43
--- /dev/null
+++ b/packages/cli/clients/cli/commands/experimental/render.mjs
@@ -0,0 +1,113 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx experimental render` — a page to one self-contained HTML
+ * file, and back. Experimental (spec:AST-017 FR27): it is registered only
+ * under the `experimental` group.
+ *
+ * The command surface comes from the colocated CommandDoc via
+ * `defineCommand`; this file reads flags, calls `render()`, and prints.
+ *
+ * Usage:
+ * astryx experimental render page.tsx --out page.html
+ * astryx experimental render --reverse page.html --out page.tsx
+ */
+
+import {getCliInvocation} from '../../../../foundation/env/package-manager.mjs';
+import {jsonOut} from '../../../../foundation/response/json.mjs';
+import {resultSet} from '../../../../foundation/debug/index.mjs';
+import {emit, section, text, record, list} from '../../formatters/index.mjs';
+import {cliError} from '../../lib/cli-error.mjs';
+import {defineCommand} from '../../lib/define-command.mjs';
+import {render as renderApi} from '../../../../api/render/render.mjs';
+import {doc as renderCommand} from '../experimental-render.doc.mjs';
+import {doc as renderFn} from '../../../../api/render/render.doc.mjs';
+
+/** @param {number} n */
+const kb = n => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KB`);
+
+/**
+ * Register `render` under the `experimental` group.
+ * @param {import('commander').Command} group the `experimental` command
+ * @param {import('commander').Command} program the root program
+ */
+export function registerExperimentalRender(group, program) {
+ defineCommand(group, renderCommand, {
+ fn: renderFn,
+ action: async (
+ /** @type {string | undefined} */ file,
+ /** @type {{out?: string, reverse?: boolean, title?: string, overwrite?: boolean}} */ options,
+ ) => {
+ const json = program.opts().json || false;
+ /** @type {Awaited<ReturnType<typeof renderApi>>} */
+ let result;
+ try {
+ result = await renderApi(file ?? '', {
+ cwd: process.cwd(),
+ out: options.out,
+ reverse: options.reverse ?? false,
+ title: options.title,
+ overwrite: options.overwrite ?? false,
+ });
+ } catch (e) {
+ const err = /** @type {import('../../../../api/error.mjs').AstryxError} */ (e);
+ return cliError(err.message, {suggestions: err.suggestions, code: err.code});
+ }
+ const answered = resultSet({count: 1, resultKind: 'mixed', directMatch: true});
+ if (json) {
+ jsonOut(result);
+ return answered;
+ }
+ const run = getCliInvocation();
+ if (result.type === 'render.page') {
+ const d = result.data;
+ emit(
+ section(`Rendered ${d.input}`),
+ record({
+ input: d.input,
+ output: d.output,
+ bytes: kb(d.bytes),
+ cssBytes: kb(d.cssBytes),
+ classes: d.classes,
+ images: d.images,
+ files: d.files.join(', '),
+ stylesheets: d.stylesheets.join(', ') || 'none',
+ }),
+ ...(d.warnings.length > 0
+ ? [section('Warnings'), list(d.warnings.map(w => w.message))]
+ : []),
+ text(`Give it back: ${run} experimental render --reverse ${d.output}`),
+ );
+ return answered;
+ }
+ const d = result.data;
+ emit(
+ section(d.mode === 'embedded' ? `Restored ${d.output}` : `Rebuilt ${d.output}`),
+ record({
+ input: d.input,
+ mode: d.mode,
+ exact: d.exact,
+ output: d.output,
+ files: d.files.join(', '),
+ ...(d.missing?.length ? {missing: d.missing.join(', ')} : {}),
+ ...(d.mode === 'rebuilt'
+ ? {
+ components: (d.components ?? []).join(', ') || 'none',
+ elements: d.elements ?? 0,
+ ...(d.omitted?.length ? {omitted: d.omitted.join(', ')} : {}),
+ ...(d.unknown?.length ? {unknown: d.unknown.join(', ')} : {}),
+ }
+ : {}),
+ }),
+ ...(d.mode === 'rebuilt'
+ ? [
+ text(
+ 'The file had no embedded source, so the page was rebuilt from its Astryx markup: text and layout only. Review it before use.',
+ ),
+ ]
+ : []),
+ );
+ return answered;
+ },
+ });
+}
diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
index f990a30aad..ae2809ee32 100644
--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs
+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
@@ -29,6 +29,7 @@ import {describe, it, expect, beforeAll, afterAll} from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
+import * as crypto from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {runCli} from '../../../test-utils/run-cli.mjs';
import {writeIconPackage} from '../../../test-utils/icon-set-fixture.mjs';
@@ -420,6 +421,51 @@ const CASES = [
'score — the reason states the tier',
],
},
+ {
+ name: 'experimental render',
+ args: ['experimental', 'render', 'page.jsx'],
+ cwd: '__TMP__',
+ // A page with no imports, in a folder that can resolve React.
+ setup: dir => {
+ fs.mkdirSync(path.join(dir, 'node_modules'), {recursive: true});
+ for (const pkg of ['react', 'react-dom']) {
+ fs.symlinkSync(
+ path.join(REPO_ROOT, 'node_modules', pkg),
+ path.join(dir, 'node_modules', pkg),
+ );
+ }
+ fs.writeFileSync(
+ path.join(dir, 'page.jsx'),
+ 'export default function Page() { return <h1>Hello</h1>; }\n',
+ );
+ },
+ jsonFieldAllowlist: ['warnings — listed under Warnings when present'],
+ },
+ {
+ // The --reverse projection (same command, same folder as the case above).
+ name: 'experimental render',
+ args: ['experimental', 'render', '--reverse', 'carried.html', '--out', 'back.tsx', '--overwrite'],
+ cwd: '__TMP__',
+ // A rendered file that carries its page.
+ setup: dir => {
+ const source = Buffer.from('export default function Page() { return <h1>Hello</h1>; }\n');
+ const json = JSON.stringify({
+ version: 1,
+ entry: 'page.jsx',
+ files: [
+ {
+ path: 'page.jsx',
+ sha256: crypto.createHash('sha256').update(source).digest('hex'),
+ base64: source.toString('base64'),
+ },
+ ],
+ });
+ fs.writeFileSync(
+ path.join(dir, 'carried.html'),
+ `<!doctype html><html><body><h1 class="astryx-heading">Hello</h1><script type="application/x-astryx-source">${json}</script></body></html>`,
+ );
+ },
+ },
{
name: 'manifest',
args: ['manifest'],
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index 817517d55c..b6f9f5e642 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -99,6 +99,7 @@ export const JSON_SUPPORTED = new Set([
'experimental icon use',
'experimental icon new-set',
'experimental icon new-definition',
+ 'experimental render',
'build',
'swizzle',
'gap-report',
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 2066da3b5f..5320f420a2 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -123,6 +123,13 @@ const RUNNERS = {
runs: SELF_DOCS,
sites: ['import ../experimental.doc.mjs'],
},
+ 'clients/cli/commands/experimental/render.mjs': {
+ runs: SELF_DOCS,
+ sites: [
+ 'import ../../../../api/render/render.doc.mjs',
+ 'import ../experimental-render.doc.mjs',
+ ],
+ },
'clients/cli/commands/manifest.mjs': {
runs: SELF_DOCS,
sites: ['import ./manifest.doc.mjs'],
@@ -350,6 +357,14 @@ const RUNNERS = {
runs: 'authored doc files, each one handed to the compiler, with the loader its reader has always used',
sites: ['importDocModule', 'importNativeModule ×3', 'importTemplateModule'],
},
+ 'foundation/render/page-worker.mjs': {
+ runs: 'the page `astryx experimental render` renders, its local modules, React, and the StyleX compiler, in a worker',
+ sites: ['.import() ×3', 'createJiti ×2', 'require(@stylexjs/babel-plugin)'],
+ },
+ 'foundation/render/render-page.mjs': {
+ runs: 'the render worker, so a page that never finishes can be stopped',
+ sites: ['worker_threads.Worker'],
+ },
'foundation/fs/module-loader.mjs': {
runs: 'user modules (config, manifests, handlers, codemods): natively, through jiti, or by require for a fresh CommonJS read',
sites: [
diff --git a/packages/cli/foundation/render/assets.mjs b/packages/cli/foundation/render/assets.mjs
new file mode 100644
index 0000000000..1b6cbaff49
--- /dev/null
+++ b/packages/cli/foundation/render/assets.mjs
@@ -0,0 +1,102 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Local files as data: URIs for `astryx experimental render`, so the
+ * rendered page needs nothing beside it.
+ *
+ * @position foundation/render — used by page-worker.mjs and render-page.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+/** The largest single file inlined into a rendered page. */
+export const MAX_ASSET_BYTES = 8 * 1024 * 1024;
+
+/** @type {Record<string, string>} */
+const MIME = {
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ webp: 'image/webp',
+ avif: 'image/avif',
+ svg: 'image/svg+xml',
+ ico: 'image/x-icon',
+ bmp: 'image/bmp',
+ woff: 'font/woff',
+ woff2: 'font/woff2',
+ ttf: 'font/ttf',
+ otf: 'font/otf',
+ mp4: 'video/mp4',
+ webm: 'video/webm',
+ mp3: 'audio/mpeg',
+ wav: 'audio/wav',
+};
+
+/** @param {string} file */
+export const isAssetPath = file =>
+ Object.hasOwn(MIME, path.extname(file).slice(1).toLowerCase());
+
+/** An error carrying a render error code. */
+export class RenderAssetError extends Error {
+ /**
+ * @param {string} code
+ * @param {string} message
+ * @param {Record<string, unknown>} [detail]
+ */
+ constructor(code, message, detail) {
+ super(message);
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+/**
+ * Read a local file as a data: URI.
+ * @param {string} file absolute path
+ * @returns {string}
+ */
+export function assetDataUri(file) {
+ /** @type {fs.Stats} */
+ let stat;
+ try {
+ stat = fs.statSync(file);
+ } catch {
+ throw new RenderAssetError(
+ 'ERR_FILE_NOT_FOUND',
+ `The page uses ${file}, which does not exist`,
+ {module: file},
+ );
+ }
+ if (stat.size > MAX_ASSET_BYTES) {
+ throw new RenderAssetError(
+ 'ERR_RENDER_ASSET_TOO_LARGE',
+ `${path.basename(file)} is ${(stat.size / 1048576).toFixed(1)} MB; a rendered page inlines files up to ${MAX_ASSET_BYTES / 1048576} MB each. Use a smaller copy of it.`,
+ {file, bytes: stat.size, limit: MAX_ASSET_BYTES},
+ );
+ }
+ const mime = MIME[path.extname(file).slice(1).toLowerCase()] ?? 'application/octet-stream';
+ return `data:${mime};base64,${fs.readFileSync(file).toString('base64')}`;
+}
+
+/**
+ * Whether bytes are a known image, font or media format, whatever the file's
+ * extension says (a JPEG saved as `.png` is still an inert image): their
+ * leading bytes match one (an SVG is XML with an <svg> element). A carried
+ * asset is carried, and written back, only when they do.
+ * @param {Buffer} bytes
+ */
+export function isAssetBytes(bytes) {
+ const at = (/** @type {number} */ i, /** @type {string} */ text) =>
+ bytes.subarray(i, i + text.length).toString('latin1') === text;
+ const b = (/** @type {number[]} */ ...xs) => xs.every((x, i) => bytes[i] === x);
+ if (at(0, '\x89PNG\r\n\x1a\n') || b(0xff, 0xd8, 0xff) || at(0, 'GIF87a') || at(0, 'GIF89a')) return true;
+ if (at(0, 'RIFF') && (at(8, 'WEBP') || at(8, 'WAVE'))) return true;
+ if (at(4, 'ftyp')) return true; // AVIF, MP4
+ if (at(0, 'BM') || b(0, 0, 1, 0)) return true; // BMP, ICO
+ if (at(0, 'wOFF') || at(0, 'wOF2') || at(0, 'OTTO') || at(0, 'true') || b(0, 1, 0, 0)) return true;
+ if (b(0x1a, 0x45, 0xdf, 0xa3) || at(0, 'ID3') || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0)) return true;
+ const head = bytes.subarray(0, 4096).toString('utf8').replace(/^\uFEFF/, '').trimStart();
+ return head.startsWith('<') && /<svg[\s>]/i.test(head);
+}
diff --git a/packages/cli/foundation/render/component-map.mjs b/packages/cli/foundation/render/component-map.mjs
new file mode 100644
index 0000000000..85b399ae0e
--- /dev/null
+++ b/packages/cli/foundation/render/component-map.mjs
@@ -0,0 +1,141 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Which installed component draws each Astryx theme target (the
+ * `astryx-<name>` class), read from a package's built modules and
+ * declarations, for `astryx experimental render --reverse`.
+ *
+ * @position foundation/render — used by rebuild.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+
+/** @param {string} s */
+export const pascal = s => s.replace(/(^|-)([a-z0-9])/g, (_, __, c) => c.toUpperCase());
+
+/**
+ * @typedef {object} ComponentEntry
+ * @property {string} name - Export name.
+ * @property {string} module - Import specifier.
+ * @property {Set<string>} props - Prop names its declaration lists.
+ * @property {Set<string>} numeric - Props whose type includes `number`.
+ * @property {Map<string, string>} required - Props its declaration requires, with their declared types.
+ * @property {boolean} children - Whether it takes children.
+ * @property {boolean} label - Whether it takes `label`.
+ */
+
+/**
+ * Map each theme target (the `astryx-<name>` class) to the components that
+ * render it, by reading an installed package's built modules.
+ * @param {string} pkg e.g. `@astryxdesign/core`
+ * @param {string} fromDir where to resolve it from
+ * @returns {Map<string, ComponentEntry[]>}
+ */
+export function componentMap(pkg, fromDir) {
+ /** @type {Map<string, ComponentEntry[]>} */
+ const map = new Map();
+ /** @type {string} */
+ let dist;
+ try {
+ const req = createRequire(path.join(fromDir, 'noop.js'));
+ let d = path.dirname(req.resolve(pkg));
+ while (!fs.existsSync(path.join(d, 'package.json')) && path.dirname(d) !== d) d = path.dirname(d);
+ dist = path.join(d, 'dist');
+ } catch {
+ return map;
+ }
+ if (!fs.existsSync(dist)) return map;
+ // Where each name can be imported from: the package's public subpaths.
+ /** @type {Map<string, string[]>} */
+ const exported = new Map();
+ try {
+ const pj = JSON.parse(fs.readFileSync(path.join(dist, '..', 'package.json'), 'utf8'));
+ for (const [key, value] of Object.entries(pj.exports ?? {})) {
+ const target = typeof value === 'string' ? value : /** @type {any} */ (value)?.default ?? /** @type {any} */ (value)?.import;
+ if (key === '.' || typeof target !== 'string' || !target.endsWith('.js')) continue;
+ const file = path.join(dist, '..', target);
+ if (!fs.existsSync(file)) continue;
+ const js = fs.readFileSync(file, 'utf8');
+ /** @type {string[]} */
+ const names = [];
+ for (const m of js.matchAll(/export\s*\{([^}]*)\}/g)) {
+ for (const part of m[1].split(',')) {
+ const name = part.trim().split(/\s+as\s+/).pop()?.trim();
+ if (name) names.push(name);
+ }
+ }
+ for (const m of js.matchAll(/export\s+(?:function|const|class)\s+([A-Za-z0-9_]+)/g)) names.push(m[1]);
+ for (const name of names) {
+ const list = exported.get(name) ?? [];
+ list.push(`${pkg}/${key.slice(2)}`);
+ exported.set(name, list);
+ }
+ }
+ } catch {
+ // No readable exports map: fall back to folder names.
+ }
+ /** @param {string} name @param {string} folder */
+ const moduleFor = (name, folder) => {
+ const list = exported.get(name);
+ if (!list) return null;
+ return list.find(m => m.endsWith(`/${name}`)) ?? list.find(m => m.endsWith(`/${folder}`)) ?? list[0];
+ };
+ for (const dirent of fs.readdirSync(dist, {withFileTypes: true})) {
+ if (!dirent.isDirectory()) continue;
+ const folder = path.join(dist, dirent.name);
+ for (const file of fs.readdirSync(folder)) {
+ if (!file.endsWith('.js')) continue;
+ const js = fs.readFileSync(path.join(folder, file), 'utf8');
+ const targets = [...js.matchAll(/themeProps\(\s*['"]([a-z0-9-]+)['"]/g)].map(t => t[1]);
+ if (targets.length === 0) continue;
+ const names = [...js.matchAll(/^([A-Z][A-Za-z0-9]*)\.displayName = ['"]([A-Za-z0-9.]+)['"]/gm)].map(n => n[1]);
+ if (names.length === 0) continue;
+ const dts = path.join(folder, file.replace(/\.js$/, '.d.ts'));
+ const decl = fs.existsSync(dts) ? fs.readFileSync(dts, 'utf8') : '';
+ for (const target of new Set(targets)) {
+ for (const name of names) {
+ /** @type {Set<string>} */
+ const props = new Set();
+ /** @type {Set<string>} */
+ const numeric = new Set();
+ /** @type {Map<string, string>} */
+ const required = new Map();
+ const body = new RegExp(`interface ${name}Props[^{]*\\{([\\s\\S]*?)\\n\\}`).exec(decl)?.[1] ?? '';
+ for (const p of body.matchAll(/^\s{4}(?:readonly\s+)?([a-zA-Z][\w]*)\??:\s*([^;]*)/gm)) {
+ props.add(p[1]);
+ if (!/^\s{4}(?:readonly\s+)?[a-zA-Z]\w*\?/.test(p[0])) required.set(p[1], p[2].trim());
+ if (/\bnumber\b|\b\d+\b/.test(p[2])) numeric.add(p[1]);
+ }
+ const module = moduleFor(name, dirent.name);
+ if (!module) continue;
+ const entry = {
+ name,
+ module,
+ props,
+ numeric,
+ required,
+ children: props.has('children') || /extends[^{]*(PropsWithChildren|HTMLAttributes|ComponentProps)/.test(decl),
+ label: props.has('label'),
+ };
+ const list = map.get(target) ?? [];
+ if (!list.some(e => e.name === name)) list.push(entry);
+ // A stack with a fixed direction reads best as VStack / HStack.
+ if (target === 'stack' && name === 'Stack') {
+ for (const alias of ['VStack', 'HStack']) {
+ const aliasModule = moduleFor(alias, dirent.name);
+ if (!aliasModule || list.some(e => e.name === alias)) continue;
+ const aliasProps = new Set(props);
+ aliasProps.delete('direction');
+ list.push({...entry, name: alias, module: aliasModule, props: aliasProps});
+ }
+ }
+ map.set(target, list);
+ }
+ }
+ }
+ }
+ return map;
+}
+
diff --git a/packages/cli/foundation/render/css-cut.mjs b/packages/cli/foundation/render/css-cut.mjs
new file mode 100644
index 0000000000..2ab165ed83
--- /dev/null
+++ b/packages/cli/foundation/render/css-cut.mjs
@@ -0,0 +1,144 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Cut a stylesheet down to the rules a rendered page uses, for
+ * `astryx experimental render`. A rule stays when every class in one of its
+ * selectors appears in the page; rules without classes (`:root` tokens,
+ * element resets) always stay. `@property`,
+ * `@font-face` and the `@keyframes` a kept rule names stay too; `@layer`
+ * order statements are dropped for the caller to write once, first
+ * (see layerOrderOf).
+ *
+ * @position foundation/render — used by render-page.mjs
+ */
+
+import postcss from 'postcss';
+
+/**
+ * Every class name in a page's markup.
+ * @param {string} markup
+ * @returns {Set<string>}
+ */
+export function classesIn(markup) {
+ /** @type {Set<string>} */
+ const used = new Set();
+ for (const m of markup.matchAll(/\sclass="([^"]*)"/g)) {
+ for (const c of m[1].split(/\s+/)) if (c) used.add(c);
+ }
+ return used;
+}
+
+/** Unescape a CSS identifier as written in a selector. @param {string} s */
+const unescapeIdent = s =>
+ s
+ .replace(/\\([0-9a-fA-F]{1,6})\s?/g, (_, h) =>
+ String.fromCodePoint(parseInt(h, 16)),
+ )
+ .replace(/\\(.)/g, '$1');
+
+/**
+ * The classes a selector needs, ignoring any inside `:not()`, `:is()`,
+ * `:where()` or `:has()`.
+ * @param {string} selector
+ * @returns {string[]}
+ */
+export function requiredClasses(selector) {
+ let s = selector;
+ // Drop :not(), :is(), :where() and :has() groups (they can nest one level
+ // in practice): what is inside need not all appear, so a rule is never cut
+ // for classes in them.
+ for (let i = 0; i < 3 && /:(not|is|where|has)\(/.test(s); i++) {
+ s = s.replace(/:(?:not|is|where|has)\((?:[^()]|\([^()]*\))*\)/g, '');
+ }
+ return [...s.matchAll(/\.((?:\\.|[A-Za-z0-9_-])+)/g)].map(m => unescapeIdent(m[1]));
+}
+
+/**
+ * Split a selector list on top-level commas.
+ * @param {string} list
+ * @returns {string[]}
+ */
+function splitSelectors(list) {
+ /** @type {string[]} */
+ const out = [];
+ let depth = 0;
+ let start = 0;
+ for (let i = 0; i < list.length; i++) {
+ const ch = list[i];
+ if (ch === '\\') {
+ i++;
+ continue;
+ }
+ if (ch === '(' || ch === '[') depth++;
+ else if (ch === ')' || ch === ']') depth--;
+ else if (ch === ',' && depth === 0) {
+ out.push(list.slice(start, i));
+ start = i + 1;
+ }
+ }
+ out.push(list.slice(start));
+ return out.map(s => s.trim()).filter(Boolean);
+}
+
+/**
+ * Cut a stylesheet to the rules the page uses.
+ * @param {string} css
+ * @param {Set<string>} used class names in the page
+ * @returns {string}
+ */
+export function cutCss(css, used) {
+ const rootNode = postcss.parse(css);
+ rootNode.walkComments(c => {
+ c.remove();
+ });
+ // Layer order statements are written once, first, by the caller.
+ rootNode.walkAtRules('layer', at => {
+ if (!at.nodes) at.remove();
+ });
+ rootNode.walkRules(rule => {
+ const parent = /** @type {any} */ (rule.parent);
+ if (parent?.type === 'atrule' && /keyframes$/i.test(parent.name)) return;
+ const kept = splitSelectors(rule.selector).filter(sel =>
+ requiredClasses(sel).every(c => used.has(c)),
+ );
+ if (kept.length === 0) rule.remove();
+ else if (kept.length !== splitSelectors(rule.selector).length) {
+ rule.selector = kept.join(',');
+ }
+ });
+ // Drop the grouping at-rules left empty, innermost first.
+ let changed = true;
+ while (changed) {
+ changed = false;
+ rootNode.walkAtRules(at => {
+ if (
+ /^(media|supports|container|layer|scope|starting-style)$/i.test(at.name) &&
+ at.nodes &&
+ at.nodes.length === 0
+ ) {
+ at.remove();
+ changed = true;
+ }
+ });
+ }
+ // Keep only the keyframes a remaining rule names.
+ /** @type {Set<string>} */
+ const named = new Set();
+ rootNode.walkDecls(/^(animation|animation-name)$/i, d => {
+ for (const w of d.value.split(/[\s,]+/)) named.add(w);
+ });
+ rootNode.walkAtRules(/keyframes$/i, at => {
+ if (!named.has(at.params.trim())) at.remove();
+ });
+ return rootNode.toString().replace(/\n\s*\n/g, '\n');
+}
+
+/**
+ * The first `@layer a, b, c;` order statement in a stylesheet, if any.
+ * @param {string} css
+ * @returns {string}
+ */
+export function layerOrderOf(css) {
+ const bare = css.replace(/\/\*[\s\S]*?\*\//g, '');
+ return /@layer\s+[\w-]+(?:\s*,\s*[\w-]+)*\s*;/.exec(bare)?.[0] ?? '';
+}
diff --git a/packages/cli/foundation/render/embedded-files.mjs b/packages/cli/foundation/render/embedded-files.mjs
new file mode 100644
index 0000000000..ed04e5303e
--- /dev/null
+++ b/packages/cli/foundation/render/embedded-files.mjs
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Which files a rendered page may carry, for `astryx experimental
+ * render`. Rendering embeds only these, and `--reverse` writes only these: a
+ * file someone sends can name nothing else. A page is a module; beside it go
+ * only the stylesheets, JSON and images it imports. Never a dotfile or a
+ * dot-folder (such as `.git/`), never `node_modules`, never a package
+ * manifest, lockfile or tool configuration (`package.json`, `tsconfig.json`,
+ * `vite.config.ts`, `astryx.config.mjs`, ...), and never a path that climbs
+ * (`..`) or starts at the root.
+ *
+ * @position foundation/render — used by render-page.mjs and the render subject
+ */
+
+import {isAssetPath} from './assets.mjs';
+
+/** The file extensions a page module may have. */
+export const PAGE_EXTENSIONS = ['.tsx', '.jsx', '.ts', '.js', '.mjs'];
+
+/** JSON files that configure a project or a tool rather than hold page data. */
+const CONFIG_JSON =
+ /^(package|package-lock|composer|deno|turbo|vercel|nx|lerna|app|bower|now|netlify|firebase|renovate|project|workspace|angular|biome|components)\.jsonc?$|config|(^|[._-])rc\.jsonc?$|(^|[._-])lock\.jsonc?$/i;
+
+/** Tool configuration modules: `vite.config.ts`, `astryx.config.mjs`, `next.config.js`, `.eslintrc.js`, ... */
+const CONFIG_MODULE = /(^|\.)config\.[cm]?[jt]sx?$|^[a-z0-9-]+rc\.[cm]?[jt]s$/i;
+
+/** Any script module. */
+const SCRIPT = /\.(c|m)?[jt]sx?$/i;
+/** Script modules `node --test` and AVA match by a `test-*` name (no JSX). */
+const PLAIN_SCRIPT = /\.(c|m)?[jt]s$/i;
+
+/**
+ * Whether a test, story or benchmark runner would run the file with nothing
+ * importing it, by the union of their default patterns: Jest and Vitest
+ * (`*.test.*`, `*.spec.*`, `test.*`, `spec.*`, `__tests__/`), Vitest bench
+ * (`*.bench.*`, `*.benchmark.*`), Storybook (`*.stories.*`, `*.story.*`),
+ * Cypress (`*.cy.*`), Bun (`*_test.*`, `*_spec.*`), `node --test`
+ * (`*-test.*`, `test/`) and AVA (`tests/`), and `test-*` for .js and .ts.
+ * @param {string[]} segments the path where the file lands, from the project
+ * root (the folder runners search), `/`-split
+ */
+export function runnerPicksUp(segments) {
+ const base = segments[segments.length - 1];
+ if (!SCRIPT.test(base)) return false;
+ const stem = base.replace(/\.[^.]+$/, '').toLowerCase();
+ const folders = segments.slice(0, -1).map(seg => seg.toLowerCase());
+ // Jest's `?(*.)+(spec|test)` repeats: `spectest.js`, `test.spec.js`.
+ if (/(^|[._-])(test|spec)+$/.test(stem)) return true;
+ if (/\.(bench|benchmark|stories|story|cy)$/.test(stem)) return true;
+ if (folders.some(seg => seg === '__tests__' || seg === 'test' || seg === 'tests')) return true;
+ // `test-*` only for the .js and .ts families: no default runner picks up
+ // `test-results.tsx`.
+ if (PLAIN_SCRIPT.test(base) && /^test[-_]/.test(stem)) return true;
+ return false;
+}
+
+/** @param {string} p */
+const extOf = p => {
+ const base = p.slice(p.lastIndexOf('/') + 1);
+ const dot = base.lastIndexOf('.');
+ return dot > 0 ? base.slice(dot).toLowerCase() : '';
+};
+
+/**
+ * Why a path may not be carried by a rendered page, or null when it may.
+ * @param {string} p a `/`-separated path relative to the embedded tree's root
+ * @param {{page?: boolean}} [options] `page`: the path is the page itself
+ * @returns {{code: 'ERR_PATH_TRAVERSAL' | 'ERR_RENDER_SOURCE_DAMAGED', reason: string} | null}
+ */
+export function embeddedPathProblem(p, options = {}) {
+ if (typeof p !== 'string' || p.length === 0 || p.includes('\0')) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: 'an empty or invalid path'};
+ }
+ if (p.startsWith('/') || /^[a-zA-Z]:/.test(p) || p.includes('\\')) {
+ return {code: 'ERR_PATH_TRAVERSAL', reason: `an absolute path (${p})`};
+ }
+ const segments = p.split('/');
+ if (segments.some(s => s === '..' || s === '.' || s === '')) {
+ return {code: 'ERR_PATH_TRAVERSAL', reason: `a path outside its own tree (${p})`};
+ }
+ if (segments.some(s => s.startsWith('.'))) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a dotfile or dot-folder (${p})`};
+ }
+ if (segments.includes('node_modules')) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a file inside node_modules (${p})`};
+ }
+ const base = segments[segments.length - 1];
+ const ext = extOf(p);
+ // The page is judged by where it lands (its name in the file is only a
+ // default), so only its kind counts here.
+ if (options.page) {
+ if (!PAGE_EXTENSIONS.includes(ext)) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a page that is not a page module (${p})`};
+ }
+ return null;
+ }
+ // A file a test, story or benchmark runner picks up by its name or folder
+ // runs without anyone importing it.
+ if (runnerPicksUp(segments)) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a test, spec, story or benchmark file (${p})`};
+ }
+ if (((ext === '.json' || ext === '.jsonc') && CONFIG_JSON.test(base)) || CONFIG_MODULE.test(base)) {
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a project or tool configuration file (${p})`};
+ }
+ if (PAGE_EXTENSIONS.includes(ext) || ext === '.css' || ext === '.json' || isAssetPath(p)) return null;
+ return {code: 'ERR_RENDER_SOURCE_DAMAGED', reason: `a kind of file a render never embeds (${p})`};
+}
diff --git a/packages/cli/foundation/render/embedded-imports.mjs b/packages/cli/foundation/render/embedded-imports.mjs
new file mode 100644
index 0000000000..fec3486012
--- /dev/null
+++ b/packages/cli/foundation/render/embedded-imports.mjs
@@ -0,0 +1,315 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Which embedded files the page itself reaches, for `astryx
+ * experimental render --reverse`. A received file is untrusted, so its list
+ * of files is not: a file is written only when the embedded page reaches it
+ * through its own imports (static, re-exports, `import()` and `require()` of
+ * a string), followed module by module through the embedded tree. Relative
+ * imports resolve inside the tree; an alias import resolves through the
+ * receiving project's own `tsconfig.json` or `jsconfig.json` paths, never the
+ * sender's.
+ *
+ * @position foundation/render — used by the render subject's adapter
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {parse} from '@babel/parser';
+import {PAGE_EXTENSIONS} from './embedded-files.mjs';
+import postcss from 'postcss';
+import {isAssetPath} from './assets.mjs';
+
+/**
+ * What a stylesheet's `@import` rules load, read with postcss so comments
+ * are ignored.
+ * @param {string} css
+ * @returns {string[]}
+ */
+function cssImports(css) {
+ /** @type {string[]} */
+ const out = [];
+ try {
+ postcss.parse(css).walkAtRules(/^import$/i, rule => {
+ const m = /^\s*(?:url\(\s*(['"]?)([\s\S]*?)\1\s*\)|(['"])([\s\S]*?)\3)/.exec(rule.params);
+ const url = m ? (m[2] ?? m[4]) : '';
+ if (url) out.push(url);
+ });
+ } catch {
+ // Not valid CSS: it imports nothing a restore needs.
+ }
+ return out;
+}
+
+/** Extensions an extensionless import may stand for, in resolution order. */
+const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.json'];
+
+/**
+ * The string specifiers one module imports.
+ * @param {string} source
+ * @param {string} file for the parser's TypeScript/JSX choice
+ * @returns {string[]}
+ */
+export function importSpecifiers(source, file) {
+ return scanModule(source, file).imports;
+}
+
+/**
+ * Relative asset paths in a piece of text: a `./`/`../` path to an image or
+ * font, bare or inside `url(...)`.
+ * @param {string} text
+ * @returns {string[]}
+ */
+export function assetRefsIn(text) {
+ /** @type {string[]} */
+ const out = [];
+ for (const m of text.matchAll(/(?:^|url\(\s*['"]?)(\.\.?\/[^'")\s]+)/g)) {
+ const ref = m[1].split(/[?#]/)[0];
+ if (isAssetPath(ref)) out.push(ref);
+ }
+ return out;
+}
+
+/**
+ * One module's imports, and the relative asset paths its strings name
+ * (`<img src="./logo.png">`, `url(./bg.png)` in a style).
+ * @param {string} source
+ * @param {string} file
+ * @returns {{imports: string[], assets: string[]}}
+ */
+function scanModule(source, file) {
+ /** @type {string[]} */
+ const assets = [];
+ /** @type {any} */
+ let ast;
+ try {
+ ast = parse(source, {
+ sourceType: 'module',
+ allowReturnOutsideFunction: true,
+ errorRecovery: true,
+ plugins: /\.(tsx?|mts|cts)$/.test(file) ? ['jsx', 'typescript'] : ['jsx'],
+ });
+ } catch {
+ return {imports: [], assets: []};
+ }
+ /** @type {string[]} */
+ const out = [];
+ /** @param {any} node */
+ const visit = node => {
+ if (!node || typeof node.type !== 'string') return;
+ if (node.type === 'StringLiteral') assets.push(...assetRefsIn(node.value));
+ else if (node.type === 'TemplateElement') assets.push(...assetRefsIn(node.value?.cooked ?? ''));
+ if (
+ (node.type === 'ImportDeclaration' ||
+ node.type === 'ExportNamedDeclaration' ||
+ node.type === 'ExportAllDeclaration') &&
+ node.source?.type === 'StringLiteral'
+ ) {
+ out.push(node.source.value);
+ } else if (
+ node.type === 'ImportExpression' &&
+ node.source?.type === 'StringLiteral'
+ ) {
+ out.push(node.source.value);
+ } else if (
+ node.type === 'CallExpression' &&
+ node.arguments?.[0]?.type === 'StringLiteral' &&
+ (node.callee?.type === 'Import' ||
+ (node.callee?.type === 'Identifier' && node.callee.name === 'require'))
+ ) {
+ out.push(node.arguments[0].value);
+ }
+ for (const key of Object.keys(node)) {
+ if (key === 'loc' || key === 'start' || key === 'end' || key === 'extra') continue;
+ const value = node[key];
+ if (Array.isArray(value)) value.forEach(visit);
+ else if (value && typeof value === 'object' && typeof value.type === 'string') visit(value);
+ }
+ };
+ visit(ast.program);
+ return {imports: out, assets};
+}
+
+/**
+ * Path aliases (`compilerOptions.paths`) of the project that holds `dir`, as
+ * absolute prefixes: `"@/*": ["./src/*"]` becomes `["@/", "<root>/src/"]`.
+ * @param {string} dir
+ * @returns {[string, string][]}
+ */
+export function receivingAliases(dir) {
+ let d = dir;
+ while (!fs.existsSync(d) && path.dirname(d) !== d) d = path.dirname(d);
+ for (;;) {
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
+ const file = path.join(d, name);
+ if (!fs.existsSync(file)) continue;
+ try {
+ const text = fs
+ .readFileSync(file, 'utf8')
+ .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
+ .replace(/,(\s*[}\]])/g, '$1');
+ const options = JSON.parse(text)?.compilerOptions ?? {};
+ const base = path.resolve(d, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
+ /** @type {[string, string][]} */
+ const out = [];
+ for (const [key, targets] of Object.entries(options.paths ?? {})) {
+ const target = Array.isArray(targets) ? targets[0] : undefined;
+ if (typeof target !== 'string') continue;
+ if (key.endsWith('/*') && target.endsWith('/*')) {
+ out.push([key.slice(0, -1), `${path.resolve(base, target.slice(0, -2))}${path.sep}`]);
+ } else if (!key.includes('*') && !target.includes('*')) {
+ out.push([key, path.resolve(base, target)]);
+ }
+ }
+ return out;
+ } catch {
+ return [];
+ }
+ }
+ if (fs.existsSync(path.join(d, 'package.json'))) return [];
+ const up = path.dirname(d);
+ if (up === d) return [];
+ d = up;
+ }
+}
+
+/**
+ * @typedef {object} Reach
+ * @property {boolean} relative - Reached by a relative import (or it is the
+ * page), so it goes where the page's layout puts it.
+ * @property {Set<string>} aliased - Absolute paths a receiving-project alias
+ * import names for it, so it also goes there.
+ */
+
+/**
+ * The embedded files the page reaches through its imports.
+ * @param {{path: string, base64: string}[]} files the embedded files, page
+ * first; every path appears once (callers refuse duplicates first)
+ * @param {{aliases?: [string, string][]}} [options] the receiving project's
+ * path aliases, absolute (see receivingAliases)
+ * @returns {{reached: Map<string, Reach>, missing: string[]}} the reached
+ * tree paths, and the relative imports the file does not carry
+ */
+export function reachableFiles(files, {aliases = []} = {}) {
+ const byPath = new Map(files.map(f => [f.path, f]));
+ /** @type {Map<string, Reach>} */
+ const reached = new Map();
+ /** @type {Set<string>} */
+ const missing = new Set();
+ /** @param {string} candidate tree path, `/`-separated */
+ const resolveIn = candidate => {
+ if (byPath.has(candidate)) return candidate;
+ for (const ext of RESOLVE_EXTENSIONS) if (byPath.has(candidate + ext)) return candidate + ext;
+ for (const ext of RESOLVE_EXTENSIONS) if (byPath.has(`${candidate}/index${ext}`)) return `${candidate}/index${ext}`;
+ return null;
+ };
+ /**
+ * The one tree file an alias import names: the file whose path ends with
+ * the import's rest (`@/components/Header` -> `.../components/Header.tsx`).
+ * @param {string} rest
+ */
+ const bySuffix = rest => {
+ /** @type {{path: string, tail: string}[]} */
+ const hits = [];
+ for (const p of byPath.keys()) {
+ for (const tail of [rest, ...RESOLVE_EXTENSIONS.map(e => rest + e), ...RESOLVE_EXTENSIONS.map(e => `${rest}/index${e}`)]) {
+ if (p === tail || p.endsWith(`/${tail}`)) {
+ hits.push({path: p, tail});
+ break;
+ }
+ }
+ }
+ return hits.length === 1 ? hits[0] : null;
+ };
+ /** @param {string} p */
+ const reach = p => {
+ let r = reached.get(p);
+ const fresh = !r;
+ if (!r) {
+ r = {relative: false, aliased: new Set()};
+ reached.set(p, r);
+ }
+ return {r, fresh};
+ };
+ /** @type {string[]} */
+ const queue = [];
+ if (files.length > 0) {
+ reach(files[0].path).r.relative = true;
+ queue.push(files[0].path);
+ }
+ while (queue.length > 0) {
+ const current = /** @type {string} */ (queue.shift());
+ const ext = path.posix.extname(current).toLowerCase();
+ const isModule = PAGE_EXTENSIONS.includes(ext);
+ if (!isModule && ext !== '.css') continue;
+ const entry = byPath.get(current);
+ if (!entry) continue;
+ const source = Buffer.from(entry.base64, 'base64').toString('utf8');
+ // Images and fonts a module or stylesheet names by a relative path are
+ // part of the page too.
+ const scanned = isModule
+ ? scanModule(source, current)
+ : {
+ // A stylesheet's own `@import`s count as imports.
+ // A stylesheet's own relative `@import`s count as imports (read
+ // with postcss, so a commented-out one does not); a package one
+ // (`@scope/pkg/x.css`) or a remote one is not the page's file.
+ imports: cssImports(source)
+ .filter(ref => !/^([a-z]+:)?\/\//i.test(ref) && !/^[@~]/.test(ref))
+ // A bare name (`theme.css`) is the sheet beside it when the file
+ // carries one, else a package's.
+ .filter(ref => ref.startsWith('.') || byPath.has(path.posix.normalize(path.posix.join(path.posix.dirname(current), ref))))
+ .map(ref => (ref.startsWith('.') ? ref : `./${ref}`)),
+ assets: assetRefsIn(source),
+ };
+ for (const ref of scanned.assets) {
+ const joined = path.posix.normalize(path.posix.join(path.posix.dirname(current), ref));
+ if (joined.startsWith('..')) continue;
+ if (!byPath.has(joined)) {
+ missing.add(joined);
+ continue;
+ }
+ reach(joined).r.relative = true;
+ }
+ for (const spec of scanned.imports) {
+ const bare = spec.split('?')[0];
+ if (bare.startsWith('./') || bare.startsWith('../')) {
+ const joined = path.posix.normalize(path.posix.join(path.posix.dirname(current), bare));
+ const target = joined.startsWith('..') ? null : resolveIn(joined);
+ if (!target) {
+ missing.add(joined);
+ continue;
+ }
+ const {r, fresh} = reach(target);
+ r.relative = true;
+ if (fresh) queue.push(target);
+ continue;
+ }
+ for (const [key, aliasTarget] of aliases) {
+ const named = key.endsWith('/') ? bare.startsWith(key) : bare === key;
+ if (!named) continue;
+ // A wildcard alias names a path under its target; an exact alias
+ // (`"@theme": ["./src/theme.ts"]`) names its target file itself.
+ const exactExt = key.endsWith('/') ? '' : path.extname(aliasTarget);
+ const rest = key.endsWith('/')
+ ? bare.slice(key.length)
+ : path.basename(aliasTarget, exactExt);
+ const hit = rest ? bySuffix(rest) : null;
+ if (!hit) break;
+ const target = hit.path;
+ // The alias names the module without its extension or index file;
+ // the file keeps both: `@/c/Header` -> `<alias target>/c/Header.tsx`.
+ const abs = key.endsWith('/')
+ ? aliasTarget + hit.tail
+ : exactExt
+ ? aliasTarget
+ : aliasTarget + hit.tail.slice(rest.length);
+ const {r, fresh} = reach(target);
+ r.aliased.add(abs);
+ if (fresh) queue.push(target);
+ break;
+ }
+ }
+ }
+ return {reached, missing: [...missing].sort()};
+}
diff --git a/packages/cli/foundation/render/html-reader.mjs b/packages/cli/foundation/render/html-reader.mjs
new file mode 100644
index 0000000000..0c298cf9f1
--- /dev/null
+++ b/packages/cli/foundation/render/html-reader.mjs
@@ -0,0 +1,121 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file A small, forgiving HTML reader for `astryx experimental render
+ * --reverse`: enough for rendered markup, plus the helpers that ask it which
+ * Astryx component an element came from.
+ *
+ * @position foundation/render — used by rebuild.mjs and the render subject
+ */
+
+/** @typedef {{tag: string, attrs: Record<string, string>, children: Node[]}} ElementNode */
+/** @typedef {ElementNode | {text: string}} Node */
+
+export const VOID = new Set([
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta',
+ 'source', 'track', 'wbr',
+]);
+
+/** @param {string} s */
+export const decode = s =>
+ s
+ .replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
+ .replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
+ .replace(/&quot;/g, '"')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&nbsp;/g, '\u00a0')
+ .replace(/&amp;/g, '&');
+
+/**
+ * A small, forgiving HTML parser: enough for rendered markup.
+ * @param {string} html
+ * @returns {ElementNode}
+ */
+export function parseHtml(html) {
+ /** @type {ElementNode} */
+ const root = {tag: '#root', attrs: {}, children: []};
+ /** @type {ElementNode[]} */
+ const stack = [root];
+ const re = /<!--[\s\S]*?-->|<!doctype[^>]*>|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*(\/?)>|([^<]+|<)/gi;
+ /** @type {RegExpExecArray | null} */
+ let m;
+ while ((m = re.exec(html))) {
+ const top = stack[stack.length - 1];
+ if (m[1]) {
+ const tag = m[1].toLowerCase();
+ const at = stack.map(n => n.tag).lastIndexOf(tag);
+ if (at > 0) stack.length = at;
+ } else if (m[2]) {
+ const tag = m[2].toLowerCase();
+ /** @type {Record<string, string>} */
+ const attrs = {};
+ for (const a of (m[3] ?? '').matchAll(/([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) {
+ attrs[a[1].toLowerCase()] = decode(a[2] ?? a[3] ?? a[4] ?? '');
+ }
+ /** @type {ElementNode} */
+ const node = {tag, attrs, children: []};
+ top.children.push(node);
+ if (tag === 'script' || tag === 'style' || tag === 'textarea' || tag === 'title') {
+ const end = html.toLowerCase().indexOf(`</${tag}`, re.lastIndex);
+ const stop = end < 0 ? html.length : end;
+ node.children.push({text: html.slice(re.lastIndex, stop)});
+ re.lastIndex = stop;
+ stack.push(node);
+ } else if (!VOID.has(tag) && !m[4]) {
+ stack.push(node);
+ }
+ } else if (m[5]) {
+ top.children.push({text: decode(m[5])});
+ }
+ }
+ return root;
+}
+
+/** @param {Node} n @returns {n is ElementNode} */
+export const isEl = n => 'tag' in n;
+
+/** Elements whose children React refuses or treats as a value. */
+export const FORM_TAGS = new Set(['input', 'textarea', 'select']);
+
+/**
+ * Whether an element draws one of `tags` itself, not inside another Astryx
+ * component it contains.
+ * @param {ElementNode} n @param {Set<string>} tags @returns {boolean}
+ */
+export const hasTag = (n, tags) =>
+ tags.has(n.tag) ||
+ n.children.some(c => isEl(c) && !astryxClass(c) && hasTag(c, tags));
+
+/** @param {ElementNode} n @param {string} tag @returns {ElementNode | undefined} */
+export function find(n, tag) {
+ for (const c of n.children) {
+ if (!isEl(c)) continue;
+ if (c.tag === tag) return c;
+ const f = find(c, tag);
+ if (f) return f;
+ }
+ return undefined;
+}
+
+/** @param {Node} n @returns {string} */
+export const textOf = n =>
+ isEl(n)
+ ? n.tag === 'script' || n.tag === 'style'
+ ? ''
+ : n.children.map(textOf).join('')
+ : n.text;
+
+/** @param {ElementNode} n */
+export const astryxClass = n =>
+ (n.attrs.class ?? '')
+ .split(/\s+/)
+ .find(c => /^astryx-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(c))
+ ?.slice('astryx-'.length);
+
+/**
+ * Whether markup was rendered from Astryx components.
+ * @param {string} html
+ */
+export const isAstryxMarkup = html => /\sclass="(?:[^"]*\s)?astryx-[a-z0-9]/.test(html);
+
diff --git a/packages/cli/foundation/render/page-worker.mjs b/packages/cli/foundation/render/page-worker.mjs
new file mode 100644
index 0000000000..bd02b4511f
--- /dev/null
+++ b/packages/cli/foundation/render/page-worker.mjs
@@ -0,0 +1,519 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Worker for `astryx experimental render`: loads one page module from
+ * the project (TypeScript, JSX and StyleX compiled in memory) and renders its
+ * default export to static markup with the project's own React.
+ *
+ * It runs in a worker thread so a page that never finishes rendering can be
+ * stopped, and so nothing the page prints reaches the CLI's own output.
+ *
+ * @input workerData {entry, root}
+ * @output one message: {ok: true, markup, css, files, texts, logs} or
+ * {ok: false, error: {code, message, detail?}}
+ * @position foundation/render — started by render-page.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+import {format} from 'node:util';
+import {parentPort, workerData} from 'node:worker_threads';
+import {transformSync} from '@babel/core';
+import {createJiti} from 'jiti';
+import {assetDataUri, isAssetPath} from './assets.mjs';
+
+/** @typedef {{level: string, text: string}} PageLog */
+
+/** @type {{entry: string, root: string}} */
+const {entry, root} = workerData;
+const ROOT_PREFIX = root.endsWith(path.sep) ? root : root + path.sep;
+
+/** @type {PageLog[]} */
+const logs = [];
+for (const level of /** @type {const} */ (['log', 'info', 'warn', 'error', 'debug'])) {
+ console[level] = (/** @type {unknown[]} */ ...args) => {
+ const text = format(...args);
+ // The compiler's own notes are not the page's output.
+ if (text.startsWith('[BABEL]')) return;
+ logs.push({level, text});
+ };
+}
+
+const requireFromCli = createRequire(import.meta.url);
+const stylexPlugin = /** @type {any} */ (requireFromCli('@stylexjs/babel-plugin'));
+
+/** StyleX rules collected from every local module the page loads. */
+/** @type {unknown[]} */
+const stylexRules = [];
+/** CSS text of local stylesheets the page imports, in load order. */
+/** @type {{file: string, css: string}[]} */
+const importedCss = [];
+/** Every local (non-package) module the page loaded, page first. */
+/** @type {string[]} */
+const localFiles = [];
+/** Package stylesheets the page imports, by specifier and importing file. */
+/** @type {{spec: string, from: string}[]} */
+const packageCss = [];
+/** Sass and Less stylesheets the page imports, which a render cannot compile. @type {string[]} */
+const skippedCss = [];
+/** Local files inlined from asset imports. */
+/** @type {Set<string>} */
+const assetsInlined = new Set();
+/** Packages the page's own modules import from. */
+/** @type {Set<string>} */
+const packages = new Set();
+/** Static JSX text per element, for the dropped-children warning. */
+/** @type {{file: string, component: string, text: string, hidden: boolean, fn: string, line: number}[]} */
+const texts = [];
+/** Every static JSX text, by the function it is in. */
+/** @type {Record<string, string[]>} */
+const fnTexts = {};
+
+/** Components that show their content only on demand. */
+const HIDING =
+ /Dialog|Modal|Popover|Tooltip|Menu|Drawer|Sheet|Tab|Collapsible|Accordion|Disclosure|Overlay|Layer|Toast|Hover|Select|Combobox|Typeahead|Portal|Suspense|Lazy/;
+
+/** @param {any} el whether a JSX element has an open/show-style prop */
+const hasShowAttr = el =>
+ el.openingElement.attributes.some(
+ (/** @type {any} */ a) =>
+ a.type === 'JSXAttribute' &&
+ /^(open|isOpen|defaultOpen|show|isShown|visible|isVisible|hidden|expanded|isExpanded|defaultExpanded|collapsed|isCollapsed|defaultCollapsed|collapsible|when|if|max[A-Z]\w*|limit)$/.test(
+ a.name?.name,
+ ),
+ );
+
+/** @param {any} node a JSX element's name, as written */
+const jsxName = node => {
+ const n = node.openingElement.name;
+ return n.type === 'JSXIdentifier'
+ ? n.name
+ : n.type === 'JSXMemberExpression'
+ ? `${n.object.name}.${n.property.name}`
+ : '';
+};
+
+/** @type {Record<string, string>} */
+const ENTITIES = {
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0',
+ rsquo: '\u2019', lsquo: '\u2018', rdquo: '\u201d', ldquo: '\u201c',
+ mdash: '\u2014', ndash: '\u2013', hellip: '\u2026', middot: '\u00b7',
+ copy: '\u00a9', reg: '\u00ae', trade: '\u2122', times: '\u00d7', rarr: '\u2192', larr: '\u2190',
+};
+
+/** @param {any} node static JSX text as it renders, whitespace collapsed */
+const cleanText = node =>
+ node.type === 'JSXText'
+ ? String(node.extra?.raw ?? node.value)
+ .replace(/&#x([0-9a-f]+);/gi, (/** @type {string} */ _, h) => String.fromCodePoint(parseInt(h, 16)))
+ .replace(/&#(\d+);/g, (/** @type {string} */ _, d) => String.fromCodePoint(Number(d)))
+ .replace(/&([a-z]+);/gi, (/** @type {string} */ whole, e) => ENTITIES[e] ?? whole)
+ .replace(/\s+/g, ' ')
+ .trim()
+ : '';
+
+/** @param {any} p the function a JSX node is in, as a key */
+const fnKey = p => {
+ const fn = p.getFunctionParent();
+ return `${p.hub?.file?.opts?.filename ?? ''}:${fn ? fn.node.start : 'module'}`;
+};
+
+const NODE_MODULES = `${path.sep}node_modules${path.sep}`;
+
+/** A module of the project itself: inside its folder, not a package.
+ * @param {string} file */
+const isLocal = file =>
+ !file.includes(NODE_MODULES) && (file === entry || file.startsWith(ROOT_PREFIX));
+
+/**
+ * Babel plugin: replace asset imports with data: URIs and stylesheet imports
+ * with nothing (their CSS is inlined into the page), and record static text
+ * children of capitalized JSX elements.
+ * @param {string} filename
+ */
+function pagePlugin(filename) {
+ const dir = path.dirname(filename);
+ return (/** @type {any} */ {types: t}) => ({
+ visitor: {
+ ImportDeclaration(/** @type {any} */ p) {
+ const spec = /** @type {string} */ (p.node.source.value);
+ const raw = spec.split('?')[0];
+ // A stylesheet, image or JSON file imported through a project alias
+ // (`@/styles/site.css`) resolves the way modules do.
+ const bare =
+ isAliased(raw) && (/\.(css|scss|sass|less|json)$/i.test(raw) || isAssetPath(raw)) ? resolveAlias(raw) : raw;
+ if (!bare.startsWith('.') && !path.isAbsolute(bare) && !isAliased(bare)) {
+ packages.add(
+ bare.startsWith('@')
+ ? bare.split('/').slice(0, 2).join('/')
+ : bare.split('/')[0],
+ );
+ }
+ if (/\.json$/i.test(bare) && (bare.startsWith('.') || path.isAbsolute(bare))) {
+ const file = path.resolve(dir, bare);
+ if (fs.existsSync(file) && !localFiles.includes(file)) localFiles.push(file);
+ }
+ if (/\.(css|scss|sass|less)$/i.test(bare) && (/\.module\.[a-z]+$/i.test(bare) || p.node.specifiers.length > 0)) {
+ // CSS Modules (any stylesheet imported as a value) give class names
+ // at build time; a render has none.
+ const err = new Error(
+ `${path.basename(filename)} imports ${bare} as a value (CSS Modules), which a render does not support: use StyleX or a plain stylesheet imported for its side effect.`,
+ );
+ /** @type {any} */ (err).renderCode = 'ERR_RENDER_FAILED';
+ throw err;
+ }
+ if (/\.(scss|sass|less)$/i.test(bare)) {
+ // Sass and Less need their compiler: say so rather than drop them.
+ skippedCss.push(bare);
+ p.remove();
+ return;
+ }
+ if (/\.css$/i.test(bare)) {
+ if (bare.startsWith('.') || path.isAbsolute(bare)) {
+ const file = path.resolve(dir, bare);
+ // A stylesheet two modules import is inlined once, where it was
+ // first imported, as bundlers do.
+ if (!fs.existsSync(file)) {
+ const err = new Error(`${path.basename(filename)} imports ${spec}, which does not exist.`);
+ /** @type {any} */ (err).renderCode = 'ERR_FILE_NOT_FOUND';
+ throw err;
+ }
+ if (/\.css$/i.test(bare) && fs.existsSync(file) && !importedCss.some(c => c.file === file)) {
+ importedCss.push({file, css: fs.readFileSync(file, 'utf8')});
+ if (!localFiles.includes(file)) localFiles.push(file);
+ }
+ } else {
+ // A package stylesheet (a theme's, say): the caller resolves it
+ // from this file and inlines the rules the page uses.
+ packageCss.push({spec: bare, from: filename});
+ }
+ p.remove();
+ return;
+ }
+ if (isAssetPath(bare) && (bare.startsWith('.') || path.isAbsolute(bare))) {
+ const file = path.resolve(dir, bare);
+ const uri = assetDataUri(file);
+ assetsInlined.add(file);
+ if (!localFiles.includes(file)) localFiles.push(file);
+ const local = p.node.specifiers.find(
+ (/** @type {any} */ s) => s.type === 'ImportDefaultSpecifier',
+ );
+ if (!local) {
+ p.remove();
+ return;
+ }
+ p.replaceWith(
+ t.variableDeclaration('const', [
+ t.variableDeclarator(t.identifier(local.local.name), t.stringLiteral(uri)),
+ ]),
+ );
+ }
+ },
+ JSXText(/** @type {any} */ p) {
+ const v = cleanText(p.node);
+ if (v.length >= 2) (fnTexts[fnKey(p)] ??= []).push(v);
+ },
+ JSXElement(/** @type {any} */ p) {
+ const component = jsxName(p.node);
+ if (!/^[A-Z]/.test(component)) return;
+ // Only children that are all static text: the whole text must show.
+ if (p.node.children.some((/** @type {any} */ c) => c.type !== 'JSXText')) return;
+ const own = p.node.children.map(cleanText).filter(Boolean).join(' ');
+ if (!own) return;
+ // Content inside something that shows it only on demand (a closed
+ // dialog, an inactive tab) is not expected in a static render.
+ let hidden = HIDING.test(component) || hasShowAttr(p.node);
+ for (let up = p.parentPath; up && !hidden; up = up.parentPath) {
+ if (!up.isJSXElement()) continue;
+ hidden = HIDING.test(jsxName(up.node)) || hasShowAttr(up.node);
+ }
+ // Content shown only under a condition, or passed as a prop.
+ let conditional = false;
+ for (let up = p.parentPath; up && !up.isFunction() && !up.isProgram(); up = up.parentPath) {
+ if (
+ up.isConditionalExpression() ||
+ up.isLogicalExpression() ||
+ up.isIfStatement() ||
+ up.isSwitchCase() ||
+ up.isJSXAttribute()
+ ) {
+ conditional = true;
+ break;
+ }
+ }
+ // JSX kept in a variable, object or list shows only where it is used.
+ if (!conditional) {
+ let top = p;
+ while (top.parentPath && (top.parentPath.isJSXElement() || top.parentPath.isJSXFragment() || top.parentPath.isJSXExpressionContainer() || top.parentPath.isParenthesizedExpression?.())) {
+ top = top.parentPath;
+ }
+ const holder = top.parentPath;
+ conditional = Boolean(
+ holder &&
+ !holder.isReturnStatement() &&
+ !(holder.isArrowFunctionExpression() && holder.node.body === top.node),
+ );
+ }
+ // Content after an early return runs only when that return did not.
+ if (!conditional) {
+ const fn = p.getFunctionParent();
+ const stmt = fn
+ ? p.findParent((/** @type {any} */ x) => x.parentPath?.node === fn.node.body)
+ : null;
+ for (const sib of stmt?.getAllPrevSiblings?.() ?? []) {
+ let returns = sib.isReturnStatement();
+ if (!returns && (sib.isIfStatement() || sib.isSwitchStatement() || sib.isTryStatement())) {
+ sib.traverse({
+ ReturnStatement() {
+ returns = true;
+ },
+ Function(/** @type {any} */ q) {
+ q.skip();
+ },
+ });
+ }
+ if (returns) {
+ conditional = true;
+ break;
+ }
+ }
+ }
+ texts.push({
+ file: filename,
+ component,
+ text: own,
+ hidden: hidden || conditional,
+ fn: fnKey(p),
+ line: p.node.loc?.start.line ?? 0,
+ });
+ },
+ },
+ });
+}
+
+/**
+ * Path aliases from the project's tsconfig.json or jsconfig.json
+ * (`compilerOptions.paths`), as jiti aliases: `"@/*": ["./src/*"]` becomes
+ * `{"@/": "<root>/src/"}`.
+ * @returns {Record<string, string>}
+ */
+function projectAliases() {
+ /** @type {Record<string, string>} */
+ const alias = {};
+ for (const name of ['tsconfig.json', 'jsconfig.json']) {
+ const file = path.join(root, name);
+ if (!fs.existsSync(file)) continue;
+ /** @type {any} */
+ let config;
+ try {
+ // Allow the comments and trailing commas these files often carry.
+ const text = fs
+ .readFileSync(file, 'utf8')
+ .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, str) => str ?? '')
+ .replace(/,(\s*[}\]])/g, '$1');
+ config = JSON.parse(text);
+ } catch {
+ continue;
+ }
+ const options = config?.compilerOptions ?? {};
+ const baseDir = path.resolve(root, typeof options.baseUrl === 'string' ? options.baseUrl : '.');
+ for (const [key, targets] of Object.entries(options.paths ?? {})) {
+ const target = Array.isArray(targets) ? targets[0] : undefined;
+ if (typeof target !== 'string') continue;
+ if (key.endsWith('/*') && target.endsWith('/*')) {
+ alias[key.slice(0, -1)] = `${path.resolve(baseDir, target.slice(0, -2))}/`;
+ } else if (!key.includes('*') && !target.includes('*')) {
+ alias[key] = path.resolve(baseDir, target);
+ }
+ }
+ break;
+ }
+ return alias;
+}
+
+const ALIASES = projectAliases();
+
+/** @param {string} spec whether a specifier goes through a project alias */
+const isAliased = spec =>
+ Object.keys(ALIASES).some(key => (key.endsWith('/') ? spec.startsWith(key) : spec === key));
+
+/** @param {string} spec a specifier through a project alias, as an absolute path */
+const resolveAlias = spec => {
+ for (const [key, target] of Object.entries(ALIASES)) {
+ if (key.endsWith('/') ? spec.startsWith(key) : spec === key) {
+ return key.endsWith('/') ? target + spec.slice(key.length) : target;
+ }
+ }
+ return spec;
+};
+
+const plain = createJiti(entry, {fsCache: false, jsx: {runtime: 'automatic'}});
+
+const jiti = createJiti(entry, {
+ fsCache: false,
+ tryNative: false,
+ extensions: ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '.mts', '.cts', '.json'],
+ moduleCache: true,
+ interopDefault: true,
+ alias: ALIASES,
+ jsx: {runtime: 'automatic'},
+ transform(opts) {
+ const filename = opts.filename ?? '';
+ let source = opts.source;
+ if (filename && isLocal(filename) && /\.json$/i.test(filename) && !localFiles.includes(filename)) {
+ localFiles.push(filename);
+ }
+ if (filename && isLocal(filename) && /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/.test(filename)) {
+ if (!localFiles.includes(filename)) localFiles.push(filename);
+ const ts = /\.(tsx?|mts|cts)$/.test(filename);
+ const result = transformSync(source, {
+ filename,
+ babelrc: false,
+ configFile: false,
+ sourceType: 'module',
+ parserOpts: {plugins: ts ? ['jsx', 'typescript'] : ['jsx']},
+ generatorOpts: {retainLines: true},
+ compact: false,
+ plugins: [
+ pagePlugin(filename),
+ ...(source.includes('stylex')
+ ? [
+ [
+ stylexPlugin,
+ {
+ dev: false,
+ runtimeInjection: false,
+ treeshakeCompensation: true,
+ unstable_moduleResolution: {type: 'commonJS', rootDir: root},
+ },
+ ],
+ ]
+ : []),
+ ],
+ });
+ const rules = /** @type {any} */ (result?.metadata)?.stylex;
+ if (Array.isArray(rules)) stylexRules.push(...rules);
+ source = result?.code ?? source;
+ }
+ return {code: plain.transform({...opts, source, babel: {...opts.babel, compact: false}})};
+ },
+});
+
+/**
+ * @param {string} code
+ * @param {string} message
+ * @param {Record<string, unknown>} [detail]
+ */
+function fail(code, message, detail) {
+ parentPort?.postMessage({ok: false, error: {code, message, detail}, logs});
+}
+
+/** @param {unknown} e */
+function classify(e) {
+ const err = /** @type {any} */ (e);
+ if (err?.renderCode) return fail(err.renderCode, String(err.message).replace(/^\/[^:\n]*: /, ''));
+ // Babel prefixes errors raised while compiling with the file's path.
+ const message = String(err?.message ?? err).replace(/^\/[^:\n]*: /, '');
+ if (/suspended while responding to synchronous input|A component suspended/.test(message)) {
+ return fail(
+ 'ERR_RENDER_FAILED',
+ 'The page waits for data while rendering (a component suspended), and a static render cannot wait. Load the data first, or render a version of the page that has it.',
+ );
+ }
+ const missing =
+ /Cannot find (?:module|package) ['"]([^'"]+)['"]/.exec(message) ??
+ /Failed to resolve import ['"]([^'"]+)['"]/.exec(message);
+ if (missing && (isAliased(missing[1]) || /^[@~#]\/|^#/.test(missing[1]))) {
+ return fail(
+ 'ERR_FILE_NOT_FOUND',
+ `The page imports ${missing[1]} through a path alias that does not lead to a file. Check \`compilerOptions.paths\` in the project's tsconfig.json, or import it by a relative path.`,
+ {module: missing[1]},
+ );
+ }
+ if (missing && !missing[1].startsWith('.') && !path.isAbsolute(missing[1])) {
+ const spec = missing[1];
+ const pkg = spec.startsWith('@') ? spec.split('/').slice(0, 2).join('/') : spec.split('/')[0];
+ return fail('ERR_RENDER_MISSING_DEPENDENCY', `The page imports ${pkg}, which is not installed`, {package: pkg});
+ }
+ if (missing) {
+ return fail('ERR_FILE_NOT_FOUND', `The page imports ${missing[1]}, which does not exist`, {module: missing[1]});
+ }
+ if (err?.code === 'BABEL_PARSE_ERROR' || err?.reasonCode || /SyntaxError|Unexpected token/.test(`${err?.name} ${message}`)) {
+ const loc = err?.loc ? `:${err.loc.line}:${err.loc.column + 1}` : '';
+ return fail('ERR_RENDER_COMPILE', `The page does not compile${loc ? ` (line ${err.loc.line})` : ''}: ${message.split('\n')[0]}`, {
+ ...(err?.loc ? {line: err.loc.line, column: err.loc.column + 1} : {}),
+ });
+ }
+ const browser = /\b(window|document|localStorage|sessionStorage|navigator|location|matchMedia|requestAnimationFrame|IntersectionObserver|ResizeObserver|HTMLElement|customElements) is not defined/.exec(message);
+ if (browser) {
+ return fail(
+ 'ERR_RENDER_BROWSER_API',
+ `The page uses \`${browser[1]}\` while rendering, and a rendered page has no browser yet. Read it inside useEffect, or guard it with typeof ${browser[1]} !== 'undefined'.`,
+ {api: browser[1]},
+ );
+ }
+ if (err?.code === 'ERR_RENDER_ASSET_TOO_LARGE' || err?.code === 'ERR_FILE_NOT_FOUND') {
+ return fail(err.code, message, err.detail);
+ }
+ return fail('ERR_RENDER_FAILED', `The page threw while rendering: ${message.split('\n')[0]}`);
+}
+
+try {
+ /** @type {any} */
+ let mod;
+ try {
+ mod = await jiti.import(entry);
+ } catch (e) {
+ classify(e);
+ throw null;
+ }
+ const Page = mod?.default ?? (typeof mod === 'function' ? mod : undefined);
+ if (typeof Page !== 'function' && typeof Page?.$$typeof !== 'symbol') {
+ fail(
+ 'ERR_RENDER_NO_DEFAULT_EXPORT',
+ 'The page has no default export to render. Export the page component: export default function Page() { … }',
+ );
+ throw null;
+ }
+ /** @type {any} */
+ let React;
+ /** @type {any} */
+ let server;
+ try {
+ React = await jiti.import('react');
+ server = await jiti.import('react-dom/server');
+ } catch (e) {
+ classify(e);
+ throw null;
+ }
+ /** @type {string} */
+ let markup;
+ try {
+ markup = server.renderToStaticMarkup(React.createElement(Page));
+ } catch (e) {
+ classify(e);
+ throw null;
+ }
+ /** @type {string} */
+ let css = '';
+ if (stylexRules.length > 0) {
+ css = stylexPlugin.processStylexRules(stylexRules, {useLayers: false});
+ }
+ parentPort?.postMessage({
+ ok: true,
+ markup,
+ css,
+ importedCss,
+ packages: [...packages],
+ packageCss,
+ skippedCss,
+ assets: [...assetsInlined],
+ files: localFiles,
+ texts,
+ fnTexts,
+ logs,
+ });
+} catch (e) {
+ if (e !== null) classify(e);
+}
diff --git a/packages/cli/foundation/render/rebuild.mjs b/packages/cli/foundation/render/rebuild.mjs
new file mode 100644
index 0000000000..c2dd89c54b
--- /dev/null
+++ b/packages/cli/foundation/render/rebuild.mjs
@@ -0,0 +1,269 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx experimental render --reverse` without an embedded source:
+ * rebuild a page module from Astryx markup. Each element whose class list
+ * names an Astryx component (`astryx-<name>`) becomes that component, with
+ * the props its `data-*` attributes record and its text. This keeps text and
+ * layout; styling, state and behavior are not in the markup, so the result is
+ * a starting point, not the original.
+ *
+ * @position foundation/render — used by the render subject
+ */
+
+import {astryxClass, decode, find, FORM_TAGS, hasTag, isEl, parseHtml, textOf, VOID} from './html-reader.mjs';
+import {componentMap, pascal} from './component-map.mjs';
+
+/** @typedef {import('./html-reader.mjs').ElementNode} ElementNode */
+/** @typedef {import('./html-reader.mjs').Node} Node */
+/** @typedef {import('./component-map.mjs').ComponentEntry} ComponentEntry */
+
+/** @param {string} s */
+const camel = s => s.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
+
+/**
+ * Pick the component for one element.
+ * @param {ComponentEntry[]} list
+ * @param {string} target
+ * @param {ElementNode} el
+ */
+function pick(list, target, el) {
+ const exact = list.find(e => e.name === pascal(target));
+ const dir = el.attrs['data-direction'];
+ if (dir) {
+ const prefix = dir === 'horizontal' ? 'H' : dir === 'vertical' ? 'V' : '';
+ const hit = prefix ? list.find(e => e.name === `${prefix}${pascal(target)}`) : undefined;
+ if (hit) return hit;
+ }
+ return exact ?? list.find(e => e.name.endsWith(pascal(target))) ?? list[0];
+}
+
+/** Theme targets whose content the markup cannot give back (an icon's
+ * drawing is markup, not the component it came from). */
+const OMIT = new Set(['icon']);
+
+/** Attributes a component writes about itself that are not props. */
+const NOT_PROPS = new Set(['astryx-pressable', 'state']);
+
+/**
+ * A stand-in value for a required prop the markup does not record, or null
+ * when its type allows none (a list, an object, a named type).
+ * @param {string} prop
+ * @param {string} type
+ * @param {ElementNode} el
+ * @param {string} text
+ * @returns {string | null}
+ */
+function standIn(prop, type, el, text) {
+ const ty = type.replace(/\/\*[\s\S]*?\*\//g, '').trim();
+ if (/=>/.test(ty)) return `${prop}={() => {}}`;
+ if (/\[\]|Array<|Record<|\{/.test(ty)) return null;
+ if (/^number\b/.test(ty)) {
+ const v = Number(el.attrs['aria-valuenow'] ?? el.attrs[`data-${prop}`] ?? 0);
+ return `${prop}={${Number.isFinite(v) ? v : 0}}`;
+ }
+ if (/^boolean\b/.test(ty)) return `${prop}={false}`;
+ if (/^(React\.)?(ReactNode|ReactElement)/.test(ty)) return `${prop}={null}`;
+ if (/^string\b/.test(ty)) {
+ const v = el.attrs['aria-label'] ?? el.attrs.title ?? (/(label|title|name|text)$/i.test(prop) ? text : '');
+ return `${prop}=${jsxAttr(v)}`;
+ }
+ const literal = /^['"]([^'"]*)['"]/.exec(ty);
+ if (literal) return `${prop}=${jsxAttr(literal[1])}`;
+ return null;
+}
+
+/** @param {string} s */
+const jsxText = s => s.replace(/[{}<>]/g, c => `{'${c}'}`);
+
+/**
+ * A JSX attribute value: a plain quoted string when it can be one, else an
+ * expression (`{"say \\"hi\\""}`), since JSX strings take no escapes.
+ * @param {string} s
+ */
+const jsxAttr = s => (/["\\\n\r{}]/.test(s) ? `{${JSON.stringify(s)}}` : `"${s}"`);
+
+/**
+ * Text safe inside a `//` comment: every control character and line or
+ * paragraph separator becomes a space, so nothing after it can become code.
+ * @param {string} s
+ */
+const oneLine = s =>
+ [...s]
+ .map(c => {
+ const n = /** @type {number} */ (c.codePointAt(0));
+ return n < 32 || (n >= 127 && n <= 159) || n === 0x2028 || n === 0x2029 ? ' ' : c;
+ })
+ .join('');
+
+/**
+ * Rebuild a page module from Astryx markup.
+ * @param {string} html
+ * @param {string} fromDir where to find the installed packages
+ * @returns {{source: string, components: string[], elements: number, unknown: string[], omitted: string[]}}
+ */
+export function rebuildPage(html, fromDir) {
+ const doc = parseHtml(html);
+ const body = find(doc, 'body') ?? doc;
+ const maps = ['@astryxdesign/core', '@astryxdesign/lab', '@astryxdesign/charts'].map(p => componentMap(p, fromDir));
+ /** @param {string} target */
+ const lookup = target => {
+ for (const m of maps) {
+ const list = m.get(target);
+ if (list?.length) return list;
+ }
+ return undefined;
+ };
+ /** @type {Map<string, Set<string>>} */
+ const imports = new Map();
+ /** @type {Set<string>} */
+ const unknown = new Set();
+ /** @type {Set<string>} */
+ const omitted = new Set();
+ /** @type {Set<string>} */
+ const degraded = new Set();
+ let elements = 0;
+
+ /** @param {Node} n @returns {boolean} */
+ const hasAstryx = n =>
+ isEl(n) && (Boolean(astryxClass(n)) || n.children.some(hasAstryx));
+
+ /**
+ * An element's content as plain text elements, components left out.
+ * @param {Node} n
+ * @param {string} indent
+ * @returns {string[]}
+ */
+ const plain = (n, indent) => {
+ if (!isEl(n)) {
+ const t = n.text.replace(/\s+/g, ' ').trim();
+ return t ? [`${indent}<span>${jsxText(t)}</span>`] : [];
+ }
+ if (n.tag === 'script' || n.tag === 'style' || n.tag === 'template') return [];
+ const block = n.children.some(c => isEl(c) && !/^(span|strong|em|code|a|small|b|i)$/.test(c.tag));
+ if (!block) {
+ const t = textOf(n).replace(/\s+/g, ' ').trim();
+ return t ? [`${indent}<span>${jsxText(t)}</span>`] : [];
+ }
+ return n.children.flatMap(c => plain(c, indent));
+ };
+
+ /**
+ * @param {Node} n
+ * @param {string} indent
+ * @returns {string[]}
+ */
+ const emit = (n, indent) => {
+ if (!isEl(n)) {
+ const t = n.text.replace(/\s+/g, ' ').trim();
+ return t ? [`${indent}${jsxText(t)}`] : [];
+ }
+ if (n.tag === 'script' || n.tag === 'style' || n.tag === 'template') return [];
+ const target = astryxClass(n);
+ if (target && OMIT.has(target)) {
+ omitted.add(target);
+ return [];
+ }
+ const list = target ? lookup(target) : undefined;
+ if (target && !list) unknown.add(target);
+ if (!list || !target) {
+ if (n.children.some(hasAstryx)) return n.children.flatMap(c => emit(c, indent));
+ const t = textOf(n).replace(/\s+/g, ' ').trim();
+ if (!t) {
+ if (n.tag === 'img' && n.attrs.src) {
+ return [`${indent}<img src=${jsxAttr(n.attrs.src)} alt=${jsxAttr(n.attrs.alt ?? '')} />`];
+ }
+ return [];
+ }
+ const tag = /^(h[1-6]|p|span|strong|em|code|pre|li|a|label|small)$/.test(n.tag) ? n.tag : 'span';
+ const href = tag === 'a' && n.attrs.href ? ` href=${jsxAttr(n.attrs.href)}` : '';
+ return [`${indent}<${tag}${href}>${jsxText(t)}</${tag}>`];
+ }
+ const entry = pick(list, target, n);
+ // The props the markup records, as JSX.
+ /** @type {Map<string, string>} */
+ const given = new Map();
+ for (const [k, v] of Object.entries(n.attrs)) {
+ if (!k.startsWith('data-')) continue;
+ const prop = camel(k.slice(5));
+ if (NOT_PROPS.has(k.slice(5)) || !entry.props.has(prop)) continue;
+ if (v === '' || v === 'true') given.set(prop, prop);
+ else if (v === 'false') given.set(prop, `${prop}={false}`);
+ else if (/^-?\d+(\.\d+)?$/.test(v)) given.set(prop, `${prop}={${v}}`);
+ else given.set(prop, `${prop}=${jsxAttr(v)}`);
+ }
+ for (const a of ['href', 'role']) {
+ if (n.attrs[a] && entry.props.has(a)) given.set(a, `${a}=${jsxAttr(n.attrs[a])}`);
+ }
+ const t = textOf(n).replace(/\s+/g, ' ').trim();
+ // A component that draws a form control takes its text as a label, never
+ // as children (they would land on the control itself).
+ const formControl = hasTag(n, FORM_TAGS);
+ // Astryx parts inside a form control are its own drawing, not content:
+ // it is rebuilt as a leaf.
+ const nested = n.children.some(hasAstryx) && !formControl;
+ const textProp =
+ !nested && t && entry.label && (formControl || !entry.props.has('children')) ? 'label' : null;
+ // Required props the markup does not record get a stand-in when their
+ // type allows one; a component needing data it cannot hold (items,
+ // options) is not rebuilt, and its content is kept as plain text.
+ let lacking = false;
+ for (const [r, type] of entry.required) {
+ if (r === 'children' || r === textProp || given.has(r)) continue;
+ const fill = standIn(r, type, n, t);
+ if (fill == null) {
+ lacking = true;
+ break;
+ }
+ given.set(r, fill);
+ }
+ if (lacking) {
+ degraded.add(entry.name);
+ return plain(n, indent);
+ }
+ elements++;
+ const mod = imports.get(entry.module) ?? new Set();
+ mod.add(entry.name);
+ imports.set(entry.module, mod);
+ const props = [...given.values()];
+ const open = `${indent}<${entry.name}${props.length ? ` ${props.join(' ')}` : ''}`;
+ if (nested) {
+ const inner = n.children.flatMap(c => emit(c, `${indent} `));
+ return inner.length ? [`${open}>`, ...inner, `${indent}</${entry.name}>`] : [`${open} />`];
+ }
+ if (!t || VOID.has(n.tag) || (formControl && !textProp)) return [`${open} />`];
+ if (textProp) {
+ return [`${open.replace(`<${entry.name}`, `<${entry.name} label=${jsxAttr(t)}`)} />`];
+ }
+ return [`${open}>${jsxText(t)}</${entry.name}>`];
+ };
+
+ const lines = body.children.flatMap(c => emit(c, ' '));
+ const importLines = [...imports.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([mod, names]) => `import {${[...names].sort().join(', ')}} from '${mod}';`);
+ const title = decode(textOf(find(doc, 'title') ?? {text: ''})).trim();
+ const source = [
+ `// Rebuilt by astryx experimental render --reverse from rendered markup${title ? `: ${oneLine(title)}` : ''}.`,
+ '// Text and layout come from the markup; styling, state and behavior do not,',
+ '// so review it before use.',
+ '',
+ ...importLines,
+ '',
+ 'export default function Page() {',
+ ' return (',
+ ' <>',
+ ...lines.map(l => ` ${l}`),
+ ' </>',
+ ' );',
+ '}',
+ '',
+ ].join('\n');
+ return {
+ source,
+ components: [...imports.values()].flatMap(s => [...s]).sort(),
+ elements,
+ unknown: [...unknown].sort(),
+ omitted: [...omitted, ...degraded].sort(),
+ };
+}
diff --git a/packages/cli/foundation/render/render-page.mjs b/packages/cli/foundation/render/render-page.mjs
new file mode 100644
index 0000000000..17e8808148
--- /dev/null
+++ b/packages/cli/foundation/render/render-page.mjs
@@ -0,0 +1,612 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx experimental render`, forward: one page module to ONE
+ * self-contained static HTML file. The page renders on the server with the
+ * project's own React and Astryx components; its own StyleX compiles in
+ * memory; Core's stylesheets are cut to the rules the markup uses; local
+ * images become data: URIs; and the page's source rides along so
+ * `--reverse` can give it back exactly.
+ *
+ * The file needs no network and runs no script, so it works inside a
+ * sandboxed frame with a strict content security policy. Its colors follow
+ * `color-scheme` (and a `data-theme` of `light` or `dark` on the root), since
+ * Astryx tokens use light-dark().
+ *
+ * @position foundation/render — called by the render subject's adapter
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {createRequire} from 'node:module';
+import {Worker} from 'node:worker_threads';
+import postcss from 'postcss';
+import {assetDataUri, isAssetBytes, isAssetPath, RenderAssetError} from './assets.mjs';
+import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';
+import {sourceBlock} from './source-block.mjs';
+import {embeddedPathProblem} from './embedded-files.mjs';
+
+/** How long one page may take to render before it is stopped. */
+export const RENDER_TIMEOUT_MS = 60_000;
+
+export {PAGE_EXTENSIONS} from './embedded-files.mjs';
+
+/**
+ * @typedef {object} RenderWarning
+ * @property {'dropped-children' | 'remote-asset' | 'missing-asset' | 'page-output' | 'page-script' | 'no-astryx-styles' | 'chart-size' | 'not-embedded'} code - What kind of problem.
+ * @property {string} message - What happened and what to do, in one sentence.
+ */
+
+/**
+ * @typedef {object} RenderedPage
+ * @property {string} html - The whole file.
+ * @property {string[]} files - Local files the page loaded, relative to the folder that holds them all (the page's folder unless it imports from above it); the page first. Each is embedded.
+ * @property {string[]} stylesheets - The packages' stylesheets that were cut and inlined.
+ * @property {number} classes - Distinct class names in the markup.
+ * @property {number} cssBytes - Bytes of inlined CSS.
+ * @property {number} markupBytes - Bytes of rendered markup.
+ * @property {number} images - Local files inlined as data: URIs.
+ * @property {RenderWarning[]} warnings
+ */
+
+/** An error carrying a render error code. */
+export class RenderError extends Error {
+ /**
+ * @param {string} code
+ * @param {string} message
+ * @param {Record<string, unknown>} [detail]
+ */
+ constructor(code, message, detail) {
+ super(message);
+ this.code = code;
+ this.detail = detail;
+ }
+}
+
+/**
+ * The nearest folder at or above `dir` with a package.json, else `dir`.
+ * @param {string} dir
+ */
+function projectRootOf(dir) {
+ let d = dir;
+ for (;;) {
+ if (fs.existsSync(path.join(d, 'package.json'))) return d;
+ const up = path.dirname(d);
+ if (up === d) return dir;
+ d = up;
+ }
+}
+
+/** @param {string} s */
+const escapeHtml = s =>
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+
+/** @param {string} s */
+const decodeAttr = s =>
+ s
+ .replace(/&quot;/g, '"')
+ .replace(/&#x27;|&#39;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&');
+
+/**
+ * An `@import` rule's parts: what it loads, and the layer, supports() and
+ * media conditions that scope it.
+ * @param {string} params
+ * @returns {{url: string, layer: string | null, supports: string | null, media: string} | null}
+ */
+function importParams(params) {
+ const m = /^\s*(?:url\(\s*(['"]?)([\s\S]*?)\1\s*\)|(['"])([\s\S]*?)\3)\s*([\s\S]*)$/.exec(params);
+ if (!m) return null;
+ let rest = m[5];
+ /** @type {string | null} */
+ let layer = null;
+ const lay = /^layer(?:\(\s*([^)]*?)\s*\))?(?=\s|$)\s*/i.exec(rest);
+ if (lay) {
+ layer = lay[1] ?? '';
+ rest = rest.slice(lay[0].length);
+ }
+ /** @type {string | null} */
+ let supports = null;
+ const sup = /^supports\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)\s*/i.exec(rest);
+ if (sup) {
+ supports = sup[1];
+ rest = rest.slice(sup[0].length);
+ }
+ return {url: m[2] ?? m[4] ?? '', layer, supports, media: rest.trim()};
+}
+
+/**
+ * Inline a stylesheet's own `@import`s, so a stylesheet pulled in that way is
+ * part of the file: a relative one from the importing sheet's folder
+ * (carried when it is the project's own), a package one (`@scope/pkg/x.css`)
+ * by Node resolution from the importing sheet. Each keeps its `layer()`,
+ * `supports()` and media conditions, and relative url()s in it are rewritten
+ * to stay right. A remote import is dropped with a warning (a sandboxed page
+ * cannot load it), a Sass or Less one is named in a warning, and cycles are
+ * cut.
+ * @param {string} file the stylesheet's own path
+ * @param {string} css its text
+ * @param {{warnings: RenderWarning[], carried: Set<string>, included: Set<string>, packageSheets: string[], seen?: Set<string>}} ctx
+ * `included`: stylesheet files already in the page (Core's, say), never
+ * inlined twice; `packageSheets`: package stylesheets this pulled in
+ * @returns {string}
+ */
+function expandImports(file, css, ctx) {
+ if (!/@import/i.test(css)) return css;
+ const seen = ctx.seen ?? new Set([file]);
+ /** @type {import('postcss').Root} */
+ let root;
+ try {
+ root = postcss.parse(css, {from: file});
+ } catch {
+ return css;
+ }
+ root.walkAtRules(/^import$/i, rule => {
+ const parsed = importParams(rule.params);
+ if (!parsed || !parsed.url) return;
+ const {url} = parsed;
+ if (/^([a-z]+:)?\/\//i.test(url)) {
+ ctx.warnings.push({
+ code: 'remote-asset',
+ message: `${path.basename(file)} imports ${url}, which a sandboxed page cannot load, so it is left out; save it beside the stylesheet and import it instead.`,
+ });
+ rule.remove();
+ return;
+ }
+ if (/\.(scss|sass|less)$/i.test(url)) {
+ ctx.warnings.push({
+ code: 'missing-asset',
+ message: `${path.basename(file)} imports ${url}, a Sass or Less stylesheet, which a render does not compile, so its styles are missing.`,
+ });
+ rule.remove();
+ return;
+ }
+ const relative = path.resolve(path.dirname(file), url);
+ /** @type {string | null} */
+ let target;
+ let fromPackage = false;
+ if (/^\.{1,2}\//.test(url) || fs.existsSync(relative)) {
+ target = fs.existsSync(relative) ? relative : null;
+ } else {
+ try {
+ target = createRequire(file).resolve(url.replace(/^~/, ''));
+ fromPackage = true;
+ } catch {
+ target = null;
+ }
+ }
+ if (!target) {
+ ctx.warnings.push({
+ code: 'missing-asset',
+ message: `${path.basename(file)} imports ${url}, which was not found, so its styles are missing.`,
+ });
+ rule.remove();
+ return;
+ }
+ if (seen.has(target) || ctx.included.has(target)) {
+ rule.remove();
+ return;
+ }
+ seen.add(target);
+ ctx.included.add(target);
+ if (fromPackage) ctx.packageSheets.push(url.replace(/^~/, ''));
+ else ctx.carried.add(target);
+ const from = target;
+ let inner = expandImports(from, fs.readFileSync(from, 'utf8'), {...ctx, seen});
+ // Keep the imported sheet's relative url()s pointing at the same files.
+ inner = inner.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (u, q, r) => {
+ if (/^(data:|blob:|#|\/|[a-z]+:)/i.test(r)) return u;
+ const rebased = path
+ .relative(path.dirname(file), path.resolve(path.dirname(from), r))
+ .split(path.sep)
+ .join('/');
+ return `url(${q}${rebased.startsWith('.') ? rebased : `./${rebased}`}${q})`;
+ });
+ // The import's conditions still scope what it brings in.
+ if (parsed.supports) inner = `@supports (${parsed.supports.replace(/^\((.*)\)$/s, '$1')}){${inner}}`;
+ if (parsed.media) inner = `@media ${parsed.media}{${inner}}`;
+ if (parsed.layer !== null) inner = `@layer${parsed.layer ? ` ${parsed.layer}` : ''}{${inner}}`;
+ try {
+ rule.replaceWith(postcss.parse(inner, {from}).nodes);
+ } catch (e) {
+ const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
+ throw new RenderError(
+ 'ERR_RENDER_COMPILE',
+ `${path.basename(from)}, imported by ${path.basename(file)}, is not valid CSS: ${reason}`,
+ );
+ }
+ });
+ return root.toString();
+}
+
+/**
+ * Run the page in a worker, stopping it after `timeoutMs`.
+ * @param {string} entry
+ * @param {string} root
+ * @param {number} timeoutMs
+ * @returns {Promise<any>}
+ */
+function runWorker(entry, root, timeoutMs) {
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(new URL('./page-worker.mjs', import.meta.url), {
+ workerData: {entry, root},
+ execArgv: [],
+ stdout: true,
+ stderr: true,
+ resourceLimits: {maxOldGenerationSizeMb: 4096},
+ });
+ // The page's own writes to stdout/stderr never reach the CLI's output.
+ worker.stdout.resume();
+ worker.stderr.resume();
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ void worker.terminate();
+ reject(
+ new RenderError(
+ 'ERR_RENDER_TIMEOUT',
+ `The page did not finish rendering within ${timeoutMs / 1000} seconds, so it was stopped. Look for a loop that never ends or a promise the page waits on.`,
+ {seconds: timeoutMs / 1000},
+ ),
+ );
+ }, timeoutMs);
+ worker.once('message', message => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ void worker.terminate();
+ resolve(message);
+ });
+ worker.once('error', (/** @type {any} */ error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ const out =
+ /ERR_WORKER_OUT_OF_MEMORY|heap out of memory/.test(String(error?.message ?? error))
+ ? new RenderError('ERR_RENDER_FAILED', 'The page ran out of memory while rendering.')
+ : new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`);
+ reject(out);
+ });
+ worker.once('exit', code => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(new RenderError('ERR_RENDER_FAILED', `The page stopped rendering without an answer (exit ${code}).`));
+ });
+ });
+}
+
+/**
+ * Inline local images (src, srcset, poster and CSS url()) as data: URIs. A
+ * link (`href`) loads nothing, so it is left alone.
+ * @param {string} text markup or CSS
+ * @param {'html' | 'css'} kind
+ * @param {{dir: string, root: string, warnings: RenderWarning[], counted: Set<string>, localAssets: Set<string>}} ctx
+ */
+function inlineAssets(text, kind, ctx) {
+ /** @param {string} ref */
+ const resolveRef = ref => {
+ const clean = decodeAttr(ref).trim().split(/[?#]/)[0];
+ if (!clean) return null;
+ if (/^(data:|blob:|#|about:|mailto:|tel:|javascript:)/i.test(clean)) return null;
+ if (/^(https?:)?\/\//i.test(clean)) {
+ const key = `remote:${clean}`;
+ if (!ctx.counted.has(key)) {
+ ctx.counted.add(key);
+ ctx.warnings.push({
+ code: 'remote-asset',
+ message: `${clean} is loaded from the network, which a sandboxed page cannot reach; save it beside the page and import it instead.`,
+ });
+ }
+ return null;
+ }
+ if (!isAssetPath(clean)) return null;
+ const candidates = clean.startsWith('/')
+ ? [path.join(ctx.root, 'public', clean), path.join(ctx.root, clean)]
+ : [path.resolve(ctx.dir, clean)];
+ const found = candidates.find(c => fs.existsSync(c));
+ if (!found) {
+ const key = `missing:${clean}`;
+ if (!ctx.counted.has(key)) {
+ ctx.counted.add(key);
+ ctx.warnings.push({
+ code: 'missing-asset',
+ message: `${clean} was not found next to the page, so it is left as is and will not show.`,
+ });
+ }
+ return null;
+ }
+ ctx.counted.add(`file:${found}`);
+ // A relative path names a file that is part of the page: carry it.
+ if (!clean.startsWith('/')) ctx.localAssets.add(found);
+ return assetDataUri(found);
+ };
+ /** @param {string} value */
+ const urls = value =>
+ value.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (whole, q, ref) => {
+ const uri = resolveRef(ref);
+ return uri ? `url("${uri}")` : whole;
+ });
+ if (kind === 'css') return urls(text);
+ return text
+ .replace(/\s(src|poster)="([^"]*)"/g, (whole, attr, ref) => {
+ const uri = resolveRef(ref);
+ return uri ? ` ${attr}="${uri}"` : whole;
+ })
+ .replace(/\ssrcset="([^"]*)"/g, (whole, set) => {
+ const parts = decodeAttr(set)
+ .split(',')
+ .map(part => {
+ const [ref, ...rest] = part.trim().split(/\s+/);
+ const uri = ref ? resolveRef(ref) : null;
+ return [uri ?? ref, ...rest].join(' ');
+ });
+ return ` srcset="${parts.join(', ').replace(/"/g, '&quot;')}"`;
+ })
+ .replace(/\sstyle="([^"]*)"/g, (whole, style) => {
+ // The attribute holds escaped text: rewrite the CSS it means, then
+ // escape it again, so a data: URI's quotes cannot end the attribute.
+ const css = urls(decodeAttr(style));
+ return ` style="${css.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}"`;
+ });
+}
+
+/** The light and dark switch every rendered page carries. */
+const SCHEME_CSS =
+ ':root{color-scheme:light dark}:root[data-theme="light"]{color-scheme:light}:root[data-theme="dark"]{color-scheme:dark}';
+
+/**
+ * Render a page module to one self-contained HTML file.
+ * @param {string} entry absolute path of the page module
+ * @param {{title?: string, timeoutMs?: number, version?: string}} [options]
+ * @returns {Promise<RenderedPage>}
+ */
+export async function renderPage(entry, options = {}) {
+ const dir = path.dirname(entry);
+ const root = projectRootOf(dir);
+ const message = await runWorker(entry, root, options.timeoutMs ?? RENDER_TIMEOUT_MS);
+ /** @type {RenderWarning[]} */
+ const warnings = [];
+ if (!message.ok) {
+ throw new RenderError(message.error.code, message.error.message, message.error.detail);
+ }
+ /** @type {string} */
+ let markup = message.markup;
+
+ // Stylesheets: Core's reset and components, plus each official package's
+ // own stylesheet the page imports from.
+ const req = createRequire(entry);
+ /** @type {string[]} */
+ const sheets = [];
+ /** @type {string[]} */
+ const sheetText = [];
+ /** Each stylesheet's own file, so its url()s resolve from its folder. @type {string[]} */
+ const sheetFiles = [];
+ /** @param {string} spec */
+ const addSheet = spec => {
+ try {
+ const file = req.resolve(spec);
+ sheets.push(spec);
+ sheetText.push(fs.readFileSync(file, 'utf8'));
+ sheetFiles.push(file);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const hasCore = addSheet('@astryxdesign/core/reset.css');
+ if (hasCore) addSheet('@astryxdesign/core/astryx.css');
+ // Package stylesheets the page imports itself, such as a theme's.
+ for (const {spec, from} of /** @type {{spec: string, from: string}[]} */ (message.packageCss ?? [])) {
+ if (sheets.includes(spec)) continue;
+ try {
+ const file = createRequire(from).resolve(spec);
+ sheets.push(spec);
+ sheetText.push(fs.readFileSync(file, 'utf8'));
+ sheetFiles.push(file);
+ } catch {
+ warnings.push({
+ code: 'missing-asset',
+ message: `The page imports the stylesheet ${spec}, which could not be found, so its styles are missing.`,
+ });
+ }
+ }
+ for (const pkg of /** @type {string[]} */ (message.packages ?? [])) {
+ const m = /^@astryxdesign\/([a-z0-9-]+)$/.exec(pkg);
+ if (!m || m[1] === 'core') continue;
+ addSheet(`${pkg}/${m[1]}.css`);
+ }
+ if (!hasCore) {
+ warnings.push({
+ code: 'no-astryx-styles',
+ message:
+ '@astryxdesign/core is not installed where the page is, so the page has no Astryx styles; install it, or render from inside the project.',
+ });
+ }
+
+ const ctx = {dir, root, warnings, counted: new Set(), localAssets: /** @type {Set<string>} */ (new Set())};
+ /** Stylesheets pulled in by another's `@import`. @type {Set<string>} */
+ const carriedCss = new Set();
+ try {
+ markup = inlineAssets(markup, 'html', ctx);
+ // React adds `<link rel="preload">` hints for images it renders; in one
+ // static file they only fetch from the network, so they go.
+ markup = markup.replace(/<link rel="preload"[^>]*\/?>/g, '');
+ // What the page itself renders that would run or load something: the
+ // file promises neither, so say so.
+ if (/<script\b/i.test(markup)) {
+ warnings.push({
+ code: 'page-script',
+ message:
+ 'The page renders a <script> element. A sandboxed viewer blocks it, and anywhere else it runs when the file is opened; remove it from the page.',
+ });
+ }
+ for (const m of markup.matchAll(/<(link|iframe|object|embed)\b[^>]*?\s(?:href|src|data)="([^"]*)"/gi)) {
+ if (/^(data:|#)/i.test(m[2])) continue;
+ warnings.push({
+ code: 'remote-asset',
+ message: `The page renders a <${m[1].toLowerCase()}> that loads ${m[2]}, which a sandboxed page cannot reach and which loads from the network anywhere else; remove it from the page.`,
+ });
+ }
+ } catch (e) {
+ const err = /** @type {any} */ (e);
+ if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
+ throw e;
+ }
+ const used = classesIn(markup);
+ const layerOrder = sheetText.map(layerOrderOf).find(Boolean) ?? '';
+ let css = layerOrder;
+ try {
+ // A stylesheet's url()s are relative to the stylesheet, not the page: a
+ // theme's font, or an image beside an imported stylesheet.
+ const included = new Set(sheetFiles);
+ /** @type {string[]} */
+ const packageSheets = [];
+ /** A stylesheet's rules cut to the page, with its own imports inlined. @param {string} file @param {string} text */
+ const sheet = (file, text) => {
+ try {
+ const own = expandImports(file, text, {warnings, carried: carriedCss, included, packageSheets});
+ return inlineAssets(cutCss(own, used), 'css', {...ctx, dir: path.dirname(file)});
+ } catch (e) {
+ if (e instanceof RenderAssetError || e instanceof RenderError) throw e;
+ const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
+ throw new RenderError(
+ 'ERR_RENDER_COMPILE',
+ `${path.relative(dir, file).split(path.sep).join('/')} is not valid CSS: ${reason}`,
+ );
+ }
+ };
+ sheetText.forEach((text, i) => {
+ css += sheet(sheetFiles[i], text);
+ });
+ for (const {file, css: text} of /** @type {{file: string, css: string}[]} */ (message.importedCss ?? [])) {
+ css += sheet(file, text);
+ }
+ for (const spec of packageSheets) if (!sheets.includes(spec)) sheets.push(spec);
+ if (message.css) css += inlineAssets(message.css, 'css', ctx);
+ } catch (e) {
+ const err = /** @type {any} */ (e);
+ if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
+ throw e;
+ }
+ // Keep inlined CSS from ending its own <style> element.
+ css = css.replace(/<\/style/gi, '<\\/style');
+
+ // A component that dropped the text it was given: its text is missing while
+ // text next to it rendered.
+ const plainText = markup
+ .replace(/<[^>]*>/g, ' ')
+ .replace(/&amp;/g, '&')
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&quot;/g, '"')
+ .replace(/&#x27;|&#39;/g, "'")
+ .replace(/&nbsp;/g, ' ')
+ .replace(/\s+/g, ' ');
+ for (const t of /** @type {any[]} */ (message.texts ?? [])) {
+ if (t.hidden || t.text.length < 2 || plainText.includes(t.text)) continue;
+ // The code around it ran: other text from the same function rendered.
+ const around = /** @type {string[]} */ (message.fnTexts?.[t.fn] ?? []).filter(o => o !== t.text);
+ if (!around.some(o => plainText.includes(o))) continue;
+ warnings.push({
+ code: 'dropped-children',
+ message: `<${t.component}> on line ${t.line} did not render the text "${t.text.length > 60 ? `${t.text.slice(0, 57)}...` : t.text}" it was given; it takes that text through a prop (often label=), so check its props.`,
+ });
+ }
+ for (const f of /** @type {string[]} */ (message.files ?? [])) {
+ const src = fs.readFileSync(f, 'utf8');
+ if (/\bResponsiveContainer\b/.test(src)) {
+ warnings.push({
+ code: 'chart-size',
+ message: `${path.basename(f)} sizes a chart with ResponsiveContainer, which has no size until a browser measures it, so the chart is empty here; give the chart a fixed width and height.`,
+ });
+ break;
+ }
+ }
+ for (const sheet of /** @type {string[]} */ (message.skippedCss ?? [])) {
+ warnings.push({
+ code: 'missing-asset',
+ message: `The page imports ${sheet}, a Sass or Less stylesheet, which a render does not compile, so its styles are missing.`,
+ });
+ }
+ for (const log of /** @type {{level: string, text: string}[]} */ (message.logs ?? []).slice(0, 5)) {
+ warnings.push({
+ code: 'page-output',
+ message: `The page printed while rendering (${log.level}): ${log.text.split('\n')[0].slice(0, 200)}`,
+ });
+ }
+
+ const files = /** @type {string[]} */ (message.files ?? [entry]);
+ if (!files.includes(entry)) files.unshift(entry);
+ // Images and fonts the page or a stylesheet names by a relative path
+ // (`<img src="./logo.png">`, `url(./bg.png)`) are carried too, so the page
+ // comes back with them; a package's own files are not.
+ for (const sheet of carriedCss) {
+ const rel = path.relative(root, sheet);
+ if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
+ if (!files.includes(sheet)) files.push(sheet);
+ }
+ for (const asset of ctx.localAssets) {
+ const rel = path.relative(root, asset);
+ if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
+ if (files.includes(asset)) continue;
+ // Carried only when its bytes are a known image, font or media format,
+ // the same test --reverse applies, so the file always comes back.
+ if (!isAssetBytes(fs.readFileSync(asset))) {
+ warnings.push({
+ code: 'not-embedded',
+ message: `${path.relative(dir, asset).split(path.sep).join('/')} is shown inline but not carried in the file: its bytes are not a known image, font or media format, so --reverse cannot give it back.`,
+ });
+ continue;
+ }
+ files.push(asset);
+ }
+ // Paths are kept relative to the folder that holds every file: the page's
+ // folder, or an ancestor when the page imports from above it.
+ let base = dir;
+ for (const f of files) {
+ while (path.relative(base, f).startsWith('..')) base = path.dirname(base);
+ }
+ // Page first, so the reader knows which file is the page. Only files a
+ // rendered page may carry are embedded (see embedded-files.mjs).
+ const ordered = [entry, ...files.filter(f => f !== entry)];
+ /** @type {{path: string, bytes: Buffer}[]} */
+ const embedded = [];
+ for (const f of ordered) {
+ const rel = path.relative(base, f).split(path.sep).join('/');
+ if (f !== entry && embeddedPathProblem(rel)) {
+ warnings.push({
+ code: 'not-embedded',
+ message: `${rel} is not carried in the file (a rendered page carries the page and the local modules, stylesheets, JSON files and images it imports, but never project or tool configuration, or a file a test, story or benchmark runner would run), so --reverse cannot give it back.`,
+ });
+ continue;
+ }
+ embedded.push({path: rel, bytes: fs.readFileSync(f)});
+ }
+ const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(markup)?.[1]?.replace(/<[^>]*>/g, '').trim();
+ const title = options.title ?? (heading ? decodeAttr(heading) : path.basename(entry).replace(/\.[^.]+$/, ''));
+ const html =
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
+ '<meta name="color-scheme" content="light dark">' +
+ `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">` +
+ `<title>${escapeHtml(title)}</title>` +
+ `<style>${SCHEME_CSS}${css}</style></head><body>${markup}` +
+ `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
+ return {
+ html,
+ files: embedded.map(f => f.path),
+ stylesheets: sheets,
+ classes: used.size,
+ cssBytes: Buffer.byteLength(css),
+ markupBytes: Buffer.byteLength(markup),
+ images: new Set([
+ ...[...ctx.counted].filter(k => k.startsWith('file:')).map(k => k.slice(5)),
+ ...(message.assets ?? []),
+ ]).size,
+ warnings,
+ };
+}
diff --git a/packages/cli/foundation/render/render.test.mjs b/packages/cli/foundation/render/render.test.mjs
new file mode 100644
index 0000000000..235fca3a16
--- /dev/null
+++ b/packages/cli/foundation/render/render.test.mjs
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the render helpers: the CSS cut, the embedded source, the
+ * HTML reader, and the time limit.
+ */
+
+import * as fs from 'node:fs';
+import {fileURLToPath} from 'node:url';
+import * as path from 'node:path';
+import {describe, expect, it} from 'vitest';
+import {classesIn, cutCss, layerOrderOf, requiredClasses} from './css-cut.mjs';
+import {readSourceBlock, sourceBlock} from './source-block.mjs';
+import {isAstryxMarkup, parseHtml} from './html-reader.mjs';
+import {renderPage} from './render-page.mjs';
+
+describe('requiredClasses with grouped selectors', () => {
+ it('keeps a rule whose :is() or :where() alternatives are not all used', async () => {
+ const {cutCss} = await import('./css-cut.mjs');
+ const css = '.a:is(.b, .c) { color: red; } :where(.x, .y) .z { color: blue; } .gone { color: green; }';
+ const out = cutCss(css, new Set(['a', 'b', 'z']));
+ expect(out).toContain('color: red');
+ expect(out).toContain('color: blue');
+ expect(out).not.toContain('color: green');
+ });
+});
+
+describe('cutCss', () => {
+ const css = `/* @layer comment, not, order; */
+@layer reset, base;
+:root { --c: light-dark(#000, #fff); }
+@property --x { syntax: '<length>'; inherits: false; initial-value: 0px; }
+@keyframes spin { to { transform: rotate(1turn); } }
+@keyframes unused { to { opacity: 0; } }
+@layer base {
+ .a { color: red; }
+ .b .c { color: blue; }
+ .a:not(.zzz) { margin: 0; }
+ .gone, .a.d { padding: 0; }
+ @media (min-width: 1px) { .gone { color: red; } }
+ .spin { animation-name: spin; }
+}`;
+
+ it('keeps used rules, tokens, properties and named keyframes', () => {
+ const out = cutCss(css, new Set(['a', 'spin']));
+ expect(out).toContain('.a { color: red; }');
+ expect(out).toContain('.a:not(.zzz)');
+ expect(out).toContain('--c: light-dark(#000, #fff)');
+ expect(out).toContain('@property --x');
+ expect(out).toContain('@keyframes spin');
+ expect(out).not.toContain('unused');
+ expect(out).not.toContain('.b .c');
+ expect(out).not.toContain('.gone');
+ expect(out).not.toContain('@media');
+ expect(out).not.toMatch(/@layer reset, base;/);
+ });
+
+ it('reads the layer order, ignoring comments', () => {
+ expect(layerOrderOf(css)).toBe('@layer reset, base;');
+ });
+
+ it('needs every class in a selector, except inside :not()', () => {
+ expect(requiredClasses('.a .b:hover:not(.c)')).toEqual(['a', 'b']);
+ expect(requiredClasses('.x\\:y')).toEqual(['x:y']);
+ });
+
+ it('reads class names from markup', () => {
+ expect([...classesIn('<div class="a b"><p class="c"></p></div>')]).toEqual(['a', 'b', 'c']);
+ });
+});
+
+describe('the embedded source', () => {
+ it('round-trips any bytes, even text that would end a script', () => {
+ const bytes = Buffer.from('const s = "</script><!--";\r\n// ünïcode ✓\u2028', 'utf8');
+ const block = sourceBlock('page.tsx', [{path: 'page.tsx', bytes}]);
+ expect(block.match(/<\/script>/g)).toHaveLength(1);
+ const read = readSourceBlock(`<body><p>x</p>${block}</body>`);
+ expect(read.found && 'source' in read && Buffer.from(read.source.files[0].base64, 'base64')).toEqual(bytes);
+ });
+
+ it('reports a damaged block', () => {
+ const block = sourceBlock('p.tsx', [{path: 'p.tsx', bytes: Buffer.from('a')}]);
+ expect(readSourceBlock(block.replace(/"sha256":"[0-9a-f]/, '"sha256":"Z'))).toMatchObject({found: true});
+ expect('damaged' in readSourceBlock(block.replace('"version":1', '"version":2'))).toBe(true);
+ expect(readSourceBlock('<p>none</p>')).toEqual({found: false});
+ });
+});
+
+describe('the HTML reader', () => {
+ it('parses rendered markup', () => {
+ const doc = parseHtml('<!doctype html><body><div class="astryx-card" data-x="1">a &amp; b<br><img src="x"></div></body>');
+ const body = /** @type {any} */ (doc.children[0]);
+ expect(body.tag).toBe('body');
+ expect(body.children[0].attrs).toEqual({class: 'astryx-card', 'data-x': '1'});
+ expect(body.children[0].children[0].text).toBe('a & b');
+ });
+
+ it('tells Astryx markup from other HTML', () => {
+ expect(isAstryxMarkup('<div class="x astryx-button"></div>')).toBe(true);
+ expect(isAstryxMarkup('<div class="button"></div>')).toBe(false);
+ });
+});
+
+describe('renderPage time limit', () => {
+ it('stops a page that never finishes rendering', async () => {
+ const dir = fs.mkdtempSync(
+ path.join(path.dirname(fileURLToPath(import.meta.url)), '../../.astryx-render-loop-'),
+ );
+ try {
+ const file = path.join(dir, 'loop.jsx');
+ fs.writeFileSync(file, 'export default function Page() { for (;;) {} }\n');
+ await expect(renderPage(file, {timeoutMs: 1500})).rejects.toMatchObject({code: 'ERR_RENDER_TIMEOUT'});
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ }, 30_000);
+});
diff --git a/packages/cli/foundation/render/source-block.mjs b/packages/cli/foundation/render/source-block.mjs
new file mode 100644
index 0000000000..7b14cbe353
--- /dev/null
+++ b/packages/cli/foundation/render/source-block.mjs
@@ -0,0 +1,106 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The page source a rendered file carries, so `astryx experimental
+ * render --reverse` can give it back byte for byte. It is one
+ * `<script type="application/x-astryx-source">` data block: browsers never run
+ * it, and its JSON holds each file base64-encoded with its SHA-256, so no text
+ * in the source (`</script>` included) can end the block early.
+ *
+ * @position foundation/render — used by render-page.mjs and the render subject
+ */
+
+import {createHash} from 'node:crypto';
+
+/** The script type of the embedded-source block. */
+export const SOURCE_TYPE = 'application/x-astryx-source';
+
+/**
+ * @typedef {object} EmbeddedFile
+ * @property {string} path - Path relative to the folder that holds every embedded file, `/`-separated; the page itself first.
+ * @property {string} sha256 - SHA-256 of the file's bytes, hex.
+ * @property {string} base64 - The file's bytes.
+ */
+
+/**
+ * @typedef {object} EmbeddedSource
+ * @property {1} version
+ * @property {string} entry - The page's file name.
+ * @property {EmbeddedFile[]} files
+ */
+
+/** @param {Buffer} bytes */
+export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
+
+/**
+ * The data block for a page's files.
+ * @param {string} entry the page's file name
+ * @param {{path: string, bytes: Buffer}[]} files the page first
+ * @returns {string}
+ */
+export function sourceBlock(entry, files) {
+ /** @type {EmbeddedSource} */
+ const payload = {
+ version: 1,
+ entry,
+ files: files.map(f => ({
+ path: f.path,
+ sha256: sha256(f.bytes),
+ base64: f.bytes.toString('base64'),
+ })),
+ };
+ const json = JSON.stringify(payload)
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e')
+ .replace(/&/g, '\\u0026');
+ return `<script type="${SOURCE_TYPE}">${json}</script>`;
+}
+
+/**
+ * Read the embedded source from a rendered file.
+ * @param {string} html
+ * @returns {{found: false} | {found: true, source: EmbeddedSource} | {found: true, damaged: string}}
+ */
+export function readSourceBlock(html) {
+ const all = [
+ ...html.matchAll(
+ new RegExp(
+ `<script\\s+type=["']${SOURCE_TYPE.replace(/[/+.-]/g, c => `\\${c}`)}["'][^>]*>([\\s\\S]*?)</script>`,
+ 'gi',
+ ),
+ ),
+ ];
+ // The block is written last in the body; a page's own markup cannot end
+ // it, so the last one is the CLI's.
+ const m = all.at(-1);
+ if (!m) return {found: false};
+ /** @type {any} */
+ let payload;
+ try {
+ payload = JSON.parse(m[1]);
+ } catch {
+ return {found: true, damaged: 'its embedded source is not valid JSON'};
+ }
+ if (
+ payload?.version !== 1 ||
+ typeof payload.entry !== 'string' ||
+ !Array.isArray(payload.files) ||
+ payload.files.length === 0
+ ) {
+ return {found: true, damaged: 'its embedded source has an unknown shape'};
+ }
+ for (const f of payload.files) {
+ if (
+ typeof f?.path !== 'string' ||
+ typeof f.base64 !== 'string' ||
+ typeof f.sha256 !== 'string' ||
+ sha256(Buffer.from(f.base64, 'base64')) !== f.sha256
+ ) {
+ return {
+ found: true,
+ damaged: `its embedded copy of ${String(f?.path ?? 'a file')} does not match its checksum`,
+ };
+ }
+ }
+ return {found: true, source: payload};
+}
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
index 10e242fa31..f529e32042 100644
--- a/packages/cli/foundation/response/error-codes.doc.mjs
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -289,5 +289,61 @@ export const doc = {
description:
'The command needs a project (an app with Astryx installed, or an integration package) and was run outside one. Nothing was written.',
},
+
+ // Render (experimental: may change or be removed in a patch release)
+ {
+ value: 'ERR_RENDER_COMPILE',
+ stability: 'experimental',
+ description:
+ 'The page given to render does not compile. A stylesheet the page imports that is not valid CSS is reported this way too, naming the file. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_NO_DEFAULT_EXPORT',
+ stability: 'experimental',
+ description:
+ 'The page given to render has no default export to render. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_MISSING_DEPENDENCY',
+ stability: 'experimental',
+ description:
+ 'The page imports a package that is not installed where the page is. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_BROWSER_API',
+ stability: 'experimental',
+ description:
+ 'The page reads a browser-only API, such as window or document, while rendering. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_ASSET_TOO_LARGE',
+ stability: 'experimental',
+ description:
+ 'A local file the page uses is too large to inline into one file. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_TIMEOUT',
+ stability: 'experimental',
+ description:
+ 'The page did not finish rendering in time and was stopped. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_FAILED',
+ stability: 'experimental',
+ description:
+ 'The page threw while rendering. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_NOT_ASTRYX',
+ stability: 'experimental',
+ description:
+ '`render --reverse` was given a file with no embedded source and no Astryx markup. Nothing was written. Raised only by the experimental render command.',
+ },
+ {
+ value: 'ERR_RENDER_SOURCE_DAMAGED',
+ stability: 'experimental',
+ description:
+ '`render --reverse` refused the received file, and nothing was written: its embedded source is damaged (not valid, or a file does not match its checksum), lists a path twice, carries a module, stylesheet or JSON file the page does not reach through its own imports, or an image, font or media file whose bytes are not one, or carries a file a render never embeds: a dotfile or dot-folder, anything under node_modules, a package manifest, lockfile or tool configuration, a file a test, story or benchmark runner would run, or any kind but a page module, stylesheet, JSON file or image. Raised only by the experimental render command.',
+ },
],
};
diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjs
index 9acfe98350..fbb36fdcac 100644
--- a/packages/cli/foundation/response/error-codes.mjs
+++ b/packages/cli/foundation/response/error-codes.mjs
@@ -90,6 +90,15 @@
* | 'ERR_SIGNAL_TERMINATED'
* | 'ERR_VERSIONS_UNAVAILABLE'
* | 'ERR_PROJECT_REQUIRED'
+ * | 'ERR_RENDER_COMPILE'
+ * | 'ERR_RENDER_NO_DEFAULT_EXPORT'
+ * | 'ERR_RENDER_MISSING_DEPENDENCY'
+ * | 'ERR_RENDER_BROWSER_API'
+ * | 'ERR_RENDER_ASSET_TOO_LARGE'
+ * | 'ERR_RENDER_TIMEOUT'
+ * | 'ERR_RENDER_FAILED'
+ * | 'ERR_RENDER_NOT_ASTRYX'
+ * | 'ERR_RENDER_SOURCE_DAMAGED'
* )} ErrorCode
*/
@@ -253,6 +262,58 @@ export const ERROR_CODES = Object.freeze({
* integration package) and was run outside one. Nothing was written.
*/
ERR_PROJECT_REQUIRED: 'ERR_PROJECT_REQUIRED',
+
+ // ── Render (experimental) ────────────────────────────────────────
+ /**
+ * The page given to `astryx experimental render` does not compile (a syntax
+ * or type-syntax error). Nothing was written.
+ */
+ ERR_RENDER_COMPILE: 'ERR_RENDER_COMPILE',
+ /**
+ * The page module has no default export to render. Nothing was written.
+ */
+ ERR_RENDER_NO_DEFAULT_EXPORT: 'ERR_RENDER_NO_DEFAULT_EXPORT',
+ /**
+ * The page imports a package that is not installed where the page is.
+ * Nothing was written.
+ */
+ ERR_RENDER_MISSING_DEPENDENCY: 'ERR_RENDER_MISSING_DEPENDENCY',
+ /**
+ * The page reads a browser-only API (window, document, …) while rendering,
+ * and a rendered page has no browser yet. Nothing was written.
+ */
+ ERR_RENDER_BROWSER_API: 'ERR_RENDER_BROWSER_API',
+ /**
+ * A local file the page uses is too large to inline into one HTML file.
+ * Nothing was written.
+ */
+ ERR_RENDER_ASSET_TOO_LARGE: 'ERR_RENDER_ASSET_TOO_LARGE',
+ /**
+ * The page did not finish rendering in time and was stopped. Nothing was
+ * written.
+ */
+ ERR_RENDER_TIMEOUT: 'ERR_RENDER_TIMEOUT',
+ /**
+ * The page threw while rendering for any other reason. Nothing was written.
+ */
+ ERR_RENDER_FAILED: 'ERR_RENDER_FAILED',
+ /**
+ * `render --reverse` was given an HTML file that holds no Astryx markup and
+ * no embedded source, so there is nothing to rebuild. Nothing was written.
+ */
+ ERR_RENDER_NOT_ASTRYX: 'ERR_RENDER_NOT_ASTRYX',
+ /**
+ * `render --reverse` refused the received file: its embedded source is
+ * damaged (not valid, or a file does not match its checksum), lists a path
+ * twice, carries a module, stylesheet or JSON file the page does not
+ * import or an image, font or media file whose bytes are not one, or
+ * carries a file a
+ * render never embeds (a dotfile, node_modules, a manifest, lockfile or
+ * tool configuration, a file a test, story or benchmark runner would run,
+ * or any kind but a page module, stylesheet, JSON file or image). Nothing
+ * was written.
+ */
+ ERR_RENDER_SOURCE_DAMAGED: 'ERR_RENDER_SOURCE_DAMAGED',
});
/**
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 101fd28604..2f36be5d50 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -112,6 +112,19 @@ export const doc = {
description:
"One post's metadata plus the feed URL and the post's full plaintext body.",
},
+ // render (experimental: may change or be removed in a patch release)
+ {
+ value: 'render.page',
+ stability: 'experimental',
+ description:
+ 'A page rendered to one self-contained file: `input`, `output`, `bytes`, the local files embedded (`files`: modules, stylesheets, images and JSON), the package `stylesheets` cut and inlined, `classes`, `cssBytes`, `images` inlined, and `warnings` (`{code, message}`; empty when nothing looked wrong). Experimental: may change or be removed in a patch release.',
+ },
+ {
+ value: 'render.reverse',
+ stability: 'experimental',
+ description:
+ 'A rendered file turned back into a page: `input`, `mode` (`embedded`: the embedded source written back byte for byte; `rebuilt`: rebuilt from Astryx markup, text and layout only), `output`, every file written (`files`), `exact`, the relative imports it did not carry (`missing`, when any), and for a rebuilt page `components`, `elements`, `unknown` and `omitted`. Experimental: may change or be removed in a patch release.',
+ },
// experimental icon (installed icon sets, AST-084): experimental values,
// documented under `astryx docs cli/experimental`, not in this table.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 3da3f7b5dd..258a20be87 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -42,6 +42,10 @@
"types": "./api/index.d.mts",
"import": "./api/index.mjs"
},
+ "./api/experimental": {
+ "types": "./api/experimental.d.mts",
+ "import": "./api/experimental.mjs"
+ },
"./host": {
"types": "./host/index.d.ts",
"import": "./host/index.mjs"
@@ -108,6 +112,7 @@
"@babel/parser": "7.29.8",
"@babel/plugin-transform-typescript": "7.29.7",
"@babel/types": "7.29.8",
+ "@stylexjs/babel-plugin": "catalog:",
"ast-types": "0.16.3",
"commander": "^12.1.0",
"ignore": "^7.0.5",
diff --git a/packages/cli/scripts/generate-cli-readme.mjs b/packages/cli/scripts/generate-cli-readme.mjs
index bee04dc6a1..b0e457580c 100644
--- a/packages/cli/scripts/generate-cli-readme.mjs
+++ b/packages/cli/scripts/generate-cli-readme.mjs
@@ -102,7 +102,11 @@ async function build() {
.map((/** @type {any} */ c) => [`\`${c.name}\``, c.description, outsideProject(c)]);
const errorCodes = await loadDoc('foundation/response/error-codes.doc.mjs');
- const errorRows = errorCodes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);
+ // Experimental codes are documented under `astryx docs cli/experimental`,
+ // not in the stable table (spec:AST-017 FR27).
+ const errorRows = errorCodes.members
+ .filter((/** @type {any} */ m) => m.stability !== 'experimental')
+ .map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);
const responseTypes = await loadDoc(
'foundation/response/response-types.doc.mjs',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4f3abecaa4..f2e4d844cc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -784,6 +784,9 @@ importers:
'@babel/types':
specifier: 7.29.8
version: 7.29.8
+ '@stylexjs/babel-plugin':
+ specifier: 'catalog:'
+ version: 0.19.0
ast-types:
specifier: 0.16.3
version: 0.16.3
diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjs
index 6deeb70f4a..18de745ace 100644
--- a/scripts/check-cli-structure.mjs
+++ b/scripts/check-cli-structure.mjs
@@ -628,6 +628,29 @@ for (const m of apiIndexSrc.matchAll(/export\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)
}
}
+/** Functions exported from api/experimental.mjs, the experimental entry
+ * (spec:AST-017 FR21): a CommandDoc marked `stability: 'experimental'` may
+ * name one of these instead of a stable api/index.mjs export. */
+const experimentalApiExports = new Set();
+const experimentalEntry = path.join(API, 'experimental.mjs');
+if (fs.existsSync(experimentalEntry)) {
+ const src = fs.readFileSync(experimentalEntry, 'utf8');
+ for (const m of src.matchAll(/export\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g)) {
+ if (m[2].endsWith('.type.mjs')) continue;
+ for (const part of m[1].split(',')) {
+ const name = part.trim().split(/\s+/).pop();
+ if (name && /^\w+$/.test(name)) experimentalApiExports.add(name);
+ }
+ }
+ for (const name of experimentalApiExports) {
+ if (apiExports.has(name)) {
+ errors.push(
+ `api boundary: '${name}' is exported from both api/index.mjs and api/experimental.mjs — an experimental function stays off the stable entry`,
+ );
+ }
+ }
+}
+
/** @type {Set<string>} known FR1 gaps: fn values not yet exported.
* Remove an entry when the function is exported; do not add entries. */
const FR1_KNOWN_GAPS = new Set();
@@ -649,7 +672,9 @@ function checkCommandDocFn(dir) {
if (!fnMatch) continue; // group-only CommandDoc (no fn field)
fr1Count++;
const fn = fnMatch[1];
- if (!apiExports.has(fn) && !FR1_KNOWN_GAPS.has(fn)) {
+ const experimentalFn =
+ experimentalApiExports.has(fn) && /stability:\s*['"]experimental['"]/.test(src);
+ if (!apiExports.has(fn) && !experimentalFn && !FR1_KNOWN_GAPS.has(fn)) {
errors.push(
`FR1: CommandDoc ${path.relative(CLI, full)} names fn '${fn}' which is not exported from api/index.mjs`,
);