@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.
package/dist/index.cjs CHANGED
@@ -37,6 +37,7 @@ let node_fs_promises = require("node:fs/promises");
37
37
  let node_os = require("node:os");
38
38
  let node_util = require("node:util");
39
39
  let node_zlib = require("node:zlib");
40
+ let node_http = require("node:http");
40
41
 
41
42
  //#region packages/vite/src/utils.ts
42
43
  const PLUGIN_NAME = "moost-vite";
@@ -69,12 +70,13 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
69
70
  }
70
71
  return render(url, ctx);
71
72
  }
73
+ /** A CSP nonce: base64 / base64url characters, optional `=` padding. */ const NONCE_RE = /^[\w+/-]+={0,2}$/;
72
74
  /**
73
75
  * Applies an SSR render result to the HTTP response: sets the status code and
74
- * headers, then substitutes the outlet, state and head markers into the HTML
75
- * template. Shared by all three render call sites (the dev middleware, the dev
76
- * `createSSRServer` branch and the prod `createSSRServer` branch) so the render
77
- * contract stays identical across them.
76
+ * headers, then fills the outlet, state and head markers and the CSP nonce
77
+ * into the template. Shared by all three render call sites (the dev middleware,
78
+ * the dev `createSSRServer` branch and the prod `createSSRServer` branch) so the
79
+ * render contract stays identical across them.
78
80
  *
79
81
  * Fully backwards compatible: every field beyond `html` is optional, a missing
80
82
  * marker in the template is a no-op `String.replace`, and headers from the render
@@ -83,11 +85,15 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
83
85
  * rendered payloads (JSON state, JSON-LD `<head>` tags) are inserted literally
84
86
  * rather than interpreted as `String.replace` special patterns.
85
87
  */ function sendSSRResponse(res, template, markers, result) {
88
+ const { nonce } = result;
89
+ 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 =)");
86
90
  res.statusCode = result.status ?? 200;
87
91
  res.setHeader("Content-Type", "text/html");
