create-fluxstack 1.22.0 → 1.22.1

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.
Files changed (38) hide show
  1. package/app/client/src/components/AppLayout.tsx +290 -290
  2. package/app/client/src/components/BackButton.tsx +16 -16
  3. package/app/client/src/components/DemoPage.tsx +135 -135
  4. package/app/client/src/framework/ClientOnly.tsx +14 -14
  5. package/app/client/src/framework/LivePage.tsx +55 -55
  6. package/app/client/src/framework/RscHomePage.tsx +125 -125
  7. package/app/client/src/framework/RscLink.tsx +31 -31
  8. package/app/client/src/framework/RscNav.tsx +42 -42
  9. package/app/client/src/framework/RscRoot.tsx +54 -54
  10. package/app/client/src/framework/csrf.ts +22 -22
  11. package/app/client/src/framework/entry.browser.tsx +51 -51
  12. package/app/client/src/framework/entry.rsc.tsx +41 -41
  13. package/app/client/src/framework/entry.ssr.tsx +12 -12
  14. package/app/client/src/framework/navigation.ts +29 -29
  15. package/app/client/src/framework/params.tsx +22 -22
  16. package/app/client/src/framework/routes.ts +143 -143
  17. package/app/client/src/framework/vite-rsc.d.ts +21 -21
  18. package/app/client/src/live/AuthDemo.tsx +270 -270
  19. package/app/client/src/live/CounterDemo.tsx +152 -152
  20. package/app/client/src/live/FormDemo.tsx +140 -140
  21. package/app/client/src/live/PingPongDemo.tsx +180 -180
  22. package/app/client/src/live/RoomChatDemo.tsx +397 -397
  23. package/app/client/src/pages/auth.tsx +13 -13
  24. package/app/client/src/pages/blog/[slug].tsx +23 -23
  25. package/app/client/src/pages/counter.tsx +15 -15
  26. package/app/client/src/pages/form.tsx +13 -13
  27. package/app/client/src/pages/index.tsx +9 -9
  28. package/app/client/src/pages/ping-pong.tsx +13 -13
  29. package/app/client/src/pages/room-chat.tsx +13 -13
  30. package/app/client/src/pages/shared-counter.tsx +13 -13
  31. package/app/client/src/pages/sobre.tsx +19 -19
  32. package/app/server/live/rooms/index.ts +14 -14
  33. package/core/plugins/built-in/rsc/index.ts +156 -156
  34. package/core/plugins/built-in/ssr/bun-asset-loader.ts +46 -46
  35. package/core/plugins/built-in/ssr/index.ts +143 -143
  36. package/core/plugins/built-in/ssr/registry.ts +38 -38
  37. package/core/utils/version.ts +1 -1
  38. package/package.json +1 -1
