@vistagenic/vista 0.3.2 → 0.3.4

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 (118) hide show
  1. package/bin/vista.js +79 -109
  2. package/dist/ai/embeddings.d.ts +11 -11
  3. package/dist/ai/embeddings.js +71 -71
  4. package/dist/ai/index.d.ts +10 -10
  5. package/dist/ai/index.js +26 -26
  6. package/dist/ai/providers/base.js +85 -85
  7. package/dist/ai/react/react-server.d.ts +1 -1
  8. package/dist/ai/react/react-server.js +17 -17
  9. package/dist/ai/react/use-agent.js +138 -138
  10. package/dist/auth/core.d.ts +140 -140
  11. package/dist/auth/core.js +165 -165
  12. package/dist/auth/index.d.ts +20 -20
  13. package/dist/auth/index.js +369 -369
  14. package/dist/auth/react-server.d.ts +1 -1
  15. package/dist/auth/react-server.js +10 -10
  16. package/dist/auth/react.d.ts +18 -18
  17. package/dist/auth/react.js +71 -71
  18. package/dist/bin/build-rsc-flashpack.js +6 -0
  19. package/dist/bin/build-rsc.js +555 -492
  20. package/dist/bin/build.js +365 -353
  21. package/dist/bin/generate.js +513 -510
  22. package/dist/bin/webpack.config.d.ts +3 -1
  23. package/dist/bin/webpack.config.js +7 -4
  24. package/dist/build/manifest.d.ts +169 -169
  25. package/dist/build/manifest.js +423 -423
  26. package/dist/build/rsc/client-manifest.d.ts +62 -62
  27. package/dist/build/rsc/client-manifest.js +295 -295
  28. package/dist/build/rsc/compiler.d.ts +3 -1
  29. package/dist/build/rsc/compiler.js +12 -7
  30. package/dist/build/rsc/native-scanner.d.ts +135 -135
  31. package/dist/build/rsc/native-scanner.js +203 -203
  32. package/dist/build/rsc/react-client-reference-manifest.d.ts +35 -28
  33. package/dist/build/rsc/react-client-reference-manifest.js +366 -240
  34. package/dist/build/standalone.js +260 -254
  35. package/dist/client/dynamic.react-server.d.ts +2 -2
  36. package/dist/client/dynamic.react-server.js +23 -23
  37. package/dist/client/link.js +1 -1
  38. package/dist/client/link.react-server.d.ts +2 -2
  39. package/dist/client/link.react-server.js +11 -11
  40. package/dist/client/navigation.js +2 -2
  41. package/dist/client/navigation.react-server.d.ts +1 -1
  42. package/dist/client/navigation.react-server.js +17 -17
  43. package/dist/client/router.react-server.d.ts +1 -1
  44. package/dist/client/router.react-server.js +17 -17
  45. package/dist/client/rsc-router.d.ts +1 -3
  46. package/dist/client/rsc-router.js +98 -45
  47. package/dist/client/rsc-router.react-server.d.ts +1 -1
  48. package/dist/client/rsc-router.react-server.js +17 -17
  49. package/dist/client/script.react-server.d.ts +2 -2
  50. package/dist/client/script.react-server.js +23 -23
  51. package/dist/config.d.ts +1 -1
  52. package/dist/config.js +1 -7
  53. package/dist/deploy/adapters/cloudflare.js +42 -41
  54. package/dist/deploy/adapters/docker.d.ts +1 -0
  55. package/dist/deploy/adapters/docker.js +5 -4
  56. package/dist/deploy/adapters/netlify.js +60 -27
  57. package/dist/deploy/adapters/vercel.js +80 -50
  58. package/dist/deploy/preflight.js +4 -3
  59. package/dist/deploy/runtime-pack.d.ts +11 -0
  60. package/dist/deploy/runtime-pack.js +300 -0
  61. package/dist/deploy/utils.d.ts +7 -1
  62. package/dist/deploy/utils.js +95 -3
  63. package/dist/flashpack/command.js +1 -0
  64. package/dist/flashpack/runtime.js +2 -1
  65. package/dist/image/get-img-props.js +21 -11
  66. package/dist/image/image-config.d.ts +2 -0
  67. package/dist/image/image-config.js +17 -0
  68. package/dist/image/index.d.ts +18 -3
  69. package/dist/image/index.js +1 -1
  70. package/dist/image/react-server.d.ts +1 -2
  71. package/dist/image/react-server.js +1 -1
  72. package/dist/index.d.ts +23 -23
  73. package/dist/index.js +61 -61
  74. package/dist/server/app-dir.d.ts +22 -0
  75. package/dist/server/app-dir.js +77 -0
  76. package/dist/server/app-router-runtime.d.ts +1 -0
  77. package/dist/server/app-router-runtime.js +34 -9
  78. package/dist/server/cookie-parse.d.ts +4 -4
  79. package/dist/server/cookie-parse.js +14 -14
  80. package/dist/server/engine.js +5 -5
  81. package/dist/server/hydration-chunks.d.ts +7 -0
  82. package/dist/server/hydration-chunks.js +49 -0
  83. package/dist/server/image-optimizer.js +2 -1
  84. package/dist/server/index.d.ts +109 -109
  85. package/dist/server/index.js +315 -315
  86. package/dist/server/middleware-runner.d.ts +125 -125
  87. package/dist/server/middleware-runner.js +607 -615
  88. package/dist/server/middleware-security.d.ts +36 -36
  89. package/dist/server/middleware-security.js +183 -183
  90. package/dist/server/module-compile-hook.js +706 -695
  91. package/dist/server/root-resolver.js +6 -5
  92. package/dist/server/rsc-engine-flashpack.d.ts +3 -1
  93. package/dist/server/rsc-engine-flashpack.js +12 -1
  94. package/dist/server/rsc-engine.d.ts +6 -1
  95. package/dist/server/rsc-engine.js +217 -280
  96. package/dist/server/rsc-upstream.js +900 -892
  97. package/dist/server/ssr-webpack-shim.d.ts +6 -0
  98. package/dist/server/ssr-webpack-shim.js +29 -0
  99. package/dist/server/static-generator.d.ts +2 -0
  100. package/dist/server/static-generator.js +33 -32
  101. package/dist/server/structure-validator.js +2 -1
  102. package/dist/server/structure-watch.js +2 -0
  103. package/dist/server/typed-api-runtime.js +639 -635
  104. package/dist/server/vista-import-map.js +134 -134
  105. package/dist/stack/index.d.ts +34 -34
  106. package/dist/stack/index.js +49 -49
  107. package/dist/stack/server/caller.d.ts +13 -13
  108. package/dist/stack/server/caller.js +42 -42
  109. package/dist/stack/server/executor.d.ts +40 -40
  110. package/dist/stack/server/executor.js +222 -222
  111. package/dist/stack/server/index.d.ts +11 -11
  112. package/dist/stack/server/index.js +24 -24
  113. package/dist/stack/server/procedure.d.ts +20 -20
  114. package/dist/stack/server/procedure.js +66 -66
  115. package/dist/stack/server/types.d.ts +113 -113
  116. package/dist/theme/react-server.d.ts +10 -10
  117. package/dist/theme/react-server.js +16 -16
  118. package/package.json +1 -1