88
- if (result.headers) for (const [key, value] of Object.entries(result.headers)) res.setHeader(key, value);
89
- const stateScript = result.state ? `<script>window.__SSR_STATE__=${result.state}<\/script>` : "";
90
- res.end(template.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
92
+ for (const [key, value] of Object.entries(result.headers ?? {})) res.setHeader(key, value);
93
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
94
+ const stateScript = result.state ? `<script${nonceAttr}>window.__SSR_STATE__=${result.state}<\/script>` : "";
95
+ const page = nonce && markers.cspNonce ? template.split(`nonce="${markers.cspNonce}"`).join(`nonce="${nonce}"`) : template;
96
+ res.end(page.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
91
97
  }
92
98
  function entryBasename(entry) {
93
99
  return entry.split("/").pop().replace(/\.ts$/, ".js");
@@ -856,6 +862,59 @@ const DEFAULT_PRECOMPRESS_INCLUDE = /\.(?:m?js|cjs|css|html?|svg|json|webmanifes
856
862
  }
857
863
  }
858
864
 
865
+ //#endregion
866
+ //#region packages/vite/src/dev-ssr.ts
867
+ /**
868
+ * The dev server's SSR page fallback (registered after Vite's own middlewares): renders GET
869
+ * requests nobody answered with the SSR entry, through Vite's `transformIndexHtml`.
870
+ */ function devSSRFallback(server, options) {
871
+ return async (req, res, next) => {
872
+ if (req.method !== "GET") {
873
+ next();
874
+ return;
875
+ }
876
+ const url = req.originalUrl || req.url || "/";
877
+ try {
878
+ if (await options.gate?.(res)) return;
879
+ const source = await (0, node_fs_promises.readFile)((0, node_path.resolve)(server.config.root, "index.html"), "utf8");
880
+ const template = await server.transformIndexHtml(url, source);
881
+ const { render } = await server.ssrLoadModule(options.ssrEntry);
882
+ const result = await renderSSRPage({
883
+ render,
884
+ url,
885
+ req,
886
+ res,
887
+ http: options.http()
888
+ });
889
+ const cspNonce = server.config.html?.cspNonce;
890
+ sendSSRResponse(res, template, {
891
+ ...options.markers,
892
+ cspNonce
893
+ }, result);
894
+ } catch (error) {
895
+ if (error instanceof Error) server.ssrFixStacktrace(error);
896
+ console.error(error);
897
+ res.statusCode = 500;
898
+ res.end(error?.message);
899
+ }
900
+ };
901
+ }
902
+
903
+ //#endregion
904
+ //#region packages/vite/src/server-middleware.ts
905
+ /** Name of the dev-server plugin `createSSRServer()` adds for its headers, middlewares and SSR. */ const SERVER_PLUGIN_NAME = `${PLUGIN_NAME}:server`;
906
+ /** Throws, naming the header, when a name or value could not be sent. */ function validateHeaders(headers, from) {
907
+ for (const [name, value] of Object.entries(headers ?? {})) try {
908
+ (0, node_http.validateHeaderName)(name);
909
+ (0, node_http.validateHeaderValue)(name, value);
910
+ } catch (error) {
911
+ throw new TypeError(`[${PLUGIN_NAME}] ${from}: invalid header ${JSON.stringify(name)} — ${error.message}`, { cause: error });
912
+ }
913
+ }
914
+ /** Sets each of `headers` on the response (later `setHeader` calls still replace them). */ function setResponseHeaders(res, headers) {
915
+ for (const [name, value] of Object.entries(headers ?? {})) res.setHeader(name, value);
916
+ }
917
+
859
918
  //#endregion
860
919
  //#region packages/vite/src/moost-vite.ts
861
920
  /**
@@ -912,6 +971,8 @@ function moostVite(options) {
912
971
  const isTest = process.env.NODE_ENV === "test";
913
972
  const isProd = process.env.NODE_ENV === "production";
914
973
  const externals = options.externals ?? true;
974
+ validateHeaders(options.headers, "moostVite({ headers })");
975
+ /** The `headers` option: middleware mode only (backend mode: see the warning in configResolved). */ const headers = options.middleware ? options.headers : void 0;
915
976
  const prefixes = normalizePrefixes(options.prefix);
916
977
  let moostMiddleware = null;
917
978
  let localFetchTeardown = null;
@@ -1072,6 +1133,19 @@ function moostVite(options) {
1072
1133
  res.setHeader("Content-Type", "text/plain");
1073
1134
  res.end(`Moost app failed to load: ${bootError.message}`);
1074
1135
  };
1136
+ /**
1137
+ * Runs before each dev SSR render (whichever fallback renders: this plugin's or the
1138
+ * `createSSRServer()` one): the reload lock — an HMR mid-render would otherwise race
1139
+ * ssrLoadModule against a half-ejected app — and the boot-error gate, since the local-fetch
1140
+ * hook listen() installed would dispatch SSR self-fetches into a half-bound app.
1141
+ */ const ssrGate = async (res) => {
1142
+ await drainReload();
1143
+ if (bootError) {
1144
+ answerBootError(res);
1145
+ return true;
1146
+ }
1147
+ return false;
1148
+ };
1075
1149
  /** Set by the middleware-mode `config` hook: the consumer externalized the runtime themselves. */ let runtimeExternalized = false;
1076
1150
  let resolvedConfig;
1077
1151
  const pluginConfig = {
@@ -1092,7 +1166,9 @@ function moostVite(options) {
1092
1166
  __MOOST_SSR_STATE__: JSON.stringify(ssrState),
1093
1167
  __MOOST_SSR_HEAD__: JSON.stringify(ssrHead),
1094
1168
  __MOOST_PRECOMPRESS__: JSON.stringify(precompressedVariants),
1095
- __MOOST_CACHE_CONTROL__: JSON.stringify(bakedCacheControl(cfg))
1169
+ __MOOST_CACHE_CONTROL__: JSON.stringify(bakedCacheControl(cfg)),
1170
+ __MOOST_HEADERS__: JSON.stringify(options.headers ?? null),
1171
+ __MOOST_CSP_NONCE__: JSON.stringify(cfg.html?.cspNonce ?? null)
1096
1172
  };
1097
1173
  const ssrInput = {
1098
1174
  server: options.serverEntry || generatedServerEntry(cfg.root),
@@ -1199,10 +1275,13 @@ function moostVite(options) {
1199
1275
  ssrOutlet: options.ssrOutlet,
1200
1276
  ssrState: options.ssrState,
1201
1277
  ssrHead: options.ssrHead,
1202
- ssrFetchForwarding: options.ssrFetchForwarding
1278
+ ssrFetchForwarding: options.ssrFetchForwarding,
1279
+ headers
1203
1280
  };
1204
1281
  config.__moostViteHttpRef = moostHttpRef;
1282
+ config.__moostViteSsrGate = ssrGate;
1205
1283
  resolvedConfig = config;
1284
+ if (options.headers && !options.middleware) config.logger.warn(`[${PLUGIN_NAME}] The \`headers\` option applies in middleware mode only and is ignored: in backend mode Moost answers every request itself, in dev and in production — set the headers with \`new MoostHttp({ defaultHeaders })\` instead.`);
1206
1285
  },
1207
1286
  generateBundle(_outputOptions, bundle) {
1208
1287
  const cfg = resolvedConfig;
@@ -1345,45 +1424,42 @@ function moostVite(options) {
1345
1424
  delete pluginConfig.transform;
1346
1425
  delete pluginConfig.hotUpdate;
1347
1426
  }
1348
- return [pluginConfig, !isProd && !isTest && options.middleware && options.ssrEntry ? {
1349
- name: `${PLUGIN_NAME}:ssr-fallback`,
1350
- async configureServer(server) {
1351
- const fs = await import("node:fs/promises");
1352
- return () => {
1353
- server.middlewares.use(async (req, res, next) => {
1354
- if (req.method !== "GET") return next();
1355
- const url = req.originalUrl || req.url || "/";
1356
- try {
1357
- await drainReload();
1358
- if (bootError) {
1359
- answerBootError(res);
1360
- return;
1361
- }
1362
- let template = await fs.readFile((0, node_path.resolve)(server.config.root, "index.html"), "utf8");
1363
- template = await server.transformIndexHtml(url, template);
1364
- const { render } = await server.ssrLoadModule(options.ssrEntry);
1365
- const result = await renderSSRPage({
1366
- render,
1367
- url,
1368
- req,
1369
- res,
1370
- http: ssrForwarding ? moostHttpRef.current : null
1371
- });
1372
- sendSSRResponse(res, template, {
1373
- ssrOutlet,
1374
- ssrState,
1375
- ssrHead
1376
- }, result);
1377
- } catch (error) {
1378
- server.ssrFixStacktrace(error);
1379
- console.error(error);
1380
- res.statusCode = 500;
1381
- res.end(error.message);
1382
- }
1427
+ return [
1428
+ pluginConfig,
1429
+ !isProd && !isTest && options.middleware && options.ssrEntry ? {
1430
+ name: `${PLUGIN_NAME}:ssr-fallback`,
1431
+ configureServer(server) {
1432
+ if (server.config.plugins.some((p) => p.name === SERVER_PLUGIN_NAME)) return;
1433
+ const fallback = devSSRFallback(server, {
1434
+ ssrEntry: options.ssrEntry,
1435
+ markers: {
1436
+ ssrOutlet,
1437
+ ssrState,
1438
+ ssrHead
1439
+ },
1440
+ http: () => ssrForwarding ? moostHttpRef.current : null,
1441
+ gate: ssrGate
1383
1442
  });
1384
- };
1385
- }
1386
- } : null];
1443
+ return () => {
1444
+ server.middlewares.use(fallback);
1445
+ };
1446
+ }
1447
+ } : null,
1448
+ !isProd && !isTest && headers ? {
1449
+ name: `${PLUGIN_NAME}:headers`,
1450
+ enforce: "pre",
1451
+ configureServer: {
1452
+ order: "pre",
1453
+ handler(server) {
1454
+ if (server.config.plugins.some((p) => p.name === SERVER_PLUGIN_NAME)) return;
1455
+ server.middlewares.use((_req, res, next) => {
1456
+ setResponseHeaders(res, headers);
1457
+ next();
1458
+ });
1459
+ }
1460
+ }
1461
+ } : null
1462
+ ];
1387
1463
  }
1388
1464
 
1389
1465
  //#endregion
package/dist/index.d.ts CHANGED
@@ -303,6 +303,18 @@ interface TMoostViteDevOptions {
303
303
  * Default: `true`. Set `false` to send no `Cache-Control` from the server.
304
304
  */
305
305
  cacheControl?: boolean | TCacheControlOptions;
306
+ /**
307
+ * Middleware mode: headers set on every response the server sends — Moost
308
+ * routes, SSR pages, the SPA shell and static files — in dev and in the
309
+ * generated production server (e.g. `X-Frame-Options`,
310
+ * `X-Content-Type-Options`, `Referrer-Policy`). They are set first, so a
311
+ * `createSSRServer().use()` middleware, a route or the SSR render's `headers`
312
+ * replace them. A `Cache-Control` here replaces the built-in cache policy.
313
+ * `createSSRServer({ headers })` overrides the whole set. Invalid names or
314
+ * values throw at startup. Ignored, with a warning, in backend mode: Moost
315
+ * answers every request there — use the adapter's `defaultHeaders`.
316
+ */
317
+ headers?: Record<string, string>;
306
318
  }
307
319
  /** Extra packages the SSR split check should watch on top of its defaults. */
308
320
  interface TSSRExternalCheckOptions {
@@ -337,6 +349,15 @@ interface TSSRRenderResult {
337
349
  status?: number;
338
350
  /** Extra response headers — e.g. `cache-control`, or `location` alongside `status: 301`. */
339
351
  headers?: Record<string, string>;
352
+ /**
353
+ * A fresh CSP nonce for this response (base64 or base64url characters only; anything else
354
+ * fails the render). It is set on the `__SSR_STATE__` script and replaces the `html.cspNonce`
355
+ * placeholder (set in the Vite config itself) in the page template. Send the matching
356
+ * `Content-Security-Policy` in `headers`, and put it on your own `head` tags. Without a
357
+ * nonce — and in the SPA shell or any other static HTML — the placeholder ships unchanged:
358
+ * never put the placeholder in a CSP header.
359
+ */
360
+ nonce?: string;
340
361
  }
341
362
  /**
342
363
  * Context of the incoming page request, passed as the second argument to the