@@ -1,13 +1,13 @@
1
- // Página /auth (file-based). Demo Live — React normal.
2
- import { LivePage } from '../framework/LivePage'
3
- import { AuthDemo } from '../live/AuthDemo'
4
-
5
- export const title = 'Auth'
6
-
7
- export default function AuthPage() {
8
- return (
9
- <LivePage title="Auth" description="Autenticação declarativa para Live Components com $auth.">
10
- <AuthDemo />
11
- </LivePage>
12
- )
13
- }
1
+ // Página /auth (file-based). Demo Live — React normal.
2
+ import { LivePage } from '../framework/LivePage'
3
+ import { AuthDemo } from '../live/AuthDemo'
4
+
5
+ export const title = 'Auth'
6
+
7
+ export default function AuthPage() {
8
+ return (
9
+ <LivePage title="Auth" description="Autenticação declarativa para Live Components com $auth.">
10
+ <AuthDemo />
11
+ </LivePage>
12
+ )
13
+ }
@@ -1,23 +1,23 @@
1
- // Rota DINÂMICA /blog/:slug (file-based: pages/blog/[slug].tsx).
2
- // Server component (0 JS) — recebe os params como PROP. Funciona no server.
3
- import type { PageProps } from '../../framework/routes'
4
-
5
- export const title = 'Blog Post'
6
-
7
- export default function BlogPost({ params }: PageProps) {
8
- const slug = params.slug as string
9
- return (
10
- <div className="relative min-h-[calc(100vh-57px)] px-4 py-10">
11
- <div className="absolute inset-0 app-grid-bg opacity-70" />
12
- <div className="relative z-10 mx-auto max-w-3xl">
13
- <a href="/blog" className="text-sm text-gray-400 hover:text-white">← Blog</a>
14
- <h1 className="mt-4 text-4xl font-semibold text-white">Post: {slug}</h1>
15
- <p className="mt-4 text-gray-400">
16
- Rota dinâmica renderizada no <strong>server</strong> (0 JS). O slug
17
- <code className="text-theme"> {slug} </code> veio de <code className="text-theme">params</code>,
18
- extraído da URL pelo roteador file-based — arquivo <code className="text-theme">pages/blog/[slug].tsx</code>.
19
- </p>
20
- </div>
21
- </div>
22
- )
23
- }
1
+ // Rota DINÂMICA /blog/:slug (file-based: pages/blog/[slug].tsx).
2
+ // Server component (0 JS) — recebe os params como PROP. Funciona no server.
3
+ import type { PageProps } from '../../framework/routes'
4
+
5
+ export const title = 'Blog Post'
6
+
7
+ export default function BlogPost({ params }: PageProps) {
8
+ const slug = params.slug as string
9
+ return (
10
+ <div className="relative min-h-[calc(100vh-57px)] px-4 py-10">
11
+ <div className="absolute inset-0 app-grid-bg opacity-70" />
12
+ <div className="relative z-10 mx-auto max-w-3xl">
13
+ <a href="/blog" className="text-sm text-gray-400 hover:text-white">← Blog</a>
14
+ <h1 className="mt-4 text-4xl font-semibold text-white">Post: {slug}</h1>
15
+ <p className="mt-4 text-gray-400">
16
+ Rota dinâmica renderizada no <strong>server</strong> (0 JS). O slug
17
+ <code className="text-theme"> {slug} </code> veio de <code className="text-theme">params</code>,
18
+ extraído da URL pelo roteador file-based — arquivo <code className="text-theme">pages/blog/[slug].tsx</code>.
19
+ </p>
20
+ </div>
21
+ </div>
22
+ )
23
+ }
@@ -1,15 +1,15 @@
1
- // Página /counter (file-based). Demo Live — React normal.
2
- // O CounterDemo usa Live.use(); no server vira placeholder (guarda SSR),
3
- // no client monta e conecta. O LivePage cuida do Provider/ClientOnly.
4
- import { LivePage } from '../framework/LivePage'
5
- import { CounterDemo } from '../live/CounterDemo'
6
-
7
- export const title = 'Counters'
8
-
9
- export default function CounterPage() {
10
- return (
11
- <LivePage title="Counters" description="Estado local, sala isolada e sala compartilhada em tempo real.">
12
- <CounterDemo />
13
- </LivePage>
14
- )
15
- }
1
+ // Página /counter (file-based). Demo Live — React normal.
2
+ // O CounterDemo usa Live.use(); no server vira placeholder (guarda SSR),
3
+ // no client monta e conecta. O LivePage cuida do Provider/ClientOnly.
4
+ import { LivePage } from '../framework/LivePage'
5
+ import { CounterDemo } from '../live/CounterDemo'
6
+
7
+ export const title = 'Counters'
8
+
9
+ export default function CounterPage() {
10
+ return (
11
+ <LivePage title="Counters" description="Estado local, sala isolada e sala compartilhada em tempo real.">
12
+ <CounterDemo />
13
+ </LivePage>
14
+ )
15
+ }
@@ -1,13 +1,13 @@
1
- // Página /form (file-based). Demo Live — React normal.
2
- import { LivePage } from '../framework/LivePage'
3
- import { FormDemo } from '../live/FormDemo'
4
-
5
- export const title = 'Form'
6
-
7
- export default function FormPage() {
8
- return (
9
- <LivePage title="Live Form" description="Formulário com campos sincronizados pelo servidor via proxy Live.">
10
- <FormDemo />
11
- </LivePage>
12
- )
13
- }
1
+ // Página /form (file-based). Demo Live — React normal.
2
+ import { LivePage } from '../framework/LivePage'
3
+ import { FormDemo } from '../live/FormDemo'
4
+
5
+ export const title = 'Form'
6
+
7
+ export default function FormPage() {
8
+ return (
9
+ <LivePage title="Live Form" description="Formulário com campos sincronizados pelo servidor via proxy Live.">
10
+ <FormDemo />
11
+ </LivePage>
12
+ )
13
+ }
@@ -1,9 +1,9 @@
1
- // Página HOME — rota / (file-based: app/client/src/pages/index.tsx)
2
- // Componente React normal. Server component (sem Live) → 0 JS no client.
3
- import { RscHomePage } from '../framework/RscHomePage'
4
-
5
- export const title = 'Home'
6
-
7
- export default function HomePage() {
8
- return <RscHomePage />
9
- }
1
+ // Página HOME — rota / (file-based: app/client/src/pages/index.tsx)
2
+ // Componente React normal. Server component (sem Live) → 0 JS no client.
3
+ import { RscHomePage } from '../framework/RscHomePage'
4
+
5
+ export const title = 'Home'
6
+
7
+ export default function HomePage() {
8
+ return <RscHomePage />
9
+ }
@@ -1,13 +1,13 @@
1
- // Página /ping-pong (file-based). Demo Live — React normal.
2
- import { LivePage } from '../framework/LivePage'
3
- import { PingPongDemo } from '../live/PingPongDemo'
4
-
5
- export const title = 'Ping-Pong'
6
-
7
- export default function PingPongPage() {
8
- return (
9
- <LivePage title="Ping-Pong" description="Latency demo com codec binário msgpack no WebSocket.">
10
- <PingPongDemo />
11
- </LivePage>
12
- )
13
- }
1
+ // Página /ping-pong (file-based). Demo Live — React normal.
2
+ import { LivePage } from '../framework/LivePage'
3
+ import { PingPongDemo } from '../live/PingPongDemo'
4
+
5
+ export const title = 'Ping-Pong'
6
+
7
+ export default function PingPongPage() {
8
+ return (
9
+ <LivePage title="Ping-Pong" description="Latency demo com codec binário msgpack no WebSocket.">
10
+ <PingPongDemo />
11
+ </LivePage>
12
+ )
13
+ }
@@ -1,13 +1,13 @@
1
- // Página /room-chat (file-based). Demo Live — React normal.
2
- import { LivePage } from '../framework/LivePage'
3
- import { RoomChatDemo } from '../live/RoomChatDemo'
4
-
5
- export const title = 'Chat'
6
-
7
- export default function RoomChatPage() {
8
- return (
9
- <LivePage title="Room Chat" description="Chat multi-sala usando o sistema $room.">
10
- <RoomChatDemo />
11
- </LivePage>
12
- )
13
- }
1
+ // Página /room-chat (file-based). Demo Live — React normal.
2
+ import { LivePage } from '../framework/LivePage'
3
+ import { RoomChatDemo } from '../live/RoomChatDemo'
4
+
5
+ export const title = 'Chat'
6
+
7
+ export default function RoomChatPage() {
8
+ return (
9
+ <LivePage title="Room Chat" description="Chat multi-sala usando o sistema $room.">
10
+ <RoomChatDemo />
11
+ </LivePage>
12
+ )
13
+ }
@@ -1,13 +1,13 @@
1
- // Página /shared-counter (file-based). Demo Live — React normal.
2
- import { LivePage } from '../framework/LivePage'
3
- import { SharedCounterDemo } from '../live/SharedCounterDemo'
4
-
5
- export const title = 'Shared'
6
-
7
- export default function SharedCounterPage() {
8
- return (
9
- <LivePage title="Shared Counter" description="Sala global sincroniza usuários e estado entre abas.">
10
- <SharedCounterDemo />
11
- </LivePage>
12
- )
13
- }
1
+ // Página /shared-counter (file-based). Demo Live — React normal.
2
+ import { LivePage } from '../framework/LivePage'
3
+ import { SharedCounterDemo } from '../live/SharedCounterDemo'
4
+
5
+ export const title = 'Shared'
6
+
7
+ export default function SharedCounterPage() {
8
+ return (
9
+ <LivePage title="Shared Counter" description="Sala global sincroniza usuários e estado entre abas.">
10
+ <SharedCounterDemo />
11
+ </LivePage>
12
+ )
13
+ }
@@ -1,19 +1,19 @@
1
- // Página /sobre — PROVA do file-based routing. Só criar este arquivo já cria a
2
- // rota /sobre e o link na navbar. React normal, server component (0 JS).
3
- export const title = 'Sobre'
4
-
5
- export default function SobrePage() {
6
- return (
7
- <div className="relative min-h-[calc(100vh-57px)] px-4 py-10">
8
- <div className="absolute inset-0 app-grid-bg opacity-70" />
9
- <div className="relative z-10 mx-auto max-w-3xl">
10
- <h1 className="text-4xl font-semibold text-white">Sobre</h1>
11
- <p className="mt-4 text-gray-400">
12
- Esta página foi criada só adicionando <code className="text-theme">app/client/src/pages/sobre.tsx</code>.
13
- Sem editar router, sem registrar rota, sem tocar em nada. É React normal — e roda
14
- como Server Component (zero JS no client).
15
- </p>
16
- </div>
17
- </div>
18
- )
19
- }
1
+ // Página /sobre — PROVA do file-based routing. Só criar este arquivo já cria a
2
+ // rota /sobre e o link na navbar. React normal, server component (0 JS).
3
+ export const title = 'Sobre'
4
+
5
+ export default function SobrePage() {
6
+ return (
7
+ <div className="relative min-h-[calc(100vh-57px)] px-4 py-10">
8
+ <div className="absolute inset-0 app-grid-bg opacity-70" />
9
+ <div className="relative z-10 mx-auto max-w-3xl">
10
+ <h1 className="text-4xl font-semibold text-white">Sobre</h1>
11
+ <p className="mt-4 text-gray-400">
12
+ Esta página foi criada só adicionando <code className="text-theme">app/client/src/pages/sobre.tsx</code>.
13
+ Sem editar router, sem registrar rota, sem tocar em nada. É React normal — e roda
14
+ como Server Component (zero JS no client).
15
+ </p>
16
+ </div>
17
+ </div>
18
+ )
19
+ }
@@ -1,14 +1,14 @@
1
- // Registro ESTÁTICO das LiveRoom classes — usado no build de produção.
2
- //
3
- // Em dev, as rooms são auto-descobertas varrendo este diretório (import dinâmico).
4
- // Em PROD isso quebraria (import do disco carrega uma instância separada do
5
- // @fluxstack/live → context null). Aqui declaramos as rooms estaticamente para
6
- // entrarem no bundle e serem registradas no LiveServer({ rooms }).
7
- //
8
- // Ao adicionar uma room nova em rooms/, inclua-a aqui também (ou rode o gerador).
9
- import { ChatRoom } from './ChatRoom'
10
- import { CounterRoom } from './CounterRoom'
11
- import { DirectoryRoom } from './DirectoryRoom'
12
- import { PingRoom } from './PingRoom'
13
-
14
- export const liveRoomClasses = [ChatRoom, CounterRoom, DirectoryRoom, PingRoom]
1
+ // Registro ESTÁTICO das LiveRoom classes — usado no build de produção.
2
+ //
3
+ // Em dev, as rooms são auto-descobertas varrendo este diretório (import dinâmico).
4
+ // Em PROD isso quebraria (import do disco carrega uma instância separada do
5
+ // @fluxstack/live → context null). Aqui declaramos as rooms estaticamente para
6
+ // entrarem no bundle e serem registradas no LiveServer({ rooms }).
7
+ //
8
+ // Ao adicionar uma room nova em rooms/, inclua-a aqui também (ou rode o gerador).
9
+ import { ChatRoom } from './ChatRoom'
10
+ import { CounterRoom } from './CounterRoom'
11
+ import { DirectoryRoom } from './DirectoryRoom'
12
+ import { PingRoom } from './PingRoom'
13
+
14
+ export const liveRoomClasses = [ChatRoom, CounterRoom, DirectoryRoom, PingRoom]
@@ -1,156 +1,156 @@
1
- /**
2
- * FluxStack RSC Plugin
3
- *
4
- * Serve React Server Components pelo proxy interno do FluxStack (Elysia), em vez
5
- * do middleware próprio do @vitejs/plugin-rsc. Prioridade 860 > ssr (850) >
6
- * vite (800): intercepta rotas de página antes deles. Só age se RSC_ENABLED=true.
7
- *
8
- * DEV: chama o handler do ambiente Vite `rsc` via runner (Vite dev server).
9
- * PROD: importa o handler RSC BUILDADO (app/client/dist/rsc/index.js, default) e
10
- * serve os assets buildados (app/client/dist/client/assets). Sem Vite em prod.
11
- *
12
- * Em erro NÃO trata (fallback pro Vite/SPA). Requer o Vite criado com
13
- * rsc({serverHandler:false}) — ver vite.config.ts (condicionado a RSC_ENABLED).
14
- */
15
-
16
- import type { FluxStack, PluginContext, RequestContext } from '@core/plugins/types'
17
- import { FLUXSTACK_VERSION } from '@core/utils/version'
18
- import { isDevelopment } from '@core/utils/helpers'
19
- import { clientConfig, pluginsConfig } from '@config'
20
- import { isRunnableDevEnvironment } from 'vite'
21
- import { join } from 'path'
22
- import { existsSync } from 'fs'
23
-
24
- type Plugin = FluxStack.Plugin
25
- type RscHandler = (request: Request) => Promise<Response>
26
-
27
- const PLUGIN_PRIORITY = 860 // > ssr (850) > vite (800)
28
- const IS_DEV = isDevelopment()
29
-
30
- /** id do entry rsc no runner (dev) — relativo ao root app/client */
31
- const RSC_ENTRY_ID = '/src/framework/entry.rsc.tsx'
32
- /** caminho do handler RSC buildado (prod) e dos assets do client */
33
- const PROD_RSC_HANDLER = join(process.cwd(), 'app', 'client', 'dist', 'rsc', 'index.js')
34
- const PROD_CLIENT_DIR = join(process.cwd(), 'app', 'client', 'dist', 'client')
35
-
36
- const ASSET_EXT = /\.(js|mjs|ts|tsx|jsx|css|map|json|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|wasm|txt|xml|webmanifest)$/i
37
- const PASSTHROUGH_PREFIXES = ['/@', '/src/', '/node_modules/', '/api', '/swagger', '/__plugins']
38
-
39
- function isPageRoute(path: string): boolean {
40
- if (ASSET_EXT.test(path)) return false
41
- return !PASSTHROUGH_PREFIXES.some((p) => path === p || path.startsWith(p))
42
- }
43
-
44
- /** Vite dev server (dev) — capturado do vitePlugin. */
45
- let viteServer: { environments: Record<string, unknown> } | null = null
46
- /** Handler RSC buildado (prod) — importado uma vez e cacheado. */
47
- let prodHandler: RscHandler | null = null
48
-
49
- /** Normaliza a URL da request para absoluta (handler RSC precisa de URL completa). */
50
- function absoluteUrl(ctx: RequestContext): string {
51
- try {
52
- return new URL(ctx.request.url).href
53
- } catch {
54
- const host = ctx.request.headers.get('host') || `${clientConfig.vite.host}:3000`
55
- const proto = ctx.request.headers.get('x-forwarded-proto') || 'http'
56
- const q = ctx.request.url.indexOf('?')
57
- const search = q === -1 ? '' : ctx.request.url.slice(q)
58
- return `${proto}://${host}${ctx.path}${search}`
59
- }
60
- }
61
-
62
- /** Resolve o handler RSC (dev via runner, prod via import do build). */
63
- async function getHandler(): Promise<RscHandler | null> {
64
- if (IS_DEV) {
65
- if (!viteServer) return null
66
- const rscEnv = viteServer.environments.rsc
67
- if (!rscEnv || !isRunnableDevEnvironment(rscEnv as never)) return null
68
- const mod = await (rscEnv as { runner: { import: (id: string) => Promise<{ default: RscHandler }> } })
69
- .runner.import(RSC_ENTRY_ID)
70
- return mod.default
71
- }
72
- // prod: importa o handler buildado uma vez
73
- if (!prodHandler) {
74
- if (!existsSync(PROD_RSC_HANDLER)) return null
75
- const mod = await import(/* @vite-ignore */ PROD_RSC_HANDLER) as { default: RscHandler }
76
- prodHandler = mod.default
77
- }
78
- return prodHandler
79
- }
80
-
81
- export const rscPlugin: Plugin = {
82
- name: 'rsc',
83
- version: FLUXSTACK_VERSION,
84
- description: 'React Server Components served through the FluxStack proxy',
85
- author: 'FluxStack Team',
86
- priority: PLUGIN_PRIORITY,
87
- category: 'rendering',
88
- tags: ['rsc', 'react', 'server-components'],
89
- dependencies: [],
90
-
91
- setup: async (context: PluginContext) => {
92
- if (!(pluginsConfig as Record<string, unknown>).rscEnabled) {
93
- context.logger.debug('RSC plugin disabled (set RSC_ENABLED=true)')
94
- return
95
- }
96
- if (!IS_DEV && !existsSync(PROD_RSC_HANDLER)) {
97
- context.logger.warn(`RSC: handler buildado não encontrado (${PROD_RSC_HANDLER}). Rode o build com RSC_ENABLED=true.`)
98
- return
99
- }
100
- context.logger.debug(`RSC plugin active (priority ${PLUGIN_PRIORITY}, ${IS_DEV ? 'dev' : 'prod'})`)
101
- },
102
-
103
- // DEV: captura o Vite dev server (do vitePlugin) para o runner.
104
- onServerStart: async (context: PluginContext) => {
105
- if (!(pluginsConfig as Record<string, unknown>).rscEnabled || !IS_DEV) return
106
- const cfg = (context as PluginContext & { viteConfig?: { server?: unknown } }).viteConfig
107
- if (cfg?.server) {
108
- viteServer = cfg.server as { environments: Record<string, unknown> }
109
- context.logger.debug('RSC: Vite dev server capturado para o runner')
110
- }
111
- },
112
-
113
- onBeforeRoute: async (ctx: RequestContext) => {
114
- if (!(pluginsConfig as Record<string, unknown>).rscEnabled) return
115
- if (ctx.method !== 'GET') return
116
-
117
- // PROD: servir assets buildados (/assets/*, /favicon.svg) do dist/client.
118
- if (!IS_DEV && !isPageRoute(ctx.path)) {
119
- const assetPath = join(PROD_CLIENT_DIR, ctx.path)
120
- if (ctx.path !== '/' && existsSync(assetPath)) {
121
- ctx.handled = true
122
- ctx.response = new Response(Bun.file(assetPath))
123
- }
124
- return
125
- }
126
- if (!isPageRoute(ctx.path)) return // dev: assets vão pro Vite
127
-
128
- try {
129
- const handler = await getHandler()
130
- if (!handler) return // sem handler → fallback
131
-
132
- // Cold-start (dev): a 1ª render pode suspender enquanto o grafo client
133
- // carrega; um retry cobre. Em prod o handler já está pronto (1 tentativa).
134
- const attempts = IS_DEV ? 2 : 1
135
- let response: Response | null = null
136
- for (let i = 0; i < attempts; i++) {
137
- try {
138
- const request = new Request(absoluteUrl(ctx), { method: ctx.method, headers: ctx.request.headers })
139
- response = await handler(request)
140
- break
141
- } catch (e) {
142
- if (i === attempts - 1) throw e
143
- }
144
- }
145
- if (response) {
146
- ctx.handled = true
147
- ctx.response = response
148
- }
149
- } catch (err) {
150
- const msg = err instanceof Error ? err.message : String(err)
151
- console.error(`[RSC] render failed for ${ctx.path}, falling back: ${msg}`)
152
- }
153
- },
154
- }
155
-
156
- export default rscPlugin
1
+ /**
2
+ * FluxStack RSC Plugin
3
+ *
4
+ * Serve React Server Components pelo proxy interno do FluxStack (Elysia), em vez
5
+ * do middleware próprio do @vitejs/plugin-rsc. Prioridade 860 > ssr (850) >
6
+ * vite (800): intercepta rotas de página antes deles. Só age se RSC_ENABLED=true.
7
+ *
8
+ * DEV: chama o handler do ambiente Vite `rsc` via runner (Vite dev server).
9
+ * PROD: importa o handler RSC BUILDADO (app/client/dist/rsc/index.js, default) e
10
+ * serve os assets buildados (app/client/dist/client/assets). Sem Vite em prod.
11
+ *
12
+ * Em erro NÃO trata (fallback pro Vite/SPA). Requer o Vite criado com
13
+ * rsc({serverHandler:false}) — ver vite.config.ts (condicionado a RSC_ENABLED).
14
+ */
15
+
16
+ import type { FluxStack, PluginContext, RequestContext } from '@core/plugins/types'
17
+ import { FLUXSTACK_VERSION } from '@core/utils/version'
18
+ import { isDevelopment } from '@core/utils/helpers'
19
+ import { clientConfig, pluginsConfig } from '@config'
20
+ import { isRunnableDevEnvironment } from 'vite'
21
+ import { join } from 'path'
22
+ import { existsSync } from 'fs'
23
+
24
+ type Plugin = FluxStack.Plugin
25
+ type RscHandler = (request: Request) => Promise<Response>
26
+
27
+ const PLUGIN_PRIORITY = 860 // > ssr (850) > vite (800)
28
+ const IS_DEV = isDevelopment()
29
+
30
+ /** id do entry rsc no runner (dev) — relativo ao root app/client */
31
+ const RSC_ENTRY_ID = '/src/framework/entry.rsc.tsx'
32
+ /** caminho do handler RSC buildado (prod) e dos assets do client */
33
+ const PROD_RSC_HANDLER = join(process.cwd(), 'app', 'client', 'dist', 'rsc', 'index.js')
34
+ const PROD_CLIENT_DIR = join(process.cwd(), 'app', 'client', 'dist', 'client')
35
+
36
+ const ASSET_EXT = /\.(js|mjs|ts|tsx|jsx|css|map|json|svg|png|jpe?g|gif|webp|avif|ico|woff2?|ttf|eot|wasm|txt|xml|webmanifest)$/i
37
+ const PASSTHROUGH_PREFIXES = ['/@', '/src/', '/node_modules/', '/api', '/swagger', '/__plugins']
38
+
39
+ function isPageRoute(path: string): boolean {
40
+ if (ASSET_EXT.test(path)) return false
41
+ return !PASSTHROUGH_PREFIXES.some((p) => path === p || path.startsWith(p))
42
+ }
43
+
44
+ /** Vite dev server (dev) — capturado do vitePlugin. */
45
+ let viteServer: { environments: Record<string, unknown> } | null = null
46
+ /** Handler RSC buildado (prod) — importado uma vez e cacheado. */
47
+ let prodHandler: RscHandler | null = null
48
+
49
+ /** Normaliza a URL da request para absoluta (handler RSC precisa de URL completa). */
50
+ function absoluteUrl(ctx: RequestContext): string {
51
+ try {
52
+ return new URL(ctx.request.url).href
53
+ } catch {
54
+ const host = ctx.request.headers.get('host') || `${clientConfig.vite.host}:3000`
55
+ const proto = ctx.request.headers.get('x-forwarded-proto') || 'http'
56
+ const q = ctx.request.url.indexOf('?')
57
+ const search = q === -1 ? '' : ctx.request.url.slice(q)
58
+ return `${proto}://${host}${ctx.path}${search}`
59
+ }
60
+ }
61
+
62
+ /** Resolve o handler RSC (dev via runner, prod via import do build). */
63
+ async function getHandler(): Promise<RscHandler | null> {
64
+ if (IS_DEV) {
65
+ if (!viteServer) return null
66
+ const rscEnv = viteServer.environments.rsc
67
+ if (!rscEnv || !isRunnableDevEnvironment(rscEnv as never)) return null
68
+ const mod = await (rscEnv as { runner: { import: (id: string) => Promise<{ default: RscHandler }> } })
69
+ .runner.import(RSC_ENTRY_ID)
70
+ return mod.default
71
+ }
72
+ // prod: importa o handler buildado uma vez
73
+ if (!prodHandler) {
74
+ if (!existsSync(PROD_RSC_HANDLER)) return null
75
+ const mod = await import(/* @vite-ignore */ PROD_RSC_HANDLER) as { default: RscHandler }
76
+ prodHandler = mod.default
77
+ }
78
+ return prodHandler
79
+ }
80
+
81
+ export const rscPlugin: Plugin = {
82
+ name: 'rsc',
83
+ version: FLUXSTACK_VERSION,
84
+ description: 'React Server Components served through the FluxStack proxy',
85
+ author: 'FluxStack Team',
86
+ priority: PLUGIN_PRIORITY,
87
+ category: 'rendering',
88
+ tags: ['rsc', 'react', 'server-components'],
89
+ dependencies: [],
90
+
91
+ setup: async (context: PluginContext) => {
92
+ if (!(pluginsConfig as Record<string, unknown>).rscEnabled) {
93
+ context.logger.debug('RSC plugin disabled (set RSC_ENABLED=true)')
94
+ return
95
+ }
96
+ if (!IS_DEV && !existsSync(PROD_RSC_HANDLER)) {
97
+ context.logger.warn(`RSC: handler buildado não encontrado (${PROD_RSC_HANDLER}). Rode o build com RSC_ENABLED=true.`)
98
+ return
99
+ }
100
+ context.logger.debug(`RSC plugin active (priority ${PLUGIN_PRIORITY}, ${IS_DEV ? 'dev' : 'prod'})`)
101
+ },
102
+
103
+ // DEV: captura o Vite dev server (do vitePlugin) para o runner.
104
+ onServerStart: async (context: PluginContext) => {
105
+ if (!(pluginsConfig as Record<string, unknown>).rscEnabled || !IS_DEV) return
106
+ const cfg = (context as PluginContext & { viteConfig?: { server?: unknown } }).viteConfig
107
+ if (cfg?.server) {
108
+ viteServer = cfg.server as { environments: Record<string, unknown> }
109
+ context.logger.debug('RSC: Vite dev server capturado para o runner')
110
+ }
111
+ },
112
+
113
+ onBeforeRoute: async (ctx: RequestContext) => {
114
+ if (!(pluginsConfig as Record<string, unknown>).rscEnabled) return
115
+ if (ctx.method !== 'GET') return
116
+
117
+ // PROD: servir assets buildados (/assets/*, /favicon.svg) do dist/client.
118
+ if (!IS_DEV && !isPageRoute(ctx.path)) {
119
+ const assetPath = join(PROD_CLIENT_DIR, ctx.path)
120
+ if (ctx.path !== '/' && existsSync(assetPath)) {
121
+ ctx.handled = true
122
+ ctx.response = new Response(Bun.file(assetPath))
123
+ }
124
+ return
125
+ }
126
+ if (!isPageRoute(ctx.path)) return // dev: assets vão pro Vite
127
+
128
+ try {
129
+ const handler = await getHandler()
130
+ if (!handler) return // sem handler → fallback
131
+
132
+ // Cold-start (dev): a 1ª render pode suspender enquanto o grafo client
133
+ // carrega; um retry cobre. Em prod o handler já está pronto (1 tentativa).
134
+ const attempts = IS_DEV ? 2 : 1
135
+ let response: Response | null = null
136
+ for (let i = 0; i < attempts; i++) {
137
+ try {
138
+ const request = new Request(absoluteUrl(ctx), { method: ctx.method, headers: ctx.request.headers })
139
+ response = await handler(request)
140
+ break
141
+ } catch (e) {
142
+ if (i === attempts - 1) throw e
143
+ }
144
+ }
145
+ if (response) {
146
+ ctx.handled = true
147
+ ctx.response = response
148
+ }
149
+ } catch (err) {
150
+ const msg = err instanceof Error ? err.message : String(err)
151
+ console.error(`[RSC] render failed for ${ctx.path}, falling back: ${msg}`)
152
+ }
153
+ },
154
+ }
155
+
156
+ export default rscPlugin