@@ -1,127 +1,130 @@
1
- "use strict";
2
- /**
3
- * Vista RSC Build System
4
- *
5
- * Builds the application using the True RSC Architecture:
6
- * 1. Server bundle (.vista/server/) - All code for SSR
7
- * 2. Client bundle (.vista/static/) - Only client components
8
- * 3. Manifests for hydration coordination
9
- */
10
- var __importDefault = (this && this.__importDefault) || function (mod) {
11
- return (mod && mod.__esModule) ? mod : { "default": mod };
12
- };
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.buildRSC = buildRSC;
15
- exports.default = buildRSC;
16
- const path_1 = __importDefault(require("path"));
17
- const fs_1 = __importDefault(require("fs"));
18
- const webpack_1 = __importDefault(require("webpack"));
19
- const compiler_1 = require("../build/rsc/compiler");
20
- const manifest_1 = require("../build/manifest");
21
- const client_manifest_1 = require("../build/rsc/client-manifest");
22
- const server_manifest_1 = require("../build/rsc/server-manifest");
23
- const file_scanner_1 = require("./file-scanner");
24
- const config_1 = require("../config");
25
- const constants_1 = require("../constants");
26
- const structure_validator_1 = require("../server/structure-validator");
27
- const static_generator_1 = require("../server/static-generator");
28
- const structure_log_1 = require("../server/structure-log");
29
- const devtools_indicator_snippet_1 = require("./devtools-indicator-snippet");
30
- const dev_error_overlay_snippet_1 = require("./dev-error-overlay-snippet");
31
- const deploy_output_1 = require("./deploy-output");
32
- const module_boundary_validator_1 = require("../server/module-boundary-validator");
33
- const standalone_1 = require("../build/standalone");
34
- const _debug = !!process.env.VISTA_DEBUG;
35
- /**
36
- * Run PostCSS for CSS compilation
37
- */
38
- function runPostCSS(cwd, vistaDir) {
39
- const globalsCss = path_1.default.join(cwd, 'app/globals.css');
40
- if (fs_1.default.existsSync(globalsCss)) {
41
- if (_debug)
42
- console.log('[Vista JS RSC] Building CSS with PostCSS...');
43
- const { execSync } = require('child_process');
44
- try {
45
- const cssOut = path_1.default.join(vistaDir, 'client.css');
46
- execSync(`npx postcss app/globals.css -o "${cssOut}"`, {
47
- stdio: _debug ? 'inherit' : 'pipe',
48
- cwd,
49
- });
50
- if (_debug)
51
- console.log('[Vista JS RSC] CSS Built Successfully!');
52
- }
53
- catch (cssErr) {
54
- console.error('[Vista JS RSC] CSS Build failed (PostCSS error).');
55
- }
56
- }
57
- }
58
- function hasUseClientDirective(filePath) {
59
- try {
60
- const source = fs_1.default.readFileSync(filePath, 'utf-8');
61
- return /^\s*['"]use client['"]\s*;?/m.test(source);
62
- }
63
- catch {
64
- return false;
65
- }
66
- }
67
- function collectUseClientFiles(dir, collected) {
68
- if (!fs_1.default.existsSync(dir))
69
- return;
70
- const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
71
- for (const entry of entries) {
72
- const absolutePath = path_1.default.join(dir, entry.name);
73
- if (entry.isDirectory()) {
74
- if (entry.name === 'node_modules' || entry.name.startsWith('.'))
75
- continue;
76
- collectUseClientFiles(absolutePath, collected);
77
- continue;
78
- }
79
- if (!entry.isFile())
80
- continue;
81
- const ext = path_1.default.extname(entry.name);
82
- if (!['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'].includes(ext))
83
- continue;
84
- if (hasUseClientDirective(absolutePath)) {
85
- collected.add(path_1.default.resolve(absolutePath));
86
- }
87
- }
88
- }
89
- function resolvePackageRoot(cwd, packageName) {
90
- try {
91
- return path_1.default.dirname(require.resolve(`${packageName}/package.json`, { paths: [cwd] }));
92
- }
93
- catch {
94
- return null;
95
- }
96
- }
97
- function collectFrameworkClientReferences(cwd) {
98
- const roots = [resolvePackageRoot(cwd, 'vista'), resolvePackageRoot(cwd, '@vistagenic/vista')].filter((value) => Boolean(value));
99
- if (roots.length === 0) {
100
- return [];
101
- }
102
- const collected = new Set();
103
- for (const packageRoot of roots) {
104
- collectUseClientFiles(path_1.default.join(packageRoot, 'dist'), collected);
105
- collectUseClientFiles(path_1.default.join(packageRoot, 'src'), collected);
106
- }
107
- return Array.from(collected);
108
- }
109
- /**
110
- * Generate the RSC-aware client entry file
111
- */
112
- function generateRSCClientEntry(cwd, vistaDir, isDev) {
113
- const devToolsBootId = `rsc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1
+ "use strict";
2
+ /**
3
+ * Vista RSC Build System
4
+ *
5
+ * Builds the application using the True RSC Architecture:
6
+ * 1. Server bundle (.vista/server/) - All code for SSR
7
+ * 2. Client bundle (.vista/static/) - Only client components
8
+ * 3. Manifests for hydration coordination
9
+ */
10
+ var __importDefault = (this && this.__importDefault) || function (mod) {
11
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12
+ };
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.buildRSC = buildRSC;
15
+ exports.default = buildRSC;
16
+ const path_1 = __importDefault(require("path"));
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const webpack_1 = __importDefault(require("webpack"));
19
+ const compiler_1 = require("../build/rsc/compiler");
20
+ const manifest_1 = require("../build/manifest");
21
+ const client_manifest_1 = require("../build/rsc/client-manifest");
22
+ const server_manifest_1 = require("../build/rsc/server-manifest");
23
+ const file_scanner_1 = require("./file-scanner");
24
+ const config_1 = require("../config");
25
+ const constants_1 = require("../constants");
26
+ const structure_validator_1 = require("../server/structure-validator");
27
+ const static_generator_1 = require("../server/static-generator");
28
+ const structure_log_1 = require("../server/structure-log");
29
+ const devtools_indicator_snippet_1 = require("./devtools-indicator-snippet");
30
+ const dev_error_overlay_snippet_1 = require("./dev-error-overlay-snippet");
31
+ const deploy_output_1 = require("./deploy-output");
32
+ const module_boundary_validator_1 = require("../server/module-boundary-validator");
33
+ const standalone_1 = require("../build/standalone");
34
+ const app_dir_1 = require("../server/app-dir");
35
+ const _debug = !!process.env.VISTA_DEBUG;
36
+ /**
37
+ * Run PostCSS for CSS compilation
38
+ */
39
+ function runPostCSS(cwd, vistaDir) {
40
+ const globalsCss = path_1.default.join((0, app_dir_1.resolveAppDir)(cwd), 'globals.css');
41
+ if (fs_1.default.existsSync(globalsCss)) {
42
+ if (_debug)
43
+ console.log('[Vista JS RSC] Building CSS with PostCSS...');
44
+ const { execSync } = require('child_process');
45
+ try {
46
+ const cssOut = path_1.default.join(vistaDir, 'client.css');
47
+ const globalsCssRelative = path_1.default.relative(cwd, globalsCss).replace(/\\/g, '/');
48
+ execSync(`npx postcss "${globalsCssRelative}" -o "${cssOut}"`, {
49
+ stdio: _debug ? 'inherit' : 'pipe',
50
+ cwd,
51
+ });
52
+ if (_debug)
53
+ console.log('[Vista JS RSC] CSS Built Successfully!');
54
+ }
55
+ catch (cssErr) {
56
+ console.error('[Vista JS RSC] CSS Build failed (PostCSS error).');
57
+ }
58
+ }
59
+ }
60
+ function hasUseClientDirective(filePath) {
61
+ try {
62
+ const source = fs_1.default.readFileSync(filePath, 'utf-8');
63
+ return /^\s*['"]use client['"]\s*;?/m.test(source);
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ function collectUseClientFiles(dir, collected) {
70
+ if (!fs_1.default.existsSync(dir))
71
+ return;
72
+ const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
73
+ for (const entry of entries) {
74
+ const absolutePath = path_1.default.join(dir, entry.name);
75
+ if (entry.isDirectory()) {
76
+ if (entry.name === 'node_modules' || entry.name.startsWith('.'))
77
+ continue;
78
+ collectUseClientFiles(absolutePath, collected);
79
+ continue;
80
+ }
81
+ if (!entry.isFile())
82
+ continue;
83
+ const ext = path_1.default.extname(entry.name);
84
+ if (!['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'].includes(ext))
85
+ continue;
86
+ if (hasUseClientDirective(absolutePath)) {
87
+ collected.add(path_1.default.resolve(absolutePath));
88
+ }
89
+ }
90
+ }
91
+ function resolvePackageRoot(cwd, packageName) {
92
+ try {
93
+ return path_1.default.dirname(require.resolve(`${packageName}/package.json`, { paths: [cwd] }));
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ function collectFrameworkClientReferences(cwd) {
100
+ const roots = [resolvePackageRoot(cwd, 'vista'), resolvePackageRoot(cwd, '@vistagenic/vista')].filter((value) => Boolean(value));
101
+ if (roots.length === 0) {
102
+ return [];
103
+ }
104
+ const collected = new Set();
105
+ for (const packageRoot of roots) {
106
+ collectUseClientFiles(path_1.default.join(packageRoot, 'dist'), collected);
107
+ collectUseClientFiles(path_1.default.join(packageRoot, 'src'), collected);
108
+ }
109
+ return Array.from(collected);
110
+ }
111
+ /**
112
+ * Generate the RSC-aware client entry file
113
+ */
114
+ function generateRSCClientEntry(cwd, vistaDir, isDev) {
115
+ const devToolsBootId = `rsc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
114
116
  const clientEntryContent = `/**
115
117
  * Vista RSC Client Entry
116
118
  *
117
119
  * This file is auto-generated. Do not edit directly.
118
- * It hydrates using React Flight data from /rsc and enables
119
- * RSC-aware client-side navigation via RSCRouter.
120
+ * It hydrates from the inline Flight payload in the HTML document when
121
+ * present (no /rsc refetch on first load). Client navigations still use
122
+ * /rsc via RSCRouter.
120
123
  */
121
124
 
122
125
  import * as React from 'react';
123
126
  import { hydrateRoot, createRoot } from 'react-dom/client';
124
- import { createFromFetch } from 'react-server-dom-webpack/client';
127
+ import { createFromReadableStream } from 'react-server-dom-webpack/client';
125
128
  import { RSCRouter } from 'vista/client/rsc-router';
126
129
  import { callServer } from 'vista/client/server-actions';
127
130
 
@@ -197,45 +200,95 @@ if (typeof window !== 'undefined') {
197
200
  });
198
201
  }
199
202
 
203
+ function flightTextToReadableStream(flightText: string): ReadableStream<Uint8Array> {
204
+ var encoder = new TextEncoder();
205
+ var bytes = encoder.encode(flightText);
206
+ return new ReadableStream({
207
+ start: function (controller) {
208
+ controller.enqueue(bytes);
209
+ controller.close();
210
+ },
211
+ });
212
+ }
213
+
214
+ function waitForInlineFlightPayload(timeoutMs: number): Promise<string | null> {
215
+ var existing = (window as any).${constants_1.RSC_DATA_FLAG};
216
+ if (typeof existing === 'string' && existing.length > 0) {
217
+ return Promise.resolve(existing);
218
+ }
219
+ return new Promise(function (resolve) {
220
+ var started = Date.now();
221
+ var timer = setInterval(function () {
222
+ var value = (window as any).${constants_1.RSC_DATA_FLAG};
223
+ if (typeof value === 'string' && value.length > 0) {
224
+ clearInterval(timer);
225
+ resolve(value);
226
+ return;
227
+ }
228
+ if (Date.now() - started >= timeoutMs) {
229
+ clearInterval(timer);
230
+ resolve(null);
231
+ }
232
+ }, 8);
233
+ });
234
+ }
235
+
200
236
  const pathname = window.location.pathname;
201
- const search = window.location.search;
202
- const initialResponse = createFromFetch(
203
- fetch(\`/rsc\${pathname}\${search}\`, { headers: { Accept: 'text/x-component' } }),
204
- { callServer }
205
- ) as Promise<React.ReactNode>;
206
237
 
207
- var appElement = React.createElement(RSCRouter, {
208
- initialResponse,
209
- initialPathname: pathname,
210
- });
238
+ waitForInlineFlightPayload(4000).then(function (inlineFlight) {
239
+ if (typeof inlineFlight !== 'string' || inlineFlight.length === 0) {
240
+ reportDevRuntimeError(
241
+ 'Hydration Error',
242
+ new Error('Missing inline Flight payload (window.${constants_1.RSC_DATA_FLAG}). First load no longer refetches /rsc.')
243
+ );
244
+ return;
245
+ }
211
246
 
212
- try {
213
- hydrateRoot(
214
- rootElement as Document | Element,
215
- appElement,
216
- {
217
- onRecoverableError(error) {
218
- var message = String((error as any)?.message || error || '');
219
- if (/hydration|did not match|server rendered html|text content/i.test(message)) {
220
- reportDevRuntimeError('Hydration Error', error);
221
- return;
222
- }
223
- reportDevRuntimeError('Recoverable Error', error);
224
- },
225
- }
226
- );
227
- } catch (error) {
228
- reportDevRuntimeError('Hydration Error', error);
229
- if (!hydrateDocument && rootElement instanceof Element) {
230
- try {
231
- createRoot(rootElement).render(appElement);
232
- } catch (fallbackError) {
233
- reportDevRuntimeError('Client Render Fallback Failed', fallbackError);
247
+ if (/(?:^|\\n)\\d+:E\\{/.test(inlineFlight)) {
248
+ reportDevRuntimeError(
249
+ 'Hydration Error',
250
+ new Error('Inline Flight payload contains error rows. Keeping server HTML instead of hydrating the document.')
251
+ );
252
+ return;
253
+ }
254
+
255
+ const initialResponse = createFromReadableStream(flightTextToReadableStream(inlineFlight), {
256
+ callServer,
257
+ }) as Promise<React.ReactNode>;
258
+
259
+ var appElement = React.createElement(RSCRouter, {
260
+ initialResponse,
261
+ initialPathname: pathname,
262
+ });
263
+
264
+ try {
265
+ hydrateRoot(
266
+ rootElement as Document | Element,
267
+ appElement,
268
+ {
269
+ onRecoverableError(error) {
270
+ var message = String((error as any)?.message || error || '');
271
+ if (/hydration|did not match|server rendered html|text content/i.test(message)) {
272
+ reportDevRuntimeError('Hydration Error', error);
273
+ return;
274
+ }
275
+ reportDevRuntimeError('Recoverable Error', error);
276
+ },
277
+ }
278
+ );
279
+ } catch (error) {
280
+ reportDevRuntimeError('Hydration Error', error);
281
+ if (!hydrateDocument && rootElement instanceof Element) {
282
+ try {
283
+ createRoot(rootElement).render(appElement);
284
+ } catch (fallbackError) {
285
+ reportDevRuntimeError('Client Render Fallback Failed', fallbackError);
286
+ }
234
287
  }
235
288
  }
236
- }
289
+ });
237
290
 
238
- ${isDev
291
+ ${isDev
239
292
  ? `// Vista live-reload: listen for server component changes via SSE
240
293
  (function connectReload() {
241
294
  const es = new EventSource('${constants_1.SSE_ENDPOINT}');
@@ -272,347 +325,357 @@ ${isDev
272
325
  es.close();
273
326
  setTimeout(connectReload, 3000);
274
327
  };
275
- })();`
328
+ })();`
276
329
  : '// SSE live-reload disabled in production'}
277
- `;
278
- fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'rsc-client.tsx'), clientEntryContent);
279
- if (_debug)
280
- console.log('[vista:build] Generated RSC client entry file');
281
- }
282
- function syncReactServerManifests(vistaDir) {
283
- const canonicalPath = path_1.default.join(vistaDir, 'react-server-manifest.json');
284
- const legacyPath = path_1.default.join(vistaDir, 'react-ssr-manifest.json');
285
- if (fs_1.default.existsSync(canonicalPath) && !fs_1.default.existsSync(legacyPath)) {
286
- fs_1.default.copyFileSync(canonicalPath, legacyPath);
287
- }
288
- else if (fs_1.default.existsSync(legacyPath) && !fs_1.default.existsSync(canonicalPath)) {
289
- fs_1.default.copyFileSync(legacyPath, canonicalPath);
290
- }
291
- }
292
- /**
293
- * Build with RSC architecture
294
- */
295
- async function buildRSC(watch = false) {
296
- const cwd = process.cwd();
297
- const appDir = path_1.default.join(cwd, 'app');
298
- const projectClientRoots = (0, client_manifest_1.discoverProjectClientRoots)(cwd);
299
- const additionalClientRoots = projectClientRoots.filter((root) => path_1.default.resolve(root.dir) !== path_1.default.resolve(appDir));
300
- let clientReferenceFiles = [];
301
- if (_debug) {
302
- console.log('');
303
- console.log('╔══════════════════════════════════════════════════════════════╗');
304
- console.log('║ Vista JS RSC Build System (React Server Components) ║');
305
- console.log('╚══════════════════════════════════════════════════════════════╝');
306
- console.log('');
307
- }
308
- // Create .vista directory structure
309
- const vistaDirs = (0, manifest_1.createVistaDirectories)(cwd, 'rsc');
310
- const buildId = (0, manifest_1.getBuildId)(vistaDirs.root, !watch);
311
- if (_debug) {
312
- console.log(`[vista:build] Build ID: ${buildId}`);
313
- console.log(`[vista:build] Mode: ${watch ? 'Development (Watch)' : 'Production'}`);
314
- console.log('');
315
- }
316
- // ========================================================================
317
- // Pre-build Structure Validation
318
- // ========================================================================
319
- const vistaConfig = (0, config_1.loadConfig)(cwd);
320
- const engineVariant = (0, config_1.resolveAndApplyEngineVariant)(vistaConfig);
321
- const structureConfig = (0, config_1.resolveStructureValidationConfig)(vistaConfig);
322
- const cacheComponentsConfig = (0, config_1.resolveCacheComponentsConfig)(vistaConfig);
323
- if (_debug)
324
- console.log(`[vista:build] Engine variant: ${engineVariant}`);
325
- if (structureConfig.enabled) {
326
- const result = (0, structure_validator_1.validateAppStructure)({ cwd });
327
- (0, structure_log_1.logValidationResult)(result, structureConfig.logLevel);
328
- if (result.state === 'error' && structureConfig.mode === 'strict') {
329
- console.error((0, structure_log_1.formatBuildFailTable)(result));
330
- process.exit(1);
331
- }
332
- }
333
- // Scan app/ plus every other top-level project directory (components/, utils/,
334
- // lib/, src/, ...) so `'use client'` modules outside app/ still enter the
335
- // React Client Manifest. Discovery is directory membership, not the import graph.
336
- if (fs_1.default.existsSync(appDir)) {
337
- if (_debug) {
338
- console.log(`[Vista JS RSC] Using ${(0, file_scanner_1.isNativeAvailable)() ? 'Rust native' : 'JS fallback'} scanner (v${(0, file_scanner_1.getVersion)()})`);
339
- }
340
- const scanResult = (0, file_scanner_1.scanAppDirectory)(appDir);
341
- clientReferenceFiles = scanResult.clientComponents.map((component) => component.absolutePath);
342
- for (const root of additionalClientRoots) {
343
- const extraScan = (0, file_scanner_1.scanAppDirectory)(root.dir);
344
- clientReferenceFiles.push(...extraScan.clientComponents.map((component) => component.absolutePath));
345
- if (_debug && extraScan.clientComponents.length > 0) {
346
- console.log(`[Vista JS RSC] Found ${extraScan.clientComponents.length} client components ('use client') in ${root.prefix}`);
347
- }
348
- }
349
- clientReferenceFiles = Array.from(new Set(clientReferenceFiles));
350
- if (_debug) {
351
- console.log(`[Vista JS RSC] Found ${scanResult.serverComponents.length} server components`);
352
- console.log(`[Vista JS RSC] Found ${scanResult.clientComponents.length} client components ('use client') in app/`);
353
- console.log(`[Vista JS RSC] Total client reference modules: ${clientReferenceFiles.length}`);
354
- console.log('');
355
- }
356
- if (scanResult.clientComponents.length > 0 && _debug) {
357
- console.log('[Vista JS RSC] Client Components (will be hydrated on browser):');
358
- scanResult.clientComponents.forEach((c) => {
359
- console.log(` ${c.relativePath}`);
360
- });
361
- console.log('');
362
- }
363
- if (scanResult.serverComponents.length > 0 && _debug) {
364
- console.log('[Vista JS RSC] Server Components (0kb client bundle contribution):');
365
- scanResult.serverComponents.slice(0, 5).forEach((c) => {
366
- console.log(` • ${c.relativePath}`);
367
- });
368
- if (scanResult.serverComponents.length > 5) {
369
- console.log(` ... and ${scanResult.serverComponents.length - 5} more`);
370
- }
371
- console.log('');
372
- }
373
- const scanErrors = (0, module_boundary_validator_1.validateModuleBoundaries)({
374
- appDir,
375
- extraRoots: additionalClientRoots.map((root) => root.dir),
376
- cacheComponentsEnabled: cacheComponentsConfig.enabled,
377
- }).issues;
378
- if (scanErrors.length > 0) {
379
- console.log('\x1b[41m\x1b[37m ERROR \x1b[0m \x1b[31mServer/Segment Violations\x1b[0m');
380
- console.log('');
381
- for (const error of scanErrors) {
382
- console.log(`\x1b[31m✗\x1b[0m ${path_1.default.relative(cwd, error.filePath)}`);
383
- console.log(` ${error.message}`);
384
- console.log('');
385
- if (error.fix) {
386
- console.log(` \x1b[36mTo fix:\x1b[0m ${error.fix}`);
387
- console.log('');
388
- }
389
- }
390
- if (!watch) {
391
- console.log('\x1b[31mBuild failed due to server/segment violations.\x1b[0m');
392
- process.exit(1);
393
- }
394
- }
395
- }
396
- // Include framework-level client boundaries (e.g. vista/link) so external
397
- // package client modules resolve in React Flight manifests.
398
- const frameworkClientReferences = collectFrameworkClientReferences(cwd);
399
- if (frameworkClientReferences.length > 0) {
400
- clientReferenceFiles = Array.from(new Set([...clientReferenceFiles, ...frameworkClientReferences]));
401
- if (_debug) {
402
- console.log(`[Vista JS RSC] Added ${frameworkClientReferences.length} framework client references`);
403
- }
404
- }
405
- // Generate manifests
406
- if (_debug)
407
- console.log('[vista:build] Generating manifests...');
408
- const clientManifest = (0, client_manifest_1.generateClientManifestWithRoots)(cwd, appDir, additionalClientRoots);
409
- fs_1.default.writeFileSync(path_1.default.join(vistaDirs.root, 'client-manifest.json'), JSON.stringify(clientManifest, null, 2));
410
- if (_debug) {
411
- console.log(` ✓ client-manifest.json (${Object.keys(clientManifest.clientModules).length} modules)`);
412
- }
413
- const serverManifest = (0, server_manifest_1.generateServerManifest)(cwd, appDir);
414
- fs_1.default.writeFileSync(path_1.default.join(vistaDirs.server, 'server-manifest.json'), JSON.stringify(serverManifest, null, 2));
415
- if (_debug) {
416
- console.log(` ✓ server-manifest.json (${Object.keys(serverManifest.serverModules).length} modules, ${serverManifest.routes.length} routes)`);
417
- console.log('');
418
- }
419
- (0, manifest_1.writeCanonicalVistaArtifacts)(cwd, vistaDirs.root, buildId, serverManifest.routes.map((route) => ({
420
- pattern: route.pattern,
421
- pagePath: route.pagePath,
422
- type: route.type,
423
- })), serverManifest.routeHandlers.map((handler) => ({
424
- pattern: handler.pattern,
425
- filePath: handler.filePath,
426
- type: handler.type,
427
- methods: handler.methods,
428
- runtime: handler.runtime,
429
- })));
430
- (0, manifest_1.writeReservedVistaArtifacts)(vistaDirs.root, {
431
- buildId,
432
- engineVariant,
433
- imagesConfig: vistaConfig.images,
434
- });
435
- // Generate client entry
436
- generateRSCClientEntry(cwd, vistaDirs.root, watch);
437
- // Create webpack configs
438
- const options = {
439
- cwd,
440
- isDev: watch,
441
- vistaDirs,
442
- buildId,
443
- engineVariant,
444
- clientReferenceFiles,
445
- };
446
- // Build CSS
447
- runPostCSS(cwd, vistaDirs.root);
448
- if (watch) {
449
- // Development mode - return compilers for middleware
450
- if (_debug)
451
- console.log('[Vista JS RSC] Creating development compilers...');
452
- // Clear stale webpack cache. ReactFlightWebpackPlugin adds
453
- // AsyncDependenciesBlock entries that can't be serialised by webpack's
454
- // pack file cache strategy. A stale cache that was written *before* the
455
- // plugin ran will skip the parser hook entirely, causing empty Flight
456
- // manifests. Clearing on every dev-start is the safest approach –
457
- // first-compile is ~1s longer but guarantees correct manifests.
458
- const cacheDir = engineVariant === 'flashpack'
459
- ? path_1.default.join(cwd, constants_1.FLASH_DIR, 'cache', 'webpack')
460
- : path_1.default.join(vistaDirs.root, 'cache');
461
- if (fs_1.default.existsSync(cacheDir)) {
462
- fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
463
- if (_debug)
464
- console.log('[Vista JS RSC] Cleared stale webpack cache');
465
- }
466
- // Write stub Flight manifests so upstream can start before first webpack compile.
467
- // ReactFlightWebpackPlugin will overwrite these on first successful compilation.
468
- const stubManifests = [
469
- path_1.default.join(vistaDirs.root, 'react-client-manifest.json'),
470
- path_1.default.join(vistaDirs.root, 'react-server-manifest.json'),
471
- path_1.default.join(vistaDirs.root, 'react-ssr-manifest.json'),
472
- ];
473
- for (const manifestPath of stubManifests) {
474
- if (!fs_1.default.existsSync(manifestPath)) {
475
- fs_1.default.writeFileSync(manifestPath, '{}');
476
- }
477
- }
478
- const clientConfig = (0, compiler_1.createClientWebpackConfig)(options);
479
- const clientCompiler = (0, webpack_1.default)(clientConfig);
480
- syncReactServerManifests(vistaDirs.root);
481
- // Watch for CSS + source changes that can affect Tailwind output.
482
- try {
483
- const chokidar = require('chokidar');
484
- const styleWatchRoots = ['app', 'components', 'content', 'lib', 'ctx', 'data', 'utils', 'src']
485
- .map((entry) => path_1.default.join(cwd, entry))
486
- .filter((entry) => fs_1.default.existsSync(entry));
487
- let cssTimer = null;
488
- const scheduleCSSBuild = () => {
489
- if (cssTimer)
490
- clearTimeout(cssTimer);
491
- cssTimer = setTimeout(() => {
492
- if (_debug)
493
- console.log('[Vista JS RSC] Style source changed, rebuilding CSS...');
494
- runPostCSS(cwd, vistaDirs.root);
495
- }, 120);
496
- };
497
- chokidar
498
- .watch(styleWatchRoots, {
499
- ignoreInitial: true,
500
- ignored: (watchedPath) => watchedPath.includes(`${path_1.default.sep}node_modules${path_1.default.sep}`) ||
501
- watchedPath.includes(`${path_1.default.sep}.git${path_1.default.sep}`) ||
502
- watchedPath.includes(`${path_1.default.sep}.vista${path_1.default.sep}`),
503
- })
504
- .on('all', (_event, changedPath) => {
505
- if (/\.(?:css|[cm]?[jt]sx?|md|mdx)$/i.test(changedPath)) {
506
- scheduleCSSBuild();
507
- }
508
- });
509
- }
510
- catch (e) {
511
- // chokidar not installed
512
- }
513
- if (_debug) {
514
- console.log('[Vista JS RSC] Ready for development');
515
- console.log('');
516
- }
517
- return { serverCompiler: null, clientCompiler };
518
- }
519
- else {
520
- // Production build
521
- console.log('[Vista JS RSC] Building for production...');
522
- console.log('');
523
- const serverConfig = (0, compiler_1.createServerWebpackConfig)(options);
524
- const clientConfig = (0, compiler_1.createClientWebpackConfig)(options);
525
- // Build server bundle
526
- console.log('[Vista JS RSC] Building server bundle...');
527
- await new Promise((resolve, reject) => {
528
- (0, webpack_1.default)(serverConfig).run((err, stats) => {
529
- if (err) {
530
- console.error('[Vista RSC] Server build error:', err);
531
- reject(err);
532
- return;
533
- }
534
- if (stats?.hasErrors()) {
535
- console.error('[Vista RSC] Server compilation errors:', stats.toString('errors-only'));
536
- reject(new Error('Server compilation failed'));
537
- return;
538
- }
539
- console.log('[Vista JS RSC] Server bundle complete');
540
- resolve();
541
- });
542
- });
543
- // Build client bundle
544
- console.log('[Vista JS RSC] Building client bundle...');
545
- await new Promise((resolve, reject) => {
546
- (0, webpack_1.default)(clientConfig).run((err, stats) => {
547
- if (err) {
548
- console.error('[Vista RSC] Client build error:', err);
549
- reject(err);
550
- return;
551
- }
552
- if (stats?.hasErrors()) {
553
- console.error('[Vista RSC] Client compilation errors:', stats.toString('errors-only'));
554
- reject(new Error('Client compilation failed'));
555
- return;
556
- }
557
- console.log('[Vista JS RSC] Client bundle complete');
558
- console.log(stats?.toString('minimal'));
559
- syncReactServerManifests(vistaDirs.root);
560
- resolve();
561
- });
562
- });
563
- // ------------------------------------------------------------------
564
- // Static Generation (SSG / ISR)
565
- // ------------------------------------------------------------------
566
- console.log('[Vista JS RSC] Running static generation...');
567
- const ssgResult = await (0, static_generator_1.generateStaticPages)({
568
- cwd,
569
- vistaDirRoot: vistaDirs.root,
570
- manifest: serverManifest,
571
- isDev: false,
572
- buildId,
573
- });
574
- if (ssgResult.pagesGenerated > 0) {
575
- console.log(`[Vista JS RSC] Pre-rendered ${ssgResult.pagesGenerated} page(s): ${ssgResult.generatedPaths.join(', ')}`);
576
- }
577
- if (ssgResult.failedPaths.length > 0) {
578
- console.warn(`[Vista JS RSC] Failed to pre-render ${ssgResult.failedPaths.length} page(s):`, ssgResult.failedPaths.map((f) => `${f.path} (${f.error})`).join(', '));
579
- }
580
- // Write the real prerender manifest (overwrite the empty stub)
581
- const prerenderManifestPath = path_1.default.join(vistaDirs.root, 'prerender-manifest.json');
582
- fs_1.default.writeFileSync(prerenderManifestPath, JSON.stringify(ssgResult.manifest, null, 2));
583
- console.log('[Vista JS RSC] Wrote prerender-manifest.json');
584
- (0, standalone_1.generateStandaloneOutput)({
585
- cwd,
586
- vistaDir: vistaDirs.root,
587
- buildId,
588
- serverManifest,
589
- debug: _debug,
590
- });
591
- (0, deploy_output_1.generateDeploymentOutputs)({
592
- cwd,
593
- vistaDir: vistaDirs.root,
594
- debug: _debug,
595
- });
596
- (0, manifest_1.pruneEmptyVistaDirectories)(vistaDirs.root);
597
- console.log('');
598
- console.log('╔══════════════════════════════════════════════════════════════╗');
599
- console.log('║ Build Complete! 🎉 ║');
600
- console.log('╚══════════════════════════════════════════════════════════════╝');
601
- console.log('');
602
- console.log(' Output directory: .vista/');
603
- console.log(' ├── server/ (Server-side bundle - NEVER sent to client)');
604
- console.log(' ├── static/ (Client assets - only client components)');
605
- if (engineVariant === 'flashpack') {
606
- console.log(' └── cache/ (metadata bridge to the active Flashpack cache)');
607
- console.log(' Flashpack directory: .flash/');
608
- console.log(' ├── cache/ (Flashpack runtime cache)');
609
- console.log(' ├── graph/ (Rust pipeline graph snapshots)');
610
- console.log(' └── logs/ (Flashpack phase logs)');
611
- }
612
- else {
613
- console.log(' └── cache/ (Build cache for faster rebuilds)');
614
- }
615
- console.log('');
616
- return { serverCompiler: null, clientCompiler: null };
617
- }
618
- }
330
+ `;
331
+ fs_1.default.writeFileSync(path_1.default.join(vistaDir, 'rsc-client.tsx'), clientEntryContent);
332
+ if (_debug)
333
+ console.log('[vista:build] Generated RSC client entry file');
334
+ }
335
+ function syncReactServerManifests(vistaDir) {
336
+ const canonicalPath = path_1.default.join(vistaDir, 'react-server-manifest.json');
337
+ const legacyPath = path_1.default.join(vistaDir, 'react-ssr-manifest.json');
338
+ if (fs_1.default.existsSync(canonicalPath) && !fs_1.default.existsSync(legacyPath)) {
339
+ fs_1.default.copyFileSync(canonicalPath, legacyPath);
340
+ }
341
+ else if (fs_1.default.existsSync(legacyPath) && !fs_1.default.existsSync(canonicalPath)) {
342
+ fs_1.default.copyFileSync(legacyPath, canonicalPath);
343
+ }
344
+ }
345
+ /**
346
+ * Build with RSC architecture
347
+ */
348
+ async function buildRSC(watch = false) {
349
+ const cwd = process.cwd();
350
+ const appDir = (0, app_dir_1.resolveAppDir)(cwd);
351
+ const projectClientRoots = (0, client_manifest_1.discoverProjectClientRoots)(cwd);
352
+ const additionalClientRoots = projectClientRoots.filter((root) => path_1.default.resolve(root.dir) !== path_1.default.resolve(appDir));
353
+ let clientReferenceFiles = [];
354
+ if (_debug) {
355
+ console.log('');
356
+ console.log('╔══════════════════════════════════════════════════════════════╗');
357
+ console.log('║ Vista JS RSC Build System (React Server Components) ║');
358
+ console.log('╚══════════════════════════════════════════════════════════════╝');
359
+ console.log('');
360
+ }
361
+ // Create .vista directory structure
362
+ const vistaDirs = (0, manifest_1.createVistaDirectories)(cwd, 'rsc');
363
+ const buildId = (0, manifest_1.getBuildId)(vistaDirs.root, !watch);
364
+ if (_debug) {
365
+ console.log(`[vista:build] Build ID: ${buildId}`);
366
+ console.log(`[vista:build] Mode: ${watch ? 'Development (Watch)' : 'Production'}`);
367
+ console.log('');
368
+ }
369
+ // ========================================================================
370
+ // Pre-build Structure Validation
371
+ // ========================================================================
372
+ const vistaConfig = (0, config_1.loadConfig)(cwd);
373
+ const engineVariant = (0, config_1.resolveAndApplyEngineVariant)(vistaConfig);
374
+ const structureConfig = (0, config_1.resolveStructureValidationConfig)(vistaConfig);
375
+ const cacheComponentsConfig = (0, config_1.resolveCacheComponentsConfig)(vistaConfig);
376
+ const deployConfig = (0, config_1.resolveDeployConfig)(vistaConfig);
377
+ const imagesUnoptimized = vistaConfig.images?.unoptimized === true || deployConfig.output === 'static';
378
+ if (imagesUnoptimized) {
379
+ process.env.VISTA_IMAGES_UNOPTIMIZED = '1';
380
+ }
381
+ if (deployConfig.output) {
382
+ process.env.VISTA_DEPLOY_OUTPUT = deployConfig.output;
383
+ }
384
+ if (_debug)
385
+ console.log(`[vista:build] Engine variant: ${engineVariant}`);
386
+ if (structureConfig.enabled) {
387
+ const result = (0, structure_validator_1.validateAppStructure)({ cwd });
388
+ (0, structure_log_1.logValidationResult)(result, structureConfig.logLevel);
389
+ if (result.state === 'error' && structureConfig.mode === 'strict') {
390
+ console.error((0, structure_log_1.formatBuildFailTable)(result));
391
+ process.exit(1);
392
+ }
393
+ }
394
+ // Scan app/ plus every other top-level project directory (components/, utils/,
395
+ // lib/, src/, ...) so `'use client'` modules outside app/ still enter the
396
+ // React Client Manifest. Discovery is directory membership, not the import graph.
397
+ if (fs_1.default.existsSync(appDir)) {
398
+ if (_debug) {
399
+ console.log(`[Vista JS RSC] Using ${(0, file_scanner_1.isNativeAvailable)() ? 'Rust native' : 'JS fallback'} scanner (v${(0, file_scanner_1.getVersion)()})`);
400
+ }
401
+ const scanResult = (0, file_scanner_1.scanAppDirectory)(appDir);
402
+ clientReferenceFiles = scanResult.clientComponents.map((component) => component.absolutePath);
403
+ for (const root of additionalClientRoots) {
404
+ const extraScan = (0, file_scanner_1.scanAppDirectory)(root.dir);
405
+ clientReferenceFiles.push(...extraScan.clientComponents.map((component) => component.absolutePath));
406
+ if (_debug && extraScan.clientComponents.length > 0) {
407
+ console.log(`[Vista JS RSC] Found ${extraScan.clientComponents.length} client components ('use client') in ${root.prefix}`);
408
+ }
409
+ }
410
+ clientReferenceFiles = Array.from(new Set(clientReferenceFiles));
411
+ if (_debug) {
412
+ console.log(`[Vista JS RSC] Found ${scanResult.serverComponents.length} server components`);
413
+ console.log(`[Vista JS RSC] Found ${scanResult.clientComponents.length} client components ('use client') in app/`);
414
+ console.log(`[Vista JS RSC] Total client reference modules: ${clientReferenceFiles.length}`);
415
+ console.log('');
416
+ }
417
+ if (scanResult.clientComponents.length > 0 && _debug) {
418
+ console.log('[Vista JS RSC] Client Components (will be hydrated on browser):');
419
+ scanResult.clientComponents.forEach((c) => {
420
+ console.log(` ✓ ${c.relativePath}`);
421
+ });
422
+ console.log('');
423
+ }
424
+ if (scanResult.serverComponents.length > 0 && _debug) {
425
+ console.log('[Vista JS RSC] Server Components (0kb client bundle contribution):');
426
+ scanResult.serverComponents.slice(0, 5).forEach((c) => {
427
+ console.log(` • ${c.relativePath}`);
428
+ });
429
+ if (scanResult.serverComponents.length > 5) {
430
+ console.log(` ... and ${scanResult.serverComponents.length - 5} more`);
431
+ }
432
+ console.log('');
433
+ }
434
+ const scanErrors = (0, module_boundary_validator_1.validateModuleBoundaries)({
435
+ appDir,
436
+ extraRoots: additionalClientRoots.map((root) => root.dir),
437
+ cacheComponentsEnabled: cacheComponentsConfig.enabled,
438
+ }).issues;
439
+ if (scanErrors.length > 0) {
440
+ console.log('\x1b[41m\x1b[37m ERROR \x1b[0m \x1b[31mServer/Segment Violations\x1b[0m');
441
+ console.log('');
442
+ for (const error of scanErrors) {
443
+ console.log(`\x1b[31m✗\x1b[0m ${path_1.default.relative(cwd, error.filePath)}`);
444
+ console.log(` ${error.message}`);
445
+ console.log('');
446
+ if (error.fix) {
447
+ console.log(` \x1b[36mTo fix:\x1b[0m ${error.fix}`);
448
+ console.log('');
449
+ }
450
+ }
451
+ if (!watch) {
452
+ console.log('\x1b[31mBuild failed due to server/segment violations.\x1b[0m');
453
+ process.exit(1);
454
+ }
455
+ }
456
+ }
457
+ // Include framework-level client boundaries (e.g. vista/link) so external
458
+ // package client modules resolve in React Flight manifests.
459
+ const frameworkClientReferences = collectFrameworkClientReferences(cwd);
460
+ if (frameworkClientReferences.length > 0) {
461
+ clientReferenceFiles = Array.from(new Set([...clientReferenceFiles, ...frameworkClientReferences]));
462
+ if (_debug) {
463
+ console.log(`[Vista JS RSC] Added ${frameworkClientReferences.length} framework client references`);
464
+ }
465
+ }
466
+ // Generate manifests
467
+ if (_debug)
468
+ console.log('[vista:build] Generating manifests...');
469
+ const clientManifest = (0, client_manifest_1.generateClientManifestWithRoots)(cwd, appDir, additionalClientRoots);
470
+ fs_1.default.writeFileSync(path_1.default.join(vistaDirs.root, 'client-manifest.json'), JSON.stringify(clientManifest, null, 2));
471
+ if (_debug) {
472
+ console.log(` ✓ client-manifest.json (${Object.keys(clientManifest.clientModules).length} modules)`);
473
+ }
474
+ const serverManifest = (0, server_manifest_1.generateServerManifest)(cwd, appDir);
475
+ fs_1.default.writeFileSync(path_1.default.join(vistaDirs.server, 'server-manifest.json'), JSON.stringify(serverManifest, null, 2));
476
+ if (_debug) {
477
+ console.log(` ✓ server-manifest.json (${Object.keys(serverManifest.serverModules).length} modules, ${serverManifest.routes.length} routes)`);
478
+ console.log('');
479
+ }
480
+ (0, manifest_1.writeCanonicalVistaArtifacts)(cwd, vistaDirs.root, buildId, serverManifest.routes.map((route) => ({
481
+ pattern: route.pattern,
482
+ pagePath: route.pagePath,
483
+ type: route.type,
484
+ })), serverManifest.routeHandlers.map((handler) => ({
485
+ pattern: handler.pattern,
486
+ filePath: handler.filePath,
487
+ type: handler.type,
488
+ methods: handler.methods,
489
+ runtime: handler.runtime,
490
+ })));
491
+ (0, manifest_1.writeReservedVistaArtifacts)(vistaDirs.root, {
492
+ buildId,
493
+ engineVariant,
494
+ imagesConfig: vistaConfig.images,
495
+ });
496
+ // Generate client entry
497
+ generateRSCClientEntry(cwd, vistaDirs.root, watch);
498
+ // Create webpack configs
499
+ const options = {
500
+ cwd,
501
+ isDev: watch,
502
+ vistaDirs,
503
+ buildId,
504
+ engineVariant,
505
+ clientReferenceFiles,
506
+ imagesUnoptimized,
507
+ deployOutput: deployConfig.output,
508
+ };
509
+ // Build CSS
510
+ runPostCSS(cwd, vistaDirs.root);
511
+ if (watch) {
512
+ // Development mode - return compilers for middleware
513
+ if (_debug)
514
+ console.log('[Vista JS RSC] Creating development compilers...');
515
+ // Clear stale webpack cache. ReactFlightWebpackPlugin adds
516
+ // AsyncDependenciesBlock entries that can't be serialised by webpack's
517
+ // pack file cache strategy. A stale cache that was written *before* the
518
+ // plugin ran will skip the parser hook entirely, causing empty Flight
519
+ // manifests. Clearing on every dev-start is the safest approach –
520
+ // first-compile is ~1s longer but guarantees correct manifests.
521
+ const cacheDir = engineVariant === 'flashpack'
522
+ ? path_1.default.join(cwd, constants_1.FLASH_DIR, 'cache', 'webpack')
523
+ : path_1.default.join(vistaDirs.root, 'cache');
524
+ if (fs_1.default.existsSync(cacheDir)) {
525
+ fs_1.default.rmSync(cacheDir, { recursive: true, force: true });
526
+ if (_debug)
527
+ console.log('[Vista JS RSC] Cleared stale webpack cache');
528
+ }
529
+ // Write stub Flight manifests so upstream can start before first webpack compile.
530
+ // ReactFlightWebpackPlugin will overwrite these on first successful compilation.
531
+ const stubManifests = [
532
+ path_1.default.join(vistaDirs.root, 'react-client-manifest.json'),
533
+ path_1.default.join(vistaDirs.root, 'react-server-manifest.json'),
534
+ path_1.default.join(vistaDirs.root, 'react-ssr-manifest.json'),
535
+ ];
536
+ for (const manifestPath of stubManifests) {
537
+ if (!fs_1.default.existsSync(manifestPath)) {
538
+ fs_1.default.writeFileSync(manifestPath, '{}');
539
+ }
540
+ }
541
+ const clientConfig = (0, compiler_1.createClientWebpackConfig)(options);
542
+ const clientCompiler = (0, webpack_1.default)(clientConfig);
543
+ syncReactServerManifests(vistaDirs.root);
544
+ // Watch for CSS + source changes that can affect Tailwind output.
545
+ try {
546
+ const chokidar = require('chokidar');
547
+ const styleWatchRoots = ['app', 'components', 'content', 'lib', 'ctx', 'data', 'utils', 'src']
548
+ .map((entry) => path_1.default.join(cwd, entry))
549
+ .filter((entry) => fs_1.default.existsSync(entry));
550
+ let cssTimer = null;
551
+ const scheduleCSSBuild = () => {
552
+ if (cssTimer)
553
+ clearTimeout(cssTimer);
554
+ cssTimer = setTimeout(() => {
555
+ if (_debug)
556
+ console.log('[Vista JS RSC] Style source changed, rebuilding CSS...');
557
+ runPostCSS(cwd, vistaDirs.root);
558
+ }, 120);
559
+ };
560
+ chokidar
561
+ .watch(styleWatchRoots, {
562
+ ignoreInitial: true,
563
+ ignored: (watchedPath) => watchedPath.includes(`${path_1.default.sep}node_modules${path_1.default.sep}`) ||
564
+ watchedPath.includes(`${path_1.default.sep}.git${path_1.default.sep}`) ||
565
+ watchedPath.includes(`${path_1.default.sep}.vista${path_1.default.sep}`),
566
+ })
567
+ .on('all', (_event, changedPath) => {
568
+ if (/\.(?:css|[cm]?[jt]sx?|md|mdx)$/i.test(changedPath)) {
569
+ scheduleCSSBuild();
570
+ }
571
+ });
572
+ }
573
+ catch (e) {
574
+ // chokidar not installed
575
+ }
576
+ if (_debug) {
577
+ console.log('[Vista JS RSC] Ready for development');
578
+ console.log('');
579
+ }
580
+ return { serverCompiler: null, clientCompiler };
581
+ }
582
+ else {
583
+ // Production build
584
+ console.log('[Vista JS RSC] Building for production...');
585
+ console.log('');
586
+ const serverConfig = (0, compiler_1.createServerWebpackConfig)(options);
587
+ const clientConfig = (0, compiler_1.createClientWebpackConfig)(options);
588
+ // Build server bundle
589
+ console.log('[Vista JS RSC] Building server bundle...');
590
+ await new Promise((resolve, reject) => {
591
+ (0, webpack_1.default)(serverConfig).run((err, stats) => {
592
+ if (err) {
593
+ console.error('[Vista RSC] Server build error:', err);
594
+ reject(err);
595
+ return;
596
+ }
597
+ if (stats?.hasErrors()) {
598
+ console.error('[Vista RSC] Server compilation errors:', stats.toString('errors-only'));
599
+ reject(new Error('Server compilation failed'));
600
+ return;
601
+ }
602
+ console.log('[Vista JS RSC] Server bundle complete');
603
+ resolve();
604
+ });
605
+ });
606
+ // Build client bundle
607
+ console.log('[Vista JS RSC] Building client bundle...');
608
+ await new Promise((resolve, reject) => {
609
+ (0, webpack_1.default)(clientConfig).run((err, stats) => {
610
+ if (err) {
611
+ console.error('[Vista RSC] Client build error:', err);
612
+ reject(err);
613
+ return;
614
+ }
615
+ if (stats?.hasErrors()) {
616
+ console.error('[Vista RSC] Client compilation errors:', stats.toString('errors-only'));
617
+ reject(new Error('Client compilation failed'));
618
+ return;
619
+ }
620
+ console.log('[Vista JS RSC] Client bundle complete');
621
+ console.log(stats?.toString('minimal'));
622
+ syncReactServerManifests(vistaDirs.root);
623
+ resolve();
624
+ });
625
+ });
626
+ // ------------------------------------------------------------------
627
+ // Static Generation (SSG / ISR)
628
+ // ------------------------------------------------------------------
629
+ console.log('[Vista JS RSC] Running static generation...');
630
+ const ssgResult = await (0, static_generator_1.generateStaticPages)({
631
+ cwd,
632
+ vistaDirRoot: vistaDirs.root,
633
+ manifest: serverManifest,
634
+ isDev: false,
635
+ buildId,
636
+ });
637
+ if (ssgResult.pagesGenerated > 0) {
638
+ console.log(`[Vista JS RSC] Pre-rendered ${ssgResult.pagesGenerated} page(s): ${ssgResult.generatedPaths.join(', ')}`);
639
+ }
640
+ if (ssgResult.failedPaths.length > 0) {
641
+ console.warn(`[Vista JS RSC] Failed to pre-render ${ssgResult.failedPaths.length} page(s):`, ssgResult.failedPaths.map((f) => `${f.path} (${f.error})`).join(', '));
642
+ }
643
+ // Write the real prerender manifest (overwrite the empty stub)
644
+ const prerenderManifestPath = path_1.default.join(vistaDirs.root, 'prerender-manifest.json');
645
+ fs_1.default.writeFileSync(prerenderManifestPath, JSON.stringify(ssgResult.manifest, null, 2));
646
+ console.log('[Vista JS RSC] Wrote prerender-manifest.json');
647
+ (0, standalone_1.generateStandaloneOutput)({
648
+ cwd,
649
+ vistaDir: vistaDirs.root,
650
+ buildId,
651
+ serverManifest,
652
+ debug: _debug,
653
+ });
654
+ (0, deploy_output_1.generateDeploymentOutputs)({
655
+ cwd,
656
+ vistaDir: vistaDirs.root,
657
+ debug: _debug,
658
+ });
659
+ (0, manifest_1.pruneEmptyVistaDirectories)(vistaDirs.root);
660
+ console.log('');
661
+ console.log('╔══════════════════════════════════════════════════════════════╗');
662
+ console.log('║ Build Complete! 🎉 ║');
663
+ console.log('╚══════════════════════════════════════════════════════════════╝');
664
+ console.log('');
665
+ console.log(' Output directory: .vista/');
666
+ console.log(' ├── server/ (Server-side bundle - NEVER sent to client)');
667
+ console.log(' ├── static/ (Client assets - only client components)');
668
+ if (engineVariant === 'flashpack') {
669
+ console.log(' └── cache/ (metadata bridge to the active Flashpack cache)');
670
+ console.log(' Flashpack directory: .flash/');
671
+ console.log(' ├── cache/ (Flashpack runtime cache)');
672
+ console.log(' ├── graph/ (Rust pipeline graph snapshots)');
673
+ console.log(' └── logs/ (Flashpack phase logs)');
674
+ }
675
+ else {
676
+ console.log(' └── cache/ (Build cache for faster rebuilds)');
677
+ }
678
+ console.log('');
679
+ return { serverCompiler: null, clientCompiler: null };
680
+ }
681
+ }