@moostjs/vite 0.7.7 → 0.7.9

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.
@@ -3,6 +3,7 @@ let node_events = require("node:events");
3
3
  let node_fs_promises = require("node:fs/promises");
4
4
  let node_path = require("node:path");
5
5
  let moost = require("moost");
6
+ let node_http = require("node:http");
6
7
 
7
8
  //#region packages/vite/src/prod-static.ts
8
9
  const DEFAULT_ASSETS_CACHE_CONTROL = "public, max-age=31536000, immutable";
@@ -188,12 +189,13 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
188
189
  }
189
190
  return render(url, ctx);
190
191
  }
192
+ /** A CSP nonce: base64 / base64url characters, optional `=` padding. */ const NONCE_RE = /^[\w+/-]+={0,2}$/;
191
193
  /**
192
194
  * Applies an SSR render result to the HTTP response: sets the status code and
193
- * headers, then substitutes the outlet, state and head markers into the HTML
194
- * template. Shared by all three render call sites (the dev middleware, the dev
195
- * `createSSRServer` branch and the prod `createSSRServer` branch) so the render
196
- * contract stays identical across them.
195
+ * headers, then fills the outlet, state and head markers and the CSP nonce
196
+ * into the template. Shared by all three render call sites (the dev middleware,
197
+ * the dev `createSSRServer` branch and the prod `createSSRServer` branch) so the
198
+ * render contract stays identical across them.
197
199
  *
198
200
  * Fully backwards compatible: every field beyond `html` is optional, a missing
199
201
  * marker in the template is a no-op `String.replace`, and headers from the render
@@ -202,11 +204,15 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
202
204
  * rendered payloads (JSON state, JSON-LD `<head>` tags) are inserted literally
203
205
  * rather than interpreted as `String.replace` special patterns.
204
206
  */ function sendSSRResponse(res, template, markers, result) {
207
+ const { nonce } = result;
208
+ if (nonce !== void 0 && (typeof nonce !== "string" || !NONCE_RE.test(nonce))) throw new TypeError("SSR render returned an invalid `nonce`: use base64 or base64url characters only (A-Z, a-z, 0-9, +, /, -, _, with optional trailing =)");
205
209
  res.statusCode = result.status ?? 200;
206
210
  res.setHeader("Content-Type", "text/html");
207
- if (result.headers) for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
208
- const stateScript = result.state ? `<script>window.__SSR_STATE__=${result.state}<\/script>` : "";
209
- res.end(template.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
211
+ for (const [key, value] of Object.entries(result.headers ?? {})) res.setHeader(key, value);
212
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
213
+ const stateScript = result.state ? `<script${nonceAttr}>window.__SSR_STATE__=${result.state}<\/script>` : "";
214
+ const page = nonce && markers.cspNonce ? template.split(`nonce="${markers.cspNonce}"`).join(`nonce="${nonce}"`) : template;
215
+ res.end(page.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
210
216
  }
211
217
  /**
212
218
  * Normalizes the `prefix` option (single mount or list of mounts) into a list of
@@ -235,6 +241,112 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
235
241
  }
236
242
  const logger = (0, moost.createLogger)({ level: 99 }).createTopic("\x1B[2m\x1B[36m" + PLUGIN_NAME);
237
243
 
244
+ //#endregion
245
+ //#region packages/vite/src/dev-ssr.ts
246
+ /**
247
+ * The dev server's SSR page fallback (registered after Vite's own middlewares): renders GET
248
+ * requests nobody answered with the SSR entry, through Vite's `transformIndexHtml`.
249
+ */ function devSSRFallback(server, options) {
250
+ return async (req, res, next) => {
251
+ if (req.method !== "GET") {
252
+ next();
253
+ return;
254
+ }
255
+ const url = req.originalUrl || req.url || "/";
256
+ try {
257
+ if (await options.gate?.(res)) return;
258
+ const source = await (0, node_fs_promises.readFile)((0, node_path.resolve)(server.config.root, "index.html"), "utf8");
259
+ const template = await server.transformIndexHtml(url, source);
260
+ const { render } = await server.ssrLoadModule(options.ssrEntry);
261
+ const result = await renderSSRPage({
262
+ render,
263
+ url,
264
+ req,
265
+ res,
266
+ http: options.http()
267
+ });
268
+ const cspNonce = server.config.html?.cspNonce;
269
+ sendSSRResponse(res, template, {
270
+ ...options.markers,
271
+ cspNonce
272
+ }, result);
273
+ } catch (error) {
274
+ if (error instanceof Error) server.ssrFixStacktrace(error);
275
+ console.error(error);
276
+ res.statusCode = 500;
277
+ res.end(error?.message);
278
+ }
279
+ };
280
+ }
281
+
282
+ //#endregion
283
+ //#region packages/vite/src/server-middleware.ts
284
+ /** Name of the dev-server plugin `createSSRServer()` adds for its headers, middlewares and SSR. */ const SERVER_PLUGIN_NAME = `${PLUGIN_NAME}:server`;
285
+ /** Throws, naming the header, when a name or value could not be sent. */ function validateHeaders(headers, from) {
286
+ for (const [name, value] of Object.entries(headers ?? {})) try {
287
+ (0, node_http.validateHeaderName)(name);
288
+ (0, node_http.validateHeaderValue)(name, value);
289
+ } catch (error) {
290
+ throw new TypeError(`[${PLUGIN_NAME}] ${from}: invalid header ${JSON.stringify(name)} — ${error.message}`, { cause: error });
291
+ }
292
+ }
293
+ /** Sets each of `headers` on the response (later `setHeader` calls still replace them). */ function setResponseHeaders(res, headers) {
294
+ for (const [name, value] of Object.entries(headers ?? {})) res.setHeader(name, value);
295
+ }
296
+ /** Rejects an error-handling `(err, req, res, next)` middleware: it would run as a normal one. */ function assertMiddleware(middleware) {
297
+ if (typeof middleware !== "function" || middleware.length >= 4) throw new TypeError(`[${PLUGIN_NAME}] createSSRServer().use() takes a (req, res, next) middleware; error-handling (err, req, res, next) middleware is not supported`);
298
+ }
299
+ /**
300
+ * Runs `middlewares` in order, then `done()` — unless one of them answers without calling
301
+ * `next`. A middleware that calls `next(error)`, throws, or returns a rejected promise before
302
+ * calling `next` stops the chain: `done(error)`.
303
+ */ function runMiddlewares(middlewares, req, res, done) {
304
+ let i = 0;
305
+ const runNext = () => {
306
+ const middleware = middlewares[i++];
307
+ if (!middleware) {
308
+ done();
309
+ return;
310
+ }
311
+ let passed = false;
312
+ const next = (error) => {
313
+ if (passed) return;
314
+ passed = true;
315
+ if (error === void 0 || error === null) runNext();
316
+ else done(error || /* @__PURE__ */ new Error(`A use() middleware failed with ${String(error)}`));
317
+ };
318
+ const fail = (error) => next(error ?? /* @__PURE__ */ new Error(`A use() middleware failed with ${String(error)}`));
319
+ let result;
320
+ try {
321
+ result = middleware(req, res, next);
322
+ } catch (error) {
323
+ if (passed) throw error;
324
+ fail(error);
325
+ return;
326
+ }
327
+ if (typeof result?.then === "function") result.then(void 0, (error) => {
328
+ if (passed) console.error(error);
329
+ else fail(error);
330
+ });
331
+ };
332
+ runNext();
333
+ }
334
+ /** The status of a failed request: the error's `status` / `statusCode` (400–599), else `500`. */ function errorStatus(error) {
335
+ const { status, statusCode } = error ?? {};
336
+ const code = status ?? statusCode;
337
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599 ? code : 500;
338
+ }
339
+ /** Answers a request a middleware failed: logs the error, sends its status, never its message. */ function failRequest(res, error) {
340
+ console.error(error);
341
+ if (res.writableEnded) return;
342
+ if (res.headersSent) {
343
+ res.destroy();
344
+ return;
345
+ }
346
+ res.statusCode = errorStatus(error);
347
+ res.end();
348
+ }
349
+
238
350
  //#endregion
239
351
  //#region packages/vite/src/prod-server.ts
240
352
  /** URL of the address the server actually bound (wildcard binds print as localhost). */ function serverUrl(server) {
@@ -248,58 +360,52 @@ function stripUndefined(obj) {
248
360
  async function createSSRServer(options) {
249
361
  const userMiddlewares = [];
250
362
  const opts = options ? stripUndefined(options) : {};
363
+ validateHeaders(opts.headers, "createSSRServer({ headers })");
364
+ const use = (middleware) => {
365
+ assertMiddleware(middleware);
366
+ userMiddlewares.push(middleware);
367
+ };
251
368
  if (!(process.env.MOOST_DEFERRED_ENV === "production")) {
252
369
  const { createServer: createViteServer } = await import("vite");
253
- const vite = await createViteServer();
254
- const config = {
255
- ...vite.config.__moostViteOptions || {},
256
- ...opts
257
- };
258
- const ssrEntry = config.ssrEntry;
259
- const ssrOutlet = config.ssrOutlet || DEFAULT_SSR_OUTLET;
260
- const ssrState = config.ssrState || DEFAULT_SSR_STATE;
261
- const ssrHead = config.ssrHead || DEFAULT_SSR_HEAD;
262
- const ssrForwarding = config.ssrFetchForwarding !== false;
263
- const httpRef = vite.config.__moostViteHttpRef;
264
- let ssrFallback = null;
265
- if (ssrEntry) {
266
- const fs = await import("node:fs/promises");
267
- const path = await import("node:path");
268
- ssrFallback = async (req, res, next) => {
269
- if (req.method !== "GET") return next();
270
- const url = req.originalUrl || req.url || "/";
271
- try {
272
- let template = await fs.readFile(path.resolve(vite.config.root, "index.html"), "utf8");
273
- template = await vite.transformIndexHtml(url, template);
274
- const { render } = await vite.ssrLoadModule(ssrEntry);
275
- const result = await renderSSRPage({
276
- render,
277
- url,
278
- req,
279
- res,
280
- http: ssrForwarding ? httpRef?.current : null
370
+ const vite = await createViteServer({ plugins: [{
371
+ name: SERVER_PLUGIN_NAME,
372
+ configureServer: {
373
+ order: "pre",
374
+ handler(server) {
375
+ const exposed = server.config;
376
+ const config = {
377
+ ...exposed.__moostViteOptions,
378
+ ...opts
379
+ };
380
+ const headers = config.headers;
381
+ server.middlewares.use((req, res, next) => {
382
+ setResponseHeaders(res, headers);
383
+ runMiddlewares(userMiddlewares, req, res, next);
384
+ });
385
+ const ssrEntry = config.ssrEntry;
386
+ if (!ssrEntry) return;
387
+ const httpRef = exposed.__moostViteHttpRef;
388
+ const forwarding = config.ssrFetchForwarding !== false;
389
+ const fallback = devSSRFallback(server, {
390
+ ssrEntry,
391
+ markers: {
392
+ ssrOutlet: config.ssrOutlet || DEFAULT_SSR_OUTLET,
393
+ ssrState: config.ssrState || DEFAULT_SSR_STATE,
394
+ ssrHead: config.ssrHead || DEFAULT_SSR_HEAD
395
+ },
396
+ http: () => forwarding ? httpRef?.current : null,
397
+ gate: exposed.__moostViteSsrGate
281
398
  });
282
- sendSSRResponse(res, template, {
283
- ssrOutlet,
284
- ssrState,
285
- ssrHead
286
- }, result);
287
- } catch (error) {
288
- vite.ssrFixStacktrace(error);
289
- console.error(error);
290
- res.statusCode = 500;
291
- res.end(error.message);
399
+ return () => {
400
+ server.middlewares.use(fallback);
401
+ };
292
402
  }
293
- };
294
- }
403
+ }
404
+ }] });
295
405
  return {
296
- use(mw) {
297
- userMiddlewares.push(mw);
298
- },
406
+ use,
299
407
  async listen(port, host) {
300
408
  if ((port ?? host ?? opts.port ?? opts.host) !== void 0) console.warn("[moost-vite] port/host passed to createSSRServer() or listen() are ignored in dev — set server.port / server.host in vite.config instead.");
301
- for (const mw of userMiddlewares) vite.middlewares.use(mw);
302
- if (ssrFallback) vite.middlewares.use(ssrFallback);
303
409
  await vite.listen();
304
410
  vite.printUrls();
305
411
  return vite.httpServer;
@@ -320,6 +426,8 @@ async function createSSRServer(options) {
320
426
  const cache = resolveCacheControl(__MOOST_CACHE_CONTROL__, opts.cacheControl);
321
427
  const defaultPort = opts.port || Number(process.env.PORT) || 3e3;
322
428
  const defaultHost = opts.host ?? process.env.HOST;
429
+ const headers = opts.headers ?? __MOOST_HEADERS__;
430
+ const cspNonce = __MOOST_CSP_NONCE__ ?? void 0;
323
431
  const template = await fs.readFile(path.resolve(clientDir, "index.html"), "utf8");
324
432
  let render = null;
325
433
  if (__MOOST_SSR_ENTRY__ !== void 0 && !!__MOOST_SSR_ENTRY__) render = (await import(
@@ -375,7 +483,8 @@ async function createSSRServer(options) {
375
483
  sendSSRResponse(res, template, {
376
484
  ssrOutlet,
377
485
  ssrState,
378
- ssrHead
486
+ ssrHead,
487
+ cspNonce
379
488
  }, result);
380
489
  } else sendSpaShell(req, res, spaShell, cache);
381
490
  } catch (error) {
@@ -386,16 +495,14 @@ async function createSSRServer(options) {
386
495
  };
387
496
  const serveStatic = await createStaticHandler(path.resolve(clientDir), variants, cache, (req, res) => void servePage(req, res));
388
497
  return {
389
- use(mw) {
390
- userMiddlewares.push(mw);
391
- },
498
+ use,
392
499
  async listen(port, host) {
393
500
  const server = createHttpServer((req, res) => {
394
501
  const url = req.url || "/";
395
- let i = 0;
396
- const runNext = () => {
397
- if (i < userMiddlewares.length) {
398
- userMiddlewares[i++](req, res, runNext);
502
+ setResponseHeaders(res, headers);
503
+ runMiddlewares(userMiddlewares, req, res, (error) => {
504
+ if (error) {
505
+ failRequest(res, error);
399
506
  return;
400
507
  }
401
508
  if (moostHandler && (!prefixes || matchesPrefix(url, prefixes))) {
@@ -403,8 +510,7 @@ async function createSSRServer(options) {
403
510
  return;
404
511
  }
405
512
  serveStatic(req, res);
406
- };
407
- runNext();
513
+ });
408
514
  });
409
515
  server.listen(port || defaultPort, host || defaultHost);
410
516
  await (0, node_events.once)(server, "listening");
@@ -1,5 +1,5 @@
1
- import { IncomingMessage, ServerResponse } from 'node:http';
2
1
  import { Server } from 'node:net';
2
+ import { IncomingMessage, ServerResponse } from 'node:http';
3
3
 
4
4
  /**
5
5
  * `Cache-Control` policy of the generated production server. Each value is a
@@ -37,6 +37,12 @@ interface TPrecompressedOptions {
37
37
  gzip?: boolean;
38
38
  }
39
39
 
40
+ /**
41
+ * Connect-style middleware, as `createSSRServer().use()` takes it. Call `next()` to continue,
42
+ * `next(error)` to fail the request.
43
+ */
44
+ type TConnectMiddleware = (req: IncomingMessage, res: ServerResponse, next: (error?: unknown) => void) => void;
45
+
40
46
  /**
41
47
  * The value an SSR `render(url)` function may return. Only `html` is required;
42
48
  * every other field is optional, so a render returning `{ html }` (or
@@ -60,6 +66,15 @@ interface TSSRRenderResult {
60
66
  status?: number;
61
67
  /** Extra response headers — e.g. `cache-control`, or `location` alongside `status: 301`. */
62
68
  headers?: Record<string, string>;
69
+ /**
70
+ * A fresh CSP nonce for this response (base64 or base64url characters only; anything else
71
+ * fails the render). It is set on the `__SSR_STATE__` script and replaces the `html.cspNonce`
72
+ * placeholder (set in the Vite config itself) in the page template. Send the matching
73
+ * `Content-Security-Policy` in `headers`, and put it on your own `head` tags. Without a
74
+ * nonce — and in the SPA shell or any other static HTML — the placeholder ships unchanged:
75
+ * never put the placeholder in a CSP header.
76
+ */
77
+ nonce?: string;
63
78
  }
64
79
  /**
65
80
  * Context of the incoming page request, passed as the second argument to the
@@ -76,7 +91,6 @@ interface TSSRRenderContext {
76
91
  /** The SSR entry contract: `render(url, ctx?)`. `ctx` is new and optional. */
77
92
  type TSSRRender = (url: string, ctx?: TSSRRenderContext) => Promise<TSSRRenderResult> | TSSRRenderResult;
78
93
 
79
- type TMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
80
94
  interface TSSRServerOptions {
81
95
  /** Override: lazy import for the Moost app entry. */
82
96
  entry?: (() => Promise<unknown>) | string;
@@ -136,10 +150,26 @@ interface TSSRServerOptions {
136
150
  * Default: baked from the plugin's `cacheControl` option (on).
137
151
  */
138
152
  cacheControl?: boolean | TCacheControlOptions;
153
+ /**
154
+ * Override: headers set on every response the server sends — Moost routes,
155
+ * SSR pages, the SPA shell and static files — in dev and production. They are
156
+ * set first, so a `use()` middleware, a route or the SSR render's `headers`
157
+ * replace them. Replaces the plugin's `headers` option entirely. Invalid names
158
+ * or values throw at startup.
159
+ */
160
+ headers?: Record<string, string>;
139
161
  }
140
162
  interface TSSRServer {
141
- /** Add Connect-compatible middleware (runs in both dev and prod) */
142
- use(middleware: TMiddleware): void;
163
+ /**
164
+ * Add Connect-style `(req, res, next)` middleware. Middlewares run in order, after the
165
+ * `headers` option and before Moost routes, static files and the SPA/SSR page — in dev
166
+ * also before Vite's module and file serving (only Vite's own request checks, host
167
+ * validation and CORS handling run earlier). `next(error)`, a throw or a rejected promise
168
+ * fails the request (dev: Vite's error page; production: the error's `status` /
169
+ * `statusCode`, else `500`, with an empty body). Error-handling `(err, req, res, next)`
170
+ * middleware is not supported and throws.
171
+ */
172
+ use(middleware: TConnectMiddleware): void;
143
173
  /**
144
174
  * Start the server; resolves with the bound server (for `address()` / `close()`)
145
175
  * and rejects on a bind error (`EADDRINUSE`, `EACCES`, bad host).