An open source design system that's fully customizable and agent ready
TypeScript
fix(cli,docsite): keep the docs site's search function small enough to deploy (#7896)
Joey8243c42a5b11
diff --git a/.changeset/search-function-trace.md b/.changeset/search-function-trace.mdnew file mode 100644index 0000000000..276885beea--- /dev/null+++ b/.changeset/search-function-trace.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] Hosts that bundle the CLI into a server function no longer pack their whole project folder into it: one path in `integration check`'s import checks was built in a way file tracers cannot follow. The path and its results are unchanged.++@josephfarinadiff --git a/apps/docsite/package.json b/apps/docsite/package.jsonindex e3f7e07477..af093003cb 100644--- a/apps/docsite/package.json+++ b/apps/docsite/package.json@@ -7,7 +7,7 @@"generate": "node scripts/check-workspace-build.mjs && pnpm build:theme && node scripts/generate-data.mjs && node scripts/generate-scope.mjs && node scripts/generate-playground-types.mjs && node scripts/copy-vendor.mjs","dev": "pnpm generate && node ../../scripts/generate-i18n-runtime.mjs --watch -- pnpm --parallel --filter @astryxdesign/core --filter @astryxdesign/docsite dev:i18n","dev:i18n": "next dev --webpack",- "build": "pnpm generate && next build --webpack && node scripts/check-template-gallery-bundle.mjs",+ "build": "pnpm generate && next build --webpack && node scripts/check-template-gallery-bundle.mjs && node scripts/check-function-size.mjs","start": "next start","typecheck": "tsc --noEmit","test": "vitest run",diff --git a/apps/docsite/scripts/check-function-size.mjs b/apps/docsite/scripts/check-function-size.mjsnew file mode 100644index 0000000000..d685ea0ee0--- /dev/null+++ b/apps/docsite/scripts/check-function-size.mjs@@ -0,0 +1,91 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Fails the build when a server function's traced files grow past a safe+ * margin under the host's function size limit.+ *+ * Next traces every file a server route may read at run time+ * (`*.nft.json`), and each route deploys with those files. A path the tracer+ * cannot resolve (for example one built from a template string) can make it+ * include a whole folder, so a function can grow by gigabytes from one+ * unrelated change, and the deploy then fails with no local error. This reads+ * every route's trace after `next build` and fails when one passes the budget.+ */++import {+ existsSync,+ readdirSync,+ readFileSync,+ realpathSync,+ statSync,+} from 'node:fs';+import {dirname, join, relative} from 'node:path';+import {fileURLToPath} from 'node:url';++const appRoot = join(dirname(fileURLToPath(import.meta.url)), '..');+const serverRoot = join(appRoot, '.next', 'server');++/** The host's limit for one function's files, uncompressed, is 250 MB. */+export const FUNCTION_BUDGET_BYTES = 150 * 1000 * 1000;++/**+ * Every `*.nft.json` under a folder.+ * @param {string} dir+ * @returns {string[]}+ */+function traces(dir) {+ return readdirSync(dir, {withFileTypes: true}).flatMap(entry => {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) return traces(full);+ return entry.name.endsWith('.nft.json') ? [full] : [];+ });+}++/**+ * The bytes of the distinct files one trace lists.+ * @param {string} trace+ * @returns {{bytes: number, files: number}}+ */+export function tracedSize(trace) {+ const {files} = JSON.parse(readFileSync(trace, 'utf8'));+ const seen = new Set();+ let bytes = 0;+ for (const file of files) {+ const full = join(dirname(trace), file);+ if (!existsSync(full)) continue;+ const real = realpathSync(full);+ if (seen.has(real)) continue;+ const stat = statSync(real);+ if (!stat.isFile()) continue;+ seen.add(real);+ bytes += stat.size;+ }+ return {bytes, files: seen.size};+}++const mb = bytes => `${(bytes / 1e6).toFixed(1)} MB`;++if (fileURLToPath(import.meta.url) === process.argv[1]) {+ if (!existsSync(serverRoot)) {+ throw new Error(`${serverRoot} is missing: run next build first.`);+ }+ const sizes = traces(join(serverRoot, 'app'))+ .map(trace => ({trace: relative(serverRoot, trace), ...tracedSize(trace)}))+ .sort((a, b) => b.bytes - a.bytes);+ const over = sizes.filter(size => size.bytes > FUNCTION_BUDGET_BYTES);+ for (const size of over) {+ console.error(+ `${size.trace}: ${mb(size.bytes)} in ${size.files} files, over the ${mb(FUNCTION_BUDGET_BYTES)} budget`,+ );+ }+ if (over.length > 0) {+ throw new Error(+ 'A server function traces too many files. Find the import or file read the tracer cannot resolve, or add an outputFileTracingExcludes entry in next.config.mjs.',+ );+ }+ const largest = sizes[0];+ console.log(+ `Server functions: largest is ${largest.trace} at ${mb(largest.bytes)} (budget ${mb(FUNCTION_BUDGET_BYTES)}).`,+ );+}diff --git a/packages/cli/foundation/integrations/public-imports.mjs b/packages/cli/foundation/integrations/public-imports.mjsindex 8d0a53eacc..c200180ac3 100644--- a/packages/cli/foundation/integrations/public-imports.mjs+++ b/packages/cli/foundation/integrations/public-imports.mjs@@ -1439,7 +1439,7 @@ async function componentIssues(ctx, integration) {...MODULE_EXTENSIONS,...MODULE_EXTENSIONS.map(ext => `/index${ext}`),]- .map(ext => path.resolve(ctx.packageDir, `${subpath.slice(2)}${ext}`))+ .map(ext => path.resolve(ctx.packageDir, subpath.slice(2) + ext)).find(file =>file.startsWith(path.resolve(ctx.packageDir) + path.sep) &&diff --git a/packages/cli/test/traceable-paths.test.mjs b/packages/cli/test/traceable-paths.test.mjsnew file mode 100644index 0000000000..54c67413ee--- /dev/null+++ b/packages/cli/test/traceable-paths.test.mjs@@ -0,0 +1,90 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Shipped CLI code builds no `path.resolve()` path from a template+ * string.+ *+ * Hosts that bundle the CLI into a server function (the docs site's search)+ * trace the files it may read at run time. The tracer cannot resolve+ * `path.resolve(dir, `${a}${b}`)`, and treats it as possibly any file under+ * the process's working folder, so it packs that whole folder into the+ * function: one such line grew the docs site's search function from about+ * 50 MB to about 5 GB, past the host's limit, and every deploy failed. Build+ * the string first, or join plain strings (`a + b`), as the rest of the CLI+ * does.+ */++import {describe, it, expect} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';+import {parse} from '@babel/parser';++const CLI = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const SHIPPED = ['api', 'authoring', 'clients', 'foundation', 'host'];++/**+ * Every shipped source file: not a test, not a fixture.+ * @param {string} dir+ * @returns {string[]}+ */+function sources(dir) {+ return fs.readdirSync(dir, {withFileTypes: true}).flatMap(entry => {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ return entry.name === 'node_modules' || entry.name === '__fixtures__'+ ? []+ : sources(full);+ }+ return entry.name.endsWith('.mjs') && !entry.name.endsWith('.test.mjs')+ ? [full]+ : [];+ });+}++/**+ * Each `path.resolve(...)` call with an interpolated template string argument.+ * @param {string} file+ * @returns {string[]}+ */+function templateResolves(file) {+ const ast = parse(fs.readFileSync(file, 'utf8'), {+ sourceType: 'module',+ plugins: ['jsx'],+ errorRecovery: true,+ });+ /** @type {string[]} */+ const found = [];+ /** @param {any} node */+ const visit = node => {+ if (!node || typeof node.type !== 'string') return;+ if (+ node.type === 'CallExpression' &&+ node.callee.type === 'MemberExpression' &&+ node.callee.object.type === 'Identifier' &&+ node.callee.object.name === 'path' &&+ node.callee.property.name === 'resolve' &&+ node.arguments.some(+ (/** @type {any} */ arg) =>+ arg.type === 'TemplateLiteral' && arg.expressions.length > 0,+ )+ ) {+ found.push(`${path.relative(CLI, file)}:${node.loc.start.line}`);+ }+ for (const value of Object.values(node)) {+ if (Array.isArray(value)) value.forEach(visit);+ else if (value && typeof value === 'object') visit(value);+ }+ };+ visit(ast.program);+ return found;+}++describe('traceable paths', () => {+ it('builds no path.resolve() path from a template string', () => {+ const found = SHIPPED.flatMap(root =>+ sources(path.join(CLI, root)),+ ).flatMap(templateResolves);+ expect(found).toEqual([]);+ });+});