isr-engine 3.1.3 → 3.1.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 (29) hide show
  1. package/dist/{abVariantContext-Ud3aZ1yk.js → abVariantContext-BtLsLN1J.js} +2 -12
  2. package/dist/{abVariantContext-Ud3aZ1yk.js.map → abVariantContext-BtLsLN1J.js.map} +1 -1
  3. package/dist/cli/cli.js +1 -1
  4. package/dist/{createCacheInspectorMiddleware-GgzKVkq2.js → createCacheInspectorMiddleware-Cb_MZhLZ.js} +2 -2
  5. package/dist/{createCacheInspectorMiddleware-GgzKVkq2.js.map → createCacheInspectorMiddleware-Cb_MZhLZ.js.map} +1 -1
  6. package/dist/{createISRApp-DPD3Er4F.js → createISRApp-rD8EUB--.js} +2255 -1721
  7. package/dist/createISRApp-rD8EUB--.js.map +1 -0
  8. package/dist/defaults/runtime/defineSiteHooks.js +2 -2
  9. package/dist/{defineSiteHooks-bHtGQftZ.js → defineSiteHooks-BWaDDJ4B.js} +2 -2
  10. package/dist/{defineSiteHooks-bHtGQftZ.js.map → defineSiteHooks-BWaDDJ4B.js.map} +1 -1
  11. package/dist/{i18n-CnXYAgQE.js → i18n-BFCx28rB.js} +2 -8
  12. package/dist/{i18n-CnXYAgQE.js.map → i18n-BFCx28rB.js.map} +1 -1
  13. package/dist/isr-engine.js +11 -10
  14. package/dist/isr-engine.js.map +1 -1
  15. package/dist/plugin/googleFontAssets.d.ts.map +1 -1
  16. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  17. package/dist/rsc/index.js +2 -2
  18. package/dist/{rsc-BJzB9s8U.js → rsc-Da-Nc0OM.js} +2 -2
  19. package/dist/{rsc-BJzB9s8U.js.map → rsc-Da-Nc0OM.js.map} +1 -1
  20. package/dist/security/staticCspManifest.d.ts.map +1 -1
  21. package/dist/server/productionRuntime.d.ts.map +1 -1
  22. package/dist/server/requestLimits.d.ts.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/Logger-bg-doGwZ.js +0 -174
  25. package/dist/Logger-bg-doGwZ.js.map +0 -1
  26. package/dist/createISRApp-DPD3Er4F.js.map +0 -1
  27. package/dist/createImagePlugin-QNvY9vPB.js +0 -462
  28. package/dist/createImagePlugin-QNvY9vPB.js.map +0 -1
  29. package/dist/rolldown-runtime-D7D4PA-g.js +0 -13
@@ -1,20 +1,21 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { E as requestContext, S as getRequestContext, a as isUncacheable, f as setRevalidationMetricRecorder, l as registerInvalidator, r as collectTags, s as runWithTagStore } from "./abVariantContext-Ud3aZ1yk.js";
3
- import { t as Logger } from "./Logger-bg-doGwZ.js";
4
- import { c as readCookie, i as resolveI18nConfig, n as negotiateLocale, s as parseCookieHeader } from "./i18n-CnXYAgQE.js";
5
- import fs, { createReadStream } from "node:fs";
1
+ import { C as getTraceId, S as getRequestId, T as requestContext, _ as escapeSupplementalLogControls, a as isUncacheable, f as setRevalidationMetricRecorder, g as encodeSpinnerMessage, h as encodeLogField, l as registerInvalidator, m as setOriginLogger, r as collectTags, s as runWithTagStore, v as snapshotLogArgument, x as getRequestContext } from "./abVariantContext-BtLsLN1J.js";
2
+ import { o as parseCookieHeader, r as resolveI18nConfig, s as readCookie, t as negotiateLocale } from "./i18n-BFCx28rB.js";
3
+ import fs, { createReadStream, promises } from "node:fs";
6
4
  import path from "node:path";
7
5
  import express from "express";
8
6
  import { ipKeyGenerator, rateLimit } from "express-rate-limit";
9
7
  import ipaddr from "ipaddr.js";
8
+ import chalk from "chalk";
9
+ import ora from "ora";
10
10
  import * as path$2 from "path";
11
11
  import path$1 from "path";
12
+ import pino from "pino";
12
13
  import * as fs$4 from "fs";
13
14
  import fs$1 from "fs";
14
15
  import fs$2 from "fs/promises";
15
16
  import ts from "typescript";
16
- import net from "node:net";
17
- import { createServer, loadConfigFromFile, mergeConfig } from "vite";
17
+ import net, { isIP } from "node:net";
18
+ import { createServer, isFileLoadingAllowed, loadConfigFromFile, mergeConfig, normalizePath } from "vite";
18
19
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
19
20
  import compression from "compression";
20
21
  import helmet from "helmet";
@@ -22,17 +23,18 @@ import fs$3 from "node:fs/promises";
22
23
  import { pathToFileURL } from "node:url";
23
24
  import { Readable } from "node:stream";
24
25
  import os from "node:os";
25
- import http from "node:http";
26
+ import http, { request } from "node:http";
26
27
  import { LRUCache } from "lru-cache";
27
28
  import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from "prom-client";
28
29
  import { pathToFileURL as pathToFileURL$1 } from "url";
29
30
  import { createHash as createHash$1, randomUUID as randomUUID$1 } from "crypto";
30
31
  import * as esbuild from "esbuild";
32
+ import { lookup } from "node:dns/promises";
33
+ import { request as request$1 } from "node:https";
34
+ import { SitemapStream, streamToPromise } from "sitemap";
31
35
  import { parse } from "parse5";
32
36
  import { createServer as createServer$1 } from "http";
33
- import { SitemapStream, streamToPromise } from "sitemap";
34
37
  //#region src/config/resolveImageOptions.ts
35
- var resolveImageOptions_exports = /* @__PURE__ */ __exportAll({ resolveImageOptions: () => resolveImageOptions });
36
38
  /** Shared image policy for the automatic development and production endpoints. */
37
39
  function resolveImageOptions(images) {
38
40
  const invalid = () => /* @__PURE__ */ new Error("runtime.images must contain only remoteAllowlist: an array of exact host[:port] entries");
@@ -152,7 +154,8 @@ function resolveRequestLimitPolicy(category, input) {
152
154
  "globalMaxRequests",
153
155
  "maxClients"
154
156
  ]) {
155
- const value = input?.[field] === void 0 ? defaults[field] : input[field];
157
+ const configured = input?.[field];
158
+ const value = configured === void 0 ? defaults[field] : configured;
156
159
  if (!Number.isSafeInteger(value) || value <= 0 || value >= Number.MAX_SAFE_INTEGER) throw new TypeError(`server.requestLimits.${category}.${field} must be a positive safe integer`);
157
160
  result[field] = value;
158
161
  }
@@ -375,6 +378,172 @@ function requireOwnProperties(value, keys, label) {
375
378
  for (const key of keys) if (!Object.prototype.hasOwnProperty.call(value, key)) throw new Error(`ssr.config.ts 必须显式声明 ${label}.${key}`);
376
379
  }
377
380
  //#endregion
381
+ //#region src/logger/Logger.ts
382
+ var LogLevel = /* @__PURE__ */ function(LogLevel) {
383
+ LogLevel["VERBOSE"] = "verbose";
384
+ LogLevel["DEBUG"] = "debug";
385
+ LogLevel["INFO"] = "info";
386
+ LogLevel["WARN"] = "warn";
387
+ LogLevel["ERROR"] = "error";
388
+ LogLevel["SUCCESS"] = "success";
389
+ return LogLevel;
390
+ }({});
391
+ var Logger = class Logger {
392
+ static instance;
393
+ verboseMode = false;
394
+ logFile = null;
395
+ fileLogger = null;
396
+ fileDestination = null;
397
+ spinner = null;
398
+ static getInstance(options = {}) {
399
+ if (!Logger.instance) {
400
+ Logger.instance = new Logger();
401
+ setOriginLogger(Logger.instance);
402
+ }
403
+ if (options.verbose !== void 0) Logger.instance.verboseMode = options.verbose;
404
+ if (options.logFile !== void 0) Logger.instance.configureFile(options.logFile);
405
+ return Logger.instance;
406
+ }
407
+ /** File destinations are operator configuration; request data is only a record field. */
408
+ configureFile(logFile) {
409
+ if (typeof logFile !== "string" || /[\u0000-\u001f\u007f]/.test(logFile)) throw new TypeError("logFile must be a path without control characters");
410
+ const resolved = logFile ? path$1.resolve(logFile) : null;
411
+ if (resolved === this.logFile) return;
412
+ this.closeFileDestination();
413
+ if (!resolved) return;
414
+ try {
415
+ const destination = pino.destination({
416
+ dest: resolved,
417
+ mkdir: true,
418
+ sync: true
419
+ });
420
+ destination.on("error", (error) => {
421
+ if (this.fileDestination === destination) this.closeFileDestination();
422
+ this.reportFileError(error);
423
+ });
424
+ destination.once("close", () => {
425
+ if (this.fileDestination !== destination) return;
426
+ this.fileLogger = null;
427
+ this.fileDestination = null;
428
+ this.logFile = null;
429
+ });
430
+ this.fileDestination = destination;
431
+ this.fileLogger = pino({
432
+ base: null,
433
+ timestamp: false,
434
+ level: "trace",
435
+ hooks: { streamWrite: escapeSupplementalLogControls }
436
+ }, destination);
437
+ this.logFile = resolved;
438
+ } catch (error) {
439
+ this.closeFileDestination();
440
+ this.reportFileError(error);
441
+ }
442
+ }
443
+ closeFileDestination() {
444
+ const destination = this.fileDestination;
445
+ this.fileLogger = null;
446
+ this.fileDestination = null;
447
+ this.logFile = null;
448
+ if (!destination) return;
449
+ try {
450
+ destination.flushSync();
451
+ destination.end();
452
+ } catch (error) {
453
+ destination.destroy();
454
+ this.reportFileError(error);
455
+ }
456
+ }
457
+ reportFileError(error) {
458
+ try {
459
+ process.stderr.write(`Failed to write to log file: ${encodeLogField(snapshotLogArgument(error))}\n`);
460
+ } catch {}
461
+ }
462
+ getLevelColor(level) {
463
+ switch (level) {
464
+ case "error": return chalk.red.bold;
465
+ case "warn": return chalk.yellow.bold;
466
+ case "success": return chalk.green.bold;
467
+ case "info": return chalk.blue.bold;
468
+ case "debug": return chalk.magenta;
469
+ case "verbose": return chalk.gray;
470
+ default: return chalk.white;
471
+ }
472
+ }
473
+ log(level, ...args) {
474
+ if (!Object.values(LogLevel).includes(level)) throw new TypeError("Unknown log level");
475
+ if (level === "verbose" && !this.verboseMode) return;
476
+ if (level === "debug" && !this.verboseMode) return;
477
+ if (this.spinner?.isSpinning) this.spinner.stop();
478
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
479
+ const traceId = snapshotLogArgument(getTraceId());
480
+ const requestId = snapshotLogArgument(getRequestId());
481
+ const values = args.map(snapshotLogArgument);
482
+ const errors = [];
483
+ const message = values.map((value, index) => {
484
+ if (args[index] instanceof Error) {
485
+ errors.push({
486
+ argument: index,
487
+ error: value
488
+ });
489
+ if (value && typeof value === "object" && !Array.isArray(value)) return value.stack || value.message || JSON.stringify(value, null, 2);
490
+ }
491
+ return typeof value === "string" ? value : JSON.stringify(value, null, 2);
492
+ }).join(" ");
493
+ const levelTag = this.getLevelColor(level)(`[${level.toUpperCase()}]`);
494
+ const traceTag = chalk.cyan(`traceId=${encodeLogField(traceId)}`);
495
+ const requestTag = requestId === "unknown" ? "" : chalk.blue(`requestId=${encodeLogField(requestId)}`);
496
+ console.log(`${chalk.gray(timestamp)} ${levelTag} ${traceTag} ${requestTag} message=${encodeLogField(message)}`);
497
+ if (this.fileLogger) {
498
+ const transportLevel = level === "verbose" ? "trace" : level === "success" ? "info" : level;
499
+ try {
500
+ this.fileLogger[transportLevel]({
501
+ timestamp,
502
+ severity: level,
503
+ traceId,
504
+ requestId,
505
+ args: values,
506
+ errors
507
+ });
508
+ } catch (error) {
509
+ this.closeFileDestination();
510
+ this.reportFileError(error);
511
+ }
512
+ }
513
+ if (this.spinner && !this.spinner.isSpinning) this.spinner.start();
514
+ }
515
+ error(...args) {
516
+ this.log("error", ...args);
517
+ }
518
+ warn(...args) {
519
+ this.log("warn", ...args);
520
+ }
521
+ info(...args) {
522
+ this.log("info", ...args);
523
+ }
524
+ success(...args) {
525
+ this.log("success", ...args);
526
+ }
527
+ debug(...args) {
528
+ this.log("debug", ...args);
529
+ }
530
+ verbose(...args) {
531
+ this.log("verbose", ...args);
532
+ }
533
+ spin(message) {
534
+ if (this.spinner) this.spinner.succeed();
535
+ this.spinner = ora(encodeSpinnerMessage(message)).start();
536
+ return this.spinner;
537
+ }
538
+ stopSpinner(message, success = true) {
539
+ if (this.spinner) {
540
+ if (success) this.spinner.succeed(message === void 0 ? void 0 : encodeSpinnerMessage(message));
541
+ else this.spinner.fail(message === void 0 ? void 0 : encodeSpinnerMessage(message));
542
+ this.spinner = null;
543
+ }
544
+ }
545
+ };
546
+ //#endregion
378
547
  //#region src/utils/CacheCleanup.ts
379
548
  var logger$9 = Logger.getInstance();
380
549
  /**
@@ -1284,18 +1453,6 @@ async function closeViteDevServer() {
1284
1453
  * 中间件配置
1285
1454
  * 提供通用中间件和开发/生产环境特定中间件
1286
1455
  */
1287
- var middleware_exports = /* @__PURE__ */ __exportAll({
1288
- CSP_NONCE_HEADER: () => CSP_NONCE_HEADER,
1289
- CSP_NONCE_LOCAL: () => CSP_NONCE_LOCAL,
1290
- applyBaseMiddlewaresWithOptions: () => applyBaseMiddlewaresWithOptions,
1291
- createCompressionMiddleware: () => createCompressionMiddleware,
1292
- createCspNonceMiddleware: () => createCspNonceMiddleware,
1293
- createJsonMiddleware: () => createJsonMiddleware,
1294
- createSecurityMiddleware: () => createSecurityMiddleware,
1295
- createStaticMiddleware: () => createStaticMiddleware,
1296
- createUrlEncodedMiddleware: () => createUrlEncodedMiddleware,
1297
- mountViteOrStatic: () => mountViteOrStatic
1298
- });
1299
1456
  /** 用于在 res.locals 上挂 CSP nonce 的 key (Lighthouse csp-xss 审计需要) */
1300
1457
  var CSP_NONCE_LOCAL = "cspNonce";
1301
1458
  /** 用于在 req.headers 上透传 nonce 到 RSC handler 的 header 名 */
@@ -1511,7 +1668,7 @@ function resolveFetchHandler(module) {
1511
1668
  }
1512
1669
  var package_default = {
1513
1670
  name: "isr-engine",
1514
- version: "3.1.3",
1671
+ version: "3.1.4",
1515
1672
  description: "ISR/SSG/Fallback rendering orchestration on Vite + React 19 RSC.",
1516
1673
  license: "UNLICENSED",
1517
1674
  repository: {
@@ -1829,7 +1986,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
1829
1986
  signal: ctrl.signal
1830
1987
  }));
1831
1988
  if (ctrl.signal.aborted) {
1832
- response.body?.cancel(ctrl.signal.reason).catch(() => {});
1989
+ response.body?.cancel(ctrl.signal.reason).catch(() => void 0);
1833
1990
  throw ctrl.signal.reason;
1834
1991
  }
1835
1992
  reader = response.body?.getReader();
@@ -1855,7 +2012,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
1855
2012
  const abort = (reason) => {
1856
2013
  rejectAbort(reason);
1857
2014
  ctrl.abort(reason);
1858
- reader?.cancel(reason).catch(() => {});
2015
+ reader?.cancel(reason).catch(() => void 0);
1859
2016
  };
1860
2017
  const onBatchAbort = () => abort(batchSignal.reason);
1861
2018
  batchSignal.addEventListener("abort", onBatchAbort, { once: true });
