@moostjs/vite 0.7.6 → 0.7.8
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 +123 -47
- package/dist/index.d.ts +21 -0
- package/dist/index.mjs +361 -285
- package/dist/prod-server.cjs +168 -62
- package/dist/prod-server.d.ts +34 -4
- package/dist/prod-server.mjs +169 -63
- package/package.json +3 -3
package/dist/prod-server.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { once } from "node:events";
|
|
2
2
|
import "node:fs";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
|
-
import { join } from "node:path";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
5
|
import "node:module";
|
|
6
6
|
import { createLogger } from "moost";
|
|
7
|
+
import { validateHeaderName, validateHeaderValue } from "node:http";
|
|
7
8
|
|
|
8
9
|
//#region packages/vite/src/prod-static.ts
|
|
9
10
|
const DEFAULT_ASSETS_CACHE_CONTROL = "public, max-age=31536000, immutable";
|
|
@@ -189,12 +190,13 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
|
|
|
189
190
|
}
|
|
190
191
|
return render(url, ctx);
|
|
191
192
|
}
|
|
193
|
+
/** A CSP nonce: base64 / base64url characters, optional `=` padding. */ const NONCE_RE = /^[\w+/-]+={0,2}$/;
|
|
192
194
|
/**
|
|
193
195
|
* Applies an SSR render result to the HTTP response: sets the status code and
|
|
194
|
-
* headers, then
|
|
195
|
-
* template. Shared by all three render call sites (the dev middleware,
|
|
196
|
-
* `createSSRServer` branch and the prod `createSSRServer` branch) so the
|
|
197
|
-
* contract stays identical across them.
|
|
196
|
+
* headers, then fills the outlet, state and head markers and the CSP nonce
|
|
197
|
+
* into the template. Shared by all three render call sites (the dev middleware,
|
|
198
|
+
* the dev `createSSRServer` branch and the prod `createSSRServer` branch) so the
|
|
199
|
+
* render contract stays identical across them.
|
|
198
200
|
*
|
|
199
201
|
* Fully backwards compatible: every field beyond `html` is optional, a missing
|
|
200
202
|
* marker in the template is a no-op `String.replace`, and headers from the render
|
|
@@ -203,11 +205,15 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
|
|
|
203
205
|
* rendered payloads (JSON state, JSON-LD `<head>` tags) are inserted literally
|
|
204
206
|
* rather than interpreted as `String.replace` special patterns.
|
|
205
207
|
*/ function sendSSRResponse(res, template, markers, result) {
|
|
208
|
+
const { nonce } = result;
|
|
209
|
+
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 =)");
|
|
206
210
|
res.statusCode = result.status ?? 200;
|
|
207
211
|
res.setHeader("Content-Type", "text/html");
|
|
208
|
-
|
|
209
|
-
const
|
|
210
|
-
|
|
212
|
+
for (const [key, value] of Object.entries(result.headers ?? {})) res.setHeader(key, value);
|
|
213
|
+
const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
|
|
214
|
+
const stateScript = result.state ? `<script${nonceAttr}>window.__SSR_STATE__=${result.state}<\/script>` : "";
|
|
215
|
+
const page = nonce && markers.cspNonce ? template.split(`nonce="${markers.cspNonce}"`).join(`nonce="${nonce}"`) : template;
|
|
216
|
+
res.end(page.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
|
|
211
217
|
}
|
|
212
218
|
/**
|
|
213
219
|
* Normalizes the `prefix` option (single mount or list of mounts) into a list of
|
|
@@ -236,6 +242,112 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
|
|
|
236
242
|
}
|
|
237
243
|
const logger = createLogger({ level: 99 }).createTopic("\x1B[2m\x1B[36m" + PLUGIN_NAME);
|
|
238
244
|
|
|
245
|
+
//#endregion
|
|
246
|
+
//#region packages/vite/src/dev-ssr.ts
|
|
247
|
+
/**
|
|
248
|
+
* The dev server's SSR page fallback (registered after Vite's own middlewares): renders GET
|
|
249
|
+
* requests nobody answered with the SSR entry, through Vite's `transformIndexHtml`.
|
|
250
|
+
*/ function devSSRFallback(server, options) {
|
|
251
|
+
return async (req, res, next) => {
|
|
252
|
+
if (req.method !== "GET") {
|
|
253
|
+
next();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const url = req.originalUrl || req.url || "/";
|
|
257
|
+
try {
|
|
258
|
+
if (await options.gate?.(res)) return;
|
|
259
|
+
const source = await readFile(resolve(server.config.root, "index.html"), "utf8");
|
|
260
|
+
const template = await server.transformIndexHtml(url, source);
|
|
261
|
+
const { render } = await server.ssrLoadModule(options.ssrEntry);
|
|
262
|
+
const result = await renderSSRPage({
|
|
263
|
+
render,
|
|
264
|
+
url,
|
|
265
|
+
req,
|
|
266
|
+
res,
|
|
267
|
+
http: options.http()
|
|
268
|
+
});
|
|
269
|
+
const cspNonce = server.config.html?.cspNonce;
|
|
270
|
+
sendSSRResponse(res, template, {
|
|
271
|
+
...options.markers,
|
|
272
|
+
cspNonce
|
|
273
|
+
}, result);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
if (error instanceof Error) server.ssrFixStacktrace(error);
|
|
276
|
+
console.error(error);
|
|
277
|
+
res.statusCode = 500;
|
|
278
|
+
res.end(error?.message);
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region packages/vite/src/server-middleware.ts
|
|
285
|
+
/** Name of the dev-server plugin `createSSRServer()` adds for its headers, middlewares and SSR. */ const SERVER_PLUGIN_NAME = `${PLUGIN_NAME}:server`;
|
|
286
|
+
/** Throws, naming the header, when a name or value could not be sent. */ function validateHeaders(headers, from) {
|
|
287
|
+
for (const [name, value] of Object.entries(headers ?? {})) try {
|
|
288
|
+
validateHeaderName(name);
|
|
289
|
+
validateHeaderValue(name, value);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
throw new TypeError(`[${PLUGIN_NAME}] ${from}: invalid header ${JSON.stringify(name)} — ${error.message}`, { cause: error });
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** Sets each of `headers` on the response (later `setHeader` calls still replace them). */ function setResponseHeaders(res, headers) {
|
|
295
|
+
for (const [name, value] of Object.entries(headers ?? {})) res.setHeader(name, value);
|
|
296
|
+
}
|
|
297
|
+
/** Rejects an error-handling `(err, req, res, next)` middleware: it would run as a normal one. */ function assertMiddleware(middleware) {
|
|
298
|
+
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`);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Runs `middlewares` in order, then `done()` — unless one of them answers without calling
|
|
302
|
+
* `next`. A middleware that calls `next(error)`, throws, or returns a rejected promise before
|
|
303
|
+
* calling `next` stops the chain: `done(error)`.
|
|
304
|
+
*/ function runMiddlewares(middlewares, req, res, done) {
|
|
305
|
+
let i = 0;
|
|
306
|
+
const runNext = () => {
|
|
307
|
+
const middleware = middlewares[i++];
|
|
308
|
+
if (!middleware) {
|
|
309
|
+
done();
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
let passed = false;
|
|
313
|
+
const next = (error) => {
|
|
314
|
+
if (passed) return;
|
|
315
|
+
passed = true;
|
|
316
|
+
if (error === void 0 || error === null) runNext();
|
|
317
|
+
else done(error || /* @__PURE__ */ new Error(`A use() middleware failed with ${String(error)}`));
|
|
318
|
+
};
|
|
319
|
+
const fail = (error) => next(error ?? /* @__PURE__ */ new Error(`A use() middleware failed with ${String(error)}`));
|
|
320
|
+
let result;
|
|
321
|
+
try {
|
|
322
|
+
result = middleware(req, res, next);
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (passed) throw error;
|
|
325
|
+
fail(error);
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (typeof result?.then === "function") result.then(void 0, (error) => {
|
|
329
|
+
if (passed) console.error(error);
|
|
330
|
+
else fail(error);
|
|
331
|
+
});
|
|
332
|
+
};
|
|
333
|
+
runNext();
|
|
334
|
+
}
|
|
335
|
+
/** The status of a failed request: the error's `status` / `statusCode` (400–599), else `500`. */ function errorStatus(error) {
|
|
336
|
+
const { status, statusCode } = error ?? {};
|
|
337
|
+
const code = status ?? statusCode;
|
|
338
|
+
return typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599 ? code : 500;
|
|
339
|
+
}
|
|
340
|
+
/** Answers a request a middleware failed: logs the error, sends its status, never its message. */ function failRequest(res, error) {
|
|
341
|
+
console.error(error);
|
|
342
|
+
if (res.writableEnded) return;
|
|
343
|
+
if (res.headersSent) {
|
|
344
|
+
res.destroy();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
res.statusCode = errorStatus(error);
|
|
348
|
+
res.end();
|
|
349
|
+
}
|
|
350
|
+
|
|
239
351
|
//#endregion
|
|
240
352
|
//#region packages/vite/src/prod-server.ts
|
|
241
353
|
/** URL of the address the server actually bound (wildcard binds print as localhost). */ function serverUrl(server) {
|
|
@@ -249,58 +361,52 @@ function stripUndefined(obj) {
|
|
|
249
361
|
async function createSSRServer(options) {
|
|
250
362
|
const userMiddlewares = [];
|
|
251
363
|
const opts = options ? stripUndefined(options) : {};
|
|
364
|
+
validateHeaders(opts.headers, "createSSRServer({ headers })");
|
|
365
|
+
const use = (middleware) => {
|
|
366
|
+
assertMiddleware(middleware);
|
|
367
|
+
userMiddlewares.push(middleware);
|
|
368
|
+
};
|
|
252
369
|
if (!(process.env.MOOST_DEFERRED_ENV === "production")) {
|
|
253
370
|
const { createServer: createViteServer } = await import("vite");
|
|
254
|
-
const vite = await createViteServer(
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
371
|
+
const vite = await createViteServer({ plugins: [{
|
|
372
|
+
name: SERVER_PLUGIN_NAME,
|
|
373
|
+
configureServer: {
|
|
374
|
+
order: "pre",
|
|
375
|
+
handler(server) {
|
|
376
|
+
const exposed = server.config;
|
|
377
|
+
const config = {
|
|
378
|
+
...exposed.__moostViteOptions,
|
|
379
|
+
...opts
|
|
380
|
+
};
|
|
381
|
+
const headers = config.headers;
|
|
382
|
+
server.middlewares.use((req, res, next) => {
|
|
383
|
+
setResponseHeaders(res, headers);
|
|
384
|
+
runMiddlewares(userMiddlewares, req, res, next);
|
|
385
|
+
});
|
|
386
|
+
const ssrEntry = config.ssrEntry;
|
|
387
|
+
if (!ssrEntry) return;
|
|
388
|
+
const httpRef = exposed.__moostViteHttpRef;
|
|
389
|
+
const forwarding = config.ssrFetchForwarding !== false;
|
|
390
|
+
const fallback = devSSRFallback(server, {
|
|
391
|
+
ssrEntry,
|
|
392
|
+
markers: {
|
|
393
|
+
ssrOutlet: config.ssrOutlet || DEFAULT_SSR_OUTLET,
|
|
394
|
+
ssrState: config.ssrState || DEFAULT_SSR_STATE,
|
|
395
|
+
ssrHead: config.ssrHead || DEFAULT_SSR_HEAD
|
|
396
|
+
},
|
|
397
|
+
http: () => forwarding ? httpRef?.current : null,
|
|
398
|
+
gate: exposed.__moostViteSsrGate
|
|
282
399
|
});
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
ssrHead
|
|
287
|
-
}, result);
|
|
288
|
-
} catch (error) {
|
|
289
|
-
vite.ssrFixStacktrace(error);
|
|
290
|
-
console.error(error);
|
|
291
|
-
res.statusCode = 500;
|
|
292
|
-
res.end(error.message);
|
|
400
|
+
return () => {
|
|
401
|
+
server.middlewares.use(fallback);
|
|
402
|
+
};
|
|
293
403
|
}
|
|
294
|
-
}
|
|
295
|
-
}
|
|
404
|
+
}
|
|
405
|
+
}] });
|
|
296
406
|
return {
|
|
297
|
-
use
|
|
298
|
-
userMiddlewares.push(mw);
|
|
299
|
-
},
|
|
407
|
+
use,
|
|
300
408
|
async listen(port, host) {
|
|
301
409
|
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.");
|
|
302
|
-
for (const mw of userMiddlewares) vite.middlewares.use(mw);
|
|
303
|
-
if (ssrFallback) vite.middlewares.use(ssrFallback);
|
|
304
410
|
await vite.listen();
|
|
305
411
|
vite.printUrls();
|
|
306
412
|
return vite.httpServer;
|
|
@@ -321,6 +427,8 @@ async function createSSRServer(options) {
|
|
|
321
427
|
const cache = resolveCacheControl(__MOOST_CACHE_CONTROL__, opts.cacheControl);
|
|
322
428
|
const defaultPort = opts.port || Number(process.env.PORT) || 3e3;
|
|
323
429
|
const defaultHost = opts.host ?? process.env.HOST;
|
|
430
|
+
const headers = opts.headers ?? __MOOST_HEADERS__;
|
|
431
|
+
const cspNonce = __MOOST_CSP_NONCE__ ?? void 0;
|
|
324
432
|
const template = await fs.readFile(path.resolve(clientDir, "index.html"), "utf8");
|
|
325
433
|
let render = null;
|
|
326
434
|
if (__MOOST_SSR_ENTRY__ !== void 0 && !!__MOOST_SSR_ENTRY__) render = (await import(
|
|
@@ -376,7 +484,8 @@ async function createSSRServer(options) {
|
|
|
376
484
|
sendSSRResponse(res, template, {
|
|
377
485
|
ssrOutlet,
|
|
378
486
|
ssrState,
|
|
379
|
-
ssrHead
|
|
487
|
+
ssrHead,
|
|
488
|
+
cspNonce
|
|
380
489
|
}, result);
|
|
381
490
|
} else sendSpaShell(req, res, spaShell, cache);
|
|
382
491
|
} catch (error) {
|
|
@@ -387,16 +496,14 @@ async function createSSRServer(options) {
|
|
|
387
496
|
};
|
|
388
497
|
const serveStatic = await createStaticHandler(path.resolve(clientDir), variants, cache, (req, res) => void servePage(req, res));
|
|
389
498
|
return {
|
|
390
|
-
use
|
|
391
|
-
userMiddlewares.push(mw);
|
|
392
|
-
},
|
|
499
|
+
use,
|
|
393
500
|
async listen(port, host) {
|
|
394
501
|
const server = createHttpServer((req, res) => {
|
|
395
502
|
const url = req.url || "/";
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
if (
|
|
399
|
-
|
|
503
|
+
setResponseHeaders(res, headers);
|
|
504
|
+
runMiddlewares(userMiddlewares, req, res, (error) => {
|
|
505
|
+
if (error) {
|
|
506
|
+
failRequest(res, error);
|
|
400
507
|
return;
|
|
401
508
|
}
|
|
402
509
|
if (moostHandler && (!prefixes || matchesPrefix(url, prefixes))) {
|
|
@@ -404,8 +511,7 @@ async function createSSRServer(options) {
|
|
|
404
511
|
return;
|
|
405
512
|
}
|
|
406
513
|
serveStatic(req, res);
|
|
407
|
-
};
|
|
408
|
-
runNext();
|
|
514
|
+
});
|
|
409
515
|
});
|
|
410
516
|
server.listen(port || defaultPort, host || defaultHost);
|
|
411
517
|
await once(server, "listening");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moostjs/vite",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.8",
|
|
4
4
|
"description": "Vite Dev plugin for moostjs",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"composables",
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
},
|
|
59
59
|
"peerDependencies": {
|
|
60
60
|
"vite": "^8.0.0",
|
|
61
|
-
"@moostjs/event-http": "^0.7.
|
|
62
|
-
"moost": "^0.7.
|
|
61
|
+
"@moostjs/event-http": "^0.7.8",
|
|
62
|
+
"moost": "^0.7.8"
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
65
|
"pub": "pnpm publish --access public",
|