@typestyles/next 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { describe, it, expect, vi } from 'vitest';
5
+ import type { NextConfig } from 'next';
6
+ import type { Configuration } from 'webpack';
7
+ import { withTypestyles, withTypestylesExtract } from './build';
8
+
9
+ type WebpackContext = Parameters<NonNullable<NextConfig['webpack']>>[1];
10
+
11
+ describe('withTypestylesExtract', () => {
12
+ it('merges NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED into env for Turbopack + webpack', () => {
13
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: true });
14
+ expect(merged.env).toEqual({
15
+ CUSTOM: 'x',
16
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
17
+ });
18
+ });
19
+
20
+ it('does not override env when disableClientRuntime is false', () => {
21
+ const merged = withTypestylesExtract({ env: { CUSTOM: 'x' } }, { disableClientRuntime: false });
22
+ expect(merged.env).toEqual({ CUSTOM: 'x' });
23
+ });
24
+
25
+ it('chains user webpack() and adds DefinePlugin on the client', async () => {
26
+ const webpackMod = await import('webpack');
27
+ const userWebpack = vi.fn((cfg: { plugins: unknown[] }) => {
28
+ cfg.plugins.push('user-marker');
29
+ return cfg;
30
+ });
31
+ const merged = withTypestylesExtract({ webpack: userWebpack });
32
+ const config = { plugins: [] as unknown[] };
33
+ const webpackHook = merged.webpack;
34
+ if (typeof webpackHook !== 'function') {
35
+ throw new Error('expected webpack hook');
36
+ }
37
+ const result = webpackHook(
38
+ config as Configuration,
39
+ {
40
+ isServer: false,
41
+ } as WebpackContext,
42
+ );
43
+ expect(userWebpack).toHaveBeenCalled();
44
+ const hasDefine = result.plugins?.some(
45
+ (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
46
+ );
47
+ expect(hasDefine).toBe(true);
48
+ });
49
+
50
+ it('applies extract in production when a convention entry exists under root', () => {
51
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-cwd-'));
52
+ mkdirSync(join(dir, 'styles'), { recursive: true });
53
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
54
+
55
+ vi.stubEnv('NODE_ENV', 'production');
56
+ try {
57
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
58
+ expect(merged.env).toEqual({
59
+ CUSTOM: 'y',
60
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
61
+ });
62
+ } finally {
63
+ vi.unstubAllEnvs();
64
+ }
65
+
66
+ rmSync(dir, { recursive: true, force: true });
67
+ });
68
+
69
+ it('does not apply extract in development even when a convention entry exists', () => {
70
+ const dir = mkdtempSync(join(tmpdir(), 'typestyles-next-dev-'));
71
+ mkdirSync(join(dir, 'styles'), { recursive: true });
72
+ writeFileSync(join(dir, 'styles/typestyles-entry.ts'), 'export {}\n');
73
+
74
+ vi.stubEnv('NODE_ENV', 'development');
75
+ try {
76
+ const merged = withTypestyles({ env: { CUSTOM: 'y' } }, { root: dir });
77
+ expect(merged.env).toEqual({ CUSTOM: 'y' });
78
+ } finally {
79
+ vi.unstubAllEnvs();
80
+ }
81
+
82
+ rmSync(dir, { recursive: true, force: true });
83
+ });
84
+
85
+ it('does not add DefinePlugin for server bundles', async () => {
86
+ const webpackMod = await import('webpack');
87
+ const merged = withTypestylesExtract({});
88
+ const config = { plugins: [] as unknown[] };
89
+ const webpackHook = merged.webpack;
90
+ if (typeof webpackHook !== 'function') {
91
+ throw new Error('expected webpack hook');
92
+ }
93
+ const result = webpackHook(
94
+ config as Configuration,
95
+ {
96
+ isServer: true,
97
+ } as WebpackContext,
98
+ );
99
+ const hasDefine = result.plugins?.some(
100
+ (p: unknown) => p instanceof webpackMod.default.DefinePlugin,
101
+ );
102
+ expect(hasDefine).toBe(false);
103
+ });
104
+ });
package/src/build.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import {
7
+ buildManifestV2,
8
+ collectAndWriteRouteCss,
9
+ discoverDefaultExtractModules,
10
+ type TypestylesExtractManifestV1,
11
+ type TypestylesExtractManifestV2,
12
+ } from '@typestyles/build-runner';
13
+ import { collectStylesFromModules } from 'typestyles/build';
14
+ import type { NextConfig } from 'next';
15
+
16
+ /** Re-export shared convention paths (aligned with `@typestyles/vite`). */
17
+ export {
18
+ DEFAULT_EXTRACT_MODULE_CANDIDATES,
19
+ discoverDefaultExtractModules,
20
+ verifyTypestylesBuild,
21
+ VerifyTypestylesBuildError,
22
+ getRouteCss,
23
+ type TypestylesExtractManifestV1,
24
+ type TypestylesExtractManifestV2,
25
+ type VerifyTypestylesBuildOptions,
26
+ type VerifyTypestylesBuildResult,
27
+ type GetRouteCssOptions,
28
+ } from '@typestyles/build-runner';
29
+
30
+ /** Shape of `require('webpack')` for `DefinePlugin` only (webpack is an optional peer). */
31
+ type WebpackWithDefinePlugin = {
32
+ DefinePlugin: new (definitions: Record<string, string>) => unknown;
33
+ };
34
+
35
+ export interface BuildTypestylesForNextOptions {
36
+ root: string;
37
+ /**
38
+ * Style entry modules relative to `root`. When omitted, uses the same convention discovery as
39
+ * `@typestyles/vite` (see {@link discoverDefaultExtractModules}).
40
+ */
41
+ modules?: string[];
42
+ /** Output CSS path relative to `root`. Defaults to `app/typestyles.css`. */
43
+ cssOutFile?: string;
44
+ /**
45
+ * Manifest path relative to `root`. Defaults to `app/typestyles.manifest.json`.
46
+ * Pass `false` to skip writing a manifest.
47
+ */
48
+ manifestOutFile?: string | false;
49
+ /** Value stored in the manifest `css` field. Defaults to `cssOutFile`. */
50
+ manifestCssPath?: string;
51
+ /**
52
+ * Emit per-route critical CSS for App Router pages and include mappings in the manifest (v2).
53
+ * Defaults to `true` when an `app/` directory exists under `root`.
54
+ */
55
+ routeCss?: boolean;
56
+ /** Output directory for per-route CSS relative to `root`. Default: `app/_typestyles/routes`. */
57
+ routeCssOutDir?: string;
58
+ /** App Router directory relative to `root`. Default: `app`. */
59
+ appDir?: string;
60
+ }
61
+
62
+ function resolveExtractModulesForNext(root: string, modules?: string[]): string[] {
63
+ if (modules !== undefined) {
64
+ return modules;
65
+ }
66
+ const found = discoverDefaultExtractModules(root);
67
+ if (found.length === 0) {
68
+ throw new Error(
69
+ `[typestyles] No extraction entry found under ${root}. Add a convention file (see DEFAULT_EXTRACT_MODULE_CANDIDATES from @typestyles/build-runner) or pass modules to buildTypestylesForNext.`,
70
+ );
71
+ }
72
+ return found;
73
+ }
74
+
75
+ /**
76
+ * Extract TypeStyles CSS for a Next.js app (run from a script before `next build`, or in CI).
77
+ * Loads each module path (relative to `root`) so side-effect registrations run, then writes CSS.
78
+ *
79
+ * Defaults mirror `@typestyles/vite`: discovers a convention entry when `modules` is omitted,
80
+ * writes `app/typestyles.css` and `app/typestyles.manifest.json` unless overridden.
81
+ *
82
+ * When route CSS is enabled (default for App Router apps), the manifest is v2 and includes
83
+ * per-route CSS paths under `app/_typestyles/routes/` (override with `routeCssOutDir`).
84
+ */
85
+ export async function buildTypestylesForNext(
86
+ options: BuildTypestylesForNextOptions,
87
+ ): Promise<void> {
88
+ const {
89
+ root,
90
+ modules,
91
+ cssOutFile = 'app/typestyles.css',
92
+ manifestOutFile,
93
+ manifestCssPath,
94
+ routeCssOutDir = 'app/_typestyles/routes',
95
+ appDir = 'app',
96
+ } = options;
97
+
98
+ const resolvedModules = resolveExtractModulesForNext(root, modules);
99
+ const enableRouteCss = options.routeCss ?? discoverNextAppRoutesEnabled(root, appDir);
100
+
101
+ const loaders = resolvedModules.map((mod) => {
102
+ const abs = resolve(root, mod);
103
+ const href = pathToFileURL(abs).href;
104
+ return () => import(href);
105
+ });
106
+ const css = await collectStylesFromModules(loaders);
107
+ const outAbs = resolve(root, cssOutFile);
108
+ await mkdir(dirname(outAbs), { recursive: true });
109
+ await writeFile(outAbs, css, 'utf8');
110
+
111
+ const manifestRel =
112
+ manifestOutFile === false ? undefined : (manifestOutFile ?? 'app/typestyles.manifest.json');
113
+
114
+ if (manifestRel) {
115
+ const cssPath = manifestCssPath ?? cssOutFile;
116
+ let manifest: TypestylesExtractManifestV1 | TypestylesExtractManifestV2 = {
117
+ version: 1,
118
+ css: cssPath,
119
+ };
120
+
121
+ if (enableRouteCss) {
122
+ const { routes } = await collectAndWriteRouteCss({
123
+ root,
124
+ sharedModules: resolvedModules,
125
+ appDir,
126
+ routeCssOutDir,
127
+ collectCss: collectStylesFromModules,
128
+ });
129
+ manifest = buildManifestV2(cssPath, routes);
130
+ }
131
+
132
+ const manAbs = resolve(root, manifestRel);
133
+ await mkdir(dirname(manAbs), { recursive: true });
134
+ await writeFile(manAbs, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
135
+ }
136
+ }
137
+
138
+ function discoverNextAppRoutesEnabled(root: string, appDir: string): boolean {
139
+ return existsSync(resolve(root, appDir));
140
+ }
141
+
142
+ export interface WithTypestylesExtractOptions {
143
+ /**
144
+ * When true (default), client bundles skip DOM style injection (`__TYPESTYLES_RUNTIME_DISABLED__`).
145
+ * Pair with a global stylesheet from {@link buildTypestylesForNext}.
146
+ */
147
+ disableClientRuntime?: boolean;
148
+ /**
149
+ * Project root used for module resolution (e.g. loading `webpack`). Defaults to `process.cwd()`.
150
+ */
151
+ root?: string;
152
+ }
153
+
154
+ export interface WithTypestylesOptions extends WithTypestylesExtractOptions {
155
+ /**
156
+ * Project root for convention discovery. Defaults to `process.cwd()` (the directory Next runs from).
157
+ */
158
+ root?: string;
159
+ }
160
+
161
+ /**
162
+ * Production Next.js config helper aligned with `@typestyles/vite`: when `NODE_ENV === 'production'`
163
+ * and a convention entry file exists under `root`, applies {@link withTypestylesExtract}; otherwise
164
+ * returns `nextConfig` unchanged (development keeps runtime injection).
165
+ */
166
+ export function withTypestyles(
167
+ nextConfig: NextConfig = {},
168
+ options: WithTypestylesOptions = {},
169
+ ): NextConfig {
170
+ const projectRoot = options.root ?? process.cwd();
171
+ const hasConventionEntry = discoverDefaultExtractModules(projectRoot).length > 0;
172
+ const prod = process.env.NODE_ENV === 'production';
173
+
174
+ if (!prod || !hasConventionEntry) {
175
+ return nextConfig;
176
+ }
177
+
178
+ return withTypestylesExtract(nextConfig, options);
179
+ }
180
+
181
+ /**
182
+ * Merge Next.js config so client bundles use pre-extracted CSS only (no runtime `<style>` injection).
183
+ *
184
+ * - **Webpack**: adds `DefinePlugin` for `__TYPESTYLES_RUNTIME_DISABLED__` on client bundles.
185
+ * - **Turbopack** (`next dev --turbo` / Turbopack production): webpack hooks do not run; the same
186
+ * `next.config` `env` entry `NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED` is merged so the client
187
+ * bundle still disables runtime insertion (see `typestyles` `sheet` implementation).
188
+ */
189
+ export function withTypestylesExtract(
190
+ nextConfig: NextConfig = {},
191
+ options: WithTypestylesExtractOptions = {},
192
+ ): NextConfig {
193
+ const disableClientRuntime = options.disableClientRuntime !== false;
194
+ const projectRoot = options.root ?? process.cwd();
195
+
196
+ return {
197
+ ...nextConfig,
198
+ ...(disableClientRuntime
199
+ ? {
200
+ env: {
201
+ ...(typeof nextConfig.env === 'object' &&
202
+ nextConfig.env !== null &&
203
+ !Array.isArray(nextConfig.env)
204
+ ? (nextConfig.env as Record<string, string>)
205
+ : {}),
206
+ NEXT_PUBLIC_TYPESTYLES_RUNTIME_DISABLED: 'true',
207
+ },
208
+ }
209
+ : {}),
210
+ webpack(config, context) {
211
+ const nextWebpack =
212
+ typeof nextConfig.webpack === 'function' ? nextConfig.webpack(config, context) : config;
213
+
214
+ if (disableClientRuntime && !context.isServer) {
215
+ try {
216
+ const require = createRequire(join(projectRoot, 'package.json'));
217
+ const webpackLib = require('webpack') as WebpackWithDefinePlugin;
218
+ nextWebpack.plugins.push(
219
+ new webpackLib.DefinePlugin({
220
+ __TYPESTYLES_RUNTIME_DISABLED__: JSON.stringify('true'),
221
+ }),
222
+ );
223
+ } catch {
224
+ console.warn(
225
+ '[@typestyles/next/build] Could not load webpack; client bundles may still inject <style>.',
226
+ );
227
+ }
228
+ }
229
+
230
+ return nextWebpack;
231
+ },
232
+ };
233
+ }
@@ -0,0 +1,33 @@
1
+ import type * as React from 'react';
2
+ import type { useSyncExternalStore } from 'react';
3
+
4
+ /**
5
+ * Subscribe to typestyles CSS changes. Use this in client components
6
+ * that need to stay up-to-date with dynamically registered styles.
7
+ */
8
+ export function useTypestyles(): ReturnType<typeof useSyncExternalStore<string>>;
9
+
10
+ /**
11
+ * Re-export of React’s `useServerInsertedHTML` (App Router / streaming SSR).
12
+ * Declared here so consumers get a stable signature even when their `@types/react` predates the hook.
13
+ */
14
+ export function useServerInsertedHTML(callback: () => React.ReactNode | null): void;
15
+
16
+ /**
17
+ * Props for the TypestylesStylesheet component.
18
+ */
19
+ export interface TypestylesStylesheetProps {
20
+ children?: React.ReactNode;
21
+ }
22
+
23
+ /**
24
+ * A React component that renders typestyles CSS.
25
+ */
26
+ export function TypestylesStylesheet(props: TypestylesStylesheetProps): React.JSX.Element | null;
27
+
28
+ /**
29
+ * Create a Next.js layout export that includes typestyles.
30
+ */
31
+ export function createTypestylesLayout<P extends { children?: React.ReactNode }>(
32
+ layout: (props: P) => React.ReactNode,
33
+ ): (props: P) => React.JSX.Element;
package/src/client.tsx ADDED
@@ -0,0 +1,144 @@
1
+ 'use client';
2
+
3
+ import React, { useState, useEffect, useServerInsertedHTML, useSyncExternalStore } from 'react';
4
+ import { getRegisteredCss, subscribeRegisteredCss } from 'typestyles/server';
5
+
6
+ /**
7
+ * Subscribe to typestyles CSS changes. Use this in client components
8
+ * that need to stay up-to-date with dynamically registered styles.
9
+ * Re-renders whenever new CSS rules are registered on the client.
10
+ *
11
+ * @example
12
+ * ```tsx
13
+ * // components/Styles.tsx
14
+ * 'use client';
15
+ * import { useTypestyles } from '@typestyles/next/client';
16
+ *
17
+ * export function Styles() {
18
+ * useTypestyles();
19
+ * return null;
20
+ * }
21
+ * ```
22
+ */
23
+ export function useTypestyles() {
24
+ return useSyncExternalStore(
25
+ subscribeRegisteredCss,
26
+ () => getRegisteredCss(),
27
+ () => getRegisteredCss(),
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Collect styles during server rendering for App Router.
33
+ * Use this in a Client Component wrapper that collects styles from its children.
34
+ *
35
+ * @example
36
+ * ```tsx
37
+ * // components/TypestylesProvider.tsx
38
+ * 'use client';
39
+ *
40
+ * import { useServerInsertedHTML, getRegisteredCss } from '@typestyles/next/client';
41
+ *
42
+ * export function TypestylesProvider({ children }: { children: React.ReactNode }) {
43
+ * useServerInsertedHTML(() => {
44
+ * return (
45
+ * <style
46
+ * id="typestyles"
47
+ * dangerouslySetInnerHTML={{ __html: getRegisteredCss() }}
48
+ * />
49
+ * );
50
+ * });
51
+ * return <>{children}</>;
52
+ * }
53
+ * ```
54
+ */
55
+ export { useServerInsertedHTML };
56
+
57
+ /**
58
+ * Props for the TypestylesStylesheet component.
59
+ */
60
+ export interface TypestylesStylesheetProps {
61
+ /**
62
+ * The children to render (styles will be collected from these).
63
+ * If not provided, only the existing registered CSS will be included.
64
+ */
65
+ children?: React.ReactNode;
66
+ }
67
+
68
+ /**
69
+ * A React component that renders typestyles CSS.
70
+ *
71
+ * For App Router: Use this in your root layout to collect and render styles.
72
+ * Works with both Client Components and React Server Components.
73
+ *
74
+ * @example
75
+ * ```tsx
76
+ * // app/layout.tsx
77
+ * import { TypestylesStylesheet } from '@typestyles/next/client';
78
+ *
79
+ * export default function RootLayout({ children }) {
80
+ * return (
81
+ * <html>
82
+ * <head>
83
+ * <TypestylesStylesheet />
84
+ * </head>
85
+ * <body>{children}</body>
86
+ * </html>
87
+ * );
88
+ * }
89
+ * ```
90
+ */
91
+ export function TypestylesStylesheet({ children }: TypestylesStylesheetProps) {
92
+ const [css, setCss] = useState('');
93
+
94
+ useServerInsertedHTML(() => {
95
+ const registeredCss = getRegisteredCss();
96
+ if (registeredCss) {
97
+ return <style id="typestyles" dangerouslySetInnerHTML={{ __html: registeredCss }} />;
98
+ }
99
+ return null;
100
+ });
101
+
102
+ useEffect(() => {
103
+ setCss(getRegisteredCss());
104
+ }, []);
105
+
106
+ if (children) {
107
+ return (
108
+ <>
109
+ {children}
110
+ <style id="typestyles-client" dangerouslySetInnerHTML={{ __html: css }} />
111
+ </>
112
+ );
113
+ }
114
+
115
+ return null;
116
+ }
117
+
118
+ /**
119
+ * Create a Next.js layout export that includes typestyles.
120
+ *
121
+ * @example
122
+ * ```tsx
123
+ * // app/layout.tsx
124
+ * import { createTypestylesLayout } from '@typestyles/next/client';
125
+ *
126
+ * export default createTypestylesLayout(function RootLayout({ children }) {
127
+ * return (
128
+ * <html>
129
+ * <head>
130
+ * <title>My App</title>
131
+ * </head>
132
+ * <body>{children}</body>
133
+ * </html>
134
+ * );
135
+ * });
136
+ * ```
137
+ */
138
+ export function createTypestylesLayout<P extends { children?: React.ReactNode }>(
139
+ layout: (props: P) => React.ReactNode,
140
+ ): (props: P) => React.ReactNode {
141
+ return function TypestylesLayout(props: P) {
142
+ return <TypestylesStylesheet>{layout(props)}</TypestylesStylesheet>;
143
+ };
144
+ }
package/src/index.d.ts CHANGED
@@ -1,13 +1,15 @@
1
+ import type { ReactElement, ReactNode } from 'react';
2
+
1
3
  export { getRegisteredCss } from 'typestyles/server';
2
4
 
3
5
  export interface TypestylesStylesheetProps {
4
- children?: React.ReactNode;
6
+ children?: ReactNode;
5
7
  }
6
8
 
7
9
  export function TypestylesStylesheet(props: TypestylesStylesheetProps): React.JSX.Element;
8
10
 
9
- export function collectStylesFromComponent(component: React.ReactElement): Promise<string>;
11
+ export function collectStylesFromComponent(component: ReactElement): Promise<string>;
10
12
 
11
- export function createTypestylesLayout<P extends { children?: React.ReactNode }>(
12
- layout: (props: P) => React.ReactNode,
13
+ export function createTypestylesLayout<P extends { children?: ReactNode }>(
14
+ layout: (props: P) => ReactNode,
13
15
  ): (props: P) => React.JSX.Element;
package/src/index.tsx CHANGED
@@ -1,106 +1,27 @@
1
- import React, { useEffect, useState } from 'react';
2
- import { collectStyles, getRegisteredCss } from 'typestyles/server';
3
-
4
- export { getRegisteredCss };
5
-
6
- /**
7
- * Props for the TypestylesStylesheet component.
8
- */
9
- export interface TypestylesStylesheetProps {
10
- /**
11
- * The children to render (styles will be collected from these).
12
- * If not provided, only the existing registered CSS will be included.
13
- */
14
- children?: React.ReactNode;
15
- }
16
-
17
1
  /**
18
- * A React component that renders typestyles CSS.
19
- *
20
- * For App Router: Use this in your root layout to collect and render styles.
2
+ * @typestyles/next - Next.js integration for typestyles
21
3
  *
22
- * @example
23
- * ```tsx
24
- * // app/layout.tsx
25
- * import { TypestylesStylesheet } from '@typestyles/next';
4
+ * This package provides two entry points:
26
5
  *
27
- * export default function RootLayout({ children }) {
28
- * return (
29
- * <html>
30
- * <head>
31
- * <TypestylesStylesheet />
32
- * </head>
33
- * <body>{children}</body>
34
- * </html>
35
- * );
36
- * }
37
- * ```
38
- */
39
- export function TypestylesStylesheet({ children }: TypestylesStylesheetProps) {
40
- const [css, setCss] = useState('');
41
-
42
- useEffect(() => {
43
- // On client: get any CSS that was registered before hydration
44
- setCss(getRegisteredCss());
45
- }, []);
46
-
47
- if (children) {
48
- return (
49
- <>
50
- {children}
51
- <style id="typestyles" dangerouslySetInnerHTML={{ __html: css }} />
52
- </>
53
- );
54
- }
55
-
56
- return <style id="typestyles" dangerouslySetInnerHTML={{ __html: css }} />;
57
- }
58
-
59
- /**
60
- * Collect styles from a React component and return them as a string.
61
- * Useful for server components or when you need more control.
6
+ * 1. Main entry (this file) - Re-exports everything
7
+ * 2. `/server` - Server-safe utilities (getRegisteredCss, collectStylesFromComponent, getTypestylesMetadata)
8
+ * 3. `/client` - Client components (TypestylesStylesheet, useTypestyles, useServerInsertedHTML)
62
9
  *
63
- * @example
64
- * ```tsx
65
- * // app/styles.ts
66
- * import { collectStylesFromComponent } from '@typestyles/next';
67
- * import { YourApp } from './YourApp';
10
+ * For App Router, prefer using the client entry for components:
11
+ * import { TypestylesStylesheet } from '@typestyles/next/client';
68
12
  *
69
- * export async function getStyles() {
70
- * return collectStylesFromComponent(<YourApp />);
71
- * }
72
- * ```
13
+ * Or use server utilities for SSR:
14
+ * import { getRegisteredCss } from '@typestyles/next/server';
73
15
  */
74
- export async function collectStylesFromComponent(component: React.ReactElement): Promise<string> {
75
- const { renderToString } = await import('react-dom/server');
76
- const { css } = collectStyles(() => renderToString(component));
77
- return css;
78
- }
79
16
 
80
- /**
81
- * Create a Next.js layout export that includes typestyles.
82
- *
83
- * @example
84
- * ```tsx
85
- * // app/layout.tsx
86
- * import { createTypestylesLayout } from '@typestyles/next';
87
- *
88
- * export default createTypestylesLayout(function RootLayout({ children }) {
89
- * return (
90
- * <html>
91
- * <head>
92
- * <title>My App</title>
93
- * </head>
94
- * <body>{children}</body>
95
- * </html>
96
- * );
97
- * });
98
- * ```
99
- */
100
- export function createTypestylesLayout<P extends { children?: React.ReactNode }>(
101
- layout: (props: P) => React.ReactNode,
102
- ): (props: P) => React.ReactNode {
103
- return function TypestylesLayout(props: P) {
104
- return <TypestylesStylesheet>{layout(props)}</TypestylesStylesheet>;
105
- };
106
- }
17
+ // Re-export server-safe utilities
18
+ export { getRegisteredCss, collectStylesFromComponent, getTypestylesMetadata } from './server';
19
+
20
+ // Re-export client components and hooks
21
+ export {
22
+ TypestylesStylesheet,
23
+ useTypestyles,
24
+ useServerInsertedHTML,
25
+ createTypestylesLayout,
26
+ type TypestylesStylesheetProps,
27
+ } from './client';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `useServerInsertedHTML` exists at runtime in Next.js App Router / React 18.3+ client builds,
3
+ * but some `@types/react` releases omit it. Augment `react` so local `tsc` and tooling match runtime.
4
+ *
5
+ * @see https://react.dev/reference/react-dom/server/useServerInsertedHTML
6
+ */
7
+ import type { ReactNode } from 'react';
8
+
9
+ declare module 'react' {
10
+ export function useServerInsertedHTML(callback: () => ReactNode | null): void;
11
+ }
12
+
13
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { ReactElement } from 'react';
2
+ import type { GetRouteCssOptions } from '@typestyles/build-runner';
3
+
4
+ export { getRegisteredCss } from 'typestyles/server';
5
+ export { getRouteCss, type GetRouteCssOptions };
6
+
7
+ export declare function collectStylesFromComponent(component: ReactElement): Promise<string>;
8
+
9
+ export declare function getTypestylesMetadata(component: ReactElement): Promise<string>;