@foldkit/vite-plugin 0.28.0-canary.82ac2ec6c9b5 → 0.28.0-canary.90746b32d2ca

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.
package/README.md CHANGED
@@ -61,7 +61,7 @@ Pass `ssr` with the path to your server entry to render page requests through it
61
61
  plugins: [foldkit({ ssr: { serverEntry: '/src/entry.server.ts' } })]
62
62
  ```
63
63
 
64
- With this set, the dev server converts HTML page requests to Web `Request` values, passes them to the entry's `renderPage`, and serves the returned `Response`. The request URL retains Vite's configured `base` prefix and the browser's query string. Vite continues to serve the client entry, HMR, and assets, and the server entry runs through Vite's module graph, so edits to it apply without a restart. The client side of the handoff needs no plugin configuration: a server-rendered application's client entry calls `Runtime.hydrate` instead of `Runtime.run`. Hydration adopts matching DOM, rebuilds mismatched subtrees, and refuses an invalid or cross-deployment handoff. The option shapes only the dev server; production hosts import the built server entry themselves. See the [Server Rendering documentation](https://foldkit.dev/core/server-rendering) for the full contract.
64
+ With this set, the dev server converts HTML page requests to Web `Request` values, passes them to the entry's `renderPage`, and serves the returned `Response`. The request URL retains Vite's configured `base` prefix and the browser's query string. Vite continues to serve the client entry, HMR, and assets, and the server entry runs through the module runner of Vite's `ssr` environment, so edits to it apply without a restart. Release what the server entry starts, such as a `ManagedRuntime`, in an `import.meta.hot.dispose` callback in the entry; see [Releasing resources when the server entry reloads](https://foldkit.dev/core/server-rendering#releasing-resources-when-the-server-entry-reloads). The client side of the handoff needs no plugin configuration: a server-rendered application's client entry calls `Runtime.hydrate` instead of `Runtime.run`. Hydration adopts matching DOM, rebuilds mismatched subtrees, and refuses an invalid or cross-deployment handoff. The option shapes only the dev server; production hosts import the built server entry themselves. See the [Server Rendering documentation](https://foldkit.dev/core/server-rendering) for the full contract.
65
65
 
66
66
  Vite retains ownership of configured proxy routes before Foldkit handles application requests. Vite's `server.cors` option applies to Vite-owned source modules, assets, and HMR. It does not add headers to application responses or answer their preflights. Preflight ownership follows `Access-Control-Request-Method`, so a preflight for an application `POST` reaches `renderPage` even when its path looks like an asset. An `OPTIONS` request without both `Origin` and `Access-Control-Request-Method` is not a preflight and also reaches `renderPage`. Define application CORS in `renderPage`, where development and the deployed host share one policy. Vite's `allowedHosts` check runs before proxy and application handling, including `OPTIONS` and methods the Web `Request` API cannot represent.
67
67
 
package/dist/build.d.ts CHANGED
@@ -127,6 +127,10 @@ export declare const renderTargetFor: (clientDirectory: string, path: string, or
127
127
  * use the server entry's `renderDocument` export with the emitted browser assets.
128
128
  * The browser build has a script input and emits no HTML until prerendering.
129
129
  * The server bundle's default export is `{ fetch }`.
130
+ *
131
+ * With prerendering enabled, `vite preview` resolves generated directory-index
132
+ * pages at their declared paths. Vite serves the existing files without running
133
+ * the server entry. Custom application hosts retain their own routing.
130
134
  */
131
135
  export declare const foldkitBuild: (serverEntry: string, options: FoldkitBuildOptions) => Plugin<FoldkitBuildApi>;
132
136
  //# sourceMappingURL=build.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sources":["../src/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,MAAM,EAAE,MAAM,QAAQ,CAAA;AAS1C,OAAO,QAA8B,MAAM,WAAW,CAAA;AAEtD,OAAO,KAAK,EAGV,MAAM,EAGP,MAAM,MAAM,CAAA;AAEb,mEAAmE;AACnE,MAAM,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IAC7C;;;OAGG;IACH,KAAK,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAA;IAC7B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAC,CAAA;AAEF,4EAA4E;AAC5E,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC;IACzC,2HAA2H;IAC3H,WAAW,EAAE,MAAM,CAAA;IACnB,0CAA0C;IAC1C,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,yCAAyC;IACzC,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;;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EAAsE;AACtE,MAAM,MAAM,oBAAoB,GAAG,OAAO,oBAAoB,CAAC,IAAI,CAAA;AAEnE,2DAA2D;AAC3D,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC;IACrC,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAA;IACnB,uDAAuD;IACvD,aAAa,EAAE,OAAO,uBAAuB,CAAA;IAC7C;;;;OAIG;IACH,gBAAgB,EAAE,MAAM,oBAAoB,CAAA;CAC7C,CAAC,CAAA;AAcF,eAAO,MAAM,YAAY,SACjB,MAAM,aACD,MAAM,YACR,OAAO,QAAQ,KACvB,MAQF,CAAA;AA6FD,eAAO,MAAM,eAAe,oBACT,MAAM,QACjB,MAAM,UACJ,MAAM,YACL,OAAO,QAAQ,KACvB,QAAQ,CAAC;IAAE,GAAG,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CA0CrC,CAAA;AAqLD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY,gBACV,MAAM,WACV,mBAAmB,KAC3B,MAAM,CAAC,eAAe,CAgTxB,CAAA"}
package/dist/build.js CHANGED
@@ -4,6 +4,7 @@ import { existsSync } from 'node:fs';
4
4
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
5
  import nodePath, { dirname, resolve } from 'node:path';
6
6
  import { pathToFileURL } from 'node:url';
7
+ import { installPrerenderPreview } from './preview.js';
7
8
  /** Vite module id of the fetch handler Foldkit emits as the server entry. */
8
9
  export const FOLDKIT_FETCH_MODULE_ID = 'virtual:foldkit/fetch';
9
10
  /**
@@ -280,6 +281,10 @@ const assetsForFetchModule = (assets) => {
280
281
  * use the server entry's `renderDocument` export with the emitted browser assets.
281
282
  * The browser build has a script input and emits no HTML until prerendering.
282
283
  * The server bundle's default export is `{ fetch }`.
284
+ *
285
+ * With prerendering enabled, `vite preview` resolves generated directory-index
286
+ * pages at their declared paths. Vite serves the existing files without running
287
+ * the server entry. Custom application hosts retain their own routing.
283
288
  */
284
289
  export const foldkitBuild = (serverEntry, options) => {
285
290
  const state = {};
@@ -369,7 +374,10 @@ export const foldkitBuild = (serverEntry, options) => {
369
374
  };
370
375
  return {
371
376
  name: 'foldkit:build',
372
- apply: 'build',
377
+ apply: (_config, { command, isPreview }) => command === 'build' || (isPreview === true && prerender !== undefined),
378
+ ...(prerender === undefined
379
+ ? {}
380
+ : { configurePreviewServer: installPrerenderPreview }),
373
381
  sharedDuringBuild: true,
374
382
  api: {
375
383
  serverEntry,
@@ -438,10 +446,14 @@ export const foldkitBuild = (serverEntry, options) => {
438
446
  state.assets = collectDocumentAssets(Object.values(bundle), this.environment.config);
439
447
  },
440
448
  },
441
- config: userConfig => {
449
+ config: (userConfig, { isPreview }) => {
442
450
  const client = {
443
451
  build: {
444
- outDir: clientOutDir,
452
+ outDir: isPreview
453
+ ? (userConfig.environments?.['client']?.build?.outDir ??
454
+ userConfig.build?.outDir ??
455
+ clientOutDir)
456
+ : clientOutDir,
445
457
  rolldownOptions: { input: { [CLIENT_CHUNK_NAME]: CLIENT_MODULE_ID } },
446
458
  },
447
459
  };
@@ -0,0 +1,9 @@
1
+ import { Effect } from 'effect';
2
+ import type * as PlatformError from 'effect/PlatformError';
3
+ type RandomUUIDv4Crypto = Readonly<{
4
+ randomUUIDv4: Effect.Effect<string, PlatformError.PlatformError> | (() => Effect.Effect<string, PlatformError.PlatformError>);
5
+ }>;
6
+ /** Normalizes Effect Crypto's property and method forms of randomUUIDv4. */
7
+ export declare const randomUUIDv4Effect: (crypto: RandomUUIDv4Crypto) => Effect.Effect<string, PlatformError.PlatformError>;
8
+ export {};
9
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sources":["../src/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAa,MAAM,QAAQ,CAAA;AAC1C,OAAO,KAAK,KAAK,aAAa,MAAM,sBAAsB,CAAA;AAE1D,KAAK,kBAAkB,GAAG,QAAQ,CAAC;IACjC,YAAY,EACR,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,aAAa,CAAC,GAClD,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,aAAa,CAAC,CAAC,CAAA;CAC/D,CAAC,CAAA;AAEF,4EAA4E;AAC5E,eAAO,MAAM,kBAAkB,WACrB,kBAAkB,KACzB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,aAAa,CAShD,CAAA"}
package/dist/crypto.js ADDED
@@ -0,0 +1,9 @@
1
+ import { Effect, Predicate } from 'effect';
2
+ /** Normalizes Effect Crypto's property and method forms of randomUUIDv4. */
3
+ export const randomUUIDv4Effect = (crypto) => Effect.suspend(() => {
4
+ const operation = crypto.randomUUIDv4;
5
+ if (Predicate.isFunction(operation)) {
6
+ return operation.call(crypto);
7
+ }
8
+ return operation;
9
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"devToolsOverlay.d.ts","sources":["../src/devToolsOverlay.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAoIlC;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,YAC7B,OAAO,GAAG,OAAO,QACpB,MAAM,KACX,OAQF,CAAA;AAED,+EAA+E;AAC/E,eAAO,MAAM,qBAAqB,QAAO,MAmExC,CAAA"}
1
+ {"version":3,"file":"devToolsOverlay.d.ts","sources":["../src/devToolsOverlay.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAsIlC;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,YAC7B,OAAO,GAAG,OAAO,QACpB,MAAM,KACX,OAQF,CAAA;AAED,+EAA+E;AAC/E,eAAO,MAAM,qBAAqB,QAAO,MAmExC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sources":["../src/index.ts"],"names":[],"mappings":"AAg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AK,CAAA;QACnB,WAAW,CAAC,EAAE,MAAM,CAAA;QACpB,KAAK,CAAC,EAAE,KAAK,CAAA;KACd,CAAC,CACL,CAAA;IACH;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAC,CAAA;AAk/BF,eAAO,MAAM,OAAO,aAAa,oBAAoB,KAAQ,KAAK,CAAC,MAAM,CAwJxE,CAAA"}
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem';
10
10
  import * as NodePath from '@effect/platform-node/NodePath';
11
11
  import { foldkitBuild } from './build.js';
12
12
  import { foldkitBuildToken } from './buildToken.js';
13
+ import { randomUUIDv4Effect } from './crypto.js';
13
14
  import { devToolsOverlayPlugin } from './devToolsOverlay.js';
14
15
  import { crawlFoldkitPackages } from './foldkitPackages.js';
15
16
  import { publishRelayRecord, retireRelayRecord } from './relayRegistry.js';
@@ -105,6 +106,9 @@ const byConnectionOrder = Order.mapInput(Order.Number, ({ sequence }) => sequenc
105
106
  const handlePreserveModelReceived = (state, payload) => Exit.match(Schema.decodeUnknownExit(PreserveModelMessage)(payload), {
106
107
  onFailure: error => Console.warn('[foldkit:preserve] failed to decode preserve-model payload', error),
107
108
  onSuccess: ({ id, model, isReloadFlush }) => Ref.update(state.preservedModels, current => {
109
+ if (model === undefined) {
110
+ return HashMap.remove(current, id);
111
+ }
108
112
  const existingFlag = Option.exists(HashMap.get(current, id), ({ isReloadFlush }) => isReloadFlush);
109
113
  const entry = {
110
114
  model,
@@ -289,7 +293,7 @@ class RelayBindFailed extends Data.TaggedError('RelayBindFailed') {
289
293
  const isPortInUse = (error) => Predicate.hasProperty(error, 'code') && error.code === 'EADDRINUSE';
290
294
  const relayId = Effect.gen(function* () {
291
295
  const crypto = yield* Crypto.Crypto;
292
- return yield* crypto.randomUUIDv4.pipe(Effect.orDie);
296
+ return yield* randomUUIDv4Effect(crypto).pipe(Effect.orDie);
293
297
  });
294
298
  const attachRelayHandlers = (wss, enqueue) => {
295
299
  wss.on('connection', client => {
@@ -573,9 +577,18 @@ export const foldkit = (options = {}) => {
573
577
  closeBundle() {
574
578
  return Effect.runPromise(stopMain(this.environment.getTopLevelConfig()));
575
579
  },
576
- handleHotUpdate: ({ server, modules, }) => {
577
- if (modules.length === 0) {
578
- return;
580
+ // NOTE: An edit to a client or `ssr` module reloads the whole page, so
581
+ // Vite's client HMR is suppressed. This hook runs only for the client
582
+ // environment, so the `ssr` module runner receives Vite's updates, which
583
+ // run the server entry's `import.meta.hot.dispose` callback.
584
+ hotUpdate({ type, file, modules, server }) {
585
+ if (type !== 'update' || this.environment.name !== 'client') {
586
+ return undefined;
587
+ }
588
+ const serverModules = server.environments.ssr?.moduleGraph.getModulesByFile(file);
589
+ if (Array.isArrayEmpty(modules) &&
590
+ (serverModules === undefined || serverModules.size === 0)) {
591
+ return undefined;
579
592
  }
580
593
  server.ws.send({ type: 'full-reload' });
581
594
  const run = mainRuns.get(server.config);
@@ -0,0 +1,4 @@
1
+ import type { PreviewServer } from 'vite';
2
+ /** @internal Resolve generated directory indexes through Vite's preview pipeline. */
3
+ export declare const installPrerenderPreview: (server: PreviewServer) => void;
4
+ //# sourceMappingURL=preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview.d.ts","sources":["../src/preview.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAW,aAAa,EAAE,MAAM,MAAM,CAAA;AAgElD,qFAAqF;AACrF,eAAO,MAAM,uBAAuB,WAAY,aAAa,KAAG,IA6B/D,CAAA"}
@@ -0,0 +1,67 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { resolve, sep } from 'node:path';
3
+ const isContained = (root, file) => file.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
4
+ const rewriteDirectoryIndex = (request, root, base, isProxied) => {
5
+ const { method, headers, url } = request;
6
+ if ((method !== 'GET' && method !== 'HEAD') ||
7
+ url === undefined ||
8
+ isProxied(url) ||
9
+ isProxied(url.replace(/(\?|$)/, '/index.html$1')) ||
10
+ (headers.accept &&
11
+ !headers.accept.includes('text/html') &&
12
+ !headers.accept.includes('*/*'))) {
13
+ return;
14
+ }
15
+ const [pathname = ''] = url.split('?');
16
+ if (!pathname.startsWith('/') ||
17
+ pathname.startsWith('//') ||
18
+ pathname.includes('#') ||
19
+ !pathname.startsWith(base)) {
20
+ return;
21
+ }
22
+ const route = pathname.slice(base.length);
23
+ if (route === '' || route.endsWith('/')) {
24
+ return;
25
+ }
26
+ const segments = route.split('/').map(segment => decodeURIComponent(segment));
27
+ if (segments.join('/') !== decodeURI(route) ||
28
+ segments.some(segment => /^\.{1,2}$|[/\\\u0000:]/.test(segment))) {
29
+ return;
30
+ }
31
+ const file = resolve(root, ...segments);
32
+ if (!isContained(root, file) ||
33
+ file.endsWith('.html') ||
34
+ statSync(file, { throwIfNoEntry: false })?.isFile() ||
35
+ statSync(resolve(file, 'index'), { throwIfNoEntry: false })?.isFile() ||
36
+ existsSync(`${file}.html`)) {
37
+ return;
38
+ }
39
+ const index = realpathSync(resolve(file, 'index.html'));
40
+ if (isContained(realpathSync(root), index) && statSync(index).isFile()) {
41
+ request.url = `${pathname}/index.html${url.slice(pathname.length)}`;
42
+ }
43
+ };
44
+ /** @internal Resolve generated directory indexes through Vite's preview pipeline. */
45
+ export const installPrerenderPreview = (server) => {
46
+ if (server.config.appType === 'custom') {
47
+ return;
48
+ }
49
+ const client = server.config.environments['client'];
50
+ if (client === undefined) {
51
+ return;
52
+ }
53
+ const root = resolve(server.config.root, client.build.outDir);
54
+ const isProxied = (url) => Object.entries(server.config.preview.proxy ?? {}).some(([context, options]) => Boolean(options) &&
55
+ (context.startsWith('^')
56
+ ? new RegExp(context).test(url)
57
+ : url.startsWith(context)));
58
+ server.middlewares.use((request, _response, next) => {
59
+ try {
60
+ rewriteDirectoryIndex(request, root, server.config.base, isProxied);
61
+ }
62
+ catch {
63
+ return next();
64
+ }
65
+ next();
66
+ });
67
+ };
package/dist/ssr.d.ts CHANGED
@@ -53,13 +53,17 @@ export type FoldkitSsrOptions = Readonly<{
53
53
  * Serves server-rendered pages from the Vite dev server.
54
54
  *
55
55
  * Vite retains ownership of configured proxies, source modules, HMR, and
56
- * assets. Requests that fall through load the server entry through Vite's SSR
57
- * module loader, call its `renderPage` with a Web `Request`, and send the
58
- * resulting Web `Response`. Vite's host validation applies before either
59
- * owner. Foldkit then validates and normalizes the request target before Vite
60
- * or the server entry can resolve it. Vite's CORS option applies only to
56
+ * assets. Requests that fall through load the server entry through the `ssr`
57
+ * environment's module runner, call its `renderPage` with a Web `Request`, and
58
+ * send the resulting Web `Response`. Vite's host validation applies before
59
+ * either owner. Foldkit then validates and normalizes the request target before
60
+ * Vite or the server entry can resolve it. Vite's CORS option applies only to
61
61
  * Vite-owned responses, while the server entry owns CORS for application
62
- * responses. Server entry edits take effect without a restart.
62
+ * responses. Server entry edits take effect without a restart. The server
63
+ * entry accepts its own updates, and the server graph is reevaluated so Block
64
+ * Definitions and their declarations are created together. Unless
65
+ * `server.hmr` is `false`, an `import.meta.hot.dispose` callback in the entry
66
+ * runs before a hot update replaces it.
63
67
  */
64
68
  export declare const foldkitSsr: (options: FoldkitSsrOptions) => Plugin;
65
69
  //# sourceMappingURL=ssr.d.ts.map
package/dist/ssr.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ssr.d.ts","sources":["../src/ssr.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAGV,MAAM,EAGP,MAAM,MAAM,CAAA;AAIb,0EAA0E;AAC1E,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACvC;;;;;OAKG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAC,CAAA;AA6tBF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,YAAa,iBAAiB,KAAG,MAyGvD,CAAA"}
1
+ {"version":3,"file":"ssr.d.ts","sources":["../src/ssr.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAIV,MAAM,EAIP,MAAM,MAAM,CAAA;AAIb,0EAA0E;AAC1E,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACvC;;;;;OAKG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAC,CAAA;AAq0BF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,UAAU,YAAa,iBAAiB,KAAG,MAqNvD,CAAA"}
package/dist/ssr.js CHANGED
@@ -1,5 +1,6 @@
1
- import { Array, Effect, Predicate } from 'effect';
1
+ import { Array, Effect, Latch, Predicate } from 'effect';
2
2
  import * as Server from 'foldkit/experimental/server';
3
+ import MagicString from 'magic-string';
3
4
  import { readFile } from 'node:fs/promises';
4
5
  import { resolve } from 'node:path';
5
6
  import { Readable } from 'node:stream';
@@ -10,6 +11,70 @@ import { buildIdForCommand } from './buildToken.js';
10
11
  // getter is the shape every copy shares, and `in` reads its descriptor without
11
12
  // invoking it.
12
13
  const isRunnable = (environment) => 'runner' in environment;
14
+ const isHotServerEnvironment = (environment) => environment.name === 'ssr' &&
15
+ environment.config.server.hmr !== false &&
16
+ isRunnable(environment);
17
+ // NOTE: Vite reruns an edited declaration module and its importers, but keeps
18
+ // imported Block Definitions. Invalidate the full server graph so the next
19
+ // entry evaluation creates each Definition before registering its declarations.
20
+ const invalidateServerModulesForReevaluation = (environment) => {
21
+ const { moduleGraph } = environment;
22
+ const invalidatedModules = new Set();
23
+ for (const module of moduleGraph.idToModuleMap.values()) {
24
+ moduleGraph.invalidateModule(module, invalidatedModules, undefined, false, true);
25
+ }
26
+ };
27
+ const SERVER_UPDATE_SETTLED_EVENT = 'foldkit:server-update-settled';
28
+ const SERVER_UPDATE_SETTLE_TIMEOUT_MS = 1_000;
29
+ // NOTE: The entry accepts updates so Vite runs its `import.meta.hot.dispose`
30
+ // callback before evaluating the replacement. The server graph is invalidated
31
+ // separately so every Block Definition is recreated with its declarations.
32
+ // The entry also reports each update payload the runner finishes handling, so
33
+ // the dev server can hold requests until then.
34
+ const SERVER_ENTRY_HOT_SOURCE = `if (import.meta.hot) {
35
+ import.meta.hot.accept()
36
+ const reportSettledUpdate = () => {
37
+ import.meta.hot.send(${JSON.stringify(SERVER_UPDATE_SETTLED_EVENT)})
38
+ }
39
+ import.meta.hot.on('vite:afterUpdate', reportSettledUpdate)
40
+ import.meta.hot.on('vite:beforeFullReload', reportSettledUpdate)
41
+ import.meta.hot.on('vite:error', reportSettledUpdate)
42
+ }
43
+ `;
44
+ // NOTE: Vite invalidates the edited modules before it sends the update to the
45
+ // module runner. A request that imports the server entry in between evaluates
46
+ // a new copy, whose `dispose` callback replaces the old copy's, so the old copy
47
+ // is never released. The gate counts the edits to modules in the `ssr` module
48
+ // graph and holds requests until the entry reports each one settled. The
49
+ // timeout releases them when an edit never reaches the runner.
50
+ const makeServerUpdateGate = () => {
51
+ const settled = Latch.makeUnsafe(true);
52
+ let pendingUpdateCount = 0;
53
+ let settleTimeout;
54
+ const release = () => {
55
+ pendingUpdateCount = 0;
56
+ clearTimeout(settleTimeout);
57
+ settled.openUnsafe();
58
+ };
59
+ const beginUpdate = () => {
60
+ pendingUpdateCount += 1;
61
+ settled.closeUnsafe();
62
+ clearTimeout(settleTimeout);
63
+ settleTimeout = setTimeout(release, SERVER_UPDATE_SETTLE_TIMEOUT_MS).unref();
64
+ };
65
+ const settleUpdate = () => {
66
+ pendingUpdateCount = Math.max(0, pendingUpdateCount - 1);
67
+ if (pendingUpdateCount === 0) {
68
+ release();
69
+ }
70
+ };
71
+ return {
72
+ beginUpdate,
73
+ settleUpdate,
74
+ awaitSettledUpdates: settled.await,
75
+ close: release,
76
+ };
77
+ };
13
78
  const isEntryModule = (loadedModule) => Predicate.isObject(loadedModule) &&
14
79
  Predicate.hasProperty(loadedModule, 'renderPage') &&
15
80
  Predicate.isFunction(loadedModule.renderPage);
@@ -129,10 +194,11 @@ const renderDecision = (nodeRequest, requestUrl) => {
129
194
  }
130
195
  return 'Render';
131
196
  };
132
- const renderRequest = (server, options, nodeRequest, requestUrl) => Effect.gen(function* () {
197
+ const renderRequest = (server, ssrEnvironment, serverUpdates, options, nodeRequest, requestUrl) => Effect.gen(function* () {
133
198
  const { pathname, search } = new URL(requestUrl);
134
199
  const route = `${pathname}${search}`;
135
- const loadedModule = yield* Effect.promise(() => server.ssrLoadModule(options.serverEntry));
200
+ yield* serverUpdates.awaitSettledUpdates;
201
+ const loadedModule = yield* Effect.promise(() => ssrEnvironment.runner.import(options.serverEntry));
136
202
  if (!isEntryModule(loadedModule)) {
137
203
  return yield* Effect.die(new Error(`[foldkit] '${options.serverEntry}' does not export a renderPage function, so the dev server cannot render pages.`));
138
204
  }
@@ -408,7 +474,7 @@ const sendWebResponse = async (webResponse, nodeRequest, nodeResponse, isNegotia
408
474
  // The handler that turns an application-owned request into a response. OPTIONS
409
475
  // reaches it at the host boundary. Other methods reach it after Vite's modules
410
476
  // and assets have had an opportunity to answer.
411
- const renderMiddleware = (server, options, requestUrls, stateByRequest) => (nodeRequest, nodeResponse, next) => {
477
+ const renderMiddleware = (server, ssrEnvironment, serverUpdates, options, requestUrls, stateByRequest) => (nodeRequest, nodeResponse, next) => {
412
478
  const corsState = stateByRequest.get(nodeRequest);
413
479
  stateByRequest.delete(nodeRequest);
414
480
  corsState?.tracking.stop();
@@ -452,29 +518,33 @@ const renderMiddleware = (server, options, requestUrls, stateByRequest) => (node
452
518
  return;
453
519
  }
454
520
  const isNegotiated = decision === 'RenderNegotiated';
455
- void Effect.runPromise(renderRequest(server, options, nodeRequest, requestUrl))
521
+ void Effect.runPromise(renderRequest(server, ssrEnvironment, serverUpdates, options, nodeRequest, requestUrl))
456
522
  .then(response => sendWebResponse(response, nodeRequest, nodeResponse, isNegotiated))
457
- .catch((error) => {
458
- if (error instanceof Error) {
459
- server.ssrFixStacktrace(error);
460
- }
461
- next(error);
462
- });
523
+ // NOTE: The runner maps error stacks from the modules it evaluates to
524
+ // their source. `server.ssrFixStacktrace` would map them a second time
525
+ // and can point the error overlay at the wrong lines.
526
+ .catch(next);
463
527
  };
464
528
  /**
465
529
  * Serves server-rendered pages from the Vite dev server.
466
530
  *
467
531
  * Vite retains ownership of configured proxies, source modules, HMR, and
468
- * assets. Requests that fall through load the server entry through Vite's SSR
469
- * module loader, call its `renderPage` with a Web `Request`, and send the
470
- * resulting Web `Response`. Vite's host validation applies before either
471
- * owner. Foldkit then validates and normalizes the request target before Vite
472
- * or the server entry can resolve it. Vite's CORS option applies only to
532
+ * assets. Requests that fall through load the server entry through the `ssr`
533
+ * environment's module runner, call its `renderPage` with a Web `Request`, and
534
+ * send the resulting Web `Response`. Vite's host validation applies before
535
+ * either owner. Foldkit then validates and normalizes the request target before
536
+ * Vite or the server entry can resolve it. Vite's CORS option applies only to
473
537
  * Vite-owned responses, while the server entry owns CORS for application
474
- * responses. Server entry edits take effect without a restart.
538
+ * responses. Server entry edits take effect without a restart. The server
539
+ * entry accepts its own updates, and the server graph is reevaluated so Block
540
+ * Definitions and their declarations are created together. Unless
541
+ * `server.hmr` is `false`, an `import.meta.hot.dispose` callback in the entry
542
+ * runs before a hot update replaces it.
475
543
  */
476
544
  export const foldkitSsr = (options) => {
477
545
  let isDevelopmentHost = false;
546
+ const entryIds = new WeakMap();
547
+ const serverUpdates = makeServerUpdateGate();
478
548
  return {
479
549
  name: 'foldkit-ssr',
480
550
  configResolved(config) {
@@ -518,6 +588,65 @@ export const foldkitSsr = (options) => {
518
588
  }),
519
589
  };
520
590
  },
591
+ perEnvironmentWatchChangeDuringDev: true,
592
+ watchChange(id, change) {
593
+ if (!isDevelopmentHost ||
594
+ change.event !== 'update' ||
595
+ this.environment.name !== 'ssr' ||
596
+ !isRunnable(this.environment)) {
597
+ return;
598
+ }
599
+ const serverModules = this.environment.moduleGraph.getModulesByFile(id);
600
+ if (serverModules !== undefined && serverModules.size > 0) {
601
+ if (isHotServerEnvironment(this.environment)) {
602
+ serverUpdates.beginUpdate();
603
+ }
604
+ invalidateServerModulesForReevaluation(this.environment);
605
+ }
606
+ },
607
+ // NOTE: Vite invalidates the server entry when a module it imports
608
+ // dynamically changes, even when the runner has not loaded that module,
609
+ // but sends the runner no update for it. The next request would then
610
+ // evaluate a new copy without disposing the old one, so the update goes to
611
+ // the entry instead.
612
+ hotUpdate({ type, file, modules }) {
613
+ if (!isDevelopmentHost ||
614
+ type !== 'update' ||
615
+ !isHotServerEnvironment(this.environment) ||
616
+ Array.isArrayEmpty(modules)) {
617
+ return undefined;
618
+ }
619
+ const entryId = entryIds.get(this.environment);
620
+ const evaluatedModules = this.environment.runner.evaluatedModules.getModulesByFile(file);
621
+ if (entryId === undefined ||
622
+ (evaluatedModules !== undefined && evaluatedModules.size > 0)) {
623
+ return undefined;
624
+ }
625
+ const entryModule = this.environment.moduleGraph.getModuleById(entryId);
626
+ return entryModule === undefined ? undefined : [entryModule];
627
+ },
628
+ async transform(code, id) {
629
+ if (!isDevelopmentHost ||
630
+ this.environment.name !== 'ssr' ||
631
+ !isRunnable(this.environment)) {
632
+ return undefined;
633
+ }
634
+ const entryId = entryIds.get(this.environment) ??
635
+ (await this.resolve(options.serverEntry).catch(() => undefined))?.id;
636
+ if (entryId === undefined) {
637
+ return undefined;
638
+ }
639
+ entryIds.set(this.environment, entryId);
640
+ if (entryId !== id) {
641
+ return undefined;
642
+ }
643
+ const transformed = new MagicString(code);
644
+ transformed.prepend(SERVER_ENTRY_HOT_SOURCE);
645
+ return {
646
+ code: transformed.toString(),
647
+ map: transformed.generateMap({ hires: 'boundary', source: id }),
648
+ };
649
+ },
521
650
  configureServer: server => {
522
651
  // Rendering here loads the server entry through the `ssr` environment's
523
652
  // module runner, which only a runnable environment has. A host plugin
@@ -528,7 +657,8 @@ export const foldkitSsr = (options) => {
528
657
  // them here instead would run the application in Node, without the
529
658
  // bindings the deployed entry holds, while the deployment it is standing
530
659
  // in for renders in workerd.
531
- if (!isRunnable(server.environments.ssr)) {
660
+ const ssrEnvironment = server.environments.ssr;
661
+ if (!isRunnable(ssrEnvironment)) {
532
662
  if (options.quietStandDown !== true) {
533
663
  server.config.logger.warn('[foldkit] the "ssr" environment is not runnable, so another plugin owns' +
534
664
  " server-side execution. Dev-time rendering through Foldkit's Vite" +
@@ -538,12 +668,22 @@ export const foldkitSsr = (options) => {
538
668
  }
539
669
  const requestUrls = new WeakMap();
540
670
  const stateByRequest = new WeakMap();
541
- const render = renderMiddleware(server, options, requestUrls, stateByRequest);
671
+ ssrEnvironment.hot.on(SERVER_UPDATE_SETTLED_EVENT, serverUpdates.settleUpdate);
672
+ const render = renderMiddleware(server, ssrEnvironment, serverUpdates, options, requestUrls, stateByRequest);
542
673
  server.middlewares.use(requestTargetMiddleware(server, options, requestUrls, render));
543
674
  wrapViteCors(server, options, requestUrls, stateByRequest);
544
675
  return () => {
545
676
  server.middlewares.use(render);
546
677
  };
547
678
  },
679
+ closeBundle() {
680
+ if (!isDevelopmentHost ||
681
+ this.environment.name !== 'ssr' ||
682
+ !isRunnable(this.environment)) {
683
+ return;
684
+ }
685
+ this.environment.hot.off(SERVER_UPDATE_SETTLED_EVENT, serverUpdates.settleUpdate);
686
+ serverUpdates.close();
687
+ },
548
688
  };
549
689
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldkit/vite-plugin",
3
- "version": "0.28.0-canary.82ac2ec6c9b5",
3
+ "version": "0.28.0-canary.90746b32d2ca",
4
4
  "description": "Vite plugin for Foldkit with state-preserving live reload",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -16,8 +16,8 @@
16
16
  "dist"
17
17
  ],
18
18
  "peerDependencies": {
19
- "effect": "4.0.0",
20
- "foldkit": "0.169.0-canary.82ac2ec6c9b5",
19
+ "effect": "4.0.0 || 4.0.6",
20
+ "foldkit": "0.169.0-canary.90746b32d2ca",
21
21
  "vite": "^8.0.0"
22
22
  },
23
23
  "dependencies": {
@@ -32,7 +32,7 @@
32
32
  "@types/ws": "^8.18.1",
33
33
  "@vitejs/plugin-basic-ssl": "^2.3.0",
34
34
  "effect": "4.0.0",
35
- "foldkit": "0.169.0-canary.82ac2ec6c9b5",
35
+ "foldkit": "0.169.0-canary.90746b32d2ca",
36
36
  "happy-dom": "^20.14.5",
37
37
  "rimraf": "^6.1.3",
38
38
  "typescript": "7.1.0-beta",