@@ -2503,20 +2660,6 @@ function createHybridCacheStore(opts) {
2503
2660
  * - 响应时间用 Histogram(带桶),不是平均值 —— 才能正确算 P95/P99
2504
2661
  * - 默认采集 process_*(CPU / RSS / event-loop lag)—— 一行 collectDefaultMetrics
2505
2662
  */
2506
- var PromMetrics_exports = /* @__PURE__ */ __exportAll({
2507
- cacheEntriesGauge: () => cacheEntriesGauge,
2508
- cacheHitsTotal: () => cacheHitsTotal,
2509
- cacheRevalidatingGauge: () => cacheRevalidatingGauge,
2510
- createPrometheusMetricsMiddleware: () => createPrometheusMetricsMiddleware,
2511
- httpRequestDurationSeconds: () => httpRequestDurationSeconds,
2512
- httpRequestsTotal: () => httpRequestsTotal,
2513
- invalidatorFailuresTotal: () => invalidatorFailuresTotal,
2514
- invalidatorRunsTotal: () => invalidatorRunsTotal,
2515
- l2ReadTimeoutsTotal: () => l2ReadTimeoutsTotal,
2516
- normalizeRoute: () => normalizeRoute,
2517
- promRegistry: () => promRegistry,
2518
- recordHttpRequest: () => recordHttpRequest
2519
- });
2520
2663
  var promRegistry = new Registry();
2521
2664
  collectDefaultMetrics({
2522
2665
  register: promRegistry,
@@ -2778,13 +2921,6 @@ async function resolveImportPath(filePath, options) {
2778
2921
  }
2779
2922
  //#endregion
2780
2923
  //#region src/server/opsConfig.ts
2781
- var opsConfig_exports = /* @__PURE__ */ __exportAll({
2782
- bindRuntimeOpsConfig: () => bindRuntimeOpsConfig,
2783
- createOpsAuthMiddleware: () => createOpsAuthMiddleware,
2784
- getOpsRequestLimiter: () => getOpsRequestLimiter,
2785
- getRuntimeOpsConfig: () => getRuntimeOpsConfig,
2786
- resolveOpsConfig: () => resolveOpsConfig
2787
- });
2788
2924
  var opsLimiters = /* @__PURE__ */ new WeakMap();
2789
2925
  var runtimeOpsConfigs = /* @__PURE__ */ new WeakMap();
2790
2926
  /** Carry one resolved policy from the Vite plugin into its owning Express runtime. */
@@ -4003,10 +4139,6 @@ var RedisCacheAdapter = class {
4003
4139
  };
4004
4140
  //#endregion
4005
4141
  //#region src/config/resolveRuntimeRedis.ts
4006
- var resolveRuntimeRedis_exports = /* @__PURE__ */ __exportAll({
4007
- hasRuntimeRedisConnection: () => hasRuntimeRedisConnection,
4008
- resolveRuntimeRedisConfig: () => resolveRuntimeRedisConfig
4009
- });
4010
4142
  function nonEmpty(value) {
4011
4143
  const trimmed = value?.trim();
4012
4144
  return trimmed ? trimmed : void 0;
@@ -4058,7 +4190,6 @@ function hasRuntimeRedisConnection(redis) {
4058
4190
  * - runtime.redis.url/host 已设 → revision-validated response cache(Redis 原子协议 + 本机字节缓存)
4059
4191
  * - 未显式配置 Redis → MemoryCacheStore(单层 LRU,行为不变)
4060
4192
  */
4061
- var createAutoCacheStore_exports = /* @__PURE__ */ __exportAll({ createAutoCacheStore: () => createAutoCacheStore });
4062
4193
  var logger$6 = Logger.getInstance();
4063
4194
  function createAutoCacheStore(opts = {}) {
4064
4195
  const redisConfig = resolveRuntimeRedisConfig({
@@ -4092,7 +4223,6 @@ function createAutoCacheStore(opts = {}) {
4092
4223
  }
4093
4224
  //#endregion
4094
4225
  //#region src/cache/RedisInvalidationBus.ts
4095
- var RedisInvalidationBus_exports = /* @__PURE__ */ __exportAll({ RedisInvalidationBus: () => RedisInvalidationBus });
4096
4226
  function normalizeTarget(target) {
4097
4227
  if (!target || typeof target !== "object") return null;
4098
4228
  const candidate = target;
@@ -4333,12 +4463,6 @@ var RedisInvalidationBus = class {
4333
4463
  * 必须在 cache lookup 之前 set,但 cache 层会把 anon 这一条从 captured.headers 里
4334
4464
  * 剥掉再入缓存(见 plugin/isrCacheMiddleware.ts),保证缓存内容 user-agnostic。
4335
4465
  */
4336
- var createServerRequestContext_exports = /* @__PURE__ */ __exportAll({
4337
- ANON_COOKIE_MAX_AGE_SECONDS: () => ANON_COOKIE_MAX_AGE_SECONDS,
4338
- ANON_COOKIE_NAME: () => ANON_COOKIE_NAME,
4339
- applyAnonCookie: () => applyAnonCookie,
4340
- createServerRequestContext: () => createServerRequestContext
4341
- });
4342
4466
  /** anonId cookie 名称 —— engine 全局常量,避免散落字符串。 */
4343
4467
  var ANON_COOKIE_NAME = "anon";
4344
4468
  /** anonId cookie 有效期(秒)。1 年;浏览器侧最大也只能撑到这个量级。 */
@@ -4803,7 +4927,6 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4803
4927
  logger$5.info(`📋 ISR cache: 自动加载 ssr.config.ts 成功(mode=${rules.globalMode}, overrides=${Object.keys(rules.routes).length})`);
4804
4928
  }
4805
4929
  const opsConfig = resolveOpsConfig(resolvedConfig, "development");
4806
- const { bindRuntimeOpsConfig, getOpsRequestLimiter } = await Promise.resolve().then(() => opsConfig_exports);
4807
4930
  const opsLimiter = getOpsRequestLimiter(opsConfig);
4808
4931
  const metricsAuth = createOpsAuthMiddleware("metrics", opsConfig);
4809
4932
  const nextHandler = createIsrCacheHandler(resolvedConfig, withRuntimeCacheOptions(resolvedConfig, {
@@ -4811,7 +4934,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4811
4934
  development: true
4812
4935
  }));
4813
4936
  try {
4814
- const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-GgzKVkq2.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
4937
+ const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-Cb_MZhLZ.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
4815
4938
  handler = nextHandler;
4816
4939
  server.middlewares.use((req, res, next) => {
4817
4940
  if (handler !== nextHandler) return next();
@@ -4819,8 +4942,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4819
4942
  opsLimiter(req, res, (error) => {
4820
4943
  if (error) return next(error);
4821
4944
  metricsAuth(req, res, () => {
4822
- Promise.resolve().then(() => PromMetrics_exports).then(async ({ promRegistry }) => {
4823
- const body = await promRegistry.metrics();
4945
+ promRegistry.metrics().then((body) => {
4824
4946
  res.setHeader("content-type", promRegistry.contentType);
4825
4947
  res.end(body);
4826
4948
  }).catch((err) => {
@@ -4958,7 +5080,8 @@ async function handleRequest(req, res, next, ctx) {
4958
5080
  logger$5.warn(`ISR cache L2 read 失败 ${cacheKey}: ${err.message}`);
4959
5081
  }
4960
5082
  if (!isActive()) return;
4961
- if (!entry && ctx.state.invalidationGeneration === 0 && resolved.mode === "ssg" && ctx.staticSeed && (!ctx.staticSeedInfo || ctx.staticSeedInfo(logicalPath)) && !url.includes("?") && !url.endsWith(RSC_URL_POSTFIX) && !ctx.variantIsolation && !ctx.hostIsolation) {
5083
+ const staticSeed = ctx.staticSeed;
5084
+ if (!entry && ctx.state.invalidationGeneration === 0 && resolved.mode === "ssg" && staticSeed && (!ctx.staticSeedInfo || ctx.staticSeedInfo(logicalPath)) && !url.includes("?") && !url.endsWith(RSC_URL_POSTFIX) && !ctx.variantIsolation && !ctx.hostIsolation) {
4962
5085
  let seedTask = ctx.seeded.get(cacheKey);
4963
5086
  const leader = !seedTask;
4964
5087
  if (!seedTask) {
@@ -4977,7 +5100,7 @@ async function handleRequest(req, res, next, ctx) {
4977
5100
  if (!isActive()) return seedDenial(res);
4978
5101
  const generation = ctx.state.invalidationGeneration;
4979
5102
  if (generation !== 0) return true;
4980
- const seed = await raceWithTimeout(ctx.staticSeed(logicalPath, String(res.getHeader("content-security-policy") || "default-src 'self'")), ctx.l2ReadTimeoutMs);
5103
+ const seed = await raceWithTimeout(staticSeed.call(ctx, logicalPath, String(res.getHeader("content-security-policy") || "default-src 'self'")), ctx.l2ReadTimeoutMs);
4981
5104
  if (!seed) {
4982
5105
  ctx.seeded.delete(cacheKey);
4983
5106
  return true;
@@ -5636,960 +5759,935 @@ function refreshHeaders(req, ctx) {
5636
5759
  return headers;
5637
5760
  }
5638
5761
  //#endregion
5639
- //#region src/server/safeRedirect.ts
5640
- var REDIRECT_ORIGIN = "https://isr.invalid";
5641
- /** Validate the final Location value against a fixed origin, never an untrusted Host header. */
5642
- function isSafeLocalRedirect(target) {
5643
- if (!target.startsWith("/") || target.startsWith("//")) return false;
5644
- for (const character of target) {
5645
- const code = character.charCodeAt(0);
5646
- if (code < 32 || code === 127) return false;
5762
+ //#region src/plugin/remoteImageSource.ts
5763
+ var ImageSourceError = class extends Error {
5764
+ status;
5765
+ constructor(status, message) {
5766
+ super(message);
5767
+ this.status = status;
5647
5768
  }
5648
- const pathEnd = target.search(/[?#]/);
5649
- if (target.slice(0, pathEnd < 0 ? void 0 : pathEnd).includes("\\")) return false;
5769
+ };
5770
+ var resolveAll = (hostname) => lookup(hostname, {
5771
+ all: true,
5772
+ verbatim: true
5773
+ });
5774
+ function isPublicImageAddress(address) {
5650
5775
  try {
5651
- return new URL(target, REDIRECT_ORIGIN).origin === REDIRECT_ORIGIN;
5776
+ return ipaddr.parse(address).range() === "unicast";
5652
5777
  } catch {
5653
5778
  return false;
5654
5779
  }
5655
5780
  }
5656
- function readRedirectQuery(url) {
5657
- const delimiter = url.indexOf("?");
5658
- return delimiter < 0 ? void 0 : url.slice(delimiter + 1);
5781
+ async function resolveImageAddress(hostname, resolve = resolveAll) {
5782
+ const name = hostname.replace(/^\[|\]$/g, "");
5783
+ const addresses = isIP(name) ? [{
5784
+ address: name,
5785
+ family: isIP(name)
5786
+ }] : await resolve(name);
5787
+ if (!addresses.length || addresses.some((a) => !isPublicImageAddress(a.address))) throw new ImageSourceError(400, "source address not allowed");
5788
+ return addresses[0];
5789
+ }
5790
+ /** Return the configured authority, rather than carrying the request's authority past a guard. */
5791
+ function selectImageOrigin(url, allow) {
5792
+ if (url.username || url.password || !["http:", "https:"].includes(url.protocol)) return;
5793
+ const protocol = url.protocol === "https:" ? "https:" : "http:";
5794
+ const defaultPort = protocol === "https:" ? 443 : 80;
5795
+ for (const entry of allow) {
5796
+ if (/[\s/@?#*\\]/.test(entry)) continue;
5797
+ const authority = /^(\[[^\]]+\]|[^:]+)(?::([0-9]+))?$/.exec(entry);
5798
+ if (!authority) continue;
5799
+ let configured;
5800
+ try {
5801
+ configured = new URL(`${protocol}//${entry}`);
5802
+ } catch {
5803
+ continue;
5804
+ }
5805
+ const port = authority[2] === void 0 ? defaultPort : Number(authority[2]);
5806
+ if (!configured.hostname || configured.pathname !== "/" || configured.username || configured.password || url.hostname !== configured.hostname || Number(url.port || defaultPort) !== port) continue;
5807
+ return {
5808
+ protocol,
5809
+ hostname: configured.hostname.replace(/^\[|\]$/g, ""),
5810
+ authority: configured.host,
5811
+ port
5812
+ };
5813
+ }
5659
5814
  }
5660
- function redirectLocal(res, status, pathname, query) {
5661
- const target = query === void 0 ? pathname : `${pathname}?${query}`;
5662
- if (!isSafeLocalRedirect(target)) {
5663
- res.status(400).end();
5664
- return;
5815
+ async function resolveBeforeAbort(hostname, signal) {
5816
+ signal.throwIfAborted();
5817
+ let abort;
5818
+ try {
5819
+ return await Promise.race([resolveImageAddress(hostname), new Promise((_resolve, reject) => {
5820
+ abort = () => reject(signal.reason);
5821
+ signal.addEventListener("abort", abort, { once: true });
5822
+ })]);
5823
+ } finally {
5824
+ if (abort) signal.removeEventListener("abort", abort);
5665
5825
  }
5666
- res.redirect(status, target);
5667
5826
  }
5668
- //#endregion
5669
- //#region src/security/staticCspManifest.ts
5670
- var STATIC_CSP_MANIFEST = "static-csp-manifest.json";
5671
- var SCHEMA_VERSION = 3;
5672
- var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
5673
- /** parse5 follows browser tokenization, including raw script text and inert templates. */
5674
- function collectInlineScriptHashes(html) {
5675
- const hashes = /* @__PURE__ */ new Set();
5676
- function visit(node) {
5677
- if ("tagName" in node && node.tagName === "script" && !node.attrs.some((attr) => attr.name === "src")) {
5678
- const text = node.childNodes.map((child) => "value" in child ? child.value : "").join("");
5679
- hashes.add(`'sha256-${createHash("sha256").update(text).digest("base64")}'`);
5827
+ /** A fresh socket uses a validated public DNS answer and a configured origin at every hop. */
5828
+ async function fetchRemoteImage(src, allow, maxBytes) {
5829
+ const controller = new AbortController();
5830
+ const timer = setTimeout(() => controller.abort(), 1e4);
5831
+ try {
5832
+ let url = new URL(src);
5833
+ for (let hop = 0; hop <= 5; hop++) {
5834
+ const response = await requestPinnedImage(url, allow, controller.signal);
5835
+ if ([
5836
+ 301,
5837
+ 302,
5838
+ 303,
5839
+ 307,
5840
+ 308
5841
+ ].includes(response.statusCode ?? 0)) {
5842
+ response.destroy();
5843
+ if (!response.headers.location || hop === 5) throw new ImageSourceError(400, "invalid source redirect");
5844
+ url = new URL(response.headers.location, url);
5845
+ continue;
5846
+ }
5847
+ if ((response.statusCode ?? 0) < 200 || (response.statusCode ?? 0) >= 300) {
5848
+ response.destroy();
5849
+ throw new ImageSourceError(400, "source fetch failed");
5850
+ }
5851
+ if (Number(response.headers["content-length"]) > maxBytes) {
5852
+ response.destroy();
5853
+ throw new ImageSourceError(413, "source too large");
5854
+ }
5855
+ const chunks = [];
5856
+ let size = 0;
5857
+ try {
5858
+ for await (const chunk of response) {
5859
+ size += chunk.length;
5860
+ if (size > maxBytes) throw new ImageSourceError(413, "source too large");
5861
+ chunks.push(Buffer.from(chunk));
5862
+ }
5863
+ if (!response.complete) throw new ImageSourceError(400, "incomplete source response");
5864
+ return Buffer.concat(chunks, size);
5865
+ } finally {
5866
+ response.destroy();
5867
+ }
5680
5868
  }
5681
- if ("childNodes" in node) node.childNodes.forEach(visit);
5869
+ throw new ImageSourceError(400, "invalid source redirect");
5870
+ } catch (error) {
5871
+ if (error instanceof ImageSourceError) throw error;
5872
+ throw new ImageSourceError(controller.signal.aborted ? 504 : 400, "source fetch failed");
5873
+ } finally {
5874
+ clearTimeout(timer);
5682
5875
  }
5683
- visit(parse(html));
5684
- return [...hashes].sort();
5685
- }
5686
- function applyStaticScriptPolicy(policy, hashes) {
5687
- return [...policy.split(";").filter((directive) => {
5688
- const name = directive.trim().split(/\s/, 1)[0].toLowerCase();
5689
- return name !== "script-src" && name !== "script-src-elem";
5690
- }), ["script-src 'self'", ...hashes].join(" ")].join(";");
5691
5876
  }
5692
- async function readHtmlFiles(clientDir, parseScripts = false) {
5693
- const files = [];
5694
- async function walk(dir) {
5695
- for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
5696
- const absolute = path.join(dir, entry.name);
5697
- if (entry.isDirectory()) await walk(absolute);
5698
- else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
5699
- const bytes = await fs$3.readFile(absolute);
5700
- files.push({
5701
- path: path.relative(clientDir, absolute).split(path.sep).join("/"),
5702
- sha256: sha256(bytes),
5703
- scriptHashes: parseScripts ? collectInlineScriptHashes(bytes.toString("utf8")) : [],
5704
- ...parseScripts ? { generatedAt: Math.floor((await fs$3.stat(absolute)).mtimeMs) } : {}
5705
- });
5877
+ /** No transport entry point accepts a caller-supplied address or unvalidated authority. */
5878
+ async function requestPinnedImage(url, allow, signal, accept = "image/*", userAgent) {
5879
+ const origin = selectImageOrigin(url, allow);
5880
+ if (!origin) throw new ImageSourceError(400, "source origin not allowed");
5881
+ const requestPath = url.pathname + url.search;
5882
+ const resolved = await resolveBeforeAbort(origin.hostname, signal);
5883
+ const address = {
5884
+ address: resolved.address,
5885
+ family: resolved.family
5886
+ };
5887
+ signal.throwIfAborted();
5888
+ return new Promise((resolve, reject) => {
5889
+ const request$2 = (origin.protocol === "https:" ? request$1 : request)({
5890
+ protocol: origin.protocol,
5891
+ hostname: origin.hostname,
5892
+ port: origin.port,
5893
+ path: requestPath,
5894
+ agent: false,
5895
+ signal,
5896
+ maxHeaderSize: 16 * 1024,
5897
+ ...origin.protocol === "https:" ? {
5898
+ servername: isIP(origin.hostname) ? void 0 : origin.hostname,
5899
+ rejectUnauthorized: true
5900
+ } : {},
5901
+ lookup: ((_host, options, callback) => {
5902
+ if (options.all) callback(null, [address]);
5903
+ else callback(null, address.address, address.family);
5904
+ }),
5905
+ headers: {
5906
+ host: origin.authority,
5907
+ accept,
5908
+ "accept-encoding": "identity",
5909
+ ...userAgent ? { "user-agent": userAgent } : {}
5706
5910
  }
5707
- }
5911
+ }, resolve);
5912
+ request$2.once("error", reject);
5913
+ request$2.end();
5914
+ });
5915
+ }
5916
+ //#endregion
5917
+ //#region src/plugin/createImagePlugin.ts
5918
+ /**
5919
+ * createImagePlugin —— 图片优化(dev + prod 通用 endpoint)
5920
+ *
5921
+ * 工业模式(对标 next/image / @vercel/og 的图片处理路径):
5922
+ * - 端点 `/_/img?src=&w=&q=&fmt=`:sharp 按需 resize/compress/格式转换
5923
+ * - LRU 缓存 transformed buffer + ETag —— 二次命中走 304/缓存
5924
+ * - sharp 是必需依赖:提供 resize / 格式转换;fmt=original 显式读取安全栅格原图
5925
+ * - <Image> 组件(src/runtime/Image.tsx)输出 srcset,浏览器选最佳分辨率
5926
+ *
5927
+ * 安全:
5928
+ * - allowlist origin:默认仅允许 same-origin + 用户配置白名单(防 SSRF)
5929
+ * - max 输出 8192px / 输入 25MB(防 zip-bomb / OOM)
5930
+ */
5931
+ async function loadSharp() {
5932
+ try {
5933
+ return await import(
5934
+ /* @vite-ignore */
5935
+ "sharp"
5936
+ );
5937
+ } catch {
5938
+ return null;
5708
5939
  }
5709
- await walk(clientDir);
5710
- return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
5711
5940
  }
5712
- var CLIENT_BUILD_EXTENSIONS = /* @__PURE__ */ new Set([
5713
- ".js",
5714
- ".mjs",
5715
- ".cjs",
5716
- ".css",
5717
- ".wasm",
5718
- ".json",
5719
- ".html",
5720
- ".htm",
5721
- ".svg"
5941
+ var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
5942
+ "avif",
5943
+ "webp",
5944
+ "jpeg",
5945
+ "jpg",
5946
+ "png"
5722
5947
  ]);
5723
- function isDeploymentPath(relative) {
5724
- if (relative.includes("\\") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) return false;
5725
- return relative.startsWith("rsc/") || relative.startsWith("ssr/") || relative.startsWith("client/") && CLIENT_BUILD_EXTENSIONS.has(path.posix.extname(relative).toLowerCase());
5948
+ var MAX_INPUT_BYTES = 25 * 1024 * 1024;
5949
+ function createImagePlugin(options = {}, dependencies = {}) {
5950
+ return {
5951
+ name: "isr-engine:image-optimization",
5952
+ configureServer(server) {
5953
+ server.middlewares.use(createImageHandler(options, () => server.config.publicDir || void 0, dependencies, () => server));
5954
+ },
5955
+ configurePreviewServer(server) {
5956
+ const clientDir = path.resolve(server.config.root, server.config.environments?.client?.build.outDir ?? server.config.build.outDir);
5957
+ server.middlewares.use(createImageHandler(options, () => clientDir, dependencies));
5958
+ }
5959
+ };
5726
5960
  }
5727
- /** Hash executable build artifacts incrementally; do not load media or source maps from client/. */
5728
- async function readDeploymentFiles(distDir) {
5729
- const files = [];
5730
- async function walk(dir) {
5731
- for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
5732
- const absolute = path.join(dir, entry.name);
5733
- if (entry.isDirectory()) await walk(absolute);
5734
- else if (entry.isFile()) {
5735
- const relative = path.relative(distDir, absolute).split(path.sep).join("/");
5736
- if (!isDeploymentPath(relative)) continue;
5737
- const digest = createHash("sha256");
5738
- for await (const chunk of createReadStream(absolute)) digest.update(chunk);
5739
- files.push({
5740
- path: relative,
5741
- sha256: digest.digest("hex")
5742
- });
5961
+ /** Connect middleware shared by development, preview and production. */
5962
+ function createImageMiddleware(options = {}, dependencies = {}, publicDir = path.resolve(process.cwd(), "public")) {
5963
+ return createImageHandler(options, () => publicDir, dependencies);
5964
+ }
5965
+ var ImageError = ImageSourceError;
5966
+ function createImageHandler(opts, getPublicDir, dependencies, getDevServer) {
5967
+ let sharpCapability;
5968
+ const endpoint = opts.path ?? "/_/img";
5969
+ const allow = new Set(resolveImageOptions({ remoteAllowlist: opts.remoteAllowlist }).remoteAllowlist);
5970
+ const cache = new LRUCache({
5971
+ max: Math.max(1, opts.cacheMax ?? 500),
5972
+ maxSize: 64 * 1024 * 1024,
5973
+ sizeCalculation: (entry) => entry.body.byteLength,
5974
+ ttl: 6e4
5975
+ });
5976
+ const defaultQ = clamp(opts.defaultQuality ?? 75, 1, 100) || 75;
5977
+ const maxW = clamp(opts.maxWidth ?? 4096, 1, 8192) || 4096;
5978
+ let active = 0;
5979
+ return function imageMiddleware(req, res, next) {
5980
+ let u;
5981
+ try {
5982
+ u = new URL(req.url ?? "", "http://x");
5983
+ } catch {
5984
+ next();
5985
+ return;
5986
+ }
5987
+ if (u.pathname !== endpoint) {
5988
+ next();
5989
+ return;
5990
+ }
5991
+ handle(u).catch((error) => {
5992
+ if (res.destroyed || res.writableEnded) return;
5993
+ res.statusCode = error instanceof ImageError ? error.status : 500;
5994
+ res.setHeader("content-type", "text/plain; charset=utf-8");
5995
+ res.setHeader("x-content-type-options", "nosniff");
5996
+ res.setHeader("cache-control", "no-store");
5997
+ res.end(req.method === "HEAD" ? void 0 : error instanceof ImageError ? error.message : "image processing failed");
5998
+ });
5999
+ async function handle(url) {
6000
+ const src = url.searchParams.get("src");
6001
+ if (!src) throw new ImageError(400, "missing ?src=");
6002
+ if (req.method && req.method !== "GET" && req.method !== "HEAD") throw new ImageError(405, "method not allowed");
6003
+ const wParam = url.searchParams.get("w");
6004
+ const w = wParam === null ? void 0 : clamp(parseInt(wParam, 10), 1, maxW) || void 0;
6005
+ const q = clamp(parseInt(url.searchParams.get("q") ?? String(defaultQ), 10), 1, 100) || defaultQ;
6006
+ const fmt = (url.searchParams.get("fmt") ?? "").toLowerCase();
6007
+ if (fmt && fmt !== "original" && !SUPPORTED_FORMATS.has(fmt)) throw new ImageError(400, "unsupported format");
6008
+ if (fmt === "original" && (wParam !== null || url.searchParams.has("q"))) throw new ImageError(400, "original mode does not accept transformations");
6009
+ const format = fmt || pickAuto(req.headers.accept);
6010
+ const key = JSON.stringify([
6011
+ src,
6012
+ w,
6013
+ q,
6014
+ format
6015
+ ]);
6016
+ const cached = cache.get(key);
6017
+ if (cached) {
6018
+ sendImage(req, res, cached);
6019
+ return;
6020
+ }
6021
+ if (active >= 4) throw new ImageError(503, "image processing busy");
6022
+ active++;
6023
+ try {
6024
+ let out;
6025
+ let contentType;
6026
+ if (format === "original") {
6027
+ out = await loadSource(src, allow, getPublicDir(), getDevServer?.());
6028
+ contentType = originalContentType(out);
6029
+ } else {
6030
+ const sharp = await (sharpCapability ??= (dependencies.loadSharp ?? loadSharp)());
6031
+ if (!sharp) throw new ImageError(501, "image optimizer unavailable");
6032
+ const input = await loadSource(src, allow, getPublicDir(), getDevServer?.());
6033
+ let pipe = sharp.default(input, { limitInputPixels: 4e7 }).rotate();
6034
+ if (w) pipe = pipe.resize({
6035
+ width: w,
6036
+ withoutEnlargement: true
6037
+ });
6038
+ out = await pipe.toFormat(format === "jpg" ? "jpeg" : format, { quality: q }).toBuffer();
6039
+ contentType = `image/${format === "jpg" ? "jpeg" : format}`;
6040
+ }
6041
+ if (out.byteLength > MAX_INPUT_BYTES) throw new ImageError(413, "output too large");
6042
+ const entry = {
6043
+ body: out,
6044
+ contentType,
6045
+ etag: `"${createHash("sha1").update(out).digest("hex").slice(0, 16)}"`
6046
+ };
6047
+ cache.set(key, entry);
6048
+ sendImage(req, res, entry);
6049
+ } finally {
6050
+ active--;
5743
6051
  }
5744
6052
  }
6053
+ };
6054
+ }
6055
+ function clamp(n, lo, hi) {
6056
+ if (!Number.isFinite(n)) return 0;
6057
+ return Math.max(lo, Math.min(hi, n));
6058
+ }
6059
+ /** Media range specificity takes precedence over wildcard quality (RFC 9110). */
6060
+ function acceptQuality(contentType, accept) {
6061
+ if (accept === void 0) return 1;
6062
+ let specificity = -1;
6063
+ let quality = 0;
6064
+ for (const range of (Array.isArray(accept) ? accept.join(",") : accept).split(",")) {
6065
+ const [type, ...parameters] = range.trim().toLowerCase().split(";");
6066
+ const rank = type === contentType ? 2 : type === "image/*" ? 1 : type === "*/*" ? 0 : -1;
6067
+ if (rank < 0 || rank < specificity) continue;
6068
+ const qText = parameters.map((p) => p.trim()).find((p) => p.startsWith("q="))?.slice(2);
6069
+ const q = qText === void 0 ? 1 : /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/.test(qText) ? Number(qText) : 0;
6070
+ if (rank > specificity) quality = q;
6071
+ else quality = Math.max(quality, q);
6072
+ specificity = rank;
6073
+ }
6074
+ return quality;
6075
+ }
6076
+ function pickAuto(accept) {
6077
+ const candidates = [
6078
+ "jpeg",
6079
+ "webp",
6080
+ "avif"
6081
+ ];
6082
+ let selected = "";
6083
+ let best = 0;
6084
+ for (const format of candidates) {
6085
+ const quality = acceptQuality(`image/${format}`, accept);
6086
+ if (quality > best) {
6087
+ selected = format;
6088
+ best = quality;
6089
+ }
5745
6090
  }
5746
- for (const directory of [
5747
- "rsc",
5748
- "ssr",
5749
- "client"
5750
- ]) try {
5751
- await walk(path.join(distDir, directory));
5752
- } catch (error) {
5753
- if (directory !== "ssr" || error.code !== "ENOENT") throw error;
6091
+ if (!selected) throw new ImageError(406, "no acceptable image format");
6092
+ return selected;
6093
+ }
6094
+ function completePng(input) {
6095
+ let offset = 8;
6096
+ let hasPixels = false;
6097
+ while (offset + 12 <= input.length) {
6098
+ const size = input.readUInt32BE(offset);
6099
+ const type = input.toString("ascii", offset + 4, offset + 8);
6100
+ const end = offset + 12 + size;
6101
+ if (end > input.length) return false;
6102
+ if (type === "IDAT" && size > 0) hasPixels = true;
6103
+ if (type === "IEND") return size === 0 && end === input.length && hasPixels;
6104
+ offset = end;
5754
6105
  }
5755
- return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
6106
+ return false;
5756
6107
  }
5757
- function manifestPayload(manifest) {
5758
- return JSON.stringify({
5759
- schemaVersion: manifest.schemaVersion,
5760
- ...manifest.schemaVersion >= 3 ? { ssgRoutes: manifest.ssgRoutes } : {},
5761
- deploymentFiles: manifest.deploymentFiles.map((file) => ({
5762
- path: file.path,
5763
- sha256: file.sha256
5764
- })),
5765
- files: manifest.files.map((file) => ({
5766
- path: file.path,
5767
- sha256: file.sha256,
5768
- scriptHashes: file.scriptHashes,
5769
- ...manifest.schemaVersion < 3 || file.generatedAt === void 0 ? {} : { generatedAt: file.generatedAt }
5770
- }))
5771
- });
6108
+ /** Only inert raster containers are served directly; never trust extensions or upstream MIME. */
6109
+ function originalContentType(input) {
6110
+ if (input.length >= 33 && input.subarray(0, 8).equals(Buffer.from([
6111
+ 137,
6112
+ 80,
6113
+ 78,
6114
+ 71,
6115
+ 13,
6116
+ 10,
6117
+ 26,
6118
+ 10
6119
+ ])) && input.readUInt32BE(8) === 13 && input.toString("ascii", 12, 16) === "IHDR" && input.readUInt32BE(16) > 0 && input.readUInt32BE(20) > 0 && completePng(input)) return "image/png";
6120
+ if (input.length >= 4 && input[0] === 255 && input[1] === 216 && input[2] === 255 && input[input.length - 2] === 255 && input[input.length - 1] === 217) return "image/jpeg";
6121
+ if (input.length >= 14 && ["GIF87a", "GIF89a"].includes(input.toString("ascii", 0, 6)) && input.readUInt16LE(6) > 0 && input.readUInt16LE(8) > 0 && input[input.length - 1] === 59) return "image/gif";
6122
+ if (input.length >= 20 && input.toString("ascii", 0, 4) === "RIFF" && input.readUInt32LE(4) === input.length - 8 && input.toString("ascii", 8, 12) === "WEBP" && [
6123
+ "VP8 ",
6124
+ "VP8L",
6125
+ "VP8X"
6126
+ ].includes(input.toString("ascii", 12, 16))) return "image/webp";
6127
+ throw new ImageError(415, "unsupported original image type");
6128
+ }
6129
+ function sendImage(req, res, entry) {
6130
+ res.setHeader("vary", "Accept");
6131
+ res.setHeader("x-content-type-options", "nosniff");
6132
+ if (acceptQuality(entry.contentType, req.headers.accept) <= 0) throw new ImageError(406, "image type not acceptable");
6133
+ res.setHeader("cache-control", "public, max-age=60, must-revalidate");
6134
+ res.setHeader("etag", entry.etag);
6135
+ if (req.headers["if-none-match"] === entry.etag) {
6136
+ res.statusCode = 304;
6137
+ res.end();
6138
+ return;
6139
+ }
6140
+ res.statusCode = 200;
6141
+ res.setHeader("content-type", entry.contentType);
6142
+ res.setHeader("content-length", entry.body.byteLength);
6143
+ res.end(req.method === "HEAD" ? void 0 : entry.body);
5772
6144
  }
5773
- async function createManifest(distDir, ssgRoutes = []) {
5774
- assertDistinctHtmlRouteIdentities(ssgRoutes);
5775
- await fs$3.access(path.join(distDir, "rsc/index.js"));
5776
- const deploymentFiles = await readDeploymentFiles(distDir);
5777
- const files = await readHtmlFiles(path.join(distDir, "client"), true);
5778
- const payload = {
5779
- schemaVersion: SCHEMA_VERSION,
5780
- ssgRoutes: [...new Set(ssgRoutes)].sort(),
5781
- deploymentFiles,
5782
- files
5783
- };
5784
- return {
5785
- ...payload,
5786
- buildId: sha256(manifestPayload(payload))
5787
- };
6145
+ function inside(root, file) {
6146
+ const relative = path.relative(root, file);
6147
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
5788
6148
  }
5789
- /** Called only after every build environment, SSG output and SPA shell are complete. */
5790
- async function generateStaticCspManifest(distDir, options = {}) {
5791
- const manifest = await createManifest(distDir, options.ssgRoutes);
5792
- const destination = path.join(distDir, STATIC_CSP_MANIFEST);
5793
- const temporary = `${destination}.${process.pid}.tmp`;
6149
+ async function loadSource(src, allow, publicDir, server) {
6150
+ if (/^[a-z][a-z\d+.-]*:/i.test(src) || src.startsWith("//")) {
6151
+ let url;
6152
+ try {
6153
+ url = new URL(src);
6154
+ } catch {
6155
+ throw new ImageError(400, "invalid source URL");
6156
+ }
6157
+ return fetchRemoteImage(url.href, allow, MAX_INPUT_BYTES);
6158
+ }
6159
+ let pathname;
5794
6160
  try {
5795
- await fs$3.writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n");
5796
- await fs$3.rename(temporary, destination);
5797
- } finally {
5798
- await fs$3.rm(temporary, { force: true });
6161
+ pathname = decodeURIComponent(src.split(/[?#]/, 1)[0]);
6162
+ } catch {
6163
+ throw new ImageError(400, "invalid source URL");
5799
6164
  }
5800
- return manifest;
5801
- }
5802
- function validateManifest(value) {
5803
- if (!value || typeof value !== "object") throw new Error("Invalid static CSP manifest");
5804
- const manifest = value;
5805
- if (manifest.schemaVersion !== SCHEMA_VERSION && manifest.schemaVersion !== 2) throw new Error("Unsupported static CSP manifest schema");
5806
- if (manifest.schemaVersion >= 3 && (!Array.isArray(manifest.ssgRoutes) || manifest.ssgRoutes.some((route, index) => typeof route !== "string" || !route.startsWith("/") || route.includes("?") || route.includes("#") || index > 0 && route <= manifest.ssgRoutes[index - 1]))) throw new Error("Invalid static CSP manifest SSG routes");
5807
- if (manifest.ssgRoutes) assertDistinctHtmlRouteIdentities(manifest.ssgRoutes);
5808
- const digest = /^[a-f0-9]{64}$/;
5809
- if (!Array.isArray(manifest.deploymentFiles) || typeof manifest.buildId !== "string" || !digest.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error("Invalid static CSP manifest fields");
5810
- let previous = "";
5811
- for (const file of manifest.deploymentFiles) {
5812
- if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || !isDeploymentPath(file.path) || typeof file.sha256 !== "string" || !digest.test(file.sha256)) throw new Error("Invalid static CSP manifest deployment entry");
5813
- previous = file.path;
5814
- }
5815
- if (!manifest.deploymentFiles.some((file) => file.path === "rsc/index.js")) throw new Error("Static CSP manifest is missing the RSC build");
5816
- previous = "";
5817
- for (const file of manifest.files) {
5818
- if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || file.path.includes("\\") || file.path.startsWith("/") || file.path.split("/").some((segment) => !segment || segment === "." || segment === "..") || !file.path.toLowerCase().endsWith(".html") || typeof file.sha256 !== "string" || !digest.test(file.sha256) || manifest.schemaVersion === 3 && (!Number.isSafeInteger(file.generatedAt) || file.generatedAt < 0) || !Array.isArray(file.scriptHashes) || !file.scriptHashes.every((hash) => typeof hash === "string" && /^'sha256-[A-Za-z0-9+/]{43}='$/.test(hash))) throw new Error("Invalid static CSP manifest file entry");
5819
- previous = file.path;
5820
- }
5821
- if (sha256(manifestPayload(manifest)) !== manifest.buildId) throw new Error("Static CSP manifest integrity mismatch");
5822
- }
5823
- /** Missing manifests are legacy builds; present but invalid manifests always stop startup. */
5824
- async function loadStaticCspManifest(distDir, options = {}) {
5825
- let serialized;
5826
- try {
5827
- serialized = await fs$3.readFile(path.join(distDir, STATIC_CSP_MANIFEST), "utf8");
5828
- } catch (error) {
5829
- if (error.code !== "ENOENT") throw error;
5830
- const manifest = await createManifest(distDir);
5831
- options.onLegacyBuild?.();
5832
- return indexManifest(manifest, true);
5833
- }
5834
- let manifest;
6165
+ if (pathname.includes("\0") || pathname.includes("\\") || pathname.split("/").includes("..")) throw new ImageError(400, "path traversal blocked");
5835
6166
  try {
5836
- manifest = JSON.parse(serialized);
6167
+ const root = publicDir ? await promises.realpath(publicDir).catch(() => path.resolve(publicDir)) : void 0;
6168
+ const resolved = root ? path.resolve(root, pathname.replace(/^\//, "")) : void 0;
6169
+ if (root && resolved && !inside(root, resolved)) throw new ImageError(400, "path traversal blocked");
6170
+ let real;
6171
+ try {
6172
+ if (!root || !resolved) throw new Error("public directory disabled");
6173
+ real = await promises.realpath(resolved);
6174
+ if (!inside(root, real)) throw new ImageError(400, "path traversal blocked");
6175
+ } catch (error) {
6176
+ if (error instanceof ImageError || !server?.config) throw error;
6177
+ const candidate = pathname.startsWith("/@fs/") ? path.resolve(pathname.slice(4)) : path.resolve(server.config.root, pathname.replace(/^\//, ""));
6178
+ if (!isFileLoadingAllowed(server.config, normalizePath(candidate))) throw new ImageError(403, "source access denied");
6179
+ real = await promises.realpath(candidate);
6180
+ if (!isFileLoadingAllowed(server.config, normalizePath(real))) throw new ImageError(403, "source access denied");
6181
+ }
6182
+ const file = await promises.open(real, "r");
6183
+ try {
6184
+ const stat = await file.stat();
6185
+ if (!stat.isFile()) throw new ImageError(400, "invalid source file");
6186
+ if (stat.size > MAX_INPUT_BYTES) throw new ImageError(413, "source too large");
6187
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, 26214401));
6188
+ let size = 0;
6189
+ while (size < buffer.length) {
6190
+ const { bytesRead } = await file.read(buffer, size, buffer.length - size, null);
6191
+ if (!bytesRead) break;
6192
+ size += bytesRead;
6193
+ }
6194
+ if (size > MAX_INPUT_BYTES || size > stat.size) throw new ImageError(413, "source changed during read");
6195
+ return buffer.subarray(0, size);
6196
+ } finally {
6197
+ await file.close();
6198
+ }
5837
6199
  } catch (error) {
5838
- throw new Error("Invalid static CSP manifest JSON", { cause: error });
6200
+ if (error instanceof ImageError) throw error;
6201
+ throw new ImageError(404, "source not found");
5839
6202
  }
5840
- validateManifest(manifest);
5841
- const deployed = await readDeploymentFiles(distDir);
5842
- if (JSON.stringify(deployed) !== JSON.stringify(manifest.deploymentFiles)) throw new Error("Static CSP manifest does not match the deployment build");
5843
- const actual = await readHtmlFiles(path.join(distDir, "client"));
5844
- if (actual.length !== manifest.files.length || actual.some((file, index) => file.path !== manifest.files[index].path || file.sha256 !== manifest.files[index].sha256)) throw new Error("Static CSP manifest does not match deployed HTML files");
5845
- return indexManifest(manifest, false);
5846
6203
  }
5847
- function indexManifest(manifest, legacy) {
6204
+ //#endregion
6205
+ //#region src/engine/seo/config.ts
6206
+ /** 默认 SEO 配置 */
6207
+ var DEFAULT_SEO_CONFIG = {
6208
+ baseUrl: "",
6209
+ siteName: "My App",
6210
+ defaultLanguage: "zh",
6211
+ supportedLanguages: ["zh", "en"],
6212
+ defaultTitle: "My App",
6213
+ defaultDescription: "",
6214
+ titleTemplate: "%s | My App",
6215
+ keywords: [],
6216
+ author: "",
6217
+ robots: "index,follow",
6218
+ sitemap: {
6219
+ priority: {
6220
+ "/": 1,
6221
+ "/blog/*": .7,
6222
+ "*": .5
6223
+ },
6224
+ changeFreq: {
6225
+ "/": "daily",
6226
+ "/blog/*": "weekly",
6227
+ "*": "monthly"
6228
+ },
6229
+ excludePatterns: ["/admin/*", "/api/*"],
6230
+ cacheTimeout: 3600
6231
+ },
6232
+ openGraph: {
6233
+ enabled: true,
6234
+ locale: "zh_CN",
6235
+ defaultImage: "/images/og-default.jpg"
6236
+ },
6237
+ twitter: {
6238
+ enabled: true,
6239
+ card: "summary_large_image",
6240
+ site: ""
6241
+ },
6242
+ structuredData: {
6243
+ enabled: true,
6244
+ organizationLogo: ""
6245
+ }
6246
+ };
6247
+ /** 深度合并配置 */
6248
+ function mergeSEOConfig(base, override) {
5848
6249
  return {
5849
- legacy,
5850
- ssgRoutes: legacy || manifest.schemaVersion < 3 ? void 0 : Object.freeze([...manifest.ssgRoutes ?? []]),
5851
- buildId: manifest.buildId,
5852
- generatedAt: new Map(legacy || manifest.schemaVersion < 3 ? [] : manifest.files.flatMap((file) => file.generatedAt === void 0 ? [] : [[file.path, file.generatedAt]])),
5853
- scriptHashes: new Map(manifest.files.map((file) => [file.path, Object.freeze([...file.scriptHashes])]))
6250
+ ...base,
6251
+ ...override,
6252
+ sitemap: {
6253
+ ...base.sitemap,
6254
+ ...override.sitemap
6255
+ },
6256
+ openGraph: {
6257
+ ...base.openGraph,
6258
+ ...override.openGraph
6259
+ },
6260
+ twitter: {
6261
+ ...base.twitter,
6262
+ ...override.twitter
6263
+ },
6264
+ structuredData: {
6265
+ ...base.structuredData,
6266
+ ...override.structuredData
6267
+ }
5854
6268
  };
5855
6269
  }
5856
6270
  //#endregion
5857
- //#region src/server/productionRuntime.ts
5858
- /** Shared production application assembly. Listening and process signals belong to callers. */
5859
- function safeOrigin(url) {
5860
- if (!url) return void 0;
5861
- try {
5862
- return new URL(url).origin;
5863
- } catch {
5864
- return;
5865
- }
5866
- }
5867
- /**
5868
- * 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
5869
- * 导出以便单测覆盖(纯函数)
5870
- */
5871
- function extractRoutesForSitemap(config) {
5872
- const routes = config.routes ?? {};
5873
- const out = [];
5874
- for (const path of Object.keys(routes)) {
5875
- if (path.includes("*") || path.includes(":")) continue;
5876
- if (path.startsWith("/__") || path.startsWith("/api/")) continue;
5877
- out.push(path);
5878
- }
5879
- return out;
5880
- }
6271
+ //#region src/engine/seo/SEOEngine.ts
5881
6272
  /**
5882
- * 把 ssr.config.ts 的 telemetry 第三方配置映射到可选 adapter 使用的 env。
5883
- * 这一步必须发生在 import dist/rsc/index.js 之前,因为内置 entry.server 会在模块加载时
5884
- * 初始化 auto hooks。engine 仍不静态 import vendor SDK;这里仅做启动期配置桥接。
6273
+ * SEO 引擎 - 单例模式
6274
+ *
6275
+ * 核心功能:
6276
+ * - Meta 标签生成
6277
+ * - 结构化数据(JSON-LD)生成
6278
+ * - 站点地图生成
6279
+ * - Open Graph / Twitter Cards
5885
6280
  */
5886
- function applyTelemetryIntegrationEnv(runtime) {
5887
- const telemetry = runtime?.telemetry;
5888
- delete process.env.SENTRY_ENVIRONMENT;
5889
- if (!telemetry) {
5890
- process.env.SENTRY_ENABLED = "false";
5891
- delete process.env.DD_SERVICE;
5892
- delete process.env.DD_ENV;
5893
- delete process.env.DD_VERSION;
5894
- delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
5895
- delete process.env.OTEL_SERVICE_NAME;
5896
- return;
6281
+ var SEOEngine = class SEOEngine {
6282
+ static instance = null;
6283
+ logger = Logger.getInstance();
6284
+ config;
6285
+ initialized = false;
6286
+ pageDataCache = /* @__PURE__ */ new Map();
6287
+ sitemapCache = null;
6288
+ sitemapLastGenerated = 0;
6289
+ constructor(config) {
6290
+ this.config = config ? mergeSEOConfig(DEFAULT_SEO_CONFIG, config) : { ...DEFAULT_SEO_CONFIG };
5897
6291
  }
5898
- const sentryIntegration = telemetry.integrations?.sentry;
5899
- if (sentryIntegration) {
5900
- process.env.SENTRY_ENABLED = sentryIntegration.enabled ? "true" : "false";
5901
- if (sentryIntegration.enabled) {
5902
- if (sentryIntegration.dsn) process.env.SENTRY_DSN = sentryIntegration.dsn;
5903
- if (sentryIntegration.tracesSampleRate !== void 0) process.env.SENTRY_TRACES_SAMPLE_RATE = String(sentryIntegration.tracesSampleRate);
5904
- if (sentryIntegration.environment) process.env.SENTRY_ENVIRONMENT = sentryIntegration.environment;
5905
- } else {
5906
- delete process.env.SENTRY_DSN;
5907
- delete process.env.SENTRY_TRACES_SAMPLE_RATE;
5908
- }
5909
- } else {
5910
- process.env.SENTRY_ENABLED = "false";
5911
- delete process.env.SENTRY_DSN;
5912
- delete process.env.SENTRY_TRACES_SAMPLE_RATE;
6292
+ /** 获取单例实例 */
6293
+ static getInstance(config) {
6294
+ if (!SEOEngine.instance) SEOEngine.instance = new SEOEngine(config);
6295
+ return SEOEngine.instance;
5913
6296
  }
5914
- delete process.env.DD_SERVICE;
5915
- delete process.env.DD_ENV;
5916
- delete process.env.DD_VERSION;
5917
- delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
5918
- delete process.env.OTEL_SERVICE_NAME;
5919
- for (const exporter of telemetry.exporters) {
5920
- if (exporter.type === "datadog") {
5921
- if (exporter.service) process.env.DD_SERVICE = exporter.service;
5922
- if (telemetry.environment) process.env.DD_ENV = telemetry.environment;
5923
- if (telemetry.release) process.env.DD_VERSION = telemetry.release;
5924
- continue;
5925
- }
5926
- if (exporter.type === "otel") {
5927
- if (exporter.endpoint) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exporter.endpoint;
5928
- if (exporter.serviceName) process.env.OTEL_SERVICE_NAME = exporter.serviceName;
5929
- }
6297
+ /** 重置实例(仅用于测试) */
6298
+ static resetInstance() {
6299
+ SEOEngine.instance = null;
5930
6300
  }
5931
- }
5932
- async function prepareProductionBuild(root = process.cwd()) {
5933
- const rscDistEntry = path.resolve(root, "dist/rsc/index.js");
5934
- const clientDir = path.resolve(root, "dist/client");
5935
- await fs$3.access(rscDistEntry);
5936
- await fs$3.access(clientDir);
5937
- return {
5938
- rscDistEntry,
5939
- clientDir,
5940
- staticCspIndex: await loadStaticCspManifest(path.dirname(clientDir), { onLegacyBuild: () => logger$8.warn("[CSP] 构建缺少 static-csp-manifest.json;已在启动期生成兼容索引,请重新构建以生成清单") })
5941
- };
5942
- }
5943
- async function createProductionRuntime(config, options = {}) {
5944
- const { rscDistEntry, clientDir, staticCspIndex } = options.build ?? await prepareProductionBuild(options.root);
5945
- const ssgRoutes = staticCspIndex.ssgRoutes ?? (Array.isArray(config.ssg?.routes) ? config.ssg.routes : []);
5946
- const ssgFiles = new Map(ssgRoutes.map((route) => [route, routeToFilePath(route)]));
5947
- const ssgAliases = /* @__PURE__ */ new Map();
5948
- const configuredRoutes = Object.keys(config.routes ?? {});
5949
- assertDistinctHtmlRouteIdentities(configuredRoutes, { allowPatterns: true });
5950
- const routeNames = /* @__PURE__ */ new Set([...ssgFiles.keys(), ...configuredRoutes.filter((route) => !isHtmlRoutePattern(route))]);
5951
- assertDistinctHtmlRouteIdentities(routeNames);
5952
- const declaredIdentities = new Set([...routeNames].map((route) => decodeHtmlPathname(route)));
5953
- const explicitRoutes = /* @__PURE__ */ new Map();
5954
- for (const route of routeNames) {
5955
- const target = new URL(route, "http://localhost").pathname;
5956
- explicitRoutes.set(decodeHtmlPathname(route), target);
5957
- if ((route === "/" || !route.endsWith("/")) && !declaredIdentities.has(decodeHtmlPathname(route + "_.rsc"))) explicitRoutes.set(decodeHtmlPathname(route + "_.rsc"), target + "_.rsc");
6301
+ /** 更新配置 */
6302
+ updateConfig(config) {
6303
+ this.config = mergeSEOConfig(this.config, config);
6304
+ this.clearCache();
5958
6305
  }
5959
- for (const [canonical, file] of ssgFiles) {
5960
- const logical = decodeHtmlPathname(canonical);
5961
- const target = new URL(canonical, "http://localhost").pathname;
5962
- const base = logical.replace(/\/$/, "") || "/";
5963
- for (const alias of [
5964
- logical,
5965
- base,
5966
- base === "/" ? "/" : base + "/",
5967
- base === "/" ? "/index.html" : base + "/index.html",
5968
- "/" + file
5969
- ]) {
5970
- ssgAliases.set(alias, target);
5971
- ssgAliases.set(alias + "_.rsc", target + "_.rsc");
5972
- }
6306
+ /** 获取当前配置 */
6307
+ getConfig() {
6308
+ return this.config;
5973
6309
  }
5974
- const resolveSsgIdentity = (pathname) => {
5975
- const logical = decodeHtmlPathname(pathname);
5976
- const known = ssgAliases.get(logical);
5977
- return known ? explicitRoutes.get(logical) ?? known : pathname;
5978
- };
5979
- const cleanups = [];
5980
- let closed;
5981
- const close = () => closed ??= (async () => {
5982
- const errors = (await Promise.allSettled(cleanups.reverse().map((cleanup) => Promise.resolve().then(cleanup)))).filter((result) => result.status === "rejected");
5983
- if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Production runtime cleanup failed");
5984
- })();
5985
- try {
5986
- validateRequestLimits(config.server.requestLimits);
5987
- const runtime = config.runtime;
5988
- applyTelemetryIntegrationEnv(runtime);
5989
- const sentryIntegration = runtime?.telemetry ? runtime.telemetry.integrations?.sentry : void 0;
5990
- if (sentryIntegration?.enabled && process.env.SENTRY_DSN) logger$8.info(`🛰️ Sentry integration 来自 ssr.config.ts runtime.telemetry.integrations`);
5991
- else if (sentryIntegration?.enabled) logger$8.warn(`🛰️ Sentry integration 已启用但缺少 SENTRY_DSN,跳过 Sentry adapter`);
5992
- const { fetch: rscHandler } = resolveFetchHandler(await import(
5993
- /* @vite-ignore */
5994
- pathToFileURL(rscDistEntry).href
5995
- ));
5996
- const extraConnectSrc = Array.from(new Set([runtime?.services?.api, runtime?.services?.telemetry].map(safeOrigin).filter((origin) => !!origin)));
5997
- const app = express();
5998
- app.disable("x-powered-by");
5999
- app.set("trust proxy", config.server.trustProxy ?? false);
6000
- app.use(createProductionJsonMiddleware());
6001
- const opsConfig = resolveOpsConfig(config, "production");
6002
- for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
6003
- const { createSecurityMiddleware, createCompressionMiddleware, createCspNonceMiddleware } = await Promise.resolve().then(() => middleware_exports);
6004
- app.use(createCspNonceMiddleware());
6005
- app.use(createSecurityMiddleware(false, extraConnectSrc));
6006
- app.use(createCompressionMiddleware());
6007
- if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
6008
- const { requestContext } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
6009
- const { createServerRequestContext, applyAnonCookie } = await Promise.resolve().then(() => createServerRequestContext_exports);
6010
- const cookieDomain = runtime?.cookieDomain;
6011
- app.use((req, res, next) => {
6012
- const { data, needsAnonCookie } = createServerRequestContext(req);
6013
- if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
6014
- requestContext.run(data, () => next());
6015
- });
6016
- if (runtime?.i18n?.prefixDefault) {
6017
- const { createLocaleRedirectMiddleware } = await Promise.resolve().then(() => LocaleRedirect_exports);
6018
- const { resolveI18nConfig } = await import("./i18n-CnXYAgQE.js").then((n) => n.t);
6019
- const middleware = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(runtime.i18n) });
6020
- if (middleware) {
6021
- app.use(middleware);
6022
- logger$8.info(`🌐 Locale redirect 已启用 (prefixDefault=true)`);
6023
- }
6024
- }
6025
- const hasStaticExps = runtime?.experiments && Object.keys(runtime.experiments).length > 0;
6026
- const hasManifest = !!runtime?.experimentManifest?.endpoint;
6027
- let manifestLoader;
6028
- let exposureQueue;
6029
- if (hasStaticExps || hasManifest) {
6030
- const baseOrigin = runtime?.services?.api;
6031
- const { createABVariantMiddleware } = await Promise.resolve().then(() => ABVariantMiddleware_exports);
6032
- const { resolveManifestLoader } = await Promise.resolve().then(() => ManifestLoader_exports);
6033
- const { resolveExposureQueue } = await Promise.resolve().then(() => ExposureQueue_exports);
6034
- manifestLoader = resolveManifestLoader(runtime?.experimentManifest, runtime?.experiments ?? {}, baseOrigin);
6035
- if (manifestLoader) {
6036
- cleanups.push(() => manifestLoader?.destroy());
6037
- await manifestLoader.init();
6038
- }
6039
- exposureQueue = resolveExposureQueue(runtime?.experimentTracking, baseOrigin);
6040
- cleanups.push(async () => {
6041
- try {
6042
- await exposureQueue?.flush();
6043
- } finally {
6044
- exposureQueue?.destroy();
6045
- }
6046
- });
6047
- app.use(createABVariantMiddleware({
6048
- experiments: runtime?.experiments ?? {},
6049
- manifestLoader,
6050
- exposureQueue
6051
- }));
6052
- const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(runtime?.experiments ?? {});
6053
- logger$8.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
6054
- }
6055
- if (opsConfig.health.enabled) app.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
6056
- res.json({
6057
- status: "healthy",
6058
- version: package_default.version,
6059
- mode: "plugin-rsc-production",
6060
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
6061
- });
6062
- });
6063
- options.setupRoutes?.(app);
6064
- const staticHtmlLimiter = createRequestLimiter("staticHtml", config.server.requestLimits?.staticHtml);
6065
- const seoLimiter = createRequestLimiter("seo", config.server.requestLimits?.seo);
6066
- app.use((req, res, next) => {
6067
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6068
- let pathname;
6069
- try {
6070
- pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
6071
- } catch {
6072
- res.status(400).end();
6073
- return;
6074
- }
6075
- if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
6076
- next();
6077
- });
6078
- app.use(createStaticAssetMiddleware(clientDir));
6079
- app.use("/assets", (_req, res) => {
6080
- res.status(404).set("Cache-Control", "no-store").end();
6081
- });
6082
- const { createImageMiddleware } = await import("./createImagePlugin-QNvY9vPB.js").then((n) => n.r);
6083
- const { resolveImageOptions } = await Promise.resolve().then(() => resolveImageOptions_exports);
6084
- app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
6085
- const { createAutoCacheStore } = await Promise.resolve().then(() => createAutoCacheStore_exports);
6086
- const { RedisInvalidationBus } = await Promise.resolve().then(() => RedisInvalidationBus_exports);
6087
- const { hasRuntimeRedisConnection, resolveRuntimeRedisConfig } = await Promise.resolve().then(() => resolveRuntimeRedis_exports);
6088
- const redisCfg = resolveRuntimeRedisConfig(runtime?.redis);
6089
- const hasRedisConfig = hasRuntimeRedisConnection(runtime?.redis);
6090
- const cacheRoutes = { ...config.routes };
6091
- for (const route of ssgRoutes) {
6092
- const rule = cacheRoutes[route];
6093
- cacheRoutes[route] = typeof rule === "object" ? {
6094
- ...rule,
6095
- mode: "ssg"
6096
- } : "ssg";
6097
- }
6098
- const cache = createIsrCacheHandler({
6099
- ...config,
6100
- routes: cacheRoutes
6101
- }, {
6102
- buildId: process.env.APP_VERSION ?? staticCspIndex.buildId,
6103
- resolveInvalidationPath: resolveSsgIdentity,
6104
- staticSeedAdmission: (req, res) => admitRequest(staticHtmlLimiter, req, res),
6105
- staticSeedInfo: (pathname) => {
6106
- const htmlPath = ssgFiles.get(pathname);
6107
- if (!htmlPath) return;
6108
- const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
6109
- return generatedAt === void 0 || generatedAt > Date.now() ? void 0 : { generatedAt };
6110
- },
6111
- staticSeed: async (pathname, policy) => {
6112
- const htmlPath = ssgFiles.get(pathname);
6113
- if (!htmlPath) return;
6114
- const hashes = staticCspIndex.scriptHashes.get(htmlPath);
6115
- if (!hashes) return;
6116
- const absolute = path.join(clientDir, htmlPath);
6117
- const body = await fs$3.readFile(absolute);
6118
- const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
6119
- if (generatedAt === void 0) return;
6120
- return {
6121
- body,
6122
- statusCode: 200,
6123
- contentType: "text/html; charset=utf-8",
6124
- headers: {
6125
- "content-type": "text/html; charset=utf-8",
6126
- "content-security-policy": applyStaticScriptPolicy(policy, hashes),
6127
- "cache-control": "no-cache",
6128
- "x-served-by": "ssg-static"
6129
- },
6130
- storedAt: generatedAt,
6131
- expiresAt: 0,
6132
- hardExpiresAt: 0,
6133
- tags: []
6134
- };
6135
- },
6136
- store: createAutoCacheStore({
6137
- responseNamespace: `production:${process.env.ISR_CACHE_NAMESPACE ?? "default"}`,
6138
- redisUrl: redisCfg?.url,
6139
- redisHost: redisCfg?.host,
6140
- redisPort: redisCfg?.port,
6141
- redisPassword: redisCfg?.password,
6142
- redisKeyPrefix: redisCfg?.keyPrefix
6143
- }),
6144
- invalidationBus: hasRedisConfig ? new RedisInvalidationBus({
6145
- url: redisCfg?.url,
6146
- host: redisCfg?.host,
6147
- port: redisCfg?.port,
6148
- password: redisCfg?.password,
6149
- keyPrefix: redisCfg?.keyPrefix,
6150
- channel: redisCfg?.invalidationChannel
6151
- }) : void 0
6152
- });
6153
- cleanups.push(() => cache.destroy());
6154
- if (opsConfig.inventory.enabled) {
6155
- const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-GgzKVkq2.js");
6156
- app.use(createCacheInspectorMiddleware(cache, opsConfig));
6157
- logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
6158
- }
6159
- app.use((req, res, next) => {
6160
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6161
- let logical;
6162
- try {
6163
- logical = decodeHtmlPathname(req.path);
6164
- } catch {
6165
- res.status(400).end();
6166
- return;
6167
- }
6168
- const known = ssgAliases.get(logical);
6169
- if (!known) return next();
6170
- const canonical = explicitRoutes.get(logical) ?? known;
6171
- if (req.path === canonical) return next();
6172
- redirectLocal(res, 308, canonical, readRedirectQuery(req.url));
6173
- });
6174
- app.use(cache);
6175
- const staticHtml = createStaticHtmlMiddlewareWithLimiter(clientDir, staticCspIndex, staticHtmlLimiter);
6176
- app.use((req, res, next) => {
6177
- if (res.getHeader("X-Resolved-Mode") === "ssg" || ssgAliases.has(decodeHtmlPathname(req.path)) && explicitRoutes.has(decodeHtmlPathname(req.path))) return next();
6178
- staticHtml(req, res, next);
6179
- });
6180
- const { promRegistry } = await Promise.resolve().then(() => PromMetrics_exports);
6181
- if (opsConfig.metrics.enabled) app.get("/metrics", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("metrics", opsConfig), async (_req, res) => {
6182
- try {
6183
- res.set("content-type", promRegistry.contentType);
6184
- res.end(await promRegistry.metrics());
6185
- } catch (err) {
6186
- res.status(500).type("text/plain").end(`metrics error: ${String(err)}`);
6187
- }
6188
- });
6189
- const { SEOEngine } = await Promise.resolve().then(() => SEOEngine_exports);
6190
- const { resolveSeoConfig } = await Promise.resolve().then(() => resolveSeoConfig_exports);
6191
- const seoCfg = resolveSeoConfig(config);
6192
- const seo = SEOEngine.getInstance({ baseUrl: seoCfg.baseUrl });
6193
- cleanups.push(() => seo.shutdown());
6194
- await seo.initialize();
6195
- app.get("/sitemap.xml", async (_req, res) => {
6196
- try {
6197
- const xml = await seo.generateSitemap(extractRoutesForSitemap(config));
6198
- res.set("content-type", "application/xml; charset=utf-8");
6199
- res.set("cache-control", "public, max-age=3600");
6200
- res.end(xml);
6201
- } catch (err) {
6202
- res.status(500).type("text/plain").end(`sitemap error: ${String(err)}`);
6203
- }
6204
- });
6205
- app.get("/robots.txt", (_req, res) => {
6206
- res.set("content-type", "text/plain; charset=utf-8");
6207
- res.set("cache-control", "public, max-age=3600");
6208
- res.end(seo.generateRobotsTxt());
6209
- });
6210
- const { renderError500Html } = await import("./error500-template-DhaZzLOB.js");
6211
- const { getTraceId } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
6212
- app.all(/.*/, createProductionRequestHandler(rscHandler, (err, _req, res) => {
6213
- logger$8.error("[Server]", "请求处理异常", err);
6214
- if (!res.headersSent) {
6215
- const traceId = getTraceId();
6216
- res.status(500).type("text/html; charset=utf-8").send(renderError500Html(traceId));
6217
- } else res.destroy();
6218
- }));
6219
- return {
6220
- app,
6221
- close
6222
- };
6223
- } catch (error) {
6224
- await close().catch((cleanupError) => logger$8.error("[Server]", "Production initialization cleanup failed", cleanupError));
6225
- throw error;
6226
- }
6227
- }
6228
- var rawRequestBodies = /* @__PURE__ */ new WeakMap();
6229
- function createProductionJsonMiddleware() {
6230
- return express.json({
6231
- limit: "1mb",
6232
- verify: (req, _res, body) => {
6233
- rawRequestBodies.set(req, Buffer.from(body));
6234
- }
6235
- });
6236
- }
6237
- /** Own cancellation until the outgoing response finishes, not IncomingMessage.close. */
6238
- function createProductionRequestHandler(handler, onError) {
6239
- return async (req, res) => {
6240
- const controller = new AbortController();
6241
- const cleanup = () => {
6242
- req.removeListener("aborted", onAborted);
6243
- res.removeListener("close", onClose);
6244
- res.removeListener("finish", cleanup);
6245
- };
6246
- const onAborted = () => {
6247
- controller.abort(new DOMException("Client disconnected", "AbortError"));
6248
- cleanup();
6249
- };
6250
- const onClose = () => {
6251
- if (!res.writableFinished) onAborted();
6252
- else cleanup();
6253
- };
6254
- req.once("aborted", onAborted);
6255
- res.once("close", onClose);
6256
- res.once("finish", cleanup);
6257
- if (req.aborted || res.destroyed) onAborted();
6258
- try {
6259
- if (controller.signal.aborted) return;
6260
- const response = await handler(nodeToWebRequest(req, controller.signal));
6261
- if (controller.signal.aborted) {
6262
- response.body?.cancel(controller.signal.reason).catch(() => {});
6263
- return;
6310
+ /** 初始化 */
6311
+ async initialize() {
6312
+ if (this.initialized) return;
6313
+ this.logger.info("🎯 初始化 SEO 引擎...");
6314
+ this.initialized = true;
6315
+ this.logger.info("✅ SEO 引擎初始化完成");
6316
+ }
6317
+ /** 优化页面 SEO */
6318
+ async optimizePage(url, context, result) {
6319
+ const pageData = this.getOrCreatePageData(url, context);
6320
+ const seoTags = this.generateAllTags(pageData);
6321
+ const structuredData = this.generateStructuredData(pageData);
6322
+ const html = this.insertSEOTags(result.html, seoTags, structuredData);
6323
+ return {
6324
+ ...result,
6325
+ html,
6326
+ seoScore: this.calculateScore(pageData),
6327
+ meta: {
6328
+ ...result.meta,
6329
+ seoOptimized: true
6264
6330
  }
6265
- await pipeWebResponse(response, res);
6266
- } catch (error) {
6267
- if (!controller.signal.aborted) onError(error, req, res);
6268
- } finally {
6269
- if (controller.signal.aborted || res.writableFinished) cleanup();
6331
+ };
6332
+ }
6333
+ /** 生成站点地图 */
6334
+ async generateSitemap(routes) {
6335
+ const now = Date.now();
6336
+ if (this.sitemapCache && now - this.sitemapLastGenerated < this.config.sitemap.cacheTimeout * 1e3) return this.sitemapCache;
6337
+ if (!this.config.baseUrl) throw new Error("SEO baseUrl 未配置,无法生成 sitemap。请设置 ssr.config.ts runtime.site。");
6338
+ const sitemap = new SitemapStream({ hostname: this.config.baseUrl });
6339
+ const urls = routes || Array.from(this.pageDataCache.keys());
6340
+ const finalUrls = urls.length > 0 ? urls : ["/"];
6341
+ for (const url of finalUrls) {
6342
+ if (this.shouldExcludeUrl(url)) continue;
6343
+ sitemap.write({
6344
+ url,
6345
+ priority: this.getUrlPriority(url),
6346
+ changefreq: this.getUrlChangeFreq(url),
6347
+ lastmod: (/* @__PURE__ */ new Date()).toISOString()
6348
+ });
6270
6349
  }
6271
- };
6272
- }
6273
- function nodeToWebRequest(req, signal) {
6274
- const host = String(req.headers.host || "localhost");
6275
- const transport = req.socket?.encrypted ? "https" : "http";
6276
- const selected = req.protocol?.toLowerCase();
6277
- const url = `${selected === "https" || selected === "http" ? selected : transport}://${host}${req.url}`;
6278
- const headers = new Headers();
6279
- for (const [k, v] of Object.entries(req.headers)) {
6280
- if (v == null) continue;
6281
- if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
6282
- else headers.set(k, String(v));
6350
+ sitemap.end();
6351
+ this.sitemapCache = (await streamToPromise(sitemap)).toString();
6352
+ this.sitemapLastGenerated = now;
6353
+ this.logger.info(`✅ 站点地图已生成: ${urls.length} 个页面`);
6354
+ return this.sitemapCache;
6283
6355
  }
6284
- const method = req.method || "GET";
6285
- const init = {
6286
- method,
6287
- headers,
6288
- signal
6289
- };
6290
- if (method !== "GET" && method !== "HEAD") {
6291
- init.body = rawRequestBodies.get(req) ?? Readable.toWeb(req);
6292
- init.duplex = "half";
6356
+ /** 生成 Robots.txt */
6357
+ generateRobotsTxt() {
6358
+ return [
6359
+ "User-agent: *",
6360
+ "Allow: /",
6361
+ "",
6362
+ ...this.config.sitemap.excludePatterns.map((p) => `Disallow: ${p}`),
6363
+ "",
6364
+ `Sitemap: ${this.config.baseUrl}/sitemap.xml`
6365
+ ].join("\n");
6293
6366
  }
6294
- return new Request(url, init);
6295
- }
6296
- async function pipeWebResponse(response, res) {
6297
- res.status(response.status);
6298
- response.headers.forEach((v, k) => {
6299
- if (k.toLowerCase() === "content-length" || k.toLowerCase() === "set-cookie") return;
6300
- res.setHeader(k, v);
6301
- });
6302
- const cookies = response.headers.getSetCookie();
6303
- if (cookies.length) {
6304
- const existing = res.getHeader?.("set-cookie");
6305
- res.setHeader("set-cookie", [...existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)], ...cookies]);
6367
+ /** 清理缓存 */
6368
+ clearCache() {
6369
+ this.pageDataCache.clear();
6370
+ this.sitemapCache = null;
6371
+ this.sitemapLastGenerated = 0;
6306
6372
  }
6307
- if (!response.body) {
6308
- res.end();
6309
- return;
6373
+ /** 关闭引擎 */
6374
+ async shutdown() {
6375
+ this.clearCache();
6376
+ this.initialized = false;
6377
+ this.logger.debug("✅ SEO 引擎已关闭");
6310
6378
  }
6311
- const nodeReadable = Readable.fromWeb(response.body);
6312
- await new Promise((resolve, reject) => {
6313
- const cleanup = () => {
6314
- res.removeListener?.("close", onClose);
6315
- res.removeListener?.("error", onError);
6316
- };
6317
- const onClose = () => {
6318
- nodeReadable.destroy();
6319
- cleanup();
6320
- resolve();
6321
- };
6322
- const onError = (error) => {
6323
- nodeReadable.destroy();
6324
- cleanup();
6325
- reject(error);
6379
+ getOrCreatePageData(url, context) {
6380
+ const cached = this.pageDataCache.get(url);
6381
+ if (cached) return cached;
6382
+ const pageType = this.detectPageType(url);
6383
+ const pageData = {
6384
+ url: `${this.config.baseUrl}${url}`,
6385
+ title: this.generateTitle(url),
6386
+ description: this.generateDescription(url, pageType),
6387
+ keywords: [...this.config.keywords, ...this.extractKeywordsFromUrl(url)],
6388
+ image: this.config.openGraph.defaultImage,
6389
+ type: pageType,
6390
+ language: this.detectLanguage(url, context),
6391
+ modifiedTime: (/* @__PURE__ */ new Date()).toISOString()
6326
6392
  };
6327
- res.once("close", onClose);
6328
- res.once("error", onError);
6329
- nodeReadable.once("end", () => {
6330
- cleanup();
6331
- resolve();
6332
- });
6333
- nodeReadable.once("error", (error) => {
6334
- cleanup();
6335
- if (res.headersSent) res.destroy?.(error);
6336
- reject(error);
6337
- });
6338
- if (res.destroyed) onClose();
6339
- else nodeReadable.pipe(res);
6340
- });
6341
- }
6342
- function createStaticHtmlMiddlewareWithLimiter(clientDir, index, limiter) {
6343
- const targets = /* @__PURE__ */ new WeakMap();
6344
- const guarded = express.Router();
6345
- guarded.use(limiter);
6346
- guarded.use((req, res, next) => {
6347
- const target = targets.get(req);
6348
- targets.delete(req);
6349
- if (!target) return next();
6350
- res.setHeader("Content-Security-Policy", applyStaticScriptPolicy(String(res.getHeader("Content-Security-Policy") ?? "default-src 'self'"), target.hashes));
6351
- res.setHeader("Cache-Control", "public, max-age=3600");
6352
- res.setHeader("X-Served-By", "ssg-static");
6353
- res.sendFile(target.htmlPath, {
6354
- root: clientDir,
6355
- maxAge: "1h",
6356
- dotfiles: "ignore"
6357
- }, (error) => {
6358
- if (error) next(error);
6359
- });
6360
- });
6361
- return (req, res, next) => {
6362
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6363
- let pathname;
6364
- try {
6365
- pathname = decodeHtmlPathname(req.path);
6366
- } catch {
6367
- res.status(400).end();
6368
- return;
6369
- }
6370
- const relative = pathname.slice(1);
6371
- const htmlPath = relative.endsWith("/") || !relative ? relative + "index.html" : relative.toLowerCase().endsWith(".html") ? relative : relative + "/index.html";
6372
- const hashes = index.scriptHashes.get(htmlPath);
6373
- if (!hashes) return next();
6374
- targets.set(req, {
6375
- htmlPath,
6376
- hashes
6377
- });
6378
- guarded(req, res, next);
6379
- };
6380
- }
6381
- /** Asset serving must never discover HTML outside the validated build manifest. */
6382
- function normalizeStaticAssetPathname(pathname) {
6383
- return path.posix.normalize(decodeURIComponent(new URL(`http://localhost${pathname}`).pathname).replaceAll("\\", "/"));
6384
- }
6385
- function createStaticAssetMiddleware(clientDir) {
6386
- const assets = express.static(clientDir, {
6387
- index: false,
6388
- redirect: false,
6389
- maxAge: "1h",
6390
- fallthrough: true,
6391
- setHeaders: (res, filePath) => {
6392
- if (filePath.includes(`${path.sep}assets${path.sep}`)) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
6393
- else if (/\.(jpe?g|png|webp|avif|gif|svg|ico|woff2?)$/i.test(filePath)) res.setHeader("Cache-Control", "public, max-age=604800, stale-while-revalidate=86400");
6393
+ this.pageDataCache.set(url, pageData);
6394
+ return pageData;
6395
+ }
6396
+ generateAllTags(pageData) {
6397
+ const tags = [];
6398
+ tags.push(`<title>${pageData.title}</title>`);
6399
+ tags.push(`<meta name="description" content="${pageData.description}">`);
6400
+ if (pageData.keywords?.length) tags.push(`<meta name="keywords" content="${pageData.keywords.join(", ")}">`);
6401
+ tags.push(`<meta name="author" content="${this.config.author}">`);
6402
+ tags.push(`<meta name="robots" content="${this.config.robots}">`);
6403
+ tags.push(`<link rel="canonical" href="${pageData.url}">`);
6404
+ if (this.config.openGraph.enabled) {
6405
+ tags.push(`<meta property="og:title" content="${pageData.title}">`);
6406
+ tags.push(`<meta property="og:description" content="${pageData.description}">`);
6407
+ tags.push(`<meta property="og:type" content="${pageData.type}">`);
6408
+ tags.push(`<meta property="og:url" content="${pageData.url}">`);
6409
+ tags.push(`<meta property="og:site_name" content="${this.config.siteName}">`);
6410
+ tags.push(`<meta property="og:locale" content="${this.config.openGraph.locale}">`);
6411
+ if (pageData.image) tags.push(`<meta property="og:image" content="${pageData.image}">`);
6394
6412
  }
6395
- });
6396
- return (req, res, next) => {
6397
- let pathname;
6398
- try {
6399
- pathname = normalizeStaticAssetPathname(req.path);
6400
- } catch {
6401
- res.status(400).end();
6402
- return;
6413
+ if (this.config.twitter.enabled) {
6414
+ tags.push(`<meta name="twitter:card" content="${this.config.twitter.card}">`);
6415
+ tags.push(`<meta name="twitter:site" content="${this.config.twitter.site}">`);
6416
+ tags.push(`<meta name="twitter:title" content="${pageData.title}">`);
6417
+ tags.push(`<meta name="twitter:description" content="${pageData.description}">`);
6418
+ if (pageData.image) tags.push(`<meta name="twitter:image" content="${pageData.image}">`);
6403
6419
  }
6404
- if ([".html", ".htm"].includes(path.posix.extname(pathname).toLowerCase())) return next();
6405
- assets(req, res, next);
6406
- };
6420
+ return tags.join("\n ");
6421
+ }
6422
+ generateStructuredData(pageData) {
6423
+ if (!this.config.structuredData.enabled) return "";
6424
+ const data = [{
6425
+ "@context": "https://schema.org",
6426
+ "@type": "WebSite",
6427
+ name: this.config.siteName,
6428
+ url: this.config.baseUrl
6429
+ }, {
6430
+ "@context": "https://schema.org",
6431
+ "@type": "Organization",
6432
+ name: this.config.siteName,
6433
+ url: this.config.baseUrl,
6434
+ logo: this.config.structuredData.organizationLogo
6435
+ }];
6436
+ if (pageData.type === "article") data.push({
6437
+ "@context": "https://schema.org",
6438
+ "@type": "Article",
6439
+ headline: pageData.title,
6440
+ description: pageData.description,
6441
+ url: pageData.url,
6442
+ dateModified: pageData.modifiedTime,
6443
+ author: {
6444
+ "@type": "Person",
6445
+ name: pageData.author || this.config.author
6446
+ }
6447
+ });
6448
+ return `<script type="application/ld+json">${JSON.stringify(data)}<\/script>`;
6449
+ }
6450
+ insertSEOTags(html, seoTags, structuredData) {
6451
+ const headEndIndex = html.indexOf("</head>");
6452
+ if (headEndIndex === -1) return html;
6453
+ return html.slice(0, headEndIndex) + " " + seoTags + "\n " + structuredData + "\n" + html.slice(headEndIndex);
6454
+ }
6455
+ calculateScore(pageData) {
6456
+ let score = 0;
6457
+ if (pageData.title && pageData.title.length >= 30 && pageData.title.length <= 60) score += 25;
6458
+ else if (pageData.title) score += 15;
6459
+ if (pageData.description && pageData.description.length >= 100) score += 25;
6460
+ else if (pageData.description) score += 15;
6461
+ if (pageData.keywords && pageData.keywords.length >= 3) score += 20;
6462
+ if (pageData.image) score += 15;
6463
+ if (this.config.structuredData.enabled) score += 15;
6464
+ return Math.min(score, 100);
6465
+ }
6466
+ detectPageType(url) {
6467
+ if (url.includes("/blog/") || url.includes("/article/")) return "article";
6468
+ if (url.includes("/product/") || url.includes("/shop/")) return "product";
6469
+ return "website";
6470
+ }
6471
+ generateTitle(url) {
6472
+ if (url === "/") return this.config.defaultTitle;
6473
+ const title = url.split("/").filter(Boolean).map((s) => s.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())).join(" - ");
6474
+ return this.config.titleTemplate.replace("%s", title);
6475
+ }
6476
+ generateDescription(url, pageType) {
6477
+ if (url === "/") return this.config.defaultDescription;
6478
+ const topic = url.split("/").pop()?.replace(/-/g, " ") || "";
6479
+ if (pageType === "article") return `阅读关于 ${topic} 的最新文章。`;
6480
+ if (pageType === "product") return `探索 ${topic} 的详细信息。`;
6481
+ return `了解更多关于 ${topic} 的内容。`;
6482
+ }
6483
+ extractKeywordsFromUrl(url) {
6484
+ return url.split("/").filter(Boolean).flatMap((s) => s.split("-"));
6485
+ }
6486
+ detectLanguage(url, _context) {
6487
+ const pathLang = url.split("/")[1];
6488
+ if (this.config.supportedLanguages.includes(pathLang)) return pathLang;
6489
+ return this.config.defaultLanguage;
6490
+ }
6491
+ shouldExcludeUrl(url) {
6492
+ return this.config.sitemap.excludePatterns.some((pattern) => new RegExp(pattern.replace(/\*/g, ".*")).test(url));
6493
+ }
6494
+ getUrlPriority(url) {
6495
+ for (const [pattern, priority] of Object.entries(this.config.sitemap.priority)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return priority;
6496
+ return .5;
6497
+ }
6498
+ getUrlChangeFreq(url) {
6499
+ for (const [pattern, freq] of Object.entries(this.config.sitemap.changeFreq)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return freq;
6500
+ return "monthly";
6501
+ }
6502
+ };
6503
+ /** 创建 SEO 引擎实例(获取单例) */
6504
+ function createSEOEngine(config) {
6505
+ return SEOEngine.getInstance(config);
6407
6506
  }
6408
6507
  //#endregion
6409
- //#region src/server/httpServer.ts
6508
+ //#region src/engine/seo/resolveSeoConfig.ts
6410
6509
  /**
6411
- * HTTP 服务器启动器
6412
- *
6413
- * Node origin 只启动 HTTP/1.1。
6510
+ * SEO 配置解析器 —— 唯一的 baseUrl 解析入口
6414
6511
  *
6415
- * TLS / HTTP/2 / HTTP/3 / Brotli 属于 CDN / Ingress / Nginx / Envoy / ALB 边界。
6416
- * isr-engine 负责 SSR/ISR/RSC/cache/revalidate,不把网关层协议暴露为业务配置。
6512
+ * 设计目标:
6513
+ * - SEO 是 SSR/ISR 基础能力,始终启用,不暴露 enabled/sitemap/robots 开关
6514
+ * - 用户在 ssr.config.ts 里只关心 prod 域名是什么
6515
+ * - prod 只读 runtime.site,避免 SEO baseUrl 变成隐藏环境变量
6516
+ * - dev 自动用 localhost,降低本地启动成本
6417
6517
  */
6418
6518
  var logger$4 = Logger.getInstance();
6419
- var DEFAULT_TIMEOUTS = {
6420
- requestTimeoutMs: 6e4,
6421
- headersTimeoutMs: 15e3,
6422
- keepAliveTimeoutMs: 5e3,
6423
- idleTimeoutMs: 3e4,
6424
- shutdownTimeoutMs: 5e3,
6425
- maxRequestsPerSocket: 0
6426
- };
6427
- var LISTEN_BACKLOG = 8192;
6428
- var serverSockets = /* @__PURE__ */ new WeakMap();
6429
- function applyHttpTimeouts(server) {
6430
- server.requestTimeout = DEFAULT_TIMEOUTS.requestTimeoutMs;
6431
- server.headersTimeout = DEFAULT_TIMEOUTS.headersTimeoutMs;
6432
- server.keepAliveTimeout = DEFAULT_TIMEOUTS.keepAliveTimeoutMs;
6433
- server.maxRequestsPerSocket = DEFAULT_TIMEOUTS.maxRequestsPerSocket;
6434
- server.setTimeout(DEFAULT_TIMEOUTS.idleTimeoutMs);
6435
- server.__shutdownTimeoutMs = DEFAULT_TIMEOUTS.shutdownTimeoutMs;
6436
- }
6437
- function getServerAddress(server) {
6438
- const addr = server.address();
6439
- if (addr && typeof addr === "object") {
6440
- const info = addr;
6441
- return {
6442
- address: info.address,
6443
- port: info.port
6444
- };
6519
+ /**
6520
+ * 按以下顺序解析 baseUrl:
6521
+ * 1. runtime.site
6522
+ * 2. dev 模式:`http://localhost:${server.port||3000}`
6523
+ * 3. prod 且未配置:返回空串(SEOEngine 在调用 generateSitemap 时报错给出修复提示)
6524
+ */
6525
+ function resolveSeoConfig(config) {
6526
+ let baseUrl = "";
6527
+ let source = "unset";
6528
+ if (config.runtime?.site) {
6529
+ baseUrl = config.runtime.site;
6530
+ source = "runtime.site";
6531
+ } else if (isDev()) {
6532
+ const envPort = process.env.PORT ? Number(process.env.PORT) : NaN;
6533
+ baseUrl = `http://localhost:${config.server?.port ?? (Number.isFinite(envPort) ? envPort : 3e3)}`;
6534
+ source = "dev-default";
6445
6535
  }
6536
+ if (!baseUrl) logger$4.warn("⚠️ SEO baseUrl 未配置:sitemap 端点将报错。请在 ssr.config.ts 设置 runtime.site。");
6537
+ else logger$4.info(`🎯 SEO baseUrl=${baseUrl}(来源:${source})`);
6446
6538
  return {
6447
- address: "<unknown>",
6448
- port: 0
6539
+ baseUrl,
6540
+ baseUrlSource: source
6449
6541
  };
6450
6542
  }
6451
- function formatHostForUrl(address) {
6452
- if (address === "::" || address === "0.0.0.0" || address === "") return "localhost";
6453
- if (address.includes(":") && !address.startsWith("[")) return `[${address}]`;
6454
- return address;
6455
- }
6456
- /** 启动 HTTP/1.1 服务器 */
6457
- function startHttp1Server(app, config) {
6458
- const maxAttempts = config.strictPort === false ? 20 : 1;
6459
- const startPort = config.port;
6460
- return new Promise((resolve, reject) => {
6461
- const server = createServer$1(app);
6462
- applyHttpTimeouts(server);
6463
- const sockets = /* @__PURE__ */ new Set();
6464
- serverSockets.set(server, sockets);
6465
- server.on("connection", (socket) => {
6466
- sockets.add(socket);
6467
- socket.once("close", () => sockets.delete(socket));
6468
- });
6469
- let attempt = 0;
6470
- const listen = (port) => {
6471
- server.listen({
6472
- port,
6473
- host: config.host,
6474
- backlog: LISTEN_BACKLOG
6543
+ //#endregion
6544
+ //#region src/experiments/ExposureQueue.ts
6545
+ /**
6546
+ * ExposureQueue —— 曝光事件批量上报队列
6547
+ *
6548
+ * 设计取舍:
6549
+ * - **fire-and-forget**:业务渲染路径 push() 完立刻返回,不等任何 IO
6550
+ * - **批量 flush**:减小 admin-server QPS(默认 100 条 / 1s 攒一批)
6551
+ * - **不去重**:写入全量;分析期 COUNT(DISTINCT anon_id) 解(业界惯例,
6552
+ * GrowthBook / Statsig / LinkedIn LiX 同款)
6553
+ * - **不阻塞退出**:进程收到 SIGTERM 时同步 flush 一次最后批次再退出
6554
+ * - **失败丢弃 + 警告日志**:业务不应该感知 exposure 失败
6555
+ * - **采样**:sampleRate < 1 时随机丢弃,高 QPS 场景控制 admin-server 负载
6556
+ *
6557
+ * 不在本模块的事:
6558
+ * - HTTP retry / backoff 走 fetch + 短暂 retry,admin-server 全挂时丢这一批
6559
+ * - dedupe(写期不做)
6560
+ * - schema 校验(admin-server 那边做)
6561
+ */
6562
+ var logger$3 = Logger.getInstance();
6563
+ /**
6564
+ * 创建上报队列。同一进程整个 lifecycle 只创建一个;engine 入口保管 instance。
6565
+ * 返回 push() / flush() / destroy() 三个方法。
6566
+ */
6567
+ function createExposureQueue(options) {
6568
+ const batchSize = options.batchSize ?? 100;
6569
+ const flushIntervalMs = options.flushIntervalMs ?? 1e3;
6570
+ const sampleRate = options.sampleRate ?? 1;
6571
+ const maxQueueSize = options.maxQueueSize ?? batchSize * 2;
6572
+ const fetcher = options.fetcher ?? globalThis.fetch;
6573
+ const endpoint = options.endpoint;
6574
+ const state = {
6575
+ events: [],
6576
+ flushTimer: null,
6577
+ destroyed: false
6578
+ };
6579
+ const shutdownHook = () => {
6580
+ if (state.events.length > 0) flushNow().catch(() => {});
6581
+ };
6582
+ if (typeof process !== "undefined" && typeof process.on === "function") {
6583
+ process.on("SIGTERM", shutdownHook);
6584
+ process.on("SIGINT", shutdownHook);
6585
+ process.on("beforeExit", shutdownHook);
6586
+ }
6587
+ function scheduleFlush() {
6588
+ if (state.flushTimer || state.destroyed) return;
6589
+ state.flushTimer = setTimeout(() => {
6590
+ state.flushTimer = null;
6591
+ flushNow().catch((err) => {
6592
+ logger$3.warn("[ExposureQueue] flush 异常(已吞):", err);
6475
6593
  });
6476
- };
6477
- server.on("listening", () => {
6478
- const { address, port } = getServerAddress(server);
6479
- const url = `http://${formatHostForUrl(address)}:${port || config.port}`;
6480
- logger$4.info(`HTTP/1.1 服务器已启动: ${url}`);
6481
- resolve({
6482
- server,
6483
- url
6594
+ }, flushIntervalMs);
6595
+ state.flushTimer.unref?.();
6596
+ }
6597
+ const inFlight = /* @__PURE__ */ new Set();
6598
+ function flushNow() {
6599
+ const delivery = sendBatch();
6600
+ inFlight.add(delivery);
6601
+ delivery.finally(() => inFlight.delete(delivery));
6602
+ return delivery;
6603
+ }
6604
+ async function sendBatch() {
6605
+ if (state.events.length === 0) return;
6606
+ const batch = state.events.splice(0, batchSize);
6607
+ try {
6608
+ const res = await fetcher(endpoint, {
6609
+ method: "POST",
6610
+ headers: { "content-type": "application/json" },
6611
+ body: JSON.stringify({ events: batch }),
6612
+ signal: AbortSignal.timeout(3e3)
6484
6613
  });
6485
- });
6486
- server.on("error", (error) => {
6487
- if (error.code === "EADDRINUSE" && attempt + 1 < maxAttempts) {
6488
- attempt += 1;
6489
- const nextPort = startPort + attempt;
6490
- logger$4.warn(`端口 ${startPort + attempt - 1} 已占用,尝试 ${nextPort}`);
6491
- listen(nextPort);
6492
- return;
6493
- }
6494
- reject(error);
6495
- });
6496
- listen(startPort);
6497
- });
6498
- }
6499
- /** 启动 Node origin 服务器 */
6500
- function startServer(app, config) {
6501
- return startHttp1Server(app, config);
6502
- }
6503
- var closingServers = /* @__PURE__ */ new WeakMap();
6504
- /** Stop accepting requests, drain active responses, then force overdue connections closed. */
6505
- function closeServer(server) {
6506
- const existing = closingServers.get(server);
6507
- if (existing) return existing;
6508
- const closing = new Promise((resolve, reject) => {
6509
- const shutdownTimeoutMs = server.__shutdownTimeoutMs ?? DEFAULT_TIMEOUTS.shutdownTimeoutMs;
6510
- const timeout = setTimeout(() => {
6511
- try {
6512
- server.closeAllConnections();
6513
- for (const socket of serverSockets.get(server) ?? []) socket.destroy();
6514
- } catch (error) {
6515
- reject(error);
6614
+ if (!res.ok) logger$3.warn(`[ExposureQueue] admin-server 返回 ${res.status},丢弃 ${batch.length} 条曝光(不重试,业务无影响)`);
6615
+ } catch (err) {
6616
+ logger$3.warn(`[ExposureQueue] 上报失败,丢弃 ${batch.length} 条曝光(${err instanceof Error ? err.message : String(err)})`);
6617
+ }
6618
+ if (state.events.length > 0) scheduleFlush();
6619
+ }
6620
+ return {
6621
+ /**
6622
+ * 入队一个曝光事件。完全同步、永远不抛错。
6623
+ * - 队列满(maxQueueSize)→ 丢最早事件(FIFO)+ critical log
6624
+ * - 采样未命中 → 直接丢弃
6625
+ */
6626
+ push(event) {
6627
+ if (state.destroyed) return;
6628
+ if (sampleRate < 1 && Math.random() >= sampleRate) return;
6629
+ if (state.events.length >= maxQueueSize) {
6630
+ const dropped = state.events.shift();
6631
+ logger$3.warn(`[ExposureQueue] 队列满(${maxQueueSize})丢弃最早事件,admin-server 可能下线`);
6632
+ if (!dropped) return;
6516
6633
  }
6517
- }, shutdownTimeoutMs);
6518
- try {
6519
- server.close((error) => {
6520
- clearTimeout(timeout);
6521
- if (error) reject(error);
6522
- else resolve();
6523
- });
6524
- server.closeIdleConnections();
6525
- } catch (error) {
6526
- clearTimeout(timeout);
6527
- reject(error);
6634
+ state.events.push(event);
6635
+ if (state.events.length >= batchSize) {
6636
+ if (state.flushTimer) {
6637
+ clearTimeout(state.flushTimer);
6638
+ state.flushTimer = null;
6639
+ }
6640
+ flushNow().catch((err) => {
6641
+ logger$3.warn("[ExposureQueue] flush 异常(已吞):", err);
6642
+ });
6643
+ } else scheduleFlush();
6644
+ },
6645
+ /** 立即 flush 当前批次(测试 / 优雅退出用) */
6646
+ async flush() {
6647
+ do {
6648
+ await flushNow();
6649
+ await Promise.all([...inFlight]);
6650
+ } while (state.events.length > 0 || inFlight.size > 0);
6651
+ },
6652
+ /** 销毁队列(清定时器、丢残留);engine 关闭时调 */
6653
+ destroy() {
6654
+ state.destroyed = true;
6655
+ process.removeListener("SIGTERM", shutdownHook);
6656
+ process.removeListener("SIGINT", shutdownHook);
6657
+ process.removeListener("beforeExit", shutdownHook);
6658
+ if (state.flushTimer) {
6659
+ clearTimeout(state.flushTimer);
6660
+ state.flushTimer = null;
6661
+ }
6662
+ state.events.length = 0;
6663
+ },
6664
+ /** 测试用:当前队列长度 */
6665
+ get size() {
6666
+ return state.events.length;
6528
6667
  }
6529
- });
6530
- closingServers.set(server, closing);
6531
- return closing;
6668
+ };
6532
6669
  }
6533
- //#endregion
6534
- //#region src/middlewares/ABVariantMiddleware.ts
6535
- var ABVariantMiddleware_exports = /* @__PURE__ */ __exportAll({ createABVariantMiddleware: () => createABVariantMiddleware });
6536
- /** 总桶数;10000 给到 0.01% 权重精度,业界通行做法 */
6537
- var BUCKET_SPACE = 1e4;
6538
6670
  /**
6539
- * 按权重 + bucket 索引选 variant。
6540
- * 把 weights 累加得到分段边界,bucket 落在哪段就选哪个 variant。
6541
- * 同一 (variants, weights, bucket) → 永远同一结果(确定性)。
6671
+ * 解析配置,决定是否创建 queue 实例。配置缺失 / disabled / 无 endpoint 返回 null。
6672
+ * services.api 或 services.telemetry origin 用于把相对路径补全为绝对 URL。
6542
6673
  */
6543
- function pickByBucket(variants, weights, bucket) {
6544
- const w = weights && weights.length === variants.length ? weights : variants.map(() => 1);
6545
- const total = w.reduce((a, b) => a + b, 0);
6546
- let cursor = 0;
6547
- for (let i = 0; i < variants.length; i++) {
6548
- cursor += w[i] / total * BUCKET_SPACE;
6549
- if (bucket < cursor) return variants[i];
6550
- }
6551
- return variants[variants.length - 1];
6552
- }
6553
- /** 默认分桶:fnv1a(anonId + ':' + experimentKey) % BUCKET_SPACE。稳定、无外部依赖 */
6554
- function defaultAssigner(anonId, name, exp) {
6555
- const bucket = fnv1a32(`${anonId}:${name}`) % BUCKET_SPACE;
6556
- return pickByBucket(exp.variants, exp.weights, bucket);
6557
- }
6558
- function stripQuery(url) {
6559
- const i = url.indexOf("?");
6560
- return i === -1 ? url : url.slice(0, i);
6561
- }
6562
- function createABVariantMiddleware(options) {
6563
- const { experiments: staticExperiments, assigner = defaultAssigner } = options;
6564
- const { manifestLoader, exposureQueue } = options;
6565
- return function abMiddleware(req, _res, next) {
6566
- const ctx = getRequestContext();
6567
- if (!ctx) {
6568
- next();
6569
- return;
6674
+ function resolveExposureQueue(config, baseOrigin) {
6675
+ if (!config?.endpoint) return null;
6676
+ if (config.enabled === false) return null;
6677
+ let endpoint = config.endpoint;
6678
+ if (endpoint.startsWith("/")) {
6679
+ if (!baseOrigin) {
6680
+ logger$3.warn("[ExposureQueue] endpoint 是相对路径但没有 baseOrigin,跳过 exposure 上报");
6681
+ return null;
6570
6682
  }
6571
- const effectiveExperiments = manifestLoader ? manifestLoader.getCurrent() : staticExperiments;
6572
- const anonId = ctx.anonId;
6573
- const assignments = {};
6574
- for (const [name, exp] of Object.entries(effectiveExperiments)) assignments[name] = assigner(anonId, name, exp);
6575
- ctx.experiments = {
6576
- ...ctx.experiments ?? {},
6577
- ...assignments
6578
- };
6579
- ctx.flags = {
6580
- ...ctx.flags ?? {},
6581
- ...assignments
6582
- };
6583
- if (exposureQueue && Object.keys(assignments).length > 0) exposureQueue.push({
6584
- anonId,
6585
- userId: ctx.userId ?? null,
6586
- requestId: ctx.requestId,
6587
- experiments: assignments,
6588
- path: stripQuery(req.url ?? "/"),
6589
- ts: Date.now()
6590
- });
6591
- next();
6592
- };
6683
+ endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6684
+ }
6685
+ return createExposureQueue({
6686
+ endpoint,
6687
+ batchSize: config.batchSize,
6688
+ flushIntervalMs: config.flushIntervalMs,
6689
+ sampleRate: config.sampleRate
6690
+ });
6593
6691
  }
6594
6692
  //#endregion
6595
6693
  //#region src/experiments/ManifestLoader.ts
@@ -6609,12 +6707,7 @@ function createABVariantMiddleware(options) {
6609
6707
  * - 'paused' / 'killed' → 强制回第一个 variant(control)
6610
6708
  * - 'concluded' → 同上 + admin-platform 高亮
6611
6709
  */
6612
- var ManifestLoader_exports = /* @__PURE__ */ __exportAll({
6613
- createManifestLoader: () => createManifestLoader,
6614
- normalizeManifestExperiments: () => normalizeManifestExperiments,
6615
- resolveManifestLoader: () => resolveManifestLoader
6616
- });
6617
- var logger$3 = Logger.getInstance();
6710
+ var logger$2 = Logger.getInstance();
6618
6711
  /**
6619
6712
  * 把 manifest 里的实验定义归一化为 engine 内部用的 RuntimeExperimentConfig。
6620
6713
  * killed / paused / concluded 状态的实验:**weights 强制变成 [100, 0, 0, ...]**,
@@ -6673,7 +6766,7 @@ function createManifestLoader(options) {
6673
6766
  return;
6674
6767
  }
6675
6768
  state.current = normalizeManifestExperiments(json.experiments);
6676
- logger$3.debug(`[ManifestLoader] 拉取成功 version=${json.version} 实验数=${Object.keys(state.current).length}`);
6769
+ logger$2.debug(`[ManifestLoader] 拉取成功 version=${json.version} 实验数=${Object.keys(state.current).length}`);
6677
6770
  } catch (err) {
6678
6771
  applyFallback(err instanceof Error ? err.message : String(err));
6679
6772
  }
@@ -6681,226 +6774,162 @@ function createManifestLoader(options) {
6681
6774
  function applyFallback(reason) {
6682
6775
  switch (fallbackOnError) {
6683
6776
  case "cache":
6684
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),沿用 cache 快照`);
6777
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),沿用 cache 快照`);
6685
6778
  break;
6686
6779
  case "static":
6687
6780
  state.current = { ...options.staticExperiments ?? {} };
6688
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),回退到 static 配置`);
6781
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),回退到 static 配置`);
6689
6782
  break;
6690
6783
  case "empty":
6691
6784
  state.current = {};
6692
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),关闭所有实验`);
6785
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),关闭所有实验`);
6693
6786
  break;
6694
6787
  }
6695
6788
  }
6696
6789
  function schedulePoll() {
6697
- if (state.destroyed) return;
6698
- state.pollTimer = setTimeout(() => {
6699
- state.pollTimer = null;
6700
- pullOnce().finally(() => schedulePoll());
6701
- }, refreshIntervalMs);
6702
- state.pollTimer.unref?.();
6703
- }
6704
- return {
6705
- /** 立即拉一次(启动期同步等待 + 后续异步轮询) */
6706
- async init() {
6707
- await pullOnce();
6708
- schedulePoll();
6709
- },
6710
- /**
6711
- * 读取当前快照 —— 同步返回 ABVariantMiddleware 用。
6712
- * 永远返回非 null(最差是 empty);调用方不用 null 检查。
6713
- */
6714
- getCurrent() {
6715
- return state.current;
6716
- },
6717
- /** 销毁 loader(清定时器) */
6718
- destroy() {
6719
- state.destroyed = true;
6720
- if (state.pollTimer) {
6721
- clearTimeout(state.pollTimer);
6722
- state.pollTimer = null;
6723
- }
6724
- }
6725
- };
6726
- }
6727
- /**
6728
- * 解析配置,决定是否创建 loader 实例。配置缺失 / 无 endpoint 返回 null。
6729
- */
6730
- function resolveManifestLoader(config, staticExperiments, baseOrigin) {
6731
- if (!config?.endpoint) return null;
6732
- let endpoint = config.endpoint;
6733
- if (endpoint.startsWith("/")) {
6734
- if (!baseOrigin) {
6735
- logger$3.warn("[ManifestLoader] endpoint 是相对路径但没有 baseOrigin,跳过 manifest 拉取");
6736
- return null;
6737
- }
6738
- endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6739
- }
6740
- return createManifestLoader({
6741
- endpoint,
6742
- refreshIntervalMs: config.refreshIntervalMs,
6743
- fallbackOnError: config.fallbackOnError,
6744
- authHeader: config.authHeader,
6745
- staticExperiments
6746
- });
6747
- }
6748
- //#endregion
6749
- //#region src/experiments/ExposureQueue.ts
6750
- /**
6751
- * ExposureQueue —— 曝光事件批量上报队列
6752
- *
6753
- * 设计取舍:
6754
- * - **fire-and-forget**:业务渲染路径 push() 完立刻返回,不等任何 IO
6755
- * - **批量 flush**:减小 admin-server QPS(默认 100 条 / 1s 攒一批)
6756
- * - **不去重**:写入全量;分析期 COUNT(DISTINCT anon_id) 解(业界惯例,
6757
- * GrowthBook / Statsig / LinkedIn LiX 同款)
6758
- * - **不阻塞退出**:进程收到 SIGTERM 时同步 flush 一次最后批次再退出
6759
- * - **失败丢弃 + 警告日志**:业务不应该感知 exposure 失败
6760
- * - **采样**:sampleRate < 1 时随机丢弃,高 QPS 场景控制 admin-server 负载
6761
- *
6762
- * 不在本模块的事:
6763
- * - HTTP retry / backoff 走 fetch + 短暂 retry,admin-server 全挂时丢这一批
6764
- * - dedupe(写期不做)
6765
- * - schema 校验(admin-server 那边做)
6766
- */
6767
- var ExposureQueue_exports = /* @__PURE__ */ __exportAll({
6768
- createExposureQueue: () => createExposureQueue,
6769
- resolveExposureQueue: () => resolveExposureQueue
6770
- });
6771
- var logger$2 = Logger.getInstance();
6772
- /**
6773
- * 创建上报队列。同一进程整个 lifecycle 只创建一个;engine 入口保管 instance。
6774
- * 返回 push() / flush() / destroy() 三个方法。
6775
- */
6776
- function createExposureQueue(options) {
6777
- const batchSize = options.batchSize ?? 100;
6778
- const flushIntervalMs = options.flushIntervalMs ?? 1e3;
6779
- const sampleRate = options.sampleRate ?? 1;
6780
- const maxQueueSize = options.maxQueueSize ?? batchSize * 2;
6781
- const fetcher = options.fetcher ?? globalThis.fetch;
6782
- const endpoint = options.endpoint;
6783
- const state = {
6784
- events: [],
6785
- flushTimer: null,
6786
- destroyed: false
6787
- };
6788
- const shutdownHook = () => {
6789
- if (state.events.length > 0) flushNow().catch(() => {});
6790
- };
6791
- if (typeof process !== "undefined" && typeof process.on === "function") {
6792
- process.on("SIGTERM", shutdownHook);
6793
- process.on("SIGINT", shutdownHook);
6794
- process.on("beforeExit", shutdownHook);
6795
- }
6796
- function scheduleFlush() {
6797
- if (state.flushTimer || state.destroyed) return;
6798
- state.flushTimer = setTimeout(() => {
6799
- state.flushTimer = null;
6800
- flushNow().catch((err) => {
6801
- logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
6802
- });
6803
- }, flushIntervalMs);
6804
- state.flushTimer.unref?.();
6805
- }
6806
- const inFlight = /* @__PURE__ */ new Set();
6807
- function flushNow() {
6808
- const delivery = sendBatch();
6809
- inFlight.add(delivery);
6810
- delivery.finally(() => inFlight.delete(delivery));
6811
- return delivery;
6812
- }
6813
- async function sendBatch() {
6814
- if (state.events.length === 0) return;
6815
- const batch = state.events.splice(0, batchSize);
6816
- try {
6817
- const res = await fetcher(endpoint, {
6818
- method: "POST",
6819
- headers: { "content-type": "application/json" },
6820
- body: JSON.stringify({ events: batch }),
6821
- signal: AbortSignal.timeout(3e3)
6822
- });
6823
- if (!res.ok) logger$2.warn(`[ExposureQueue] admin-server 返回 ${res.status},丢弃 ${batch.length} 条曝光(不重试,业务无影响)`);
6824
- } catch (err) {
6825
- logger$2.warn(`[ExposureQueue] 上报失败,丢弃 ${batch.length} 条曝光(${err instanceof Error ? err.message : String(err)})`);
6826
- }
6827
- if (state.events.length > 0) scheduleFlush();
6790
+ if (state.destroyed) return;
6791
+ state.pollTimer = setTimeout(() => {
6792
+ state.pollTimer = null;
6793
+ pullOnce().finally(() => schedulePoll());
6794
+ }, refreshIntervalMs);
6795
+ state.pollTimer.unref?.();
6828
6796
  }
6829
6797
  return {
6798
+ /** 立即拉一次(启动期同步等待 + 后续异步轮询) */
6799
+ async init() {
6800
+ await pullOnce();
6801
+ schedulePoll();
6802
+ },
6830
6803
  /**
6831
- * 入队一个曝光事件。完全同步、永远不抛错。
6832
- * - 队列满(maxQueueSize)→ 丢最早事件(FIFO)+ critical log
6833
- * - 采样未命中 → 直接丢弃
6804
+ * 读取当前快照 —— 同步返回 ABVariantMiddleware 用。
6805
+ * 永远返回非 null(最差是 empty);调用方不用 null 检查。
6834
6806
  */
6835
- push(event) {
6836
- if (state.destroyed) return;
6837
- if (sampleRate < 1 && Math.random() >= sampleRate) return;
6838
- if (state.events.length >= maxQueueSize) {
6839
- const dropped = state.events.shift();
6840
- logger$2.warn(`[ExposureQueue] 队列满(${maxQueueSize})丢弃最早事件,admin-server 可能下线`);
6841
- if (!dropped) return;
6842
- }
6843
- state.events.push(event);
6844
- if (state.events.length >= batchSize) {
6845
- if (state.flushTimer) {
6846
- clearTimeout(state.flushTimer);
6847
- state.flushTimer = null;
6848
- }
6849
- flushNow().catch((err) => {
6850
- logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
6851
- });
6852
- } else scheduleFlush();
6853
- },
6854
- /** 立即 flush 当前批次(测试 / 优雅退出用) */
6855
- async flush() {
6856
- do {
6857
- await flushNow();
6858
- await Promise.all([...inFlight]);
6859
- } while (state.events.length > 0 || inFlight.size > 0);
6807
+ getCurrent() {
6808
+ return state.current;
6860
6809
  },
6861
- /** 销毁队列(清定时器、丢残留);engine 关闭时调 */
6810
+ /** 销毁 loader(清定时器) */
6862
6811
  destroy() {
6863
6812
  state.destroyed = true;
6864
- process.removeListener("SIGTERM", shutdownHook);
6865
- process.removeListener("SIGINT", shutdownHook);
6866
- process.removeListener("beforeExit", shutdownHook);
6867
- if (state.flushTimer) {
6868
- clearTimeout(state.flushTimer);
6869
- state.flushTimer = null;
6813
+ if (state.pollTimer) {
6814
+ clearTimeout(state.pollTimer);
6815
+ state.pollTimer = null;
6870
6816
  }
6871
- state.events.length = 0;
6872
- },
6873
- /** 测试用:当前队列长度 */
6874
- get size() {
6875
- return state.events.length;
6876
6817
  }
6877
6818
  };
6878
6819
  }
6879
6820
  /**
6880
- * 解析配置,决定是否创建 queue 实例。配置缺失 / disabled / 无 endpoint 返回 null。
6881
- * services.api 或 services.telemetry origin 用于把相对路径补全为绝对 URL。
6821
+ * 解析配置,决定是否创建 loader 实例。配置缺失 / 无 endpoint 返回 null。
6882
6822
  */
6883
- function resolveExposureQueue(config, baseOrigin) {
6823
+ function resolveManifestLoader(config, staticExperiments, baseOrigin) {
6884
6824
  if (!config?.endpoint) return null;
6885
- if (config.enabled === false) return null;
6886
6825
  let endpoint = config.endpoint;
6887
6826
  if (endpoint.startsWith("/")) {
6888
6827
  if (!baseOrigin) {
6889
- logger$2.warn("[ExposureQueue] endpoint 是相对路径但没有 baseOrigin,跳过 exposure 上报");
6828
+ logger$2.warn("[ManifestLoader] endpoint 是相对路径但没有 baseOrigin,跳过 manifest 拉取");
6890
6829
  return null;
6891
6830
  }
6892
6831
  endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6893
6832
  }
6894
- return createExposureQueue({
6833
+ return createManifestLoader({
6895
6834
  endpoint,
6896
- batchSize: config.batchSize,
6897
- flushIntervalMs: config.flushIntervalMs,
6898
- sampleRate: config.sampleRate
6835
+ refreshIntervalMs: config.refreshIntervalMs,
6836
+ fallbackOnError: config.fallbackOnError,
6837
+ authHeader: config.authHeader,
6838
+ staticExperiments
6899
6839
  });
6900
6840
  }
6901
6841
  //#endregion
6842
+ //#region src/middlewares/ABVariantMiddleware.ts
6843
+ /** 总桶数;10000 给到 0.01% 权重精度,业界通行做法 */
6844
+ var BUCKET_SPACE = 1e4;
6845
+ /**
6846
+ * 按权重 + bucket 索引选 variant。
6847
+ * 把 weights 累加得到分段边界,bucket 落在哪段就选哪个 variant。
6848
+ * 同一 (variants, weights, bucket) → 永远同一结果(确定性)。
6849
+ */
6850
+ function pickByBucket(variants, weights, bucket) {
6851
+ const w = weights && weights.length === variants.length ? weights : variants.map(() => 1);
6852
+ const total = w.reduce((a, b) => a + b, 0);
6853
+ let cursor = 0;
6854
+ for (let i = 0; i < variants.length; i++) {
6855
+ cursor += w[i] / total * BUCKET_SPACE;
6856
+ if (bucket < cursor) return variants[i];
6857
+ }
6858
+ return variants[variants.length - 1];
6859
+ }
6860
+ /** 默认分桶:fnv1a(anonId + ':' + experimentKey) % BUCKET_SPACE。稳定、无外部依赖 */
6861
+ function defaultAssigner(anonId, name, exp) {
6862
+ const bucket = fnv1a32(`${anonId}:${name}`) % BUCKET_SPACE;
6863
+ return pickByBucket(exp.variants, exp.weights, bucket);
6864
+ }
6865
+ function stripQuery(url) {
6866
+ const i = url.indexOf("?");
6867
+ return i === -1 ? url : url.slice(0, i);
6868
+ }
6869
+ function createABVariantMiddleware(options) {
6870
+ const { experiments: staticExperiments, assigner = defaultAssigner } = options;
6871
+ const { manifestLoader, exposureQueue } = options;
6872
+ return function abMiddleware(req, _res, next) {
6873
+ const ctx = getRequestContext();
6874
+ if (!ctx) {
6875
+ next();
6876
+ return;
6877
+ }
6878
+ const effectiveExperiments = manifestLoader ? manifestLoader.getCurrent() : staticExperiments;
6879
+ const anonId = ctx.anonId;
6880
+ const assignments = {};
6881
+ for (const [name, exp] of Object.entries(effectiveExperiments)) assignments[name] = assigner(anonId, name, exp);
6882
+ ctx.experiments = {
6883
+ ...ctx.experiments ?? {},
6884
+ ...assignments
6885
+ };
6886
+ ctx.flags = {
6887
+ ...ctx.flags ?? {},
6888
+ ...assignments
6889
+ };
6890
+ if (exposureQueue && Object.keys(assignments).length > 0) exposureQueue.push({
6891
+ anonId,
6892
+ userId: ctx.userId ?? null,
6893
+ requestId: ctx.requestId,
6894
+ experiments: assignments,
6895
+ path: stripQuery(req.url ?? "/"),
6896
+ ts: Date.now()
6897
+ });
6898
+ next();
6899
+ };
6900
+ }
6901
+ //#endregion
6902
+ //#region src/server/safeRedirect.ts
6903
+ var REDIRECT_ORIGIN = "https://isr.invalid";
6904
+ /** Validate the final Location value against a fixed origin, never an untrusted Host header. */
6905
+ function isSafeLocalRedirect(target) {
6906
+ if (!target.startsWith("/") || target.startsWith("//")) return false;
6907
+ for (const character of target) {
6908
+ const code = character.charCodeAt(0);
6909
+ if (code < 32 || code === 127) return false;
6910
+ }
6911
+ const pathEnd = target.search(/[?#]/);
6912
+ if (target.slice(0, pathEnd < 0 ? void 0 : pathEnd).includes("\\")) return false;
6913
+ try {
6914
+ return new URL(target, REDIRECT_ORIGIN).origin === REDIRECT_ORIGIN;
6915
+ } catch {
6916
+ return false;
6917
+ }
6918
+ }
6919
+ function readRedirectQuery(url) {
6920
+ const delimiter = url.indexOf("?");
6921
+ return delimiter < 0 ? void 0 : url.slice(delimiter + 1);
6922
+ }
6923
+ function redirectLocal(res, status, pathname, query) {
6924
+ const target = query === void 0 ? pathname : `${pathname}?${query}`;
6925
+ if (!isSafeLocalRedirect(target)) {
6926
+ res.status(400).end();
6927
+ return;
6928
+ }
6929
+ res.redirect(status, target);
6930
+ }
6931
+ //#endregion
6902
6932
  //#region src/middlewares/LocaleRedirect.ts
6903
- var LocaleRedirect_exports = /* @__PURE__ */ __exportAll({ createLocaleRedirectMiddleware: () => createLocaleRedirectMiddleware });
6904
6933
  var FRAMEWORK_SKIP_PREFIXES = [
6905
6934
  "/api/",
6906
6935
  "/_rsc",
@@ -6950,635 +6979,1140 @@ function createLocaleRedirectMiddleware(options) {
6950
6979
  return;
6951
6980
  }
6952
6981
  }
6953
- const cookieLocale = readCookieLocale(typeof req.headers["cookie"] === "string" ? req.headers["cookie"] : "");
6954
- const target = (cookieLocale && localePrefixes.has(cookieLocale) ? cookieLocale : null) || negotiateLocale(typeof req.headers["accept-language"] === "string" ? req.headers["accept-language"] : null, i18n);
6955
- const prefix = localePrefixes.get(target);
6956
- if (!prefix) {
6957
- res.status(400).end();
6958
- return;
6959
- }
6960
- redirectLocale(res, 302, prefix, path, rscSuffix, req.url);
6982
+ const cookieLocale = readCookieLocale(typeof req.headers["cookie"] === "string" ? req.headers["cookie"] : "");
6983
+ const target = (cookieLocale && localePrefixes.has(cookieLocale) ? cookieLocale : null) || negotiateLocale(typeof req.headers["accept-language"] === "string" ? req.headers["accept-language"] : null, i18n);
6984
+ const prefix = localePrefixes.get(target);
6985
+ if (!prefix) {
6986
+ res.status(400).end();
6987
+ return;
6988
+ }
6989
+ redirectLocale(res, 302, prefix, path, rscSuffix, req.url);
6990
+ };
6991
+ }
6992
+ function readCookieLocale(header) {
6993
+ if (!header) return null;
6994
+ for (const part of header.split(";")) {
6995
+ const trimmed = part.trim();
6996
+ const eq = trimmed.indexOf("=");
6997
+ if (eq <= 0) continue;
6998
+ if (trimmed.slice(0, eq).trim() === "locale") try {
6999
+ return decodeURIComponent(trimmed.slice(eq + 1).trim());
7000
+ } catch {
7001
+ return trimmed.slice(eq + 1).trim();
7002
+ }
7003
+ }
7004
+ return null;
7005
+ }
7006
+ //#endregion
7007
+ //#region src/security/staticCspManifest.ts
7008
+ var STATIC_CSP_MANIFEST = "static-csp-manifest.json";
7009
+ var SCHEMA_VERSION = 3;
7010
+ var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
7011
+ /** parse5 follows browser tokenization, including raw script text and inert templates. */
7012
+ function collectInlineScriptHashes(html) {
7013
+ const hashes = /* @__PURE__ */ new Set();
7014
+ function visit(node) {
7015
+ if ("tagName" in node && node.tagName === "script" && !node.attrs.some((attr) => attr.name === "src")) {
7016
+ const text = node.childNodes.map((child) => "value" in child ? child.value : "").join("");
7017
+ hashes.add(`'sha256-${createHash("sha256").update(text).digest("base64")}'`);
7018
+ }
7019
+ if ("childNodes" in node) node.childNodes.forEach(visit);
7020
+ }
7021
+ visit(parse(html));
7022
+ return [...hashes].sort();
7023
+ }
7024
+ function applyStaticScriptPolicy(policy, hashes) {
7025
+ return [...policy.split(";").filter((directive) => {
7026
+ const name = directive.trim().split(/\s/, 1)[0].toLowerCase();
7027
+ return name !== "script-src" && name !== "script-src-elem";
7028
+ }), ["script-src 'self'", ...hashes].join(" ")].join(";");
7029
+ }
7030
+ async function readHtmlFiles(clientDir, parseScripts = false) {
7031
+ const files = [];
7032
+ async function walk(dir) {
7033
+ for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
7034
+ const absolute = path.join(dir, entry.name);
7035
+ if (entry.isDirectory()) await walk(absolute);
7036
+ else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
7037
+ const bytes = await fs$3.readFile(absolute);
7038
+ files.push({
7039
+ path: path.relative(clientDir, absolute).split(path.sep).join("/"),
7040
+ sha256: sha256(bytes),
7041
+ scriptHashes: parseScripts ? collectInlineScriptHashes(bytes.toString("utf8")) : [],
7042
+ ...parseScripts ? { generatedAt: Math.floor((await fs$3.stat(absolute)).mtimeMs) } : {}
7043
+ });
7044
+ }
7045
+ }
7046
+ }
7047
+ await walk(clientDir);
7048
+ return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
7049
+ }
7050
+ var CLIENT_BUILD_EXTENSIONS = /* @__PURE__ */ new Set([
7051
+ ".js",
7052
+ ".mjs",
7053
+ ".cjs",
7054
+ ".css",
7055
+ ".wasm",
7056
+ ".json",
7057
+ ".html",
7058
+ ".htm",
7059
+ ".svg"
7060
+ ]);
7061
+ function isDeploymentPath(relative) {
7062
+ if (relative.includes("\\") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) return false;
7063
+ return relative.startsWith("rsc/") || relative.startsWith("ssr/") || relative.startsWith("client/") && CLIENT_BUILD_EXTENSIONS.has(path.posix.extname(relative).toLowerCase());
7064
+ }
7065
+ /** Hash executable build artifacts incrementally; do not load media or source maps from client/. */
7066
+ async function readDeploymentFiles(distDir) {
7067
+ const files = [];
7068
+ async function walk(dir) {
7069
+ for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
7070
+ const absolute = path.join(dir, entry.name);
7071
+ if (entry.isDirectory()) await walk(absolute);
7072
+ else if (entry.isFile()) {
7073
+ const relative = path.relative(distDir, absolute).split(path.sep).join("/");
7074
+ if (!isDeploymentPath(relative)) continue;
7075
+ const digest = createHash("sha256");
7076
+ for await (const chunk of createReadStream(absolute)) digest.update(chunk);
7077
+ files.push({
7078
+ path: relative,
7079
+ sha256: digest.digest("hex")
7080
+ });
7081
+ }
7082
+ }
7083
+ }
7084
+ for (const directory of [
7085
+ "rsc",
7086
+ "ssr",
7087
+ "client"
7088
+ ]) try {
7089
+ await walk(path.join(distDir, directory));
7090
+ } catch (error) {
7091
+ if (directory !== "ssr" || error.code !== "ENOENT") throw error;
7092
+ }
7093
+ return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
7094
+ }
7095
+ function manifestPayload(manifest) {
7096
+ return JSON.stringify({
7097
+ schemaVersion: manifest.schemaVersion,
7098
+ ...manifest.schemaVersion >= 3 ? { ssgRoutes: manifest.ssgRoutes } : {},
7099
+ deploymentFiles: manifest.deploymentFiles.map((file) => ({
7100
+ path: file.path,
7101
+ sha256: file.sha256
7102
+ })),
7103
+ files: manifest.files.map((file) => ({
7104
+ path: file.path,
7105
+ sha256: file.sha256,
7106
+ scriptHashes: file.scriptHashes,
7107
+ ...manifest.schemaVersion < 3 || file.generatedAt === void 0 ? {} : { generatedAt: file.generatedAt }
7108
+ }))
7109
+ });
7110
+ }
7111
+ async function createManifest(distDir, ssgRoutes = []) {
7112
+ assertDistinctHtmlRouteIdentities(ssgRoutes);
7113
+ await fs$3.access(path.join(distDir, "rsc/index.js"));
7114
+ const deploymentFiles = await readDeploymentFiles(distDir);
7115
+ const files = await readHtmlFiles(path.join(distDir, "client"), true);
7116
+ const payload = {
7117
+ schemaVersion: SCHEMA_VERSION,
7118
+ ssgRoutes: [...new Set(ssgRoutes)].sort(),
7119
+ deploymentFiles,
7120
+ files
7121
+ };
7122
+ return {
7123
+ ...payload,
7124
+ buildId: sha256(manifestPayload(payload))
6961
7125
  };
6962
7126
  }
6963
- function readCookieLocale(header) {
6964
- if (!header) return null;
6965
- for (const part of header.split(";")) {
6966
- const trimmed = part.trim();
6967
- const eq = trimmed.indexOf("=");
6968
- if (eq <= 0) continue;
6969
- if (trimmed.slice(0, eq).trim() === "locale") try {
6970
- return decodeURIComponent(trimmed.slice(eq + 1).trim());
6971
- } catch {
6972
- return trimmed.slice(eq + 1).trim();
6973
- }
7127
+ /** Called only after every build environment, SSG output and SPA shell are complete. */
7128
+ async function generateStaticCspManifest(distDir, options = {}) {
7129
+ const manifest = await createManifest(distDir, options.ssgRoutes);
7130
+ const destination = path.join(distDir, STATIC_CSP_MANIFEST);
7131
+ const temporary = `${destination}.${process.pid}.tmp`;
7132
+ try {
7133
+ await fs$3.writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n");
7134
+ await fs$3.rename(temporary, destination);
7135
+ } finally {
7136
+ await fs$3.rm(temporary, { force: true });
6974
7137
  }
6975
- return null;
7138
+ return manifest;
6976
7139
  }
6977
- //#endregion
6978
- //#region src/server/manager.ts
6979
- /**
6980
- * 服务器管理器
6981
- * 整合 Vite 开发服务器、HTTP 服务器和中间件
6982
- * ISREngine 唯一需要关心的服务器入口
6983
- */
6984
- var logger$1 = Logger.getInstance();
6985
- /** 服务器上下文 */
6986
- var serverContext = null;
6987
- var productionRuntime;
6988
- var starting;
6989
- var stopping;
6990
- var developmentCleanups = [];
6991
- async function closeDevelopmentResources() {
6992
- const owned = developmentCleanups.splice(0).reverse();
6993
- const failures = (await Promise.allSettled(owned.map((close) => Promise.resolve().then(close)))).filter((result) => result.status === "rejected");
6994
- if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Development cleanup failed");
7140
+ function validateManifest(value) {
7141
+ if (!value || typeof value !== "object") throw new Error("Invalid static CSP manifest");
7142
+ const manifest = value;
7143
+ if (manifest.schemaVersion !== SCHEMA_VERSION && manifest.schemaVersion !== 2) throw new Error("Unsupported static CSP manifest schema");
7144
+ const { ssgRoutes } = manifest;
7145
+ if (manifest.schemaVersion >= 3 && (!Array.isArray(ssgRoutes) || ssgRoutes.some((route, index) => typeof route !== "string" || !route.startsWith("/") || route.includes("?") || route.includes("#") || index > 0 && route <= ssgRoutes[index - 1]))) throw new Error("Invalid static CSP manifest SSG routes");
7146
+ if (ssgRoutes) assertDistinctHtmlRouteIdentities(ssgRoutes);
7147
+ const digest = /^[a-f0-9]{64}$/;
7148
+ if (!Array.isArray(manifest.deploymentFiles) || typeof manifest.buildId !== "string" || !digest.test(manifest.buildId) || !Array.isArray(manifest.files)) throw new Error("Invalid static CSP manifest fields");
7149
+ let previous = "";
7150
+ for (const file of manifest.deploymentFiles) {
7151
+ if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || !isDeploymentPath(file.path) || typeof file.sha256 !== "string" || !digest.test(file.sha256)) throw new Error("Invalid static CSP manifest deployment entry");
7152
+ previous = file.path;
7153
+ }
7154
+ if (!manifest.deploymentFiles.some((file) => file.path === "rsc/index.js")) throw new Error("Static CSP manifest is missing the RSC build");
7155
+ previous = "";
7156
+ for (const file of manifest.files) {
7157
+ if (!file || typeof file !== "object" || typeof file.path !== "string" || file.path <= previous || file.path.includes("\\") || file.path.startsWith("/") || file.path.split("/").some((segment) => !segment || segment === "." || segment === "..") || !file.path.toLowerCase().endsWith(".html") || typeof file.sha256 !== "string" || !digest.test(file.sha256) || manifest.schemaVersion === 3 && (typeof file.generatedAt !== "number" || !Number.isSafeInteger(file.generatedAt) || file.generatedAt < 0) || !Array.isArray(file.scriptHashes) || !file.scriptHashes.every((hash) => typeof hash === "string" && /^'sha256-[A-Za-z0-9+/]{43}='$/.test(hash))) throw new Error("Invalid static CSP manifest file entry");
7158
+ previous = file.path;
7159
+ }
7160
+ if (sha256(manifestPayload(manifest)) !== manifest.buildId) throw new Error("Static CSP manifest integrity mismatch");
6995
7161
  }
6996
- /** Retain the optional public ServerContext manifest for programmatic consumers. */
6997
- function loadProdManifest() {
6998
- for (const relativePath of [
6999
- "dist/.vite/manifest.json",
7000
- "dist/client/.vite/manifest.json",
7001
- "dist/manifest.json"
7002
- ]) {
7003
- const absolutePath = path.resolve(process.cwd(), relativePath);
7004
- if (!fs.existsSync(absolutePath)) continue;
7005
- try {
7006
- return JSON.parse(fs.readFileSync(absolutePath, "utf8"));
7007
- } catch {
7008
- logger$1.warn(`Manifest 解析失败: ${relativePath}`);
7009
- }
7162
+ /** Missing manifests are legacy builds; present but invalid manifests always stop startup. */
7163
+ async function loadStaticCspManifest(distDir, options = {}) {
7164
+ let serialized;
7165
+ try {
7166
+ serialized = await fs$3.readFile(path.join(distDir, STATIC_CSP_MANIFEST), "utf8");
7167
+ } catch (error) {
7168
+ if (error.code !== "ENOENT") throw error;
7169
+ const manifest = await createManifest(distDir);
7170
+ options.onLegacyBuild?.();
7171
+ return indexManifest(manifest, true);
7010
7172
  }
7011
- return null;
7173
+ let manifest;
7174
+ try {
7175
+ manifest = JSON.parse(serialized);
7176
+ } catch (error) {
7177
+ throw new Error("Invalid static CSP manifest JSON", { cause: error });
7178
+ }
7179
+ validateManifest(manifest);
7180
+ const deployed = await readDeploymentFiles(distDir);
7181
+ if (JSON.stringify(deployed) !== JSON.stringify(manifest.deploymentFiles)) throw new Error("Static CSP manifest does not match the deployment build");
7182
+ const actual = await readHtmlFiles(path.join(distDir, "client"));
7183
+ if (actual.length !== manifest.files.length || actual.some((file, index) => file.path !== manifest.files[index].path || file.sha256 !== manifest.files[index].sha256)) throw new Error("Static CSP manifest does not match deployed HTML files");
7184
+ return indexManifest(manifest, false);
7012
7185
  }
7013
- /**
7014
- * 初始化开发模式服务器上下文
7015
- */
7016
- async function initDevContext(requestHandler, config) {
7017
- logger$1.info("🔧 初始化开发模式服务器...");
7018
- const viteDevMiddleware = await createViteDevServer();
7019
- bindRuntimeOpsConfig(requestHandler, getRuntimeOpsConfig(viteDevMiddleware) ?? resolveOpsConfig(config, "development"));
7186
+ function indexManifest(manifest, legacy) {
7020
7187
  return {
7021
- requestHandler,
7022
- viteDevMiddleware,
7023
- isDev: true,
7024
- manifest: null,
7025
- httpServer: null
7188
+ legacy,
7189
+ ssgRoutes: legacy || manifest.schemaVersion < 3 ? void 0 : Object.freeze([...manifest.ssgRoutes ?? []]),
7190
+ buildId: manifest.buildId,
7191
+ generatedAt: new Map(legacy || manifest.schemaVersion < 3 ? [] : manifest.files.flatMap((file) => file.generatedAt === void 0 ? [] : [[file.path, file.generatedAt]])),
7192
+ scriptHashes: new Map(manifest.files.map((file) => [file.path, Object.freeze([...file.scriptHashes])]))
7026
7193
  };
7027
7194
  }
7195
+ //#endregion
7196
+ //#region src/server/productionRuntime.ts
7197
+ /** Shared production application assembly. Listening and process signals belong to callers. */
7198
+ function safeOrigin(url) {
7199
+ if (!url) return void 0;
7200
+ try {
7201
+ return new URL(url).origin;
7202
+ } catch {
7203
+ return;
7204
+ }
7205
+ }
7028
7206
  /**
7029
- * 初始化服务器上下文(内部使用)
7207
+ * 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
7208
+ * 导出以便单测覆盖(纯函数)
7030
7209
  */
7031
- async function initServerContext(config) {
7032
- if (serverContext) return serverContext;
7033
- serverContext = await initDevContext(express(), config);
7034
- developmentCleanups.push(closeViteDevServer);
7035
- applyBaseMiddlewaresWithOptions(serverContext);
7036
- const cookieDomain = config?.runtime?.cookieDomain;
7037
- serverContext.requestHandler.use((req, res, next) => {
7038
- const { data, needsAnonCookie } = createServerRequestContext(req);
7039
- if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
7040
- requestContext.run(data, () => next());
7041
- });
7042
- if (config?.runtime?.i18n?.prefixDefault) {
7043
- const localeRedirect = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(config.runtime.i18n) });
7044
- if (localeRedirect) serverContext.requestHandler.use(localeRedirect);
7210
+ function extractRoutesForSitemap(config) {
7211
+ const routes = config.routes ?? {};
7212
+ const out = [];
7213
+ for (const path of Object.keys(routes)) {
7214
+ if (path.includes("*") || path.includes(":")) continue;
7215
+ if (path.startsWith("/__") || path.startsWith("/api/")) continue;
7216
+ out.push(path);
7045
7217
  }
7046
- const hasStaticExps = config?.runtime?.experiments && Object.keys(config.runtime.experiments).length > 0;
7047
- const hasManifest = !!config?.runtime?.experimentManifest?.endpoint;
7048
- if (hasStaticExps || hasManifest) {
7049
- const baseOrigin = config?.runtime?.services?.api;
7050
- const manifestLoader = resolveManifestLoader(config?.runtime?.experimentManifest, config?.runtime?.experiments ?? {}, baseOrigin);
7051
- if (manifestLoader) {
7052
- developmentCleanups.push(() => manifestLoader.destroy());
7053
- await manifestLoader.init();
7218
+ return out;
7219
+ }
7220
+ /**
7221
+ * 把 ssr.config.ts 的 telemetry 第三方配置映射到可选 adapter 使用的 env。
7222
+ * 这一步必须发生在 import dist/rsc/index.js 之前,因为内置 entry.server 会在模块加载时
7223
+ * 初始化 auto hooks。engine 仍不静态 import vendor SDK;这里仅做启动期配置桥接。
7224
+ */
7225
+ function applyTelemetryIntegrationEnv(runtime) {
7226
+ const telemetry = runtime?.telemetry;
7227
+ delete process.env.SENTRY_ENVIRONMENT;
7228
+ if (!telemetry) {
7229
+ process.env.SENTRY_ENABLED = "false";
7230
+ delete process.env.DD_SERVICE;
7231
+ delete process.env.DD_ENV;
7232
+ delete process.env.DD_VERSION;
7233
+ delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
7234
+ delete process.env.OTEL_SERVICE_NAME;
7235
+ return;
7236
+ }
7237
+ const sentryIntegration = telemetry.integrations?.sentry;
7238
+ if (sentryIntegration) {
7239
+ process.env.SENTRY_ENABLED = sentryIntegration.enabled ? "true" : "false";
7240
+ if (sentryIntegration.enabled) {
7241
+ if (sentryIntegration.dsn) process.env.SENTRY_DSN = sentryIntegration.dsn;
7242
+ if (sentryIntegration.tracesSampleRate !== void 0) process.env.SENTRY_TRACES_SAMPLE_RATE = String(sentryIntegration.tracesSampleRate);
7243
+ if (sentryIntegration.environment) process.env.SENTRY_ENVIRONMENT = sentryIntegration.environment;
7244
+ } else {
7245
+ delete process.env.SENTRY_DSN;
7246
+ delete process.env.SENTRY_TRACES_SAMPLE_RATE;
7247
+ }
7248
+ } else {
7249
+ process.env.SENTRY_ENABLED = "false";
7250
+ delete process.env.SENTRY_DSN;
7251
+ delete process.env.SENTRY_TRACES_SAMPLE_RATE;
7252
+ }
7253
+ delete process.env.DD_SERVICE;
7254
+ delete process.env.DD_ENV;
7255
+ delete process.env.DD_VERSION;
7256
+ delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
7257
+ delete process.env.OTEL_SERVICE_NAME;
7258
+ for (const exporter of telemetry.exporters) {
7259
+ if (exporter.type === "datadog") {
7260
+ if (exporter.service) process.env.DD_SERVICE = exporter.service;
7261
+ if (telemetry.environment) process.env.DD_ENV = telemetry.environment;
7262
+ if (telemetry.release) process.env.DD_VERSION = telemetry.release;
7263
+ continue;
7264
+ }
7265
+ if (exporter.type === "otel") {
7266
+ if (exporter.endpoint) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exporter.endpoint;
7267
+ if (exporter.serviceName) process.env.OTEL_SERVICE_NAME = exporter.serviceName;
7054
7268
  }
7055
- const exposureQueue = resolveExposureQueue(config?.runtime?.experimentTracking, baseOrigin);
7056
- if (exposureQueue) developmentCleanups.push(async () => {
7057
- try {
7058
- await exposureQueue.flush();
7059
- } finally {
7060
- exposureQueue.destroy();
7061
- }
7062
- });
7063
- serverContext.requestHandler.use(createABVariantMiddleware({
7064
- experiments: config?.runtime?.experiments ?? {},
7065
- manifestLoader,
7066
- exposureQueue
7067
- }));
7068
- const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(config?.runtime?.experiments ?? {});
7069
- logger$1.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
7070
7269
  }
7071
- logger$1.info(`✅ 服务器上下文已初始化 (${isDev() ? "开发" : "生产"}模式)`);
7072
- return serverContext;
7073
7270
  }
7074
- /**
7075
- * 启动服务器
7076
- * @returns 服务器上下文,包含 loadRenderFunction 等方法
7077
- */
7078
- function startAppServer(config, setupRoutes) {
7079
- if (stopping) return stopping.then(() => startAppServer(config, setupRoutes));
7080
- if (starting) return starting;
7081
- if (serverContext?.httpServer) return Promise.resolve(serverContext);
7082
- starting = startAppServerInternal(config, setupRoutes).finally(() => {
7083
- starting = void 0;
7084
- });
7085
- return starting;
7271
+ async function prepareProductionBuild(root = process.cwd()) {
7272
+ const rscDistEntry = path.resolve(root, "dist/rsc/index.js");
7273
+ const clientDir = path.resolve(root, "dist/client");
7274
+ await fs$3.access(rscDistEntry);
7275
+ await fs$3.access(clientDir);
7276
+ return {
7277
+ rscDistEntry,
7278
+ clientDir,
7279
+ staticCspIndex: await loadStaticCspManifest(path.dirname(clientDir), { onLegacyBuild: () => logger$8.warn("[CSP] 构建缺少 static-csp-manifest.json;已在启动期生成兼容索引,请重新构建以生成清单") })
7280
+ };
7086
7281
  }
7087
- async function startAppServerInternal(config, setupRoutes) {
7088
- try {
7089
- return await createAndListenAppServer(config, setupRoutes);
7090
- } catch (error) {
7091
- if (serverContext?.isDev || developmentCleanups.length) {
7092
- const context = serverContext;
7093
- serverContext = null;
7094
- const rollback = await Promise.allSettled([context?.httpServer ? closeServer(context.httpServer) : Promise.resolve()]);
7095
- rollback.push(...await Promise.allSettled([closeDevelopmentResources()]));
7096
- for (const result of rollback) if (result.status === "rejected") logger$1.warn("Development startup cleanup failed", result.reason);
7097
- }
7098
- throw error;
7282
+ async function createProductionRuntime(config, options = {}) {
7283
+ const { rscDistEntry, clientDir, staticCspIndex } = options.build ?? await prepareProductionBuild(options.root);
7284
+ const ssgRoutes = staticCspIndex.ssgRoutes ?? (Array.isArray(config.ssg?.routes) ? config.ssg.routes : []);
7285
+ const ssgFiles = new Map(ssgRoutes.map((route) => [route, routeToFilePath(route)]));
7286
+ const ssgAliases = /* @__PURE__ */ new Map();
7287
+ const configuredRoutes = Object.keys(config.routes ?? {});
7288
+ assertDistinctHtmlRouteIdentities(configuredRoutes, { allowPatterns: true });
7289
+ const routeNames = /* @__PURE__ */ new Set([...ssgFiles.keys(), ...configuredRoutes.filter((route) => !isHtmlRoutePattern(route))]);
7290
+ assertDistinctHtmlRouteIdentities(routeNames);
7291
+ const declaredIdentities = new Set([...routeNames].map((route) => decodeHtmlPathname(route)));
7292
+ const explicitRoutes = /* @__PURE__ */ new Map();
7293
+ for (const route of routeNames) {
7294
+ const target = new URL(route, "http://localhost").pathname;
7295
+ explicitRoutes.set(decodeHtmlPathname(route), target);
7296
+ if ((route === "/" || !route.endsWith("/")) && !declaredIdentities.has(decodeHtmlPathname(route + "_.rsc"))) explicitRoutes.set(decodeHtmlPathname(route + "_.rsc"), target + "_.rsc");
7099
7297
  }
7100
- }
7101
- async function createAndListenAppServer(config, setupRoutes) {
7102
- if (!isDev()) {
7103
- if (serverContext) return serverContext;
7104
- const runtime = await createProductionRuntime(config, { setupRoutes });
7105
- try {
7106
- const result = await startServer(runtime.app, config.server);
7107
- productionRuntime = runtime;
7108
- serverContext = {
7109
- requestHandler: runtime.app,
7110
- viteDevMiddleware: null,
7111
- httpServer: result.server,
7112
- url: result.url,
7113
- isDev: false,
7114
- manifest: loadProdManifest()
7115
- };
7116
- return serverContext;
7117
- } catch (error) {
7118
- try {
7119
- await runtime.close();
7120
- } catch (cleanupError) {
7121
- logger$1.warn("Production startup cleanup failed", cleanupError);
7122
- }
7123
- throw error;
7298
+ for (const [canonical, file] of ssgFiles) {
7299
+ const logical = decodeHtmlPathname(canonical);
7300
+ const target = new URL(canonical, "http://localhost").pathname;
7301
+ const base = logical.replace(/\/$/, "") || "/";
7302
+ for (const alias of [
7303
+ logical,
7304
+ base,
7305
+ base === "/" ? "/" : base + "/",
7306
+ base === "/" ? "/index.html" : base + "/index.html",
7307
+ "/" + file
7308
+ ]) {
7309
+ ssgAliases.set(alias, target);
7310
+ ssgAliases.set(alias + "_.rsc", target + "_.rsc");
7124
7311
  }
7125
7312
  }
7126
- if (!serverContext) await initServerContext(config);
7127
- if (!serverContext) throw new Error("服务器上下文初始化失败");
7128
- setupRoutes(serverContext.requestHandler);
7129
- mountViteOrStatic(serverContext);
7130
- const serverConfig = {
7131
- port: config.server.port,
7132
- host: config.server.host,
7133
- strictPort: config.server.strictPort
7313
+ const resolveSsgIdentity = (pathname) => {
7314
+ const logical = decodeHtmlPathname(pathname);
7315
+ const known = ssgAliases.get(logical);
7316
+ return known ? explicitRoutes.get(logical) ?? known : pathname;
7134
7317
  };
7135
- const result = await startServer(serverContext.requestHandler, serverConfig);
7136
- serverContext.httpServer = result.server;
7137
- serverContext.url = result.url;
7138
- logger$1.success(`🚀 ${isDev() ? "开发" : "生产"}服务器已启动: ${result.url}`);
7139
- return serverContext;
7140
- }
7141
- /**
7142
- * 关闭服务器
7143
- */
7144
- function shutdownServer() {
7145
- if (stopping) return stopping;
7146
- stopping = stopAppServer().finally(() => {
7147
- stopping = void 0;
7148
- });
7149
- return stopping;
7150
- }
7151
- async function stopAppServer() {
7152
- await starting?.catch(() => void 0);
7153
- if (!serverContext) return;
7154
- const context = serverContext;
7155
- const runtime = productionRuntime;
7156
- serverContext = null;
7157
- productionRuntime = void 0;
7158
- const errors = (await Promise.allSettled([context.httpServer ? closeServer(context.httpServer) : Promise.resolve()])).concat(await Promise.allSettled([Promise.resolve().then(() => context.isDev ? closeDevelopmentResources() : void 0), Promise.resolve().then(() => runtime?.close())])).filter((result) => result.status === "rejected");
7159
- if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Server shutdown failed");
7160
- logger$1.success("✅ 服务器已完全关闭");
7161
- }
7162
- //#endregion
7163
- //#region src/isr/ISRRoutes.ts
7164
- var ISRRoutes = class {
7165
- engine;
7166
- logger;
7167
- defaultMode;
7168
- routes;
7169
- requestLimits;
7170
- constructor(engine, logger, config) {
7171
- this.engine = engine;
7172
- this.logger = logger;
7173
- this.defaultMode = config.renderMode;
7174
- this.routes = config.routes || {};
7175
- this.requestLimits = config.requestLimits;
7176
- }
7177
- setup(requestHandler) {
7178
- const seoLimiter = createRequestLimiter("seo", this.requestLimits?.seo);
7179
- const opsConfig = getRuntimeOpsConfig(requestHandler) ?? resolveOpsConfig({ server: { requestLimits: this.requestLimits } }, "development");
7180
- if (opsConfig.health.enabled) requestHandler.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
7181
- res.json({
7182
- status: "healthy",
7183
- version: package_default.version,
7184
- mode: "plugin-rsc",
7185
- defaultRenderMode: this.defaultMode,
7186
- routes: Object.keys(this.routes).length,
7187
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
7188
- });
7318
+ const cleanups = [];
7319
+ let closed;
7320
+ const close = () => closed ??= (async () => {
7321
+ const errors = (await Promise.allSettled(cleanups.reverse().map((cleanup) => Promise.resolve().then(cleanup)))).filter((result) => result.status === "rejected");
7322
+ if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Production runtime cleanup failed");
7323
+ })();
7324
+ try {
7325
+ validateRequestLimits(config.server.requestLimits);
7326
+ const runtime = config.runtime;
7327
+ applyTelemetryIntegrationEnv(runtime);
7328
+ const sentryIntegration = runtime?.telemetry ? runtime.telemetry.integrations?.sentry : void 0;
7329
+ if (sentryIntegration?.enabled && process.env.SENTRY_DSN) logger$8.info(`🛰️ Sentry integration 来自 ssr.config.ts runtime.telemetry.integrations`);
7330
+ else if (sentryIntegration?.enabled) logger$8.warn(`🛰️ Sentry integration 已启用但缺少 SENTRY_DSN,跳过 Sentry adapter`);
7331
+ const { fetch: rscHandler } = resolveFetchHandler(await import(
7332
+ /* @vite-ignore */
7333
+ pathToFileURL(rscDistEntry).href
7334
+ ));
7335
+ const extraConnectSrc = Array.from(new Set([runtime?.services?.api, runtime?.services?.telemetry].map(safeOrigin).filter((origin) => !!origin)));
7336
+ const app = express();
7337
+ app.disable("x-powered-by");
7338
+ app.set("trust proxy", config.server.trustProxy ?? false);
7339
+ app.use(createProductionJsonMiddleware());
7340
+ const opsConfig = resolveOpsConfig(config, "production");
7341
+ for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
7342
+ app.use(createCspNonceMiddleware());
7343
+ app.use(createSecurityMiddleware(false, extraConnectSrc));
7344
+ app.use(createCompressionMiddleware());
7345
+ if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
7346
+ const cookieDomain = runtime?.cookieDomain;
7347
+ app.use((req, res, next) => {
7348
+ const { data, needsAnonCookie } = createServerRequestContext(req);
7349
+ if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
7350
+ requestContext.run(data, () => next());
7189
7351
  });
7190
- requestHandler.get("/sitemap.xml", seoLimiter, async (_req, res) => {
7191
- try {
7192
- const candidates = [
7193
- path.resolve(process.cwd(), "dist/client/sitemap.xml"),
7194
- path.resolve(process.cwd(), ".isr-hyou/ssg/sitemap.xml"),
7195
- path.resolve(process.cwd(), "public/sitemap.xml")
7196
- ];
7197
- for (const p of candidates) if (fs.existsSync(p)) {
7198
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7199
- res.send(await fs.promises.readFile(p, "utf-8"));
7200
- return;
7201
- }
7202
- await this.engine.generateSeo();
7203
- for (const p of candidates) if (fs.existsSync(p)) {
7204
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7205
- res.send(await fs.promises.readFile(p, "utf-8"));
7206
- return;
7207
- }
7208
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7209
- res.send(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>`);
7210
- } catch (error) {
7211
- this.logger.error("生成 sitemap 失败:", error);
7212
- res.status(500).send("Internal Server Error");
7352
+ if (runtime?.i18n?.prefixDefault) {
7353
+ const middleware = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(runtime.i18n) });
7354
+ if (middleware) {
7355
+ app.use(middleware);
7356
+ logger$8.info(`🌐 Locale redirect 已启用 (prefixDefault=true)`);
7357
+ }
7358
+ }
7359
+ const hasStaticExps = runtime?.experiments && Object.keys(runtime.experiments).length > 0;
7360
+ const hasManifest = !!runtime?.experimentManifest?.endpoint;
7361
+ let manifestLoader;
7362
+ let exposureQueue;
7363
+ if (hasStaticExps || hasManifest) {
7364
+ const baseOrigin = runtime?.services?.api;
7365
+ manifestLoader = resolveManifestLoader(runtime?.experimentManifest, runtime?.experiments ?? {}, baseOrigin);
7366
+ if (manifestLoader) {
7367
+ cleanups.push(() => manifestLoader?.destroy());
7368
+ await manifestLoader.init();
7213
7369
  }
7370
+ exposureQueue = resolveExposureQueue(runtime?.experimentTracking, baseOrigin);
7371
+ cleanups.push(async () => {
7372
+ try {
7373
+ await exposureQueue?.flush();
7374
+ } finally {
7375
+ exposureQueue?.destroy();
7376
+ }
7377
+ });
7378
+ app.use(createABVariantMiddleware({
7379
+ experiments: runtime?.experiments ?? {},
7380
+ manifestLoader,
7381
+ exposureQueue
7382
+ }));
7383
+ const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(runtime?.experiments ?? {});
7384
+ logger$8.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
7385
+ }
7386
+ if (opsConfig.health.enabled) app.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
7387
+ res.json({
7388
+ status: "healthy",
7389
+ version: package_default.version,
7390
+ mode: "plugin-rsc-production",
7391
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
7392
+ });
7214
7393
  });
7215
- requestHandler.get("/robots.txt", seoLimiter, async (_req, res) => {
7394
+ options.setupRoutes?.(app);
7395
+ const staticHtmlLimiter = createRequestLimiter("staticHtml", config.server.requestLimits?.staticHtml);
7396
+ const seoLimiter = createRequestLimiter("seo", config.server.requestLimits?.seo);
7397
+ app.use((req, res, next) => {
7398
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
7399
+ let pathname;
7216
7400
  try {
7217
- const candidates = [
7218
- path.resolve(process.cwd(), "dist/client/robots.txt"),
7219
- path.resolve(process.cwd(), ".isr-hyou/ssg/robots.txt"),
7220
- path.resolve(process.cwd(), "public/robots.txt")
7221
- ];
7222
- for (const p of candidates) if (fs.existsSync(p)) {
7223
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
7224
- res.send(await fs.promises.readFile(p, "utf-8"));
7225
- return;
7226
- }
7227
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
7228
- res.send("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n");
7229
- } catch (error) {
7230
- this.logger.error("生成 robots.txt 失败:", error);
7231
- res.status(500).send("Internal Server Error");
7401
+ pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
7402
+ } catch {
7403
+ res.status(400).end();
7404
+ return;
7232
7405
  }
7406
+ if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
7407
+ next();
7233
7408
  });
7234
- this.logger.debug("ISRRoutes: 已注册 ops 端点 (/health, /sitemap.xml, /robots.txt)");
7235
- }
7236
- };
7237
- //#endregion
7238
- //#region src/engine/seo/config.ts
7239
- /** 默认 SEO 配置 */
7240
- var DEFAULT_SEO_CONFIG = {
7241
- baseUrl: "",
7242
- siteName: "My App",
7243
- defaultLanguage: "zh",
7244
- supportedLanguages: ["zh", "en"],
7245
- defaultTitle: "My App",
7246
- defaultDescription: "",
7247
- titleTemplate: "%s | My App",
7248
- keywords: [],
7249
- author: "",
7250
- robots: "index,follow",
7251
- sitemap: {
7252
- priority: {
7253
- "/": 1,
7254
- "/blog/*": .7,
7255
- "*": .5
7256
- },
7257
- changeFreq: {
7258
- "/": "daily",
7259
- "/blog/*": "weekly",
7260
- "*": "monthly"
7261
- },
7262
- excludePatterns: ["/admin/*", "/api/*"],
7263
- cacheTimeout: 3600
7264
- },
7265
- openGraph: {
7266
- enabled: true,
7267
- locale: "zh_CN",
7268
- defaultImage: "/images/og-default.jpg"
7269
- },
7270
- twitter: {
7271
- enabled: true,
7272
- card: "summary_large_image",
7273
- site: ""
7274
- },
7275
- structuredData: {
7276
- enabled: true,
7277
- organizationLogo: ""
7278
- }
7279
- };
7280
- /** 深度合并配置 */
7281
- function mergeSEOConfig(base, override) {
7282
- return {
7283
- ...base,
7284
- ...override,
7285
- sitemap: {
7286
- ...base.sitemap,
7287
- ...override.sitemap
7288
- },
7289
- openGraph: {
7290
- ...base.openGraph,
7291
- ...override.openGraph
7292
- },
7293
- twitter: {
7294
- ...base.twitter,
7295
- ...override.twitter
7296
- },
7297
- structuredData: {
7298
- ...base.structuredData,
7299
- ...override.structuredData
7409
+ app.use(createStaticAssetMiddleware(clientDir));
7410
+ app.use("/assets", (_req, res) => {
7411
+ res.status(404).set("Cache-Control", "no-store").end();
7412
+ });
7413
+ app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
7414
+ const redisCfg = resolveRuntimeRedisConfig(runtime?.redis);
7415
+ const hasRedisConfig = hasRuntimeRedisConnection(runtime?.redis);
7416
+ const cacheRoutes = { ...config.routes };
7417
+ for (const route of ssgRoutes) {
7418
+ const rule = cacheRoutes[route];
7419
+ cacheRoutes[route] = typeof rule === "object" ? {
7420
+ ...rule,
7421
+ mode: "ssg"
7422
+ } : "ssg";
7300
7423
  }
7301
- };
7302
- }
7303
- //#endregion
7304
- //#region src/engine/seo/SEOEngine.ts
7305
- /**
7306
- * SEO 引擎 - 单例模式
7307
- *
7308
- * 核心功能:
7309
- * - Meta 标签生成
7310
- * - 结构化数据(JSON-LD)生成
7311
- * - 站点地图生成
7312
- * - Open Graph / Twitter Cards
7313
- */
7314
- var SEOEngine_exports = /* @__PURE__ */ __exportAll({
7315
- SEOEngine: () => SEOEngine,
7316
- createSEOEngine: () => createSEOEngine
7317
- });
7318
- var SEOEngine = class SEOEngine {
7319
- static instance = null;
7320
- logger = Logger.getInstance();
7321
- config;
7322
- initialized = false;
7323
- pageDataCache = /* @__PURE__ */ new Map();
7324
- sitemapCache = null;
7325
- sitemapLastGenerated = 0;
7326
- constructor(config) {
7327
- this.config = config ? mergeSEOConfig(DEFAULT_SEO_CONFIG, config) : { ...DEFAULT_SEO_CONFIG };
7328
- }
7329
- /** 获取单例实例 */
7330
- static getInstance(config) {
7331
- if (!SEOEngine.instance) SEOEngine.instance = new SEOEngine(config);
7332
- return SEOEngine.instance;
7333
- }
7334
- /** 重置实例(仅用于测试) */
7335
- static resetInstance() {
7336
- SEOEngine.instance = null;
7337
- }
7338
- /** 更新配置 */
7339
- updateConfig(config) {
7340
- this.config = mergeSEOConfig(this.config, config);
7341
- this.clearCache();
7342
- }
7343
- /** 获取当前配置 */
7344
- getConfig() {
7345
- return this.config;
7346
- }
7347
- /** 初始化 */
7348
- async initialize() {
7349
- if (this.initialized) return;
7350
- this.logger.info("🎯 初始化 SEO 引擎...");
7351
- this.initialized = true;
7352
- this.logger.info("✅ SEO 引擎初始化完成");
7353
- }
7354
- /** 优化页面 SEO */
7355
- async optimizePage(url, context, result) {
7356
- const pageData = this.getOrCreatePageData(url, context);
7357
- const seoTags = this.generateAllTags(pageData);
7358
- const structuredData = this.generateStructuredData(pageData);
7359
- const html = this.insertSEOTags(result.html, seoTags, structuredData);
7360
- return {
7361
- ...result,
7362
- html,
7363
- seoScore: this.calculateScore(pageData),
7364
- meta: {
7365
- ...result.meta,
7366
- seoOptimized: true
7424
+ const cache = createIsrCacheHandler({
7425
+ ...config,
7426
+ routes: cacheRoutes
7427
+ }, {
7428
+ buildId: process.env.APP_VERSION ?? staticCspIndex.buildId,
7429
+ resolveInvalidationPath: resolveSsgIdentity,
7430
+ staticSeedAdmission: (req, res) => admitRequest(staticHtmlLimiter, req, res),
7431
+ staticSeedInfo: (pathname) => {
7432
+ const htmlPath = ssgFiles.get(pathname);
7433
+ if (!htmlPath) return;
7434
+ const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
7435
+ return generatedAt === void 0 || generatedAt > Date.now() ? void 0 : { generatedAt };
7436
+ },
7437
+ staticSeed: async (pathname, policy) => {
7438
+ const htmlPath = ssgFiles.get(pathname);
7439
+ if (!htmlPath) return;
7440
+ const hashes = staticCspIndex.scriptHashes.get(htmlPath);
7441
+ if (!hashes) return;
7442
+ const absolute = path.join(clientDir, htmlPath);
7443
+ const body = await fs$3.readFile(absolute);
7444
+ const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
7445
+ if (generatedAt === void 0) return;
7446
+ return {
7447
+ body,
7448
+ statusCode: 200,
7449
+ contentType: "text/html; charset=utf-8",
7450
+ headers: {
7451
+ "content-type": "text/html; charset=utf-8",
7452
+ "content-security-policy": applyStaticScriptPolicy(policy, hashes),
7453
+ "cache-control": "no-cache",
7454
+ "x-served-by": "ssg-static"
7455
+ },
7456
+ storedAt: generatedAt,
7457
+ expiresAt: 0,
7458
+ hardExpiresAt: 0,
7459
+ tags: []
7460
+ };
7461
+ },
7462
+ store: createAutoCacheStore({
7463
+ responseNamespace: `production:${process.env.ISR_CACHE_NAMESPACE ?? "default"}`,
7464
+ redisUrl: redisCfg?.url,
7465
+ redisHost: redisCfg?.host,
7466
+ redisPort: redisCfg?.port,
7467
+ redisPassword: redisCfg?.password,
7468
+ redisKeyPrefix: redisCfg?.keyPrefix
7469
+ }),
7470
+ invalidationBus: hasRedisConfig ? new RedisInvalidationBus({
7471
+ url: redisCfg?.url,
7472
+ host: redisCfg?.host,
7473
+ port: redisCfg?.port,
7474
+ password: redisCfg?.password,
7475
+ keyPrefix: redisCfg?.keyPrefix,
7476
+ channel: redisCfg?.invalidationChannel
7477
+ }) : void 0
7478
+ });
7479
+ cleanups.push(() => cache.destroy());
7480
+ if (opsConfig.inventory.enabled) {
7481
+ const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-Cb_MZhLZ.js");
7482
+ app.use(createCacheInspectorMiddleware(cache, opsConfig));
7483
+ logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
7484
+ }
7485
+ app.use((req, res, next) => {
7486
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
7487
+ let logical;
7488
+ try {
7489
+ logical = decodeHtmlPathname(req.path);
7490
+ } catch {
7491
+ res.status(400).end();
7492
+ return;
7493
+ }
7494
+ const known = ssgAliases.get(logical);
7495
+ if (!known) return next();
7496
+ const canonical = explicitRoutes.get(logical) ?? known;
7497
+ if (req.path === canonical) return next();
7498
+ redirectLocal(res, 308, canonical, readRedirectQuery(req.url));
7499
+ });
7500
+ app.use(cache);
7501
+ const staticHtml = createStaticHtmlMiddlewareWithLimiter(clientDir, staticCspIndex, staticHtmlLimiter);
7502
+ app.use((req, res, next) => {
7503
+ if (res.getHeader("X-Resolved-Mode") === "ssg" || ssgAliases.has(decodeHtmlPathname(req.path)) && explicitRoutes.has(decodeHtmlPathname(req.path))) return next();
7504
+ staticHtml(req, res, next);
7505
+ });
7506
+ if (opsConfig.metrics.enabled) app.get("/metrics", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("metrics", opsConfig), async (_req, res) => {
7507
+ try {
7508
+ res.set("content-type", promRegistry.contentType);
7509
+ res.end(await promRegistry.metrics());
7510
+ } catch (err) {
7511
+ res.status(500).type("text/plain").end(`metrics error: ${String(err)}`);
7512
+ }
7513
+ });
7514
+ const seoCfg = resolveSeoConfig(config);
7515
+ const seo = SEOEngine.getInstance({ baseUrl: seoCfg.baseUrl });
7516
+ cleanups.push(() => seo.shutdown());
7517
+ await seo.initialize();
7518
+ app.get("/sitemap.xml", async (_req, res) => {
7519
+ try {
7520
+ const xml = await seo.generateSitemap(extractRoutesForSitemap(config));
7521
+ res.set("content-type", "application/xml; charset=utf-8");
7522
+ res.set("cache-control", "public, max-age=3600");
7523
+ res.end(xml);
7524
+ } catch (err) {
7525
+ res.status(500).type("text/plain").end(`sitemap error: ${String(err)}`);
7367
7526
  }
7527
+ });
7528
+ app.get("/robots.txt", (_req, res) => {
7529
+ res.set("content-type", "text/plain; charset=utf-8");
7530
+ res.set("cache-control", "public, max-age=3600");
7531
+ res.end(seo.generateRobotsTxt());
7532
+ });
7533
+ const { renderError500Html } = await import("./error500-template-DhaZzLOB.js");
7534
+ app.all(/.*/, createProductionRequestHandler(rscHandler, (err, _req, res) => {
7535
+ logger$8.error("[Server]", "请求处理异常", err);
7536
+ if (!res.headersSent) {
7537
+ const traceId = getTraceId();
7538
+ res.status(500).type("text/html; charset=utf-8").send(renderError500Html(traceId));
7539
+ } else res.destroy();
7540
+ }));
7541
+ return {
7542
+ app,
7543
+ close
7368
7544
  };
7545
+ } catch (error) {
7546
+ await close().catch((cleanupError) => logger$8.error("[Server]", "Production initialization cleanup failed", cleanupError));
7547
+ throw error;
7369
7548
  }
7370
- /** 生成站点地图 */
7371
- async generateSitemap(routes) {
7372
- const now = Date.now();
7373
- if (this.sitemapCache && now - this.sitemapLastGenerated < this.config.sitemap.cacheTimeout * 1e3) return this.sitemapCache;
7374
- if (!this.config.baseUrl) throw new Error("SEO baseUrl 未配置,无法生成 sitemap。请设置 ssr.config.ts runtime.site。");
7375
- const sitemap = new SitemapStream({ hostname: this.config.baseUrl });
7376
- const urls = routes || Array.from(this.pageDataCache.keys());
7377
- const finalUrls = urls.length > 0 ? urls : ["/"];
7378
- for (const url of finalUrls) {
7379
- if (this.shouldExcludeUrl(url)) continue;
7380
- sitemap.write({
7381
- url,
7382
- priority: this.getUrlPriority(url),
7383
- changefreq: this.getUrlChangeFreq(url),
7384
- lastmod: (/* @__PURE__ */ new Date()).toISOString()
7385
- });
7549
+ }
7550
+ var rawRequestBodies = /* @__PURE__ */ new WeakMap();
7551
+ function createProductionJsonMiddleware() {
7552
+ return express.json({
7553
+ limit: "1mb",
7554
+ verify: (req, _res, body) => {
7555
+ rawRequestBodies.set(req, Buffer.from(body));
7386
7556
  }
7387
- sitemap.end();
7388
- this.sitemapCache = (await streamToPromise(sitemap)).toString();
7389
- this.sitemapLastGenerated = now;
7390
- this.logger.info(`✅ 站点地图已生成: ${urls.length} 个页面`);
7391
- return this.sitemapCache;
7557
+ });
7558
+ }
7559
+ /** Own cancellation until the outgoing response finishes, not IncomingMessage.close. */
7560
+ function createProductionRequestHandler(handler, onError) {
7561
+ return async (req, res) => {
7562
+ const controller = new AbortController();
7563
+ const cleanup = () => {
7564
+ req.removeListener("aborted", onAborted);
7565
+ res.removeListener("close", onClose);
7566
+ res.removeListener("finish", cleanup);
7567
+ };
7568
+ const onAborted = () => {
7569
+ controller.abort(new DOMException("Client disconnected", "AbortError"));
7570
+ cleanup();
7571
+ };
7572
+ const onClose = () => {
7573
+ if (!res.writableFinished) onAborted();
7574
+ else cleanup();
7575
+ };
7576
+ req.once("aborted", onAborted);
7577
+ res.once("close", onClose);
7578
+ res.once("finish", cleanup);
7579
+ if (req.aborted || res.destroyed) onAborted();
7580
+ try {
7581
+ if (controller.signal.aborted) return;
7582
+ const response = await handler(nodeToWebRequest(req, controller.signal));
7583
+ if (controller.signal.aborted) {
7584
+ response.body?.cancel(controller.signal.reason).catch(() => {});
7585
+ return;
7586
+ }
7587
+ await pipeWebResponse(response, res);
7588
+ } catch (error) {
7589
+ if (!controller.signal.aborted) onError(error, req, res);
7590
+ } finally {
7591
+ if (controller.signal.aborted || res.writableFinished) cleanup();
7592
+ }
7593
+ };
7594
+ }
7595
+ function nodeToWebRequest(req, signal) {
7596
+ const host = String(req.headers.host || "localhost");
7597
+ const transport = req.socket?.encrypted ? "https" : "http";
7598
+ const selected = req.protocol?.toLowerCase();
7599
+ const url = `${selected === "https" || selected === "http" ? selected : transport}://${host}${req.url}`;
7600
+ const headers = new Headers();
7601
+ for (const [k, v] of Object.entries(req.headers)) {
7602
+ if (v == null) continue;
7603
+ if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
7604
+ else headers.set(k, String(v));
7392
7605
  }
7393
- /** 生成 Robots.txt */
7394
- generateRobotsTxt() {
7395
- return [
7396
- "User-agent: *",
7397
- "Allow: /",
7398
- "",
7399
- ...this.config.sitemap.excludePatterns.map((p) => `Disallow: ${p}`),
7400
- "",
7401
- `Sitemap: ${this.config.baseUrl}/sitemap.xml`
7402
- ].join("\n");
7606
+ const method = req.method || "GET";
7607
+ const init = {
7608
+ method,
7609
+ headers,
7610
+ signal
7611
+ };
7612
+ if (method !== "GET" && method !== "HEAD") {
7613
+ init.body = rawRequestBodies.get(req) ?? Readable.toWeb(req);
7614
+ init.duplex = "half";
7403
7615
  }
7404
- /** 清理缓存 */
7405
- clearCache() {
7406
- this.pageDataCache.clear();
7407
- this.sitemapCache = null;
7408
- this.sitemapLastGenerated = 0;
7616
+ return new Request(url, init);
7617
+ }
7618
+ async function pipeWebResponse(response, res) {
7619
+ res.status(response.status);
7620
+ response.headers.forEach((v, k) => {
7621
+ if (k.toLowerCase() === "content-length" || k.toLowerCase() === "set-cookie") return;
7622
+ res.setHeader(k, v);
7623
+ });
7624
+ const cookies = response.headers.getSetCookie();
7625
+ if (cookies.length) {
7626
+ const existing = res.getHeader?.("set-cookie");
7627
+ res.setHeader("set-cookie", [...existing == null ? [] : Array.isArray(existing) ? existing : [String(existing)], ...cookies]);
7409
7628
  }
7410
- /** 关闭引擎 */
7411
- async shutdown() {
7412
- this.clearCache();
7413
- this.initialized = false;
7414
- this.logger.debug("✅ SEO 引擎已关闭");
7629
+ if (!response.body) {
7630
+ res.end();
7631
+ return;
7415
7632
  }
7416
- getOrCreatePageData(url, context) {
7417
- const cached = this.pageDataCache.get(url);
7418
- if (cached) return cached;
7419
- const pageType = this.detectPageType(url);
7420
- const pageData = {
7421
- url: `${this.config.baseUrl}${url}`,
7422
- title: this.generateTitle(url),
7423
- description: this.generateDescription(url, pageType),
7424
- keywords: [...this.config.keywords, ...this.extractKeywordsFromUrl(url)],
7425
- image: this.config.openGraph.defaultImage,
7426
- type: pageType,
7427
- language: this.detectLanguage(url, context),
7428
- modifiedTime: (/* @__PURE__ */ new Date()).toISOString()
7633
+ const nodeReadable = Readable.fromWeb(response.body);
7634
+ await new Promise((resolve, reject) => {
7635
+ const cleanup = () => {
7636
+ res.removeListener?.("close", onClose);
7637
+ res.removeListener?.("error", onError);
7429
7638
  };
7430
- this.pageDataCache.set(url, pageData);
7431
- return pageData;
7432
- }
7433
- generateAllTags(pageData) {
7434
- const tags = [];
7435
- tags.push(`<title>${pageData.title}</title>`);
7436
- tags.push(`<meta name="description" content="${pageData.description}">`);
7437
- if (pageData.keywords?.length) tags.push(`<meta name="keywords" content="${pageData.keywords.join(", ")}">`);
7438
- tags.push(`<meta name="author" content="${this.config.author}">`);
7439
- tags.push(`<meta name="robots" content="${this.config.robots}">`);
7440
- tags.push(`<link rel="canonical" href="${pageData.url}">`);
7441
- if (this.config.openGraph.enabled) {
7442
- tags.push(`<meta property="og:title" content="${pageData.title}">`);
7443
- tags.push(`<meta property="og:description" content="${pageData.description}">`);
7444
- tags.push(`<meta property="og:type" content="${pageData.type}">`);
7445
- tags.push(`<meta property="og:url" content="${pageData.url}">`);
7446
- tags.push(`<meta property="og:site_name" content="${this.config.siteName}">`);
7447
- tags.push(`<meta property="og:locale" content="${this.config.openGraph.locale}">`);
7448
- if (pageData.image) tags.push(`<meta property="og:image" content="${pageData.image}">`);
7639
+ const onClose = () => {
7640
+ nodeReadable.destroy();
7641
+ cleanup();
7642
+ resolve();
7643
+ };
7644
+ const onError = (error) => {
7645
+ nodeReadable.destroy();
7646
+ cleanup();
7647
+ reject(error);
7648
+ };
7649
+ res.once("close", onClose);
7650
+ res.once("error", onError);
7651
+ nodeReadable.once("end", () => {
7652
+ cleanup();
7653
+ resolve();
7654
+ });
7655
+ nodeReadable.once("error", (error) => {
7656
+ cleanup();
7657
+ if (res.headersSent) res.destroy?.(error);
7658
+ reject(error);
7659
+ });
7660
+ if (res.destroyed) onClose();
7661
+ else nodeReadable.pipe(res);
7662
+ });
7663
+ }
7664
+ function createStaticHtmlMiddlewareWithLimiter(clientDir, index, limiter) {
7665
+ const targets = /* @__PURE__ */ new WeakMap();
7666
+ const guarded = express.Router();
7667
+ guarded.use(limiter);
7668
+ guarded.use((req, res, next) => {
7669
+ const target = targets.get(req);
7670
+ targets.delete(req);
7671
+ if (!target) return next();
7672
+ res.setHeader("Content-Security-Policy", applyStaticScriptPolicy(String(res.getHeader("Content-Security-Policy") ?? "default-src 'self'"), target.hashes));
7673
+ res.setHeader("Cache-Control", "public, max-age=3600");
7674
+ res.setHeader("X-Served-By", "ssg-static");
7675
+ res.sendFile(target.htmlPath, {
7676
+ root: clientDir,
7677
+ maxAge: "1h",
7678
+ dotfiles: "ignore"
7679
+ }, (error) => {
7680
+ if (error) next(error);
7681
+ });
7682
+ });
7683
+ return (req, res, next) => {
7684
+ if (req.method !== "GET" && req.method !== "HEAD") return next();
7685
+ let pathname;
7686
+ try {
7687
+ pathname = decodeHtmlPathname(req.path);
7688
+ } catch {
7689
+ res.status(400).end();
7690
+ return;
7691
+ }
7692
+ const relative = pathname.slice(1);
7693
+ const htmlPath = relative.endsWith("/") || !relative ? relative + "index.html" : relative.toLowerCase().endsWith(".html") ? relative : relative + "/index.html";
7694
+ const hashes = index.scriptHashes.get(htmlPath);
7695
+ if (!hashes) return next();
7696
+ targets.set(req, {
7697
+ htmlPath,
7698
+ hashes
7699
+ });
7700
+ guarded(req, res, next);
7701
+ };
7702
+ }
7703
+ /** Asset serving must never discover HTML outside the validated build manifest. */
7704
+ function normalizeStaticAssetPathname(pathname) {
7705
+ return path.posix.normalize(decodeURIComponent(new URL(`http://localhost${pathname}`).pathname).replaceAll("\\", "/"));
7706
+ }
7707
+ function createStaticAssetMiddleware(clientDir) {
7708
+ const assets = express.static(clientDir, {
7709
+ index: false,
7710
+ redirect: false,
7711
+ maxAge: "1h",
7712
+ fallthrough: true,
7713
+ setHeaders: (res, filePath) => {
7714
+ if (filePath.includes(`${path.sep}assets${path.sep}`)) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
7715
+ else if (/\.(jpe?g|png|webp|avif|gif|svg|ico|woff2?)$/i.test(filePath)) res.setHeader("Cache-Control", "public, max-age=604800, stale-while-revalidate=86400");
7449
7716
  }
7450
- if (this.config.twitter.enabled) {
7451
- tags.push(`<meta name="twitter:card" content="${this.config.twitter.card}">`);
7452
- tags.push(`<meta name="twitter:site" content="${this.config.twitter.site}">`);
7453
- tags.push(`<meta name="twitter:title" content="${pageData.title}">`);
7454
- tags.push(`<meta name="twitter:description" content="${pageData.description}">`);
7455
- if (pageData.image) tags.push(`<meta name="twitter:image" content="${pageData.image}">`);
7717
+ });
7718
+ return (req, res, next) => {
7719
+ let pathname;
7720
+ try {
7721
+ pathname = normalizeStaticAssetPathname(req.path);
7722
+ } catch {
7723
+ res.status(400).end();
7724
+ return;
7456
7725
  }
7457
- return tags.join("\n ");
7726
+ if ([".html", ".htm"].includes(path.posix.extname(pathname).toLowerCase())) return next();
7727
+ assets(req, res, next);
7728
+ };
7729
+ }
7730
+ //#endregion
7731
+ //#region src/server/httpServer.ts
7732
+ /**
7733
+ * HTTP 服务器启动器
7734
+ *
7735
+ * Node origin 只启动 HTTP/1.1。
7736
+ *
7737
+ * TLS / HTTP/2 / HTTP/3 / Brotli 属于 CDN / Ingress / Nginx / Envoy / ALB 边界。
7738
+ * isr-engine 负责 SSR/ISR/RSC/cache/revalidate,不把网关层协议暴露为业务配置。
7739
+ */
7740
+ var logger$1 = Logger.getInstance();
7741
+ var DEFAULT_TIMEOUTS = {
7742
+ requestTimeoutMs: 6e4,
7743
+ headersTimeoutMs: 15e3,
7744
+ keepAliveTimeoutMs: 5e3,
7745
+ idleTimeoutMs: 3e4,
7746
+ shutdownTimeoutMs: 5e3,
7747
+ maxRequestsPerSocket: 0
7748
+ };
7749
+ var LISTEN_BACKLOG = 8192;
7750
+ var serverSockets = /* @__PURE__ */ new WeakMap();
7751
+ function applyHttpTimeouts(server) {
7752
+ server.requestTimeout = DEFAULT_TIMEOUTS.requestTimeoutMs;
7753
+ server.headersTimeout = DEFAULT_TIMEOUTS.headersTimeoutMs;
7754
+ server.keepAliveTimeout = DEFAULT_TIMEOUTS.keepAliveTimeoutMs;
7755
+ server.maxRequestsPerSocket = DEFAULT_TIMEOUTS.maxRequestsPerSocket;
7756
+ server.setTimeout(DEFAULT_TIMEOUTS.idleTimeoutMs);
7757
+ server.__shutdownTimeoutMs = DEFAULT_TIMEOUTS.shutdownTimeoutMs;
7758
+ }
7759
+ function getServerAddress(server) {
7760
+ const addr = server.address();
7761
+ if (addr && typeof addr === "object") {
7762
+ const info = addr;
7763
+ return {
7764
+ address: info.address,
7765
+ port: info.port
7766
+ };
7458
7767
  }
7459
- generateStructuredData(pageData) {
7460
- if (!this.config.structuredData.enabled) return "";
7461
- const data = [{
7462
- "@context": "https://schema.org",
7463
- "@type": "WebSite",
7464
- name: this.config.siteName,
7465
- url: this.config.baseUrl
7466
- }, {
7467
- "@context": "https://schema.org",
7468
- "@type": "Organization",
7469
- name: this.config.siteName,
7470
- url: this.config.baseUrl,
7471
- logo: this.config.structuredData.organizationLogo
7472
- }];
7473
- if (pageData.type === "article") data.push({
7474
- "@context": "https://schema.org",
7475
- "@type": "Article",
7476
- headline: pageData.title,
7477
- description: pageData.description,
7478
- url: pageData.url,
7479
- dateModified: pageData.modifiedTime,
7480
- author: {
7481
- "@type": "Person",
7482
- name: pageData.author || this.config.author
7768
+ return {
7769
+ address: "<unknown>",
7770
+ port: 0
7771
+ };
7772
+ }
7773
+ function formatHostForUrl(address) {
7774
+ if (address === "::" || address === "0.0.0.0" || address === "") return "localhost";
7775
+ if (address.includes(":") && !address.startsWith("[")) return `[${address}]`;
7776
+ return address;
7777
+ }
7778
+ /** 启动 HTTP/1.1 服务器 */
7779
+ function startHttp1Server(app, config) {
7780
+ const maxAttempts = config.strictPort === false ? 20 : 1;
7781
+ const startPort = config.port;
7782
+ return new Promise((resolve, reject) => {
7783
+ const server = createServer$1(app);
7784
+ applyHttpTimeouts(server);
7785
+ const sockets = /* @__PURE__ */ new Set();
7786
+ serverSockets.set(server, sockets);
7787
+ server.on("connection", (socket) => {
7788
+ sockets.add(socket);
7789
+ socket.once("close", () => sockets.delete(socket));
7790
+ });
7791
+ let attempt = 0;
7792
+ const listen = (port) => {
7793
+ server.listen({
7794
+ port,
7795
+ host: config.host,
7796
+ backlog: LISTEN_BACKLOG
7797
+ });
7798
+ };
7799
+ server.on("listening", () => {
7800
+ const { address, port } = getServerAddress(server);
7801
+ const url = `http://${formatHostForUrl(address)}:${port || config.port}`;
7802
+ logger$1.info(`HTTP/1.1 服务器已启动: ${url}`);
7803
+ resolve({
7804
+ server,
7805
+ url
7806
+ });
7807
+ });
7808
+ server.on("error", (error) => {
7809
+ if (error.code === "EADDRINUSE" && attempt + 1 < maxAttempts) {
7810
+ attempt += 1;
7811
+ const nextPort = startPort + attempt;
7812
+ logger$1.warn(`端口 ${startPort + attempt - 1} 已占用,尝试 ${nextPort}`);
7813
+ listen(nextPort);
7814
+ return;
7483
7815
  }
7816
+ reject(error);
7484
7817
  });
7485
- return `<script type="application/ld+json">${JSON.stringify(data)}<\/script>`;
7486
- }
7487
- insertSEOTags(html, seoTags, structuredData) {
7488
- const headEndIndex = html.indexOf("</head>");
7489
- if (headEndIndex === -1) return html;
7490
- return html.slice(0, headEndIndex) + " " + seoTags + "\n " + structuredData + "\n" + html.slice(headEndIndex);
7491
- }
7492
- calculateScore(pageData) {
7493
- let score = 0;
7494
- if (pageData.title && pageData.title.length >= 30 && pageData.title.length <= 60) score += 25;
7495
- else if (pageData.title) score += 15;
7496
- if (pageData.description && pageData.description.length >= 100) score += 25;
7497
- else if (pageData.description) score += 15;
7498
- if (pageData.keywords && pageData.keywords.length >= 3) score += 20;
7499
- if (pageData.image) score += 15;
7500
- if (this.config.structuredData.enabled) score += 15;
7501
- return Math.min(score, 100);
7502
- }
7503
- detectPageType(url) {
7504
- if (url.includes("/blog/") || url.includes("/article/")) return "article";
7505
- if (url.includes("/product/") || url.includes("/shop/")) return "product";
7506
- return "website";
7507
- }
7508
- generateTitle(url) {
7509
- if (url === "/") return this.config.defaultTitle;
7510
- const title = url.split("/").filter(Boolean).map((s) => s.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())).join(" - ");
7511
- return this.config.titleTemplate.replace("%s", title);
7512
- }
7513
- generateDescription(url, pageType) {
7514
- if (url === "/") return this.config.defaultDescription;
7515
- const topic = url.split("/").pop()?.replace(/-/g, " ") || "";
7516
- if (pageType === "article") return `阅读关于 ${topic} 的最新文章。`;
7517
- if (pageType === "product") return `探索 ${topic} 的详细信息。`;
7518
- return `了解更多关于 ${topic} 的内容。`;
7519
- }
7520
- extractKeywordsFromUrl(url) {
7521
- return url.split("/").filter(Boolean).flatMap((s) => s.split("-"));
7522
- }
7523
- detectLanguage(url, _context) {
7524
- const pathLang = url.split("/")[1];
7525
- if (this.config.supportedLanguages.includes(pathLang)) return pathLang;
7526
- return this.config.defaultLanguage;
7527
- }
7528
- shouldExcludeUrl(url) {
7529
- return this.config.sitemap.excludePatterns.some((pattern) => new RegExp(pattern.replace(/\*/g, ".*")).test(url));
7530
- }
7531
- getUrlPriority(url) {
7532
- for (const [pattern, priority] of Object.entries(this.config.sitemap.priority)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return priority;
7533
- return .5;
7534
- }
7535
- getUrlChangeFreq(url) {
7536
- for (const [pattern, freq] of Object.entries(this.config.sitemap.changeFreq)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return freq;
7537
- return "monthly";
7818
+ listen(startPort);
7819
+ });
7820
+ }
7821
+ /** 启动 Node origin 服务器 */
7822
+ function startServer(app, config) {
7823
+ return startHttp1Server(app, config);
7824
+ }
7825
+ var closingServers = /* @__PURE__ */ new WeakMap();
7826
+ /** Stop accepting requests, drain active responses, then force overdue connections closed. */
7827
+ function closeServer(server) {
7828
+ const existing = closingServers.get(server);
7829
+ if (existing) return existing;
7830
+ const closing = new Promise((resolve, reject) => {
7831
+ const shutdownTimeoutMs = server.__shutdownTimeoutMs ?? DEFAULT_TIMEOUTS.shutdownTimeoutMs;
7832
+ const timeout = setTimeout(() => {
7833
+ try {
7834
+ server.closeAllConnections();
7835
+ for (const socket of serverSockets.get(server) ?? []) socket.destroy();
7836
+ } catch (error) {
7837
+ reject(error);
7838
+ }
7839
+ }, shutdownTimeoutMs);
7840
+ try {
7841
+ server.close((error) => {
7842
+ clearTimeout(timeout);
7843
+ if (error) reject(error);
7844
+ else resolve();
7845
+ });
7846
+ server.closeIdleConnections();
7847
+ } catch (error) {
7848
+ clearTimeout(timeout);
7849
+ reject(error);
7850
+ }
7851
+ });
7852
+ closingServers.set(server, closing);
7853
+ return closing;
7854
+ }
7855
+ //#endregion
7856
+ //#region src/server/manager.ts
7857
+ /**
7858
+ * 服务器管理器
7859
+ * 整合 Vite 开发服务器、HTTP 服务器和中间件
7860
+ * ISREngine 唯一需要关心的服务器入口
7861
+ */
7862
+ var logger = Logger.getInstance();
7863
+ /** 服务器上下文 */
7864
+ var serverContext = null;
7865
+ var productionRuntime;
7866
+ var starting;
7867
+ var stopping;
7868
+ var developmentCleanups = [];
7869
+ async function closeDevelopmentResources() {
7870
+ const owned = developmentCleanups.splice(0).reverse();
7871
+ const failures = (await Promise.allSettled(owned.map((close) => Promise.resolve().then(close)))).filter((result) => result.status === "rejected");
7872
+ if (failures.length) throw new AggregateError(failures.map((result) => result.reason), "Development cleanup failed");
7873
+ }
7874
+ /** Retain the optional public ServerContext manifest for programmatic consumers. */
7875
+ function loadProdManifest() {
7876
+ for (const relativePath of [
7877
+ "dist/.vite/manifest.json",
7878
+ "dist/client/.vite/manifest.json",
7879
+ "dist/manifest.json"
7880
+ ]) {
7881
+ const absolutePath = path.resolve(process.cwd(), relativePath);
7882
+ if (!fs.existsSync(absolutePath)) continue;
7883
+ try {
7884
+ return JSON.parse(fs.readFileSync(absolutePath, "utf8"));
7885
+ } catch {
7886
+ logger.warn(`Manifest 解析失败: ${relativePath}`);
7887
+ }
7538
7888
  }
7539
- };
7540
- /** 创建 SEO 引擎实例(获取单例) */
7541
- function createSEOEngine(config) {
7542
- return SEOEngine.getInstance(config);
7889
+ return null;
7543
7890
  }
7544
- //#endregion
7545
- //#region src/engine/seo/resolveSeoConfig.ts
7546
7891
  /**
7547
- * SEO 配置解析器 —— 唯一的 baseUrl 解析入口
7548
- *
7549
- * 设计目标:
7550
- * - SEO 是 SSR/ISR 基础能力,始终启用,不暴露 enabled/sitemap/robots 开关
7551
- * - 用户在 ssr.config.ts 里只关心 prod 域名是什么
7552
- * - prod 只读 runtime.site,避免 SEO baseUrl 变成隐藏环境变量
7553
- * - dev 自动用 localhost,降低本地启动成本
7892
+ * 初始化开发模式服务器上下文
7554
7893
  */
7555
- var resolveSeoConfig_exports = /* @__PURE__ */ __exportAll({ resolveSeoConfig: () => resolveSeoConfig });
7556
- var logger = Logger.getInstance();
7894
+ async function initDevContext(requestHandler, config) {
7895
+ logger.info("🔧 初始化开发模式服务器...");
7896
+ const viteDevMiddleware = await createViteDevServer();
7897
+ bindRuntimeOpsConfig(requestHandler, getRuntimeOpsConfig(viteDevMiddleware) ?? resolveOpsConfig(config, "development"));
7898
+ return {
7899
+ requestHandler,
7900
+ viteDevMiddleware,
7901
+ isDev: true,
7902
+ manifest: null,
7903
+ httpServer: null
7904
+ };
7905
+ }
7557
7906
  /**
7558
- * 按以下顺序解析 baseUrl:
7559
- * 1. runtime.site
7560
- * 2. dev 模式:`http://localhost:${server.port||3000}`
7561
- * 3. prod 且未配置:返回空串(SEOEngine 在调用 generateSitemap 时报错给出修复提示)
7907
+ * 初始化服务器上下文(内部使用)
7562
7908
  */
7563
- function resolveSeoConfig(config) {
7564
- let baseUrl = "";
7565
- let source = "unset";
7566
- if (config.runtime?.site) {
7567
- baseUrl = config.runtime.site;
7568
- source = "runtime.site";
7569
- } else if (isDev()) {
7570
- const envPort = process.env.PORT ? Number(process.env.PORT) : NaN;
7571
- baseUrl = `http://localhost:${config.server?.port ?? (Number.isFinite(envPort) ? envPort : 3e3)}`;
7572
- source = "dev-default";
7909
+ async function initServerContext(config) {
7910
+ if (serverContext) return serverContext;
7911
+ serverContext = await initDevContext(express(), config);
7912
+ developmentCleanups.push(closeViteDevServer);
7913
+ applyBaseMiddlewaresWithOptions(serverContext);
7914
+ const cookieDomain = config?.runtime?.cookieDomain;
7915
+ serverContext.requestHandler.use((req, res, next) => {
7916
+ const { data, needsAnonCookie } = createServerRequestContext(req);
7917
+ if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
7918
+ requestContext.run(data, () => next());
7919
+ });
7920
+ if (config?.runtime?.i18n?.prefixDefault) {
7921
+ const localeRedirect = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(config.runtime.i18n) });
7922
+ if (localeRedirect) serverContext.requestHandler.use(localeRedirect);
7573
7923
  }
7574
- if (!baseUrl) logger.warn("⚠️ SEO baseUrl 未配置:sitemap 端点将报错。请在 ssr.config.ts 设置 runtime.site。");
7575
- else logger.info(`🎯 SEO baseUrl=${baseUrl}(来源:${source})`);
7576
- return {
7577
- baseUrl,
7578
- baseUrlSource: source
7924
+ const hasStaticExps = config?.runtime?.experiments && Object.keys(config.runtime.experiments).length > 0;
7925
+ const hasManifest = !!config?.runtime?.experimentManifest?.endpoint;
7926
+ if (hasStaticExps || hasManifest) {
7927
+ const baseOrigin = config?.runtime?.services?.api;
7928
+ const manifestLoader = resolveManifestLoader(config?.runtime?.experimentManifest, config?.runtime?.experiments ?? {}, baseOrigin);
7929
+ if (manifestLoader) {
7930
+ developmentCleanups.push(() => manifestLoader.destroy());
7931
+ await manifestLoader.init();
7932
+ }
7933
+ const exposureQueue = resolveExposureQueue(config?.runtime?.experimentTracking, baseOrigin);
7934
+ if (exposureQueue) developmentCleanups.push(async () => {
7935
+ try {
7936
+ await exposureQueue.flush();
7937
+ } finally {
7938
+ exposureQueue.destroy();
7939
+ }
7940
+ });
7941
+ serverContext.requestHandler.use(createABVariantMiddleware({
7942
+ experiments: config?.runtime?.experiments ?? {},
7943
+ manifestLoader,
7944
+ exposureQueue
7945
+ }));
7946
+ const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(config?.runtime?.experiments ?? {});
7947
+ logger.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
7948
+ }
7949
+ logger.info(`✅ 服务器上下文已初始化 (${isDev() ? "开发" : "生产"}模式)`);
7950
+ return serverContext;
7951
+ }
7952
+ /**
7953
+ * 启动服务器
7954
+ * @returns 服务器上下文,包含 loadRenderFunction 等方法
7955
+ */
7956
+ function startAppServer(config, setupRoutes) {
7957
+ if (stopping) return stopping.then(() => startAppServer(config, setupRoutes));
7958
+ if (starting) return starting;
7959
+ if (serverContext?.httpServer) return Promise.resolve(serverContext);
7960
+ starting = startAppServerInternal(config, setupRoutes).finally(() => {
7961
+ starting = void 0;
7962
+ });
7963
+ return starting;
7964
+ }
7965
+ async function startAppServerInternal(config, setupRoutes) {
7966
+ try {
7967
+ return await createAndListenAppServer(config, setupRoutes);
7968
+ } catch (error) {
7969
+ if (serverContext?.isDev || developmentCleanups.length) {
7970
+ const context = serverContext;
7971
+ serverContext = null;
7972
+ const rollback = await Promise.allSettled([context?.httpServer ? closeServer(context.httpServer) : Promise.resolve()]);
7973
+ rollback.push(...await Promise.allSettled([closeDevelopmentResources()]));
7974
+ for (const result of rollback) if (result.status === "rejected") logger.warn("Development startup cleanup failed", result.reason);
7975
+ }
7976
+ throw error;
7977
+ }
7978
+ }
7979
+ async function createAndListenAppServer(config, setupRoutes) {
7980
+ if (!isDev()) {
7981
+ if (serverContext) return serverContext;
7982
+ const runtime = await createProductionRuntime(config, { setupRoutes });
7983
+ try {
7984
+ const result = await startServer(runtime.app, config.server);
7985
+ productionRuntime = runtime;
7986
+ serverContext = {
7987
+ requestHandler: runtime.app,
7988
+ viteDevMiddleware: null,
7989
+ httpServer: result.server,
7990
+ url: result.url,
7991
+ isDev: false,
7992
+ manifest: loadProdManifest()
7993
+ };
7994
+ return serverContext;
7995
+ } catch (error) {
7996
+ try {
7997
+ await runtime.close();
7998
+ } catch (cleanupError) {
7999
+ logger.warn("Production startup cleanup failed", cleanupError);
8000
+ }
8001
+ throw error;
8002
+ }
8003
+ }
8004
+ if (!serverContext) await initServerContext(config);
8005
+ if (!serverContext) throw new Error("服务器上下文初始化失败");
8006
+ setupRoutes(serverContext.requestHandler);
8007
+ mountViteOrStatic(serverContext);
8008
+ const serverConfig = {
8009
+ port: config.server.port,
8010
+ host: config.server.host,
8011
+ strictPort: config.server.strictPort
7579
8012
  };
8013
+ const result = await startServer(serverContext.requestHandler, serverConfig);
8014
+ serverContext.httpServer = result.server;
8015
+ serverContext.url = result.url;
8016
+ logger.success(`🚀 ${isDev() ? "开发" : "生产"}服务器已启动: ${result.url}`);
8017
+ return serverContext;
8018
+ }
8019
+ /**
8020
+ * 关闭服务器
8021
+ */
8022
+ function shutdownServer() {
8023
+ if (stopping) return stopping;
8024
+ stopping = stopAppServer().finally(() => {
8025
+ stopping = void 0;
8026
+ });
8027
+ return stopping;
8028
+ }
8029
+ async function stopAppServer() {
8030
+ await starting?.catch(() => void 0);
8031
+ if (!serverContext) return;
8032
+ const context = serverContext;
8033
+ const runtime = productionRuntime;
8034
+ serverContext = null;
8035
+ productionRuntime = void 0;
8036
+ const errors = (await Promise.allSettled([context.httpServer ? closeServer(context.httpServer) : Promise.resolve()])).concat(await Promise.allSettled([Promise.resolve().then(() => context.isDev ? closeDevelopmentResources() : void 0), Promise.resolve().then(() => runtime?.close())])).filter((result) => result.status === "rejected");
8037
+ if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Server shutdown failed");
8038
+ logger.success("✅ 服务器已完全关闭");
7580
8039
  }
7581
8040
  //#endregion
8041
+ //#region src/isr/ISRRoutes.ts
8042
+ var ISRRoutes = class {
8043
+ engine;
8044
+ logger;
8045
+ defaultMode;
8046
+ routes;
8047
+ requestLimits;
8048
+ constructor(engine, logger, config) {
8049
+ this.engine = engine;
8050
+ this.logger = logger;
8051
+ this.defaultMode = config.renderMode;
8052
+ this.routes = config.routes || {};
8053
+ this.requestLimits = config.requestLimits;
8054
+ }
8055
+ setup(requestHandler) {
8056
+ const seoLimiter = createRequestLimiter("seo", this.requestLimits?.seo);
8057
+ const opsConfig = getRuntimeOpsConfig(requestHandler) ?? resolveOpsConfig({ server: { requestLimits: this.requestLimits } }, "development");
8058
+ if (opsConfig.health.enabled) requestHandler.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
8059
+ res.json({
8060
+ status: "healthy",
8061
+ version: package_default.version,
8062
+ mode: "plugin-rsc",
8063
+ defaultRenderMode: this.defaultMode,
8064
+ routes: Object.keys(this.routes).length,
8065
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
8066
+ });
8067
+ });
8068
+ requestHandler.get("/sitemap.xml", seoLimiter, async (_req, res) => {
8069
+ try {
8070
+ const candidates = [
8071
+ path.resolve(process.cwd(), "dist/client/sitemap.xml"),
8072
+ path.resolve(process.cwd(), ".isr-hyou/ssg/sitemap.xml"),
8073
+ path.resolve(process.cwd(), "public/sitemap.xml")
8074
+ ];
8075
+ for (const p of candidates) if (fs.existsSync(p)) {
8076
+ res.setHeader("Content-Type", "application/xml; charset=utf-8");
8077
+ res.send(await fs.promises.readFile(p, "utf-8"));
8078
+ return;
8079
+ }
8080
+ await this.engine.generateSeo();
8081
+ for (const p of candidates) if (fs.existsSync(p)) {
8082
+ res.setHeader("Content-Type", "application/xml; charset=utf-8");
8083
+ res.send(await fs.promises.readFile(p, "utf-8"));
8084
+ return;
8085
+ }
8086
+ res.setHeader("Content-Type", "application/xml; charset=utf-8");
8087
+ res.send(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>`);
8088
+ } catch (error) {
8089
+ this.logger.error("生成 sitemap 失败:", error);
8090
+ res.status(500).send("Internal Server Error");
8091
+ }
8092
+ });
8093
+ requestHandler.get("/robots.txt", seoLimiter, async (_req, res) => {
8094
+ try {
8095
+ const candidates = [
8096
+ path.resolve(process.cwd(), "dist/client/robots.txt"),
8097
+ path.resolve(process.cwd(), ".isr-hyou/ssg/robots.txt"),
8098
+ path.resolve(process.cwd(), "public/robots.txt")
8099
+ ];
8100
+ for (const p of candidates) if (fs.existsSync(p)) {
8101
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
8102
+ res.send(await fs.promises.readFile(p, "utf-8"));
8103
+ return;
8104
+ }
8105
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
8106
+ res.send("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n");
8107
+ } catch (error) {
8108
+ this.logger.error("生成 robots.txt 失败:", error);
8109
+ res.status(500).send("Internal Server Error");
8110
+ }
8111
+ });
8112
+ this.logger.debug("ISRRoutes: 已注册 ops 端点 (/health, /sitemap.xml, /robots.txt)");
8113
+ }
8114
+ };
8115
+ //#endregion
7582
8116
  //#region src/middlewares/MiddlewareComposer.ts
7583
8117
  var MiddlewareComposer = class MiddlewareComposer {
7584
8118
  static instance;
@@ -7841,6 +8375,6 @@ async function createISRApp(appOption) {
7841
8375
  };
7842
8376
  }
7843
8377
  //#endregion
7844
- export { isCodeFile as $, createHybridCacheStore as A, spiderSsgRoutes as B, getOpsRequestLimiter as C, invalidatorRunsTotal as D, invalidatorFailuresTotal as E, resolveRenderMode as F, DEFAULT_SCAN_CONFIG as G, DEFAULT_PORT as H, FallbackChain as I, scanRoutes as J, scanComponents as K, InternalStrategies as L, getFallbackChain as M, getRouteFallbackChain as N, promRegistry as O, matchRoutePattern as P, parseRoutes as Q, RenderModes as R, createOpsAuthMiddleware as S, createPrometheusMetricsMiddleware as T, package_default as U, logger$8 as V, resolveFetchHandler as W, parseComponents as X, parseComponentFromFile as Y, parseRouteFromFile as Z, RedisInvalidationBus as _, DEFAULT_SEO_CONFIG as a, CacheCleanup as at, createCoherentCacheStore as b, startAppServer as c, startServer as d, isTestFile as et, createProductionRuntime as f, createIsrCacheMiddleware as g, createIsrCacheHandler as h, createSEOEngine as i, getEnv as it, createMemoryCacheStore as j, recordHttpRequest as k, createABVariantMiddleware as l, generateStaticCspManifest as m, ISREngine as n, isDev as nt, mergeSEOConfig as o, assertDistinctHtmlRouteIdentities as ot, prepareProductionBuild as p, scanProject as q, SEOEngine as r, isProd as rt, shutdownServer as s, resolveImageOptions as st, createISRApp as t, readDirRecursive as tt, closeServer as u, RedisCacheAdapter as v, loadConfig as w, createDevAssetRequestMiddleware as x, MemoryCacheAdapter as y, extractSsgRoutes as z };
8378
+ export { parseComponents as $, invalidatorRunsTotal as A, InternalStrategies as B, createCoherentCacheStore as C, loadConfig as D, getOpsRequestLimiter as E, getFallbackChain as F, DEFAULT_PORT as G, extractSsgRoutes as H, getRouteFallbackChain as I, DEFAULT_SCAN_CONFIG as J, package_default as K, matchRoutePattern as L, recordHttpRequest as M, createHybridCacheStore as N, createPrometheusMetricsMiddleware as O, createMemoryCacheStore as P, parseComponentFromFile as Q, resolveRenderMode as R, MemoryCacheAdapter as S, createOpsAuthMiddleware as T, spiderSsgRoutes as U, RenderModes as V, logger$8 as W, scanProject as X, scanComponents as Y, scanRoutes as Z, requestPinnedImage as _, closeServer as a, isDev as at, RedisInvalidationBus as b, prepareProductionBuild as c, CacheCleanup as ct, SEOEngine as d, resolveImageOptions as dt, parseRouteFromFile as et, createSEOEngine as f, createImagePlugin as g, createImageMiddleware as h, startAppServer as i, readDirRecursive as it, promRegistry as j, invalidatorFailuresTotal as k, generateStaticCspManifest as l, Logger as lt, mergeSEOConfig as m, ISREngine as n, isCodeFile as nt, startServer as o, isProd as ot, DEFAULT_SEO_CONFIG as p, resolveFetchHandler as q, shutdownServer as r, isTestFile as rt, createProductionRuntime as s, getEnv as st, createISRApp as t, parseRoutes as tt, createABVariantMiddleware as u, assertDistinctHtmlRouteIdentities as ut, createIsrCacheHandler as v, createDevAssetRequestMiddleware as w, RedisCacheAdapter as x, createIsrCacheMiddleware as y, FallbackChain as z };
7845
8379
 
7846
- //# sourceMappingURL=createISRApp-DPD3Er4F.js.map
8380
+ //# sourceMappingURL=createISRApp-rD8EUB--.js.map