Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions openframe-frontend-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,35 @@ Extend the shared Tailwind config in your project:

```ts
import designSystemConfig from '@flamingo-stack/openframe-frontend-core/tailwind.config.ts'
import { appStyleSources } from '@flamingo-stack/openframe-frontend-core/style-sources'

export default {
...designSystemConfig,
content: [
'./src/**/*.{js,ts,jsx,tsx}',
'./node_modules/@flamingo-stack/openframe-frontend-core/src/**/*.{js,ts,jsx,tsx}'
]
presets: [designSystemConfig],
// The files your App Router routes import, yours and this library's: never this library's whole
// `dist` or `src`, which puts every component's classes in the stylesheet every page blocks on.
content: appStyleSources({ root: __dirname, appDir: 'src/app' }),
}
```

`appStyleSources` (`scripts/style-sources.cjs`) walks the import graph from the route files, tree-shaken
as your bundler does. A host can leave the lazily loaded chat out of the page's stylesheet with
`firstPaint: true`, and give `EmbeddableChat` a `loadStyles` that loads a full stylesheet built
without it (see the file's header).

Then send the stylesheet inside each page's HTML, so a page never waits on a second request to paint,
and hold its size to a budget in your checks (`scripts/next-styles.cjs` says why and what it costs):

```js
// next.config.mjs
import { withInlineStyles } from '@flamingo-stack/openframe-frontend-core/next-styles'
export default withInlineStyles(nextConfig)
```

```bash
node node_modules/@flamingo-stack/openframe-frontend-core/dist/build/next-styles.cjs budget \
--input src/app/globals.css --config tailwind.config.ts --budget 31500
```

## Package Exports

| Export Path | Description |
Expand All @@ -67,6 +86,8 @@ export default {
| `./utils` | Utilities (cn, formatDate, formatPrice, getPlatformUrl, platform-config) |
| `./types` | TypeScript type definitions |
| `./styles` | CSS styles and ODS design tokens |
| `./style-sources` | Tailwind `content` for an app: the files its routes import (`appStyleSources`) |
| `./next-styles` | The stylesheet inside each page's HTML (`withInlineStyles`) and its size gate (`measureStylesheet`, `budget` command) |
| `./nats` | NATS WebSocket utilities |
| `./fonts` | Font configuration |

Expand Down
12 changes: 11 additions & 1 deletion openframe-frontend-core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@
"require": "./dist/build/optimize-imports-loader.cjs",
"default": "./dist/build/optimize-imports-loader.cjs"
},
"./style-sources": {
"types": "./dist/build/style-sources.d.ts",
"require": "./dist/build/style-sources.cjs",
"default": "./dist/build/style-sources.cjs"
},
"./next-styles": {
"types": "./dist/build/next-styles.d.ts",
"require": "./dist/build/next-styles.cjs",
"default": "./dist/build/next-styles.cjs"
},

Check notice on line 40 in openframe-frontend-core/package.json

View check run for this annotation

Flamingo / Flamingo Code Review

New `./style-sources` and `./next-styles` exports omit the `import` condition used by every other entry

New `./style-sources` and `./next-styles` exports omit the `import` condition used by every other entry Every existing exports entry in package.json (`.`, `./contexts`, `./components`, `./components/ui`, `./components/chat`, …) follows the four-condition pattern: types, import, require, default. The two new entries added here (`./style-sources`, `./next-styles`) only declare `types`, `require`, and `default` — no `import` condition. Node resolves these the same way today because the targets are `.cjs` files and `default` is used for both import and require resolution when no `import` condition is present, but it breaks the established, documented four-condition convention this rule requires, and a future bundler or stricter resolver that requires an explicit `import` condition for ESM consumers would fail to resolve these subpaths. **What it risks:** A consumer bundler that enforces conditions strictly (e.g. one that does not fall back to `default` for ESM `import`) will fail to resolve `@flamingo-stack/openframe-frontend-core/style-sources` or `/next-styles`, and the inconsistency makes the exports map harder to audit. **How to fix:** Add an explicit `import` condition to both new exports entries, consistent with the rest of the map (pointing at the same .cjs file or an .mjs wrapper if ESM import is desired).
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
"./dist/*.js": {
"import": "./dist/*.js",
"default": "./dist/*.js"
Expand Down Expand Up @@ -478,6 +488,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.4",
"date-fns": "^3.6.0",
"esbuild": "^0.28.2",
Comment thread
michaelassraf marked this conversation as resolved.
Resolved
"eslint-config-next": "^16.3.0",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^3.10.1",
Expand Down Expand Up @@ -540,7 +551,6 @@
"@types/node": "^24.10.4",
"@vitest/ui": "^4.0.16",
"autoprefixer": "^10.4.23",
"esbuild": "^0.28.2",
"eslint": "^9.39.0",
"husky": "9.1.7",
"jsdom": "^27.4.0",
Expand Down
4 changes: 4 additions & 0 deletions openframe-frontend-core/scripts/build-export-map.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ function main() {
mkdirSync(OUT_DIR, { recursive: true });
writeFileSync(join(OUT_DIR, 'export-map.json'), `${JSON.stringify({ package: pkg.name, entries })}\n`);
copyFileSync(join(ROOT, 'scripts', 'optimize-imports-loader.cjs'), join(OUT_DIR, 'optimize-imports-loader.cjs'));
copyFileSync(join(ROOT, 'scripts', 'style-sources.cjs'), join(OUT_DIR, 'style-sources.cjs'));
copyFileSync(join(ROOT, 'scripts', 'style-sources.d.ts'), join(OUT_DIR, 'style-sources.d.ts'));
copyFileSync(join(ROOT, 'scripts', 'next-styles.cjs'), join(OUT_DIR, 'next-styles.cjs'));
copyFileSync(join(ROOT, 'scripts', 'next-styles.d.ts'), join(OUT_DIR, 'next-styles.d.ts'));
console.log(`Export map: ${names} names over ${Object.keys(entries).length} entries`);
}

Expand Down
156 changes: 156 additions & 0 deletions openframe-frontend-core/scripts/next-styles.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/**
* How a Next.js app that uses this library ships its stylesheet: inside the page, and measured.
*
* const { withInlineStyles } = require('<package>/next-styles')
* export default withInlineStyles(nextConfig) // next.config
*
* node node_modules/<package>/dist/build/next-styles.cjs budget \
* --input src/app/globals.css --config tailwind.config.ts --budget 31500 // the build gate
*
* WHY. A page cannot paint before its stylesheet arrives, and a stylesheet in a file of its own is
* requested only once the HTML names it: one more round trip after the HTML, whatever the file weighs.
* Measured on flamingo.run (CU-17tkuw617h7, Lighthouse mobile, slow 4G): the 44 KB sheet took 856 ms
* from request to last byte, a 1 KB sheet beside it 570 ms, and the page painted 65 ms after the large
* one landed. Cutting the sheet by a quarter moved LCP by nothing measurable; sending the sheet inside
* the HTML moved the home page's LCP from 1.50 s to 0.93 s and a blog post's from 1.60 s to 0.95 s.
*
* WHAT. `withInlineStyles` turns on Next's `experimental.inlineCss`: every stylesheet a route links is
* written into its HTML as a `<style>` tag instead (production builds, `output: 'export'` included;
* `next dev` keeps its links). The price is paid in the HTML: the sheet arrives with every page and is
* not cached apart from it, and Next sends it twice on a first load (the tag and the page's data).
* That is a good trade only while the sheet is small, so it comes with its gate: `measureStylesheet`
* builds the app's stylesheet the way its build does (Tailwind, minified) and reports its size
* brotli-compressed, as a CDN serves it, and the `budget` command fails past a stated size. Keep the
* sheet small with `appStyleSources` (`./style-sources`): Tailwind content from what the routes import.
*
* Per page: a sheet cut per route from the import graph was measured too, and saved 10% (26.4 KB
* against 29.3 KB brotli on flamingo): a site's shared layout reaches most of the design system, so a
* page's sheet is mostly its layout's. Inlining removes the wait; a smaller sheet only makes it cheap.
*/
const { execFile } = require('node:child_process');
const { mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { dirname, isAbsolute, join, resolve } = require('node:path');
const { promisify } = require('node:util');
const { brotliCompressSync, constants } = require('node:zlib');

/** `nextConfig` with every route's stylesheets written into its HTML. Composes with a config function. */
function withInlineStyles(nextConfig) {
const apply = config => ({ ...config, experimental: { ...config.experimental, inlineCss: true } });
if (typeof nextConfig === 'function') {
return async (...args) => apply(await nextConfig(...args));
}
return apply(nextConfig);
}

/**
* The stylesheet `input` with each `@import` made an absolute path: the Tailwind CLI resolves an import
* by path only, never through a package's `exports` (`@import '<package>/styles'`), which a bundler does.
*/
function resolveImports(input, root) {
const from = dirname(input);
return readFileSync(input, 'utf8').replace(/@import\s+(['"])([^'"]+)\1\s*;/g, (statement, _quote, specifier) => {
if (/^(https?:)?\/\//.test(specifier)) return statement;
const file =
specifier.startsWith('.') || isAbsolute(specifier)
? resolve(from, specifier)
: require.resolve(specifier, { paths: [root, from] });
return `@import "${file}";`;
});
}

Check warning on line 60 in openframe-frontend-core/scripts/next-styles.cjs

View check run for this annotation

Flamingo / Flamingo Code Review / tests and mutation

measureStylesheet breaks a stylesheet with a relative @config

measureStylesheet copies the input into a temporary folder and resolveImports rewrites only @import paths. A relative @config (the hub's app/full.css has `@config "../tailwind.full.config.ts"`) then resolves against the temporary folder and Tailwind fails: 'The config file at "../tailwind.full.config.ts" does not exist'. Tailwind also refuses an absolute @config path, so rewriting it the same way would not work. Risk: The budget command cannot measure any stylesheet that names its own config, so an app cannot hold such a sheet to a budget; today the hub measures only app/globals.css, which has no @config. Fix: Write the resolved copy next to the input (same folder, a hidden name) instead of in tmpdir, so @config and any relative url() keep resolving, and remove it afterwards; or strip the @config line and rely on the --config the caller passes. Add a test with a relative @config.
Comment thread
michaelassraf marked this conversation as resolved.
Resolved

/**
* Builds `input` with Tailwind and `config` the way the app's build does, minified, and measures it.
*
* root the app's directory (absolute); `input` and `config` are relative to it.
* input the stylesheet the root layout imports ('src/app/globals.css').
* config the Tailwind config that builds it ('tailwind.config.ts').
* env variables the config reads (an app that builds one site per `NEXT_PUBLIC_APP_TYPE`).
*
* Resolves to `{ css, raw, brotli }`: the minified stylesheet, its bytes, and its bytes brotli-compressed
* at the quality a CDN serves static files with.
*/
async function measureStylesheet({ root, input, config, env = {} }) {
if (!isAbsolute(root)) throw new Error('measureStylesheet: root must be an absolute path');
const dir = mkdtempSync(join(tmpdir(), 'next-styles-'));
try {
const source = join(dir, 'input.css');
const output = join(dir, 'output.css');
writeFileSync(source, resolveImports(resolve(root, input), root));
// The app's own Tailwind, the one its build runs; this package's where the app has none of its own.
const cli = require.resolve('tailwindcss/lib/cli.js', { paths: [root, __dirname] });
await promisify(execFile)(
process.execPath,
[cli, '-c', resolve(root, config), '-i', source, '-o', output, '--minify'],
{
cwd: root,
env: { ...process.env, ...env },
maxBuffer: 64 * 1024 * 1024,
},
);
const css = readFileSync(output, 'utf8');
const brotli = brotliCompressSync(Buffer.from(css), {
params: { [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY },
}).length;
return { css, raw: Buffer.byteLength(css), brotli };
} finally {
rmSync(dir, { recursive: true, force: true });
}
}

const kb = bytes => `${(bytes / 1024).toFixed(1)} KB`;

/** `--name value` pairs of the command line; `--env KEY=VALUE` may repeat. */
function parseArgs(argv) {
const args = { env: {} };
for (let i = 0; i < argv.length; i += 2) {
const [name, value] = [argv[i], argv[i + 1]];
if (!name.startsWith('--') || value === undefined) throw new Error(`next-styles: bad argument ${name}`);
if (name === '--env') {
const at = value.indexOf('=');
args.env[value.slice(0, at)] = value.slice(at + 1);
} else {
args[name.slice(2)] = value;
}
}
return args;
}

/** `budget --input <css> --config <tailwind config> --budget <brotli bytes> [--name <label>] [--env K=V]` */
async function budgetCommand(argv) {
const args = parseArgs(argv);
const budget = Number(args.budget);
if (!args.input || !args.config || !Number.isInteger(budget) || budget <= 0) {
throw new Error('usage: next-styles budget --input <css> --config <tailwind config> --budget <brotli bytes>');
}
const name = args.name ?? args.input;
const { raw, brotli } = await measureStylesheet({
root: process.cwd(),
input: args.input,
config: args.config,
env: args.env,
});
console.log(`[css-budget] ${name}: ${kb(raw)} raw, ${kb(brotli)} brotli (budget ${kb(budget)})`);
if (brotli > budget) {
console.error(
`[css-budget] FAIL: ${name} is over its budget. Every page carries this stylesheet in its HTML: find what a ` +
'route now imports that it does not render, or raise the budget with the reason.',
);
process.exitCode = 1;
}
}

if (require.main === module) {
const [command, ...rest] = process.argv.slice(2);
Promise.resolve()
.then(() => {
if (command !== 'budget') throw new Error(`next-styles: unknown command ${command ?? '(none)'}; try "budget"`);
return budgetCommand(rest);
})
.catch(error => {
console.error(`[css-budget] ${error.message}`);
process.exitCode = 1;
});
}

module.exports = { withInlineStyles, measureStylesheet, resolveImports };
21 changes: 21 additions & 0 deletions openframe-frontend-core/scripts/next-styles.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/** `nextConfig` (an object, or a config function) with every route's stylesheets written into its HTML. */
export function withInlineStyles<A extends unknown[], T extends object>(
nextConfig: (...args: A) => T | Promise<T>,
): (...args: A) => Promise<T & { experimental: { inlineCss: true } }>;
export function withInlineStyles<T extends object>(nextConfig: T): T & { experimental: { inlineCss: true } };

/** Options of {@link measureStylesheet}; each is described in `next-styles.cjs`. */
export interface MeasureStylesheetOptions {
root: string;
input: string;
config: string;
env?: Record<string, string>;
}

/** The app's stylesheet built as its build builds it, minified: its bytes raw and brotli-compressed. */
export function measureStylesheet(
options: MeasureStylesheetOptions,
): Promise<{ css: string; raw: number; brotli: number }>;

/** The stylesheet at `input` with each `@import` resolved to an absolute path (packages through their `exports`). */
export function resolveImports(input: string, root: string): string;
Loading
Loading