isr-engine 3.1.2 → 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 (67) 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/config/loadConfig.d.ts.map +1 -1
  5. package/dist/{createCacheInspectorMiddleware-Dhc_2DWt.js → createCacheInspectorMiddleware-Cb_MZhLZ.js} +2 -2
  6. package/dist/{createCacheInspectorMiddleware-Dhc_2DWt.js.map → createCacheInspectorMiddleware-Cb_MZhLZ.js.map} +1 -1
  7. package/dist/{createISRApp-GKE91WpD.js → createISRApp-rD8EUB--.js} +2275 -1749
  8. package/dist/createISRApp-rD8EUB--.js.map +1 -0
  9. package/dist/defaults/runtime/defineSiteHooks.js +2 -2
  10. package/dist/{defineSiteHooks-bHtGQftZ.js → defineSiteHooks-BWaDDJ4B.js} +2 -2
  11. package/dist/{defineSiteHooks-bHtGQftZ.js.map → defineSiteHooks-BWaDDJ4B.js.map} +1 -1
  12. package/dist/{i18n-CnXYAgQE.js → i18n-BFCx28rB.js} +2 -8
  13. package/dist/{i18n-CnXYAgQE.js.map → i18n-BFCx28rB.js.map} +1 -1
  14. package/dist/isr-engine.js +11 -10
  15. package/dist/isr-engine.js.map +1 -1
  16. package/dist/plugin/googleFontAssets.d.ts.map +1 -1
  17. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  18. package/dist/rsc/index.js +2 -2
  19. package/dist/{rsc-BJzB9s8U.js → rsc-Da-Nc0OM.js} +2 -2
  20. package/dist/{rsc-BJzB9s8U.js.map → rsc-Da-Nc0OM.js.map} +1 -1
  21. package/dist/security/staticCspManifest.d.ts.map +1 -1
  22. package/dist/server/productionRuntime.d.ts.map +1 -1
  23. package/dist/server/requestLimits.d.ts.map +1 -1
  24. package/package.json +20 -28
  25. package/dist/Logger-DqBS_3v8.cjs +0 -184
  26. package/dist/Logger-DqBS_3v8.cjs.map +0 -1
  27. package/dist/Logger-bg-doGwZ.js +0 -174
  28. package/dist/Logger-bg-doGwZ.js.map +0 -1
  29. package/dist/abVariantContext-BvAMuhjj.cjs +0 -510
  30. package/dist/abVariantContext-BvAMuhjj.cjs.map +0 -1
  31. package/dist/adapters/observability/index.cjs +0 -152
  32. package/dist/adapters/observability/index.cjs.map +0 -1
  33. package/dist/adapters/runtime/index.cjs +0 -100
  34. package/dist/adapters/runtime/index.cjs.map +0 -1
  35. package/dist/cli/cli.cjs +0 -372
  36. package/dist/cli/cli.cjs.map +0 -1
  37. package/dist/config/defineConfig.cjs +0 -26
  38. package/dist/config/defineConfig.cjs.map +0 -1
  39. package/dist/createCacheInspectorMiddleware-Cq1C9TOB.cjs +0 -112
  40. package/dist/createCacheInspectorMiddleware-Cq1C9TOB.cjs.map +0 -1
  41. package/dist/createISRApp-CMBRb7yC.cjs +0 -8232
  42. package/dist/createISRApp-CMBRb7yC.cjs.map +0 -1
  43. package/dist/createISRApp-GKE91WpD.js.map +0 -1
  44. package/dist/createImagePlugin-BkCgZvI4.js +0 -462
  45. package/dist/createImagePlugin-BkCgZvI4.js.map +0 -1
  46. package/dist/createImagePlugin-D3zO2lFv.cjs +0 -487
  47. package/dist/createImagePlugin-D3zO2lFv.cjs.map +0 -1
  48. package/dist/defaults/auto-observability.cjs +0 -147
  49. package/dist/defaults/auto-observability.cjs.map +0 -1
  50. package/dist/defaults/runtime/defineSiteHooks.cjs +0 -11
  51. package/dist/defineSiteHooks-BuhvW5YB.cjs +0 -770
  52. package/dist/defineSiteHooks-BuhvW5YB.cjs.map +0 -1
  53. package/dist/error500-template-BvZmvKoa.cjs +0 -63
  54. package/dist/error500-template-BvZmvKoa.cjs.map +0 -1
  55. package/dist/i18n-CS5QhOO0.cjs +0 -221
  56. package/dist/i18n-CS5QhOO0.cjs.map +0 -1
  57. package/dist/image/index.cjs +0 -93
  58. package/dist/image/index.cjs.map +0 -1
  59. package/dist/isr-engine.cjs +0 -3332
  60. package/dist/isr-engine.cjs.map +0 -1
  61. package/dist/rolldown-runtime-D7D4PA-g.js +0 -13
  62. package/dist/rolldown-runtime-DakpK96I.cjs +0 -43
  63. package/dist/rsc/browser.cjs +0 -109
  64. package/dist/rsc/browser.cjs.map +0 -1
  65. package/dist/rsc/index.cjs +0 -32
  66. package/dist/rsc-CYT6B6bf.cjs +0 -237
  67. package/dist/rsc-CYT6B6bf.cjs.map +0 -1
@@ -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.2",
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: {
@@ -1525,7 +1682,7 @@ var package_default = {
1525
1682
  "registry": "https://registry.npmjs.org/"
1526
1683
  },
1527
1684
  type: "module",
1528
- main: "./dist/isr-engine.cjs",
1685
+ main: "./dist/isr-engine.js",
1529
1686
  module: "./dist/isr-engine.js",
1530
1687
  types: "./dist/index.d.ts",
1531
1688
  bin: { "isr-engine": "./dist/cli/cli.js" },
@@ -1544,47 +1701,39 @@ var package_default = {
1544
1701
  ],
1545
1702
  exports: {
1546
1703
  ".": {
1547
- "import": "./dist/isr-engine.js",
1548
- "require": "./dist/isr-engine.cjs",
1549
- "types": "./dist/index.d.ts"
1704
+ "types": "./dist/index.d.ts",
1705
+ "default": "./dist/isr-engine.js"
1550
1706
  },
1551
1707
  "./rsc": {
1708
+ "types": "./dist/rsc/index.d.ts",
1552
1709
  "browser": "./dist/rsc/browser.js",
1553
- "import": "./dist/rsc/index.js",
1554
- "require": "./dist/rsc/index.cjs",
1555
- "types": "./dist/rsc/index.d.ts"
1710
+ "default": "./dist/rsc/index.js"
1556
1711
  },
1557
1712
  "./server-entry": { "default": "./src/defaults/runtime/defineServerEntry.tsx" },
1558
1713
  "./client-entry": { "default": "./src/defaults/runtime/defineClientEntry.tsx" },
1559
1714
  "./auto-observability": {
1560
1715
  "types": "./dist/defaults/auto-observability.d.ts",
1561
- "import": "./dist/defaults/auto-observability.js",
1562
- "require": "./dist/defaults/auto-observability.cjs"
1716
+ "default": "./dist/defaults/auto-observability.js"
1563
1717
  },
1564
1718
  "./site-hooks": {
1565
1719
  "types": "./dist/defaults/runtime/defineSiteHooks.d.ts",
1566
- "import": "./dist/defaults/runtime/defineSiteHooks.js",
1567
- "require": "./dist/defaults/runtime/defineSiteHooks.cjs"
1720
+ "default": "./dist/defaults/runtime/defineSiteHooks.js"
1568
1721
  },
1569
1722
  "./config": {
1570
1723
  "types": "./dist/config/defineConfig.d.ts",
1571
- "import": "./dist/config/defineConfig.js",
1572
- "require": "./dist/config/defineConfig.cjs"
1724
+ "default": "./dist/config/defineConfig.js"
1573
1725
  },
1574
1726
  "./adapters/observability": {
1575
- "import": "./dist/adapters/observability/index.js",
1576
- "require": "./dist/adapters/observability/index.cjs",
1577
- "types": "./dist/adapters/observability/index.d.ts"
1727
+ "types": "./dist/adapters/observability/index.d.ts",
1728
+ "default": "./dist/adapters/observability/index.js"
1578
1729
  },
1579
1730
  "./adapters/runtime": {
1580
- "import": "./dist/adapters/runtime/index.js",
1581
- "require": "./dist/adapters/runtime/index.cjs",
1582
- "types": "./dist/adapters/runtime/index.d.ts"
1731
+ "types": "./dist/adapters/runtime/index.d.ts",
1732
+ "default": "./dist/adapters/runtime/index.js"
1583
1733
  },
1584
1734
  "./image": {
1585
- "import": "./dist/image/index.js",
1586
- "require": "./dist/image/index.cjs",
1587
- "types": "./dist/runtime/Image.d.ts"
1735
+ "types": "./dist/runtime/Image.d.ts",
1736
+ "default": "./dist/image/index.js"
1588
1737
  },
1589
1738
  "./runtime": {
1590
1739
  "types": "./dist/runtime/index.d.ts",
@@ -1593,7 +1742,7 @@ var package_default = {
1593
1742
  "./package.json": "./package.json"
1594
1743
  },
1595
1744
  scripts: {
1596
- "build": "vite build && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && chmod +x dist/cli/cli.js dist/cli/cli.cjs",
1745
+ "build": "vite build && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && chmod +x dist/cli/cli.js",
1597
1746
  "watch": "vite build --watch",
1598
1747
  "clean": "rimraf dist",
1599
1748
  "lint": "eslint . --ext .ts,.tsx,.js,.jsx",
@@ -1607,13 +1756,13 @@ var package_default = {
1607
1756
  "bench": "node bench/runner.mjs",
1608
1757
  "check": "pnpm run type-check && pnpm run lint && pnpm run test",
1609
1758
  "audit:security": "pnpm audit --registry=https://registry.npmjs.org --audit-level=low",
1759
+ "version": "pnpm run build",
1610
1760
  "prepublishOnly": "pnpm run audit:security",
1611
1761
  "release": "semantic-release",
1612
1762
  "prepare": "husky",
1613
- "test:package": "node scripts/check-package-exports.mjs",
1614
- "test:package:installed": "node scripts/check-installed-package.mjs",
1615
- "test:workers": "tsc --noEmit -p scripts/fixtures/tsconfig.json && node scripts/check-workers-runtime.mjs",
1616
- "test:release": "node scripts/check-release.mjs"
1763
+ "test:package": "node e2e/package/check.mjs",
1764
+ "test:workers": "tsc -p e2e/workers && node --test e2e/workers/runtime.test.mjs",
1765
+ "test:release": "node --test e2e/release-policy.test.mjs"
1617
1766
  },
1618
1767
  engines: { "node": "24.15.0" },
1619
1768
  packageManager: "pnpm@9.15.9",
@@ -1837,7 +1986,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
1837
1986
  signal: ctrl.signal
1838
1987
  }));
1839
1988
  if (ctrl.signal.aborted) {
1840
- response.body?.cancel(ctrl.signal.reason).catch(() => {});
1989
+ response.body?.cancel(ctrl.signal.reason).catch(() => void 0);
1841
1990
  throw ctrl.signal.reason;
1842
1991
  }
1843
1992
  reader = response.body?.getReader();
@@ -1863,7 +2012,7 @@ async function fetchWithTimeout(handler, url, timeoutMs, batchSignal) {
1863
2012
  const abort = (reason) => {
1864
2013
  rejectAbort(reason);
1865
2014
  ctrl.abort(reason);
1866
- reader?.cancel(reason).catch(() => {});
2015
+ reader?.cancel(reason).catch(() => void 0);
1867
2016
  };
1868
2017
  const onBatchAbort = () => abort(batchSignal.reason);
1869
2018
  batchSignal.addEventListener("abort", onBatchAbort, { once: true });
@@ -2511,20 +2660,6 @@ function createHybridCacheStore(opts) {
2511
2660
  * - 响应时间用 Histogram(带桶),不是平均值 —— 才能正确算 P95/P99
2512
2661
  * - 默认采集 process_*(CPU / RSS / event-loop lag)—— 一行 collectDefaultMetrics
2513
2662
  */
2514
- var PromMetrics_exports = /* @__PURE__ */ __exportAll({
2515
- cacheEntriesGauge: () => cacheEntriesGauge,
2516
- cacheHitsTotal: () => cacheHitsTotal,
2517
- cacheRevalidatingGauge: () => cacheRevalidatingGauge,
2518
- createPrometheusMetricsMiddleware: () => createPrometheusMetricsMiddleware,
2519
- httpRequestDurationSeconds: () => httpRequestDurationSeconds,
2520
- httpRequestsTotal: () => httpRequestsTotal,
2521
- invalidatorFailuresTotal: () => invalidatorFailuresTotal,
2522
- invalidatorRunsTotal: () => invalidatorRunsTotal,
2523
- l2ReadTimeoutsTotal: () => l2ReadTimeoutsTotal,
2524
- normalizeRoute: () => normalizeRoute,
2525
- promRegistry: () => promRegistry,
2526
- recordHttpRequest: () => recordHttpRequest
2527
- });
2528
2663
  var promRegistry = new Registry();
2529
2664
  collectDefaultMetrics({
2530
2665
  register: promRegistry,
@@ -2768,7 +2903,7 @@ async function resolveImportPath(filePath, options) {
2768
2903
  name: "externalize-except-engine",
2769
2904
  setup(build) {
2770
2905
  build.onResolve({ filter: /^[^./]/ }, (args) => {
2771
- if (/^isr-engine(?:\/|$)/.test(args.path)) return null;
2906
+ if (args.kind === "entry-point" || path$1.isAbsolute(args.path) || /^isr-engine(?:\/|$)/.test(args.path)) return null;
2772
2907
  return {
2773
2908
  path: args.path,
2774
2909
  external: true
@@ -2786,13 +2921,6 @@ async function resolveImportPath(filePath, options) {
2786
2921
  }
2787
2922
  //#endregion
2788
2923
  //#region src/server/opsConfig.ts
2789
- var opsConfig_exports = /* @__PURE__ */ __exportAll({
2790
- bindRuntimeOpsConfig: () => bindRuntimeOpsConfig,
2791
- createOpsAuthMiddleware: () => createOpsAuthMiddleware,
2792
- getOpsRequestLimiter: () => getOpsRequestLimiter,
2793
- getRuntimeOpsConfig: () => getRuntimeOpsConfig,
2794
- resolveOpsConfig: () => resolveOpsConfig
2795
- });
2796
2924
  var opsLimiters = /* @__PURE__ */ new WeakMap();
2797
2925
  var runtimeOpsConfigs = /* @__PURE__ */ new WeakMap();
2798
2926
  /** Carry one resolved policy from the Vite plugin into its owning Express runtime. */
@@ -4011,10 +4139,6 @@ var RedisCacheAdapter = class {
4011
4139
  };
4012
4140
  //#endregion
4013
4141
  //#region src/config/resolveRuntimeRedis.ts
4014
- var resolveRuntimeRedis_exports = /* @__PURE__ */ __exportAll({
4015
- hasRuntimeRedisConnection: () => hasRuntimeRedisConnection,
4016
- resolveRuntimeRedisConfig: () => resolveRuntimeRedisConfig
4017
- });
4018
4142
  function nonEmpty(value) {
4019
4143
  const trimmed = value?.trim();
4020
4144
  return trimmed ? trimmed : void 0;
@@ -4066,7 +4190,6 @@ function hasRuntimeRedisConnection(redis) {
4066
4190
  * - runtime.redis.url/host 已设 → revision-validated response cache(Redis 原子协议 + 本机字节缓存)
4067
4191
  * - 未显式配置 Redis → MemoryCacheStore(单层 LRU,行为不变)
4068
4192
  */
4069
- var createAutoCacheStore_exports = /* @__PURE__ */ __exportAll({ createAutoCacheStore: () => createAutoCacheStore });
4070
4193
  var logger$6 = Logger.getInstance();
4071
4194
  function createAutoCacheStore(opts = {}) {
4072
4195
  const redisConfig = resolveRuntimeRedisConfig({
@@ -4100,7 +4223,6 @@ function createAutoCacheStore(opts = {}) {
4100
4223
  }
4101
4224
  //#endregion
4102
4225
  //#region src/cache/RedisInvalidationBus.ts
4103
- var RedisInvalidationBus_exports = /* @__PURE__ */ __exportAll({ RedisInvalidationBus: () => RedisInvalidationBus });
4104
4226
  function normalizeTarget(target) {
4105
4227
  if (!target || typeof target !== "object") return null;
4106
4228
  const candidate = target;
@@ -4341,12 +4463,6 @@ var RedisInvalidationBus = class {
4341
4463
  * 必须在 cache lookup 之前 set,但 cache 层会把 anon 这一条从 captured.headers 里
4342
4464
  * 剥掉再入缓存(见 plugin/isrCacheMiddleware.ts),保证缓存内容 user-agnostic。
4343
4465
  */
4344
- var createServerRequestContext_exports = /* @__PURE__ */ __exportAll({
4345
- ANON_COOKIE_MAX_AGE_SECONDS: () => ANON_COOKIE_MAX_AGE_SECONDS,
4346
- ANON_COOKIE_NAME: () => ANON_COOKIE_NAME,
4347
- applyAnonCookie: () => applyAnonCookie,
4348
- createServerRequestContext: () => createServerRequestContext
4349
- });
4350
4466
  /** anonId cookie 名称 —— engine 全局常量,避免散落字符串。 */
4351
4467
  var ANON_COOKIE_NAME = "anon";
4352
4468
  /** anonId cookie 有效期(秒)。1 年;浏览器侧最大也只能撑到这个量级。 */
@@ -4811,7 +4927,6 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4811
4927
  logger$5.info(`📋 ISR cache: 自动加载 ssr.config.ts 成功(mode=${rules.globalMode}, overrides=${Object.keys(rules.routes).length})`);
4812
4928
  }
4813
4929
  const opsConfig = resolveOpsConfig(resolvedConfig, "development");
4814
- const { bindRuntimeOpsConfig, getOpsRequestLimiter } = await Promise.resolve().then(() => opsConfig_exports);
4815
4930
  const opsLimiter = getOpsRequestLimiter(opsConfig);
4816
4931
  const metricsAuth = createOpsAuthMiddleware("metrics", opsConfig);
4817
4932
  const nextHandler = createIsrCacheHandler(resolvedConfig, withRuntimeCacheOptions(resolvedConfig, {
@@ -4819,7 +4934,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4819
4934
  development: true
4820
4935
  }));
4821
4936
  try {
4822
- const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-Dhc_2DWt.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
4937
+ const inspector = opsConfig.inventory.enabled ? (await import("./createCacheInspectorMiddleware-Cb_MZhLZ.js")).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
4823
4938
  handler = nextHandler;
4824
4939
  server.middlewares.use((req, res, next) => {
4825
4940
  if (handler !== nextHandler) return next();
@@ -4827,8 +4942,7 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
4827
4942
  opsLimiter(req, res, (error) => {
4828
4943
  if (error) return next(error);
4829
4944
  metricsAuth(req, res, () => {
4830
- Promise.resolve().then(() => PromMetrics_exports).then(async ({ promRegistry }) => {
4831
- const body = await promRegistry.metrics();
4945
+ promRegistry.metrics().then((body) => {
4832
4946
  res.setHeader("content-type", promRegistry.contentType);
4833
4947
  res.end(body);
4834
4948
  }).catch((err) => {
@@ -4966,7 +5080,8 @@ async function handleRequest(req, res, next, ctx) {
4966
5080
  logger$5.warn(`ISR cache L2 read 失败 ${cacheKey}: ${err.message}`);
4967
5081
  }
4968
5082
  if (!isActive()) return;
4969
- 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) {
4970
5085
  let seedTask = ctx.seeded.get(cacheKey);
4971
5086
  const leader = !seedTask;
4972
5087
  if (!seedTask) {
@@ -4985,7 +5100,7 @@ async function handleRequest(req, res, next, ctx) {
4985
5100
  if (!isActive()) return seedDenial(res);
4986
5101
  const generation = ctx.state.invalidationGeneration;
4987
5102
  if (generation !== 0) return true;
4988
- 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);
4989
5104
  if (!seed) {
4990
5105
  ctx.seeded.delete(cacheKey);
4991
5106
  return true;
@@ -5644,960 +5759,935 @@ function refreshHeaders(req, ctx) {
5644
5759
  return headers;
5645
5760
  }
5646
5761
  //#endregion
5647
- //#region src/server/safeRedirect.ts
5648
- var REDIRECT_ORIGIN = "https://isr.invalid";
5649
- /** Validate the final Location value against a fixed origin, never an untrusted Host header. */
5650
- function isSafeLocalRedirect(target) {
5651
- if (!target.startsWith("/") || target.startsWith("//")) return false;
5652
- for (const character of target) {
5653
- const code = character.charCodeAt(0);
5654
- 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;
5655
5768
  }
5656
- const pathEnd = target.search(/[?#]/);
5657
- 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) {
5658
5775
  try {
5659
- return new URL(target, REDIRECT_ORIGIN).origin === REDIRECT_ORIGIN;
5776
+ return ipaddr.parse(address).range() === "unicast";
5660
5777
  } catch {
5661
5778
  return false;
5662
5779
  }
5663
5780
  }
5664
- function readRedirectQuery(url) {
5665
- const delimiter = url.indexOf("?");
5666
- 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
+ }
5667
5814
  }
5668
- function redirectLocal(res, status, pathname, query) {
5669
- const target = query === void 0 ? pathname : `${pathname}?${query}`;
5670
- if (!isSafeLocalRedirect(target)) {
5671
- res.status(400).end();
5672
- 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);
5673
5825
  }
5674
- res.redirect(status, target);
5675
5826
  }
5676
- //#endregion
5677
- //#region src/security/staticCspManifest.ts
5678
- var STATIC_CSP_MANIFEST = "static-csp-manifest.json";
5679
- var SCHEMA_VERSION = 3;
5680
- var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
5681
- /** parse5 follows browser tokenization, including raw script text and inert templates. */
5682
- function collectInlineScriptHashes(html) {
5683
- const hashes = /* @__PURE__ */ new Set();
5684
- function visit(node) {
5685
- if ("tagName" in node && node.tagName === "script" && !node.attrs.some((attr) => attr.name === "src")) {
5686
- const text = node.childNodes.map((child) => "value" in child ? child.value : "").join("");
5687
- 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
+ }
5688
5868
  }
5689
- 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);
5690
5875
  }
5691
- visit(parse(html));
5692
- return [...hashes].sort();
5693
- }
5694
- function applyStaticScriptPolicy(policy, hashes) {
5695
- return [...policy.split(";").filter((directive) => {
5696
- const name = directive.trim().split(/\s/, 1)[0].toLowerCase();
5697
- return name !== "script-src" && name !== "script-src-elem";
5698
- }), ["script-src 'self'", ...hashes].join(" ")].join(";");
5699
5876
  }
5700
- async function readHtmlFiles(clientDir, parseScripts = false) {
5701
- const files = [];
5702
- async function walk(dir) {
5703
- for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
5704
- const absolute = path.join(dir, entry.name);
5705
- if (entry.isDirectory()) await walk(absolute);
5706
- else if (entry.isFile() && entry.name.toLowerCase().endsWith(".html")) {
5707
- const bytes = await fs$3.readFile(absolute);
5708
- files.push({
5709
- path: path.relative(clientDir, absolute).split(path.sep).join("/"),
5710
- sha256: sha256(bytes),
5711
- scriptHashes: parseScripts ? collectInlineScriptHashes(bytes.toString("utf8")) : [],
5712
- ...parseScripts ? { generatedAt: Math.floor((await fs$3.stat(absolute)).mtimeMs) } : {}
5713
- });
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 } : {}
5714
5910
  }
5715
- }
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;
5716
5939
  }
5717
- await walk(clientDir);
5718
- return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
5719
5940
  }
5720
- var CLIENT_BUILD_EXTENSIONS = /* @__PURE__ */ new Set([
5721
- ".js",
5722
- ".mjs",
5723
- ".cjs",
5724
- ".css",
5725
- ".wasm",
5726
- ".json",
5727
- ".html",
5728
- ".htm",
5729
- ".svg"
5941
+ var SUPPORTED_FORMATS = /* @__PURE__ */ new Set([
5942
+ "avif",
5943
+ "webp",
5944
+ "jpeg",
5945
+ "jpg",
5946
+ "png"
5730
5947
  ]);
5731
- function isDeploymentPath(relative) {
5732
- if (relative.includes("\\") || relative.split("/").some((segment) => !segment || segment === "." || segment === "..")) return false;
5733
- 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
+ };
5734
5960
  }
5735
- /** Hash executable build artifacts incrementally; do not load media or source maps from client/. */
5736
- async function readDeploymentFiles(distDir) {
5737
- const files = [];
5738
- async function walk(dir) {
5739
- for (const entry of await fs$3.readdir(dir, { withFileTypes: true })) {
5740
- const absolute = path.join(dir, entry.name);
5741
- if (entry.isDirectory()) await walk(absolute);
5742
- else if (entry.isFile()) {
5743
- const relative = path.relative(distDir, absolute).split(path.sep).join("/");
5744
- if (!isDeploymentPath(relative)) continue;
5745
- const digest = createHash("sha256");
5746
- for await (const chunk of createReadStream(absolute)) digest.update(chunk);
5747
- files.push({
5748
- path: relative,
5749
- sha256: digest.digest("hex")
5750
- });
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--;
5751
6051
  }
5752
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
+ }
5753
6090
  }
5754
- for (const directory of [
5755
- "rsc",
5756
- "ssr",
5757
- "client"
5758
- ]) try {
5759
- await walk(path.join(distDir, directory));
5760
- } catch (error) {
5761
- 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;
5762
6105
  }
5763
- return files.sort((left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0);
6106
+ return false;
5764
6107
  }
5765
- function manifestPayload(manifest) {
5766
- return JSON.stringify({
5767
- schemaVersion: manifest.schemaVersion,
5768
- ...manifest.schemaVersion >= 3 ? { ssgRoutes: manifest.ssgRoutes } : {},
5769
- deploymentFiles: manifest.deploymentFiles.map((file) => ({
5770
- path: file.path,
5771
- sha256: file.sha256
5772
- })),
5773
- files: manifest.files.map((file) => ({
5774
- path: file.path,
5775
- sha256: file.sha256,
5776
- scriptHashes: file.scriptHashes,
5777
- ...manifest.schemaVersion < 3 || file.generatedAt === void 0 ? {} : { generatedAt: file.generatedAt }
5778
- }))
5779
- });
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);
5780
6144
  }
5781
- async function createManifest(distDir, ssgRoutes = []) {
5782
- assertDistinctHtmlRouteIdentities(ssgRoutes);
5783
- await fs$3.access(path.join(distDir, "rsc/index.js"));
5784
- const deploymentFiles = await readDeploymentFiles(distDir);
5785
- const files = await readHtmlFiles(path.join(distDir, "client"), true);
5786
- const payload = {
5787
- schemaVersion: SCHEMA_VERSION,
5788
- ssgRoutes: [...new Set(ssgRoutes)].sort(),
5789
- deploymentFiles,
5790
- files
5791
- };
5792
- return {
5793
- ...payload,
5794
- buildId: sha256(manifestPayload(payload))
5795
- };
6145
+ function inside(root, file) {
6146
+ const relative = path.relative(root, file);
6147
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
5796
6148
  }
5797
- /** Called only after every build environment, SSG output and SPA shell are complete. */
5798
- async function generateStaticCspManifest(distDir, options = {}) {
5799
- const manifest = await createManifest(distDir, options.ssgRoutes);
5800
- const destination = path.join(distDir, STATIC_CSP_MANIFEST);
5801
- 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;
5802
6160
  try {
5803
- await fs$3.writeFile(temporary, JSON.stringify(manifest, null, 2) + "\n");
5804
- await fs$3.rename(temporary, destination);
5805
- } finally {
5806
- await fs$3.rm(temporary, { force: true });
6161
+ pathname = decodeURIComponent(src.split(/[?#]/, 1)[0]);
6162
+ } catch {
6163
+ throw new ImageError(400, "invalid source URL");
5807
6164
  }
5808
- return manifest;
5809
- }
5810
- function validateManifest(value) {
5811
- if (!value || typeof value !== "object") throw new Error("Invalid static CSP manifest");
5812
- const manifest = value;
5813
- if (manifest.schemaVersion !== SCHEMA_VERSION && manifest.schemaVersion !== 2) throw new Error("Unsupported static CSP manifest schema");
5814
- 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");
5815
- if (manifest.ssgRoutes) assertDistinctHtmlRouteIdentities(manifest.ssgRoutes);
5816
- const digest = /^[a-f0-9]{64}$/;
5817
- 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");
5818
- let previous = "";
5819
- for (const file of manifest.deploymentFiles) {
5820
- 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");
5821
- previous = file.path;
5822
- }
5823
- if (!manifest.deploymentFiles.some((file) => file.path === "rsc/index.js")) throw new Error("Static CSP manifest is missing the RSC build");
5824
- previous = "";
5825
- for (const file of manifest.files) {
5826
- 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");
5827
- previous = file.path;
5828
- }
5829
- if (sha256(manifestPayload(manifest)) !== manifest.buildId) throw new Error("Static CSP manifest integrity mismatch");
5830
- }
5831
- /** Missing manifests are legacy builds; present but invalid manifests always stop startup. */
5832
- async function loadStaticCspManifest(distDir, options = {}) {
5833
- let serialized;
5834
- try {
5835
- serialized = await fs$3.readFile(path.join(distDir, STATIC_CSP_MANIFEST), "utf8");
5836
- } catch (error) {
5837
- if (error.code !== "ENOENT") throw error;
5838
- const manifest = await createManifest(distDir);
5839
- options.onLegacyBuild?.();
5840
- return indexManifest(manifest, true);
5841
- }
5842
- let manifest;
6165
+ if (pathname.includes("\0") || pathname.includes("\\") || pathname.split("/").includes("..")) throw new ImageError(400, "path traversal blocked");
5843
6166
  try {
5844
- 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
+ }
5845
6199
  } catch (error) {
5846
- 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");
5847
6202
  }
5848
- validateManifest(manifest);
5849
- const deployed = await readDeploymentFiles(distDir);
5850
- if (JSON.stringify(deployed) !== JSON.stringify(manifest.deploymentFiles)) throw new Error("Static CSP manifest does not match the deployment build");
5851
- const actual = await readHtmlFiles(path.join(distDir, "client"));
5852
- 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");
5853
- return indexManifest(manifest, false);
5854
6203
  }
5855
- 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) {
5856
6249
  return {
5857
- legacy,
5858
- ssgRoutes: legacy || manifest.schemaVersion < 3 ? void 0 : Object.freeze([...manifest.ssgRoutes ?? []]),
5859
- buildId: manifest.buildId,
5860
- generatedAt: new Map(legacy || manifest.schemaVersion < 3 ? [] : manifest.files.flatMap((file) => file.generatedAt === void 0 ? [] : [[file.path, file.generatedAt]])),
5861
- 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
+ }
5862
6268
  };
5863
6269
  }
5864
6270
  //#endregion
5865
- //#region src/server/productionRuntime.ts
5866
- /** Shared production application assembly. Listening and process signals belong to callers. */
5867
- function safeOrigin(url) {
5868
- if (!url) return void 0;
5869
- try {
5870
- return new URL(url).origin;
5871
- } catch {
5872
- return;
5873
- }
5874
- }
5875
- /**
5876
- * 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
5877
- * 导出以便单测覆盖(纯函数)
5878
- */
5879
- function extractRoutesForSitemap(config) {
5880
- const routes = config.routes ?? {};
5881
- const out = [];
5882
- for (const path of Object.keys(routes)) {
5883
- if (path.includes("*") || path.includes(":")) continue;
5884
- if (path.startsWith("/__") || path.startsWith("/api/")) continue;
5885
- out.push(path);
5886
- }
5887
- return out;
5888
- }
6271
+ //#region src/engine/seo/SEOEngine.ts
5889
6272
  /**
5890
- * 把 ssr.config.ts 的 telemetry 第三方配置映射到可选 adapter 使用的 env。
5891
- * 这一步必须发生在 import dist/rsc/index.js 之前,因为内置 entry.server 会在模块加载时
5892
- * 初始化 auto hooks。engine 仍不静态 import vendor SDK;这里仅做启动期配置桥接。
6273
+ * SEO 引擎 - 单例模式
6274
+ *
6275
+ * 核心功能:
6276
+ * - Meta 标签生成
6277
+ * - 结构化数据(JSON-LD)生成
6278
+ * - 站点地图生成
6279
+ * - Open Graph / Twitter Cards
5893
6280
  */
5894
- function applyTelemetryIntegrationEnv(runtime) {
5895
- const telemetry = runtime?.telemetry;
5896
- delete process.env.SENTRY_ENVIRONMENT;
5897
- if (!telemetry) {
5898
- process.env.SENTRY_ENABLED = "false";
5899
- delete process.env.DD_SERVICE;
5900
- delete process.env.DD_ENV;
5901
- delete process.env.DD_VERSION;
5902
- delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
5903
- delete process.env.OTEL_SERVICE_NAME;
5904
- 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 };
5905
6291
  }
5906
- const sentryIntegration = telemetry.integrations?.sentry;
5907
- if (sentryIntegration) {
5908
- process.env.SENTRY_ENABLED = sentryIntegration.enabled ? "true" : "false";
5909
- if (sentryIntegration.enabled) {
5910
- if (sentryIntegration.dsn) process.env.SENTRY_DSN = sentryIntegration.dsn;
5911
- if (sentryIntegration.tracesSampleRate !== void 0) process.env.SENTRY_TRACES_SAMPLE_RATE = String(sentryIntegration.tracesSampleRate);
5912
- if (sentryIntegration.environment) process.env.SENTRY_ENVIRONMENT = sentryIntegration.environment;
5913
- } else {
5914
- delete process.env.SENTRY_DSN;
5915
- delete process.env.SENTRY_TRACES_SAMPLE_RATE;
5916
- }
5917
- } else {
5918
- process.env.SENTRY_ENABLED = "false";
5919
- delete process.env.SENTRY_DSN;
5920
- 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;
5921
6296
  }
5922
- delete process.env.DD_SERVICE;
5923
- delete process.env.DD_ENV;
5924
- delete process.env.DD_VERSION;
5925
- delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
5926
- delete process.env.OTEL_SERVICE_NAME;
5927
- for (const exporter of telemetry.exporters) {
5928
- if (exporter.type === "datadog") {
5929
- if (exporter.service) process.env.DD_SERVICE = exporter.service;
5930
- if (telemetry.environment) process.env.DD_ENV = telemetry.environment;
5931
- if (telemetry.release) process.env.DD_VERSION = telemetry.release;
5932
- continue;
5933
- }
5934
- if (exporter.type === "otel") {
5935
- if (exporter.endpoint) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exporter.endpoint;
5936
- if (exporter.serviceName) process.env.OTEL_SERVICE_NAME = exporter.serviceName;
5937
- }
6297
+ /** 重置实例(仅用于测试) */
6298
+ static resetInstance() {
6299
+ SEOEngine.instance = null;
5938
6300
  }
5939
- }
5940
- async function prepareProductionBuild(root = process.cwd()) {
5941
- const rscDistEntry = path.resolve(root, "dist/rsc/index.js");
5942
- const clientDir = path.resolve(root, "dist/client");
5943
- await fs$3.access(rscDistEntry);
5944
- await fs$3.access(clientDir);
5945
- return {
5946
- rscDistEntry,
5947
- clientDir,
5948
- staticCspIndex: await loadStaticCspManifest(path.dirname(clientDir), { onLegacyBuild: () => logger$8.warn("[CSP] 构建缺少 static-csp-manifest.json;已在启动期生成兼容索引,请重新构建以生成清单") })
5949
- };
5950
- }
5951
- async function createProductionRuntime(config, options = {}) {
5952
- const { rscDistEntry, clientDir, staticCspIndex } = options.build ?? await prepareProductionBuild(options.root);
5953
- const ssgRoutes = staticCspIndex.ssgRoutes ?? (Array.isArray(config.ssg?.routes) ? config.ssg.routes : []);
5954
- const ssgFiles = new Map(ssgRoutes.map((route) => [route, routeToFilePath(route)]));
5955
- const ssgAliases = /* @__PURE__ */ new Map();
5956
- const configuredRoutes = Object.keys(config.routes ?? {});
5957
- assertDistinctHtmlRouteIdentities(configuredRoutes, { allowPatterns: true });
5958
- const routeNames = /* @__PURE__ */ new Set([...ssgFiles.keys(), ...configuredRoutes.filter((route) => !isHtmlRoutePattern(route))]);
5959
- assertDistinctHtmlRouteIdentities(routeNames);
5960
- const declaredIdentities = new Set([...routeNames].map((route) => decodeHtmlPathname(route)));
5961
- const explicitRoutes = /* @__PURE__ */ new Map();
5962
- for (const route of routeNames) {
5963
- const target = new URL(route, "http://localhost").pathname;
5964
- explicitRoutes.set(decodeHtmlPathname(route), target);
5965
- 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();
5966
6305
  }
5967
- for (const [canonical, file] of ssgFiles) {
5968
- const logical = decodeHtmlPathname(canonical);
5969
- const target = new URL(canonical, "http://localhost").pathname;
5970
- const base = logical.replace(/\/$/, "") || "/";
5971
- for (const alias of [
5972
- logical,
5973
- base,
5974
- base === "/" ? "/" : base + "/",
5975
- base === "/" ? "/index.html" : base + "/index.html",
5976
- "/" + file
5977
- ]) {
5978
- ssgAliases.set(alias, target);
5979
- ssgAliases.set(alias + "_.rsc", target + "_.rsc");
5980
- }
6306
+ /** 获取当前配置 */
6307
+ getConfig() {
6308
+ return this.config;
5981
6309
  }
5982
- const resolveSsgIdentity = (pathname) => {
5983
- const logical = decodeHtmlPathname(pathname);
5984
- const known = ssgAliases.get(logical);
5985
- return known ? explicitRoutes.get(logical) ?? known : pathname;
5986
- };
5987
- const cleanups = [];
5988
- let closed;
5989
- const close = () => closed ??= (async () => {
5990
- const errors = (await Promise.allSettled(cleanups.reverse().map((cleanup) => Promise.resolve().then(cleanup)))).filter((result) => result.status === "rejected");
5991
- if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Production runtime cleanup failed");
5992
- })();
5993
- try {
5994
- validateRequestLimits(config.server.requestLimits);
5995
- const runtime = config.runtime;
5996
- applyTelemetryIntegrationEnv(runtime);
5997
- const sentryIntegration = runtime?.telemetry ? runtime.telemetry.integrations?.sentry : void 0;
5998
- if (sentryIntegration?.enabled && process.env.SENTRY_DSN) logger$8.info(`🛰️ Sentry integration 来自 ssr.config.ts runtime.telemetry.integrations`);
5999
- else if (sentryIntegration?.enabled) logger$8.warn(`🛰️ Sentry integration 已启用但缺少 SENTRY_DSN,跳过 Sentry adapter`);
6000
- const { fetch: rscHandler } = resolveFetchHandler(await import(
6001
- /* @vite-ignore */
6002
- pathToFileURL(rscDistEntry).href
6003
- ));
6004
- const extraConnectSrc = Array.from(new Set([runtime?.services?.api, runtime?.services?.telemetry].map(safeOrigin).filter((origin) => !!origin)));
6005
- const app = express();
6006
- app.disable("x-powered-by");
6007
- app.set("trust proxy", config.server.trustProxy ?? false);
6008
- app.use(createProductionJsonMiddleware());
6009
- const opsConfig = resolveOpsConfig(config, "production");
6010
- for (const warning of opsConfig.warnings) logger$8.warn(`[Ops] ${warning}`);
6011
- const { createSecurityMiddleware, createCompressionMiddleware, createCspNonceMiddleware } = await Promise.resolve().then(() => middleware_exports);
6012
- app.use(createCspNonceMiddleware());
6013
- app.use(createSecurityMiddleware(false, extraConnectSrc));
6014
- app.use(createCompressionMiddleware());
6015
- if (extraConnectSrc.length > 0) logger$8.info(`🔒 CSP connect-src 加入:${extraConnectSrc.join(", ")}`);
6016
- const { requestContext } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
6017
- const { createServerRequestContext, applyAnonCookie } = await Promise.resolve().then(() => createServerRequestContext_exports);
6018
- const cookieDomain = runtime?.cookieDomain;
6019
- app.use((req, res, next) => {
6020
- const { data, needsAnonCookie } = createServerRequestContext(req);
6021
- if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
6022
- requestContext.run(data, () => next());
6023
- });
6024
- if (runtime?.i18n?.prefixDefault) {
6025
- const { createLocaleRedirectMiddleware } = await Promise.resolve().then(() => LocaleRedirect_exports);
6026
- const { resolveI18nConfig } = await import("./i18n-CnXYAgQE.js").then((n) => n.t);
6027
- const middleware = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(runtime.i18n) });
6028
- if (middleware) {
6029
- app.use(middleware);
6030
- logger$8.info(`🌐 Locale redirect 已启用 (prefixDefault=true)`);
6031
- }
6032
- }
6033
- const hasStaticExps = runtime?.experiments && Object.keys(runtime.experiments).length > 0;
6034
- const hasManifest = !!runtime?.experimentManifest?.endpoint;
6035
- let manifestLoader;
6036
- let exposureQueue;
6037
- if (hasStaticExps || hasManifest) {
6038
- const baseOrigin = runtime?.services?.api;
6039
- const { createABVariantMiddleware } = await Promise.resolve().then(() => ABVariantMiddleware_exports);
6040
- const { resolveManifestLoader } = await Promise.resolve().then(() => ManifestLoader_exports);
6041
- const { resolveExposureQueue } = await Promise.resolve().then(() => ExposureQueue_exports);
6042
- manifestLoader = resolveManifestLoader(runtime?.experimentManifest, runtime?.experiments ?? {}, baseOrigin);
6043
- if (manifestLoader) {
6044
- cleanups.push(() => manifestLoader?.destroy());
6045
- await manifestLoader.init();
6046
- }
6047
- exposureQueue = resolveExposureQueue(runtime?.experimentTracking, baseOrigin);
6048
- cleanups.push(async () => {
6049
- try {
6050
- await exposureQueue?.flush();
6051
- } finally {
6052
- exposureQueue?.destroy();
6053
- }
6054
- });
6055
- app.use(createABVariantMiddleware({
6056
- experiments: runtime?.experiments ?? {},
6057
- manifestLoader,
6058
- exposureQueue
6059
- }));
6060
- const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(runtime?.experiments ?? {});
6061
- logger$8.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
6062
- }
6063
- if (opsConfig.health.enabled) app.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
6064
- res.json({
6065
- status: "healthy",
6066
- version: package_default.version,
6067
- mode: "plugin-rsc-production",
6068
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
6069
- });
6070
- });
6071
- options.setupRoutes?.(app);
6072
- const staticHtmlLimiter = createRequestLimiter("staticHtml", config.server.requestLimits?.staticHtml);
6073
- const seoLimiter = createRequestLimiter("seo", config.server.requestLimits?.seo);
6074
- app.use((req, res, next) => {
6075
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6076
- let pathname;
6077
- try {
6078
- pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
6079
- } catch {
6080
- res.status(400).end();
6081
- return;
6082
- }
6083
- if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
6084
- next();
6085
- });
6086
- app.use(createStaticAssetMiddleware(clientDir));
6087
- app.use("/assets", (_req, res) => {
6088
- res.status(404).set("Cache-Control", "no-store").end();
6089
- });
6090
- const { createImageMiddleware } = await import("./createImagePlugin-BkCgZvI4.js").then((n) => n.r);
6091
- const { resolveImageOptions } = await Promise.resolve().then(() => resolveImageOptions_exports);
6092
- app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
6093
- const { createAutoCacheStore } = await Promise.resolve().then(() => createAutoCacheStore_exports);
6094
- const { RedisInvalidationBus } = await Promise.resolve().then(() => RedisInvalidationBus_exports);
6095
- const { hasRuntimeRedisConnection, resolveRuntimeRedisConfig } = await Promise.resolve().then(() => resolveRuntimeRedis_exports);
6096
- const redisCfg = resolveRuntimeRedisConfig(runtime?.redis);
6097
- const hasRedisConfig = hasRuntimeRedisConnection(runtime?.redis);
6098
- const cacheRoutes = { ...config.routes };
6099
- for (const route of ssgRoutes) {
6100
- const rule = cacheRoutes[route];
6101
- cacheRoutes[route] = typeof rule === "object" ? {
6102
- ...rule,
6103
- mode: "ssg"
6104
- } : "ssg";
6105
- }
6106
- const cache = createIsrCacheHandler({
6107
- ...config,
6108
- routes: cacheRoutes
6109
- }, {
6110
- buildId: process.env.APP_VERSION ?? staticCspIndex.buildId,
6111
- resolveInvalidationPath: resolveSsgIdentity,
6112
- staticSeedAdmission: (req, res) => admitRequest(staticHtmlLimiter, req, res),
6113
- staticSeedInfo: (pathname) => {
6114
- const htmlPath = ssgFiles.get(pathname);
6115
- if (!htmlPath) return;
6116
- const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
6117
- return generatedAt === void 0 || generatedAt > Date.now() ? void 0 : { generatedAt };
6118
- },
6119
- staticSeed: async (pathname, policy) => {
6120
- const htmlPath = ssgFiles.get(pathname);
6121
- if (!htmlPath) return;
6122
- const hashes = staticCspIndex.scriptHashes.get(htmlPath);
6123
- if (!hashes) return;
6124
- const absolute = path.join(clientDir, htmlPath);
6125
- const body = await fs$3.readFile(absolute);
6126
- const generatedAt = staticCspIndex.generatedAt?.get(htmlPath);
6127
- if (generatedAt === void 0) return;
6128
- return {
6129
- body,
6130
- statusCode: 200,
6131
- contentType: "text/html; charset=utf-8",
6132
- headers: {
6133
- "content-type": "text/html; charset=utf-8",
6134
- "content-security-policy": applyStaticScriptPolicy(policy, hashes),
6135
- "cache-control": "no-cache",
6136
- "x-served-by": "ssg-static"
6137
- },
6138
- storedAt: generatedAt,
6139
- expiresAt: 0,
6140
- hardExpiresAt: 0,
6141
- tags: []
6142
- };
6143
- },
6144
- store: createAutoCacheStore({
6145
- responseNamespace: `production:${process.env.ISR_CACHE_NAMESPACE ?? "default"}`,
6146
- redisUrl: redisCfg?.url,
6147
- redisHost: redisCfg?.host,
6148
- redisPort: redisCfg?.port,
6149
- redisPassword: redisCfg?.password,
6150
- redisKeyPrefix: redisCfg?.keyPrefix
6151
- }),
6152
- invalidationBus: hasRedisConfig ? new RedisInvalidationBus({
6153
- url: redisCfg?.url,
6154
- host: redisCfg?.host,
6155
- port: redisCfg?.port,
6156
- password: redisCfg?.password,
6157
- keyPrefix: redisCfg?.keyPrefix,
6158
- channel: redisCfg?.invalidationChannel
6159
- }) : void 0
6160
- });
6161
- cleanups.push(() => cache.destroy());
6162
- if (opsConfig.inventory.enabled) {
6163
- const { createCacheInspectorMiddleware } = await import("./createCacheInspectorMiddleware-Dhc_2DWt.js");
6164
- app.use(createCacheInspectorMiddleware(cache, opsConfig));
6165
- logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
6166
- }
6167
- app.use((req, res, next) => {
6168
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6169
- let logical;
6170
- try {
6171
- logical = decodeHtmlPathname(req.path);
6172
- } catch {
6173
- res.status(400).end();
6174
- return;
6175
- }
6176
- const known = ssgAliases.get(logical);
6177
- if (!known) return next();
6178
- const canonical = explicitRoutes.get(logical) ?? known;
6179
- if (req.path === canonical) return next();
6180
- redirectLocal(res, 308, canonical, readRedirectQuery(req.url));
6181
- });
6182
- app.use(cache);
6183
- const staticHtml = createStaticHtmlMiddlewareWithLimiter(clientDir, staticCspIndex, staticHtmlLimiter);
6184
- app.use((req, res, next) => {
6185
- if (res.getHeader("X-Resolved-Mode") === "ssg" || ssgAliases.has(decodeHtmlPathname(req.path)) && explicitRoutes.has(decodeHtmlPathname(req.path))) return next();
6186
- staticHtml(req, res, next);
6187
- });
6188
- const { promRegistry } = await Promise.resolve().then(() => PromMetrics_exports);
6189
- if (opsConfig.metrics.enabled) app.get("/metrics", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("metrics", opsConfig), async (_req, res) => {
6190
- try {
6191
- res.set("content-type", promRegistry.contentType);
6192
- res.end(await promRegistry.metrics());
6193
- } catch (err) {
6194
- res.status(500).type("text/plain").end(`metrics error: ${String(err)}`);
6195
- }
6196
- });
6197
- const { SEOEngine } = await Promise.resolve().then(() => SEOEngine_exports);
6198
- const { resolveSeoConfig } = await Promise.resolve().then(() => resolveSeoConfig_exports);
6199
- const seoCfg = resolveSeoConfig(config);
6200
- const seo = SEOEngine.getInstance({ baseUrl: seoCfg.baseUrl });
6201
- cleanups.push(() => seo.shutdown());
6202
- await seo.initialize();
6203
- app.get("/sitemap.xml", async (_req, res) => {
6204
- try {
6205
- const xml = await seo.generateSitemap(extractRoutesForSitemap(config));
6206
- res.set("content-type", "application/xml; charset=utf-8");
6207
- res.set("cache-control", "public, max-age=3600");
6208
- res.end(xml);
6209
- } catch (err) {
6210
- res.status(500).type("text/plain").end(`sitemap error: ${String(err)}`);
6211
- }
6212
- });
6213
- app.get("/robots.txt", (_req, res) => {
6214
- res.set("content-type", "text/plain; charset=utf-8");
6215
- res.set("cache-control", "public, max-age=3600");
6216
- res.end(seo.generateRobotsTxt());
6217
- });
6218
- const { renderError500Html } = await import("./error500-template-DhaZzLOB.js");
6219
- const { getTraceId } = await import("./abVariantContext-Ud3aZ1yk.js").then((n) => n.y);
6220
- app.all(/.*/, createProductionRequestHandler(rscHandler, (err, _req, res) => {
6221
- logger$8.error("[Server]", "请求处理异常", err);
6222
- if (!res.headersSent) {
6223
- const traceId = getTraceId();
6224
- res.status(500).type("text/html; charset=utf-8").send(renderError500Html(traceId));
6225
- } else res.destroy();
6226
- }));
6227
- return {
6228
- app,
6229
- close
6230
- };
6231
- } catch (error) {
6232
- await close().catch((cleanupError) => logger$8.error("[Server]", "Production initialization cleanup failed", cleanupError));
6233
- throw error;
6234
- }
6235
- }
6236
- var rawRequestBodies = /* @__PURE__ */ new WeakMap();
6237
- function createProductionJsonMiddleware() {
6238
- return express.json({
6239
- limit: "1mb",
6240
- verify: (req, _res, body) => {
6241
- rawRequestBodies.set(req, Buffer.from(body));
6242
- }
6243
- });
6244
- }
6245
- /** Own cancellation until the outgoing response finishes, not IncomingMessage.close. */
6246
- function createProductionRequestHandler(handler, onError) {
6247
- return async (req, res) => {
6248
- const controller = new AbortController();
6249
- const cleanup = () => {
6250
- req.removeListener("aborted", onAborted);
6251
- res.removeListener("close", onClose);
6252
- res.removeListener("finish", cleanup);
6253
- };
6254
- const onAborted = () => {
6255
- controller.abort(new DOMException("Client disconnected", "AbortError"));
6256
- cleanup();
6257
- };
6258
- const onClose = () => {
6259
- if (!res.writableFinished) onAborted();
6260
- else cleanup();
6261
- };
6262
- req.once("aborted", onAborted);
6263
- res.once("close", onClose);
6264
- res.once("finish", cleanup);
6265
- if (req.aborted || res.destroyed) onAborted();
6266
- try {
6267
- if (controller.signal.aborted) return;
6268
- const response = await handler(nodeToWebRequest(req, controller.signal));
6269
- if (controller.signal.aborted) {
6270
- response.body?.cancel(controller.signal.reason).catch(() => {});
6271
- 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
6272
6330
  }
6273
- await pipeWebResponse(response, res);
6274
- } catch (error) {
6275
- if (!controller.signal.aborted) onError(error, req, res);
6276
- } finally {
6277
- 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
+ });
6278
6349
  }
6279
- };
6280
- }
6281
- function nodeToWebRequest(req, signal) {
6282
- const host = String(req.headers.host || "localhost");
6283
- const transport = req.socket?.encrypted ? "https" : "http";
6284
- const selected = req.protocol?.toLowerCase();
6285
- const url = `${selected === "https" || selected === "http" ? selected : transport}://${host}${req.url}`;
6286
- const headers = new Headers();
6287
- for (const [k, v] of Object.entries(req.headers)) {
6288
- if (v == null) continue;
6289
- if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
6290
- 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;
6291
6355
  }
6292
- const method = req.method || "GET";
6293
- const init = {
6294
- method,
6295
- headers,
6296
- signal
6297
- };
6298
- if (method !== "GET" && method !== "HEAD") {
6299
- init.body = rawRequestBodies.get(req) ?? Readable.toWeb(req);
6300
- 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");
6301
6366
  }
6302
- return new Request(url, init);
6303
- }
6304
- async function pipeWebResponse(response, res) {
6305
- res.status(response.status);
6306
- response.headers.forEach((v, k) => {
6307
- if (k.toLowerCase() === "content-length" || k.toLowerCase() === "set-cookie") return;
6308
- res.setHeader(k, v);
6309
- });
6310
- const cookies = response.headers.getSetCookie();
6311
- if (cookies.length) {
6312
- const existing = res.getHeader?.("set-cookie");
6313
- 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;
6314
6372
  }
6315
- if (!response.body) {
6316
- res.end();
6317
- return;
6373
+ /** 关闭引擎 */
6374
+ async shutdown() {
6375
+ this.clearCache();
6376
+ this.initialized = false;
6377
+ this.logger.debug("✅ SEO 引擎已关闭");
6318
6378
  }
6319
- const nodeReadable = Readable.fromWeb(response.body);
6320
- await new Promise((resolve, reject) => {
6321
- const cleanup = () => {
6322
- res.removeListener?.("close", onClose);
6323
- res.removeListener?.("error", onError);
6324
- };
6325
- const onClose = () => {
6326
- nodeReadable.destroy();
6327
- cleanup();
6328
- resolve();
6329
- };
6330
- const onError = (error) => {
6331
- nodeReadable.destroy();
6332
- cleanup();
6333
- 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()
6334
6392
  };
6335
- res.once("close", onClose);
6336
- res.once("error", onError);
6337
- nodeReadable.once("end", () => {
6338
- cleanup();
6339
- resolve();
6340
- });
6341
- nodeReadable.once("error", (error) => {
6342
- cleanup();
6343
- if (res.headersSent) res.destroy?.(error);
6344
- reject(error);
6345
- });
6346
- if (res.destroyed) onClose();
6347
- else nodeReadable.pipe(res);
6348
- });
6349
- }
6350
- function createStaticHtmlMiddlewareWithLimiter(clientDir, index, limiter) {
6351
- const targets = /* @__PURE__ */ new WeakMap();
6352
- const guarded = express.Router();
6353
- guarded.use(limiter);
6354
- guarded.use((req, res, next) => {
6355
- const target = targets.get(req);
6356
- targets.delete(req);
6357
- if (!target) return next();
6358
- res.setHeader("Content-Security-Policy", applyStaticScriptPolicy(String(res.getHeader("Content-Security-Policy") ?? "default-src 'self'"), target.hashes));
6359
- res.setHeader("Cache-Control", "public, max-age=3600");
6360
- res.setHeader("X-Served-By", "ssg-static");
6361
- res.sendFile(target.htmlPath, {
6362
- root: clientDir,
6363
- maxAge: "1h",
6364
- dotfiles: "ignore"
6365
- }, (error) => {
6366
- if (error) next(error);
6367
- });
6368
- });
6369
- return (req, res, next) => {
6370
- if (req.method !== "GET" && req.method !== "HEAD") return next();
6371
- let pathname;
6372
- try {
6373
- pathname = decodeHtmlPathname(req.path);
6374
- } catch {
6375
- res.status(400).end();
6376
- return;
6377
- }
6378
- const relative = pathname.slice(1);
6379
- const htmlPath = relative.endsWith("/") || !relative ? relative + "index.html" : relative.toLowerCase().endsWith(".html") ? relative : relative + "/index.html";
6380
- const hashes = index.scriptHashes.get(htmlPath);
6381
- if (!hashes) return next();
6382
- targets.set(req, {
6383
- htmlPath,
6384
- hashes
6385
- });
6386
- guarded(req, res, next);
6387
- };
6388
- }
6389
- /** Asset serving must never discover HTML outside the validated build manifest. */
6390
- function normalizeStaticAssetPathname(pathname) {
6391
- return path.posix.normalize(decodeURIComponent(new URL(`http://localhost${pathname}`).pathname).replaceAll("\\", "/"));
6392
- }
6393
- function createStaticAssetMiddleware(clientDir) {
6394
- const assets = express.static(clientDir, {
6395
- index: false,
6396
- redirect: false,
6397
- maxAge: "1h",
6398
- fallthrough: true,
6399
- setHeaders: (res, filePath) => {
6400
- if (filePath.includes(`${path.sep}assets${path.sep}`)) res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
6401
- 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}">`);
6402
6412
  }
6403
- });
6404
- return (req, res, next) => {
6405
- let pathname;
6406
- try {
6407
- pathname = normalizeStaticAssetPathname(req.path);
6408
- } catch {
6409
- res.status(400).end();
6410
- 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}">`);
6411
6419
  }
6412
- if ([".html", ".htm"].includes(path.posix.extname(pathname).toLowerCase())) return next();
6413
- assets(req, res, next);
6414
- };
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);
6415
6506
  }
6416
6507
  //#endregion
6417
- //#region src/server/httpServer.ts
6508
+ //#region src/engine/seo/resolveSeoConfig.ts
6418
6509
  /**
6419
- * HTTP 服务器启动器
6420
- *
6421
- * Node origin 只启动 HTTP/1.1。
6510
+ * SEO 配置解析器 —— 唯一的 baseUrl 解析入口
6422
6511
  *
6423
- * TLS / HTTP/2 / HTTP/3 / Brotli 属于 CDN / Ingress / Nginx / Envoy / ALB 边界。
6424
- * 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,降低本地启动成本
6425
6517
  */
6426
6518
  var logger$4 = Logger.getInstance();
6427
- var DEFAULT_TIMEOUTS = {
6428
- requestTimeoutMs: 6e4,
6429
- headersTimeoutMs: 15e3,
6430
- keepAliveTimeoutMs: 5e3,
6431
- idleTimeoutMs: 3e4,
6432
- shutdownTimeoutMs: 5e3,
6433
- maxRequestsPerSocket: 0
6434
- };
6435
- var LISTEN_BACKLOG = 8192;
6436
- var serverSockets = /* @__PURE__ */ new WeakMap();
6437
- function applyHttpTimeouts(server) {
6438
- server.requestTimeout = DEFAULT_TIMEOUTS.requestTimeoutMs;
6439
- server.headersTimeout = DEFAULT_TIMEOUTS.headersTimeoutMs;
6440
- server.keepAliveTimeout = DEFAULT_TIMEOUTS.keepAliveTimeoutMs;
6441
- server.maxRequestsPerSocket = DEFAULT_TIMEOUTS.maxRequestsPerSocket;
6442
- server.setTimeout(DEFAULT_TIMEOUTS.idleTimeoutMs);
6443
- server.__shutdownTimeoutMs = DEFAULT_TIMEOUTS.shutdownTimeoutMs;
6444
- }
6445
- function getServerAddress(server) {
6446
- const addr = server.address();
6447
- if (addr && typeof addr === "object") {
6448
- const info = addr;
6449
- return {
6450
- address: info.address,
6451
- port: info.port
6452
- };
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";
6453
6535
  }
6536
+ if (!baseUrl) logger$4.warn("⚠️ SEO baseUrl 未配置:sitemap 端点将报错。请在 ssr.config.ts 设置 runtime.site。");
6537
+ else logger$4.info(`🎯 SEO baseUrl=${baseUrl}(来源:${source})`);
6454
6538
  return {
6455
- address: "<unknown>",
6456
- port: 0
6539
+ baseUrl,
6540
+ baseUrlSource: source
6457
6541
  };
6458
6542
  }
6459
- function formatHostForUrl(address) {
6460
- if (address === "::" || address === "0.0.0.0" || address === "") return "localhost";
6461
- if (address.includes(":") && !address.startsWith("[")) return `[${address}]`;
6462
- return address;
6463
- }
6464
- /** 启动 HTTP/1.1 服务器 */
6465
- function startHttp1Server(app, config) {
6466
- const maxAttempts = config.strictPort === false ? 20 : 1;
6467
- const startPort = config.port;
6468
- return new Promise((resolve, reject) => {
6469
- const server = createServer$1(app);
6470
- applyHttpTimeouts(server);
6471
- const sockets = /* @__PURE__ */ new Set();
6472
- serverSockets.set(server, sockets);
6473
- server.on("connection", (socket) => {
6474
- sockets.add(socket);
6475
- socket.once("close", () => sockets.delete(socket));
6476
- });
6477
- let attempt = 0;
6478
- const listen = (port) => {
6479
- server.listen({
6480
- port,
6481
- host: config.host,
6482
- 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);
6483
6593
  });
6484
- };
6485
- server.on("listening", () => {
6486
- const { address, port } = getServerAddress(server);
6487
- const url = `http://${formatHostForUrl(address)}:${port || config.port}`;
6488
- logger$4.info(`HTTP/1.1 服务器已启动: ${url}`);
6489
- resolve({
6490
- server,
6491
- 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)
6492
6613
  });
6493
- });
6494
- server.on("error", (error) => {
6495
- if (error.code === "EADDRINUSE" && attempt + 1 < maxAttempts) {
6496
- attempt += 1;
6497
- const nextPort = startPort + attempt;
6498
- logger$4.warn(`端口 ${startPort + attempt - 1} 已占用,尝试 ${nextPort}`);
6499
- listen(nextPort);
6500
- return;
6501
- }
6502
- reject(error);
6503
- });
6504
- listen(startPort);
6505
- });
6506
- }
6507
- /** 启动 Node origin 服务器 */
6508
- function startServer(app, config) {
6509
- return startHttp1Server(app, config);
6510
- }
6511
- var closingServers = /* @__PURE__ */ new WeakMap();
6512
- /** Stop accepting requests, drain active responses, then force overdue connections closed. */
6513
- function closeServer(server) {
6514
- const existing = closingServers.get(server);
6515
- if (existing) return existing;
6516
- const closing = new Promise((resolve, reject) => {
6517
- const shutdownTimeoutMs = server.__shutdownTimeoutMs ?? DEFAULT_TIMEOUTS.shutdownTimeoutMs;
6518
- const timeout = setTimeout(() => {
6519
- try {
6520
- server.closeAllConnections();
6521
- for (const socket of serverSockets.get(server) ?? []) socket.destroy();
6522
- } catch (error) {
6523
- 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;
6524
6633
  }
6525
- }, shutdownTimeoutMs);
6526
- try {
6527
- server.close((error) => {
6528
- clearTimeout(timeout);
6529
- if (error) reject(error);
6530
- else resolve();
6531
- });
6532
- server.closeIdleConnections();
6533
- } catch (error) {
6534
- clearTimeout(timeout);
6535
- 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;
6536
6667
  }
6537
- });
6538
- closingServers.set(server, closing);
6539
- return closing;
6668
+ };
6540
6669
  }
6541
- //#endregion
6542
- //#region src/middlewares/ABVariantMiddleware.ts
6543
- var ABVariantMiddleware_exports = /* @__PURE__ */ __exportAll({ createABVariantMiddleware: () => createABVariantMiddleware });
6544
- /** 总桶数;10000 给到 0.01% 权重精度,业界通行做法 */
6545
- var BUCKET_SPACE = 1e4;
6546
6670
  /**
6547
- * 按权重 + bucket 索引选 variant。
6548
- * 把 weights 累加得到分段边界,bucket 落在哪段就选哪个 variant。
6549
- * 同一 (variants, weights, bucket) → 永远同一结果(确定性)。
6671
+ * 解析配置,决定是否创建 queue 实例。配置缺失 / disabled / 无 endpoint 返回 null。
6672
+ * services.api 或 services.telemetry origin 用于把相对路径补全为绝对 URL。
6550
6673
  */
6551
- function pickByBucket(variants, weights, bucket) {
6552
- const w = weights && weights.length === variants.length ? weights : variants.map(() => 1);
6553
- const total = w.reduce((a, b) => a + b, 0);
6554
- let cursor = 0;
6555
- for (let i = 0; i < variants.length; i++) {
6556
- cursor += w[i] / total * BUCKET_SPACE;
6557
- if (bucket < cursor) return variants[i];
6558
- }
6559
- return variants[variants.length - 1];
6560
- }
6561
- /** 默认分桶:fnv1a(anonId + ':' + experimentKey) % BUCKET_SPACE。稳定、无外部依赖 */
6562
- function defaultAssigner(anonId, name, exp) {
6563
- const bucket = fnv1a32(`${anonId}:${name}`) % BUCKET_SPACE;
6564
- return pickByBucket(exp.variants, exp.weights, bucket);
6565
- }
6566
- function stripQuery(url) {
6567
- const i = url.indexOf("?");
6568
- return i === -1 ? url : url.slice(0, i);
6569
- }
6570
- function createABVariantMiddleware(options) {
6571
- const { experiments: staticExperiments, assigner = defaultAssigner } = options;
6572
- const { manifestLoader, exposureQueue } = options;
6573
- return function abMiddleware(req, _res, next) {
6574
- const ctx = getRequestContext();
6575
- if (!ctx) {
6576
- next();
6577
- 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;
6578
6682
  }
6579
- const effectiveExperiments = manifestLoader ? manifestLoader.getCurrent() : staticExperiments;
6580
- const anonId = ctx.anonId;
6581
- const assignments = {};
6582
- for (const [name, exp] of Object.entries(effectiveExperiments)) assignments[name] = assigner(anonId, name, exp);
6583
- ctx.experiments = {
6584
- ...ctx.experiments ?? {},
6585
- ...assignments
6586
- };
6587
- ctx.flags = {
6588
- ...ctx.flags ?? {},
6589
- ...assignments
6590
- };
6591
- if (exposureQueue && Object.keys(assignments).length > 0) exposureQueue.push({
6592
- anonId,
6593
- userId: ctx.userId ?? null,
6594
- requestId: ctx.requestId,
6595
- experiments: assignments,
6596
- path: stripQuery(req.url ?? "/"),
6597
- ts: Date.now()
6598
- });
6599
- next();
6600
- };
6683
+ endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6684
+ }
6685
+ return createExposureQueue({
6686
+ endpoint,
6687
+ batchSize: config.batchSize,
6688
+ flushIntervalMs: config.flushIntervalMs,
6689
+ sampleRate: config.sampleRate
6690
+ });
6601
6691
  }
6602
6692
  //#endregion
6603
6693
  //#region src/experiments/ManifestLoader.ts
@@ -6617,12 +6707,7 @@ function createABVariantMiddleware(options) {
6617
6707
  * - 'paused' / 'killed' → 强制回第一个 variant(control)
6618
6708
  * - 'concluded' → 同上 + admin-platform 高亮
6619
6709
  */
6620
- var ManifestLoader_exports = /* @__PURE__ */ __exportAll({
6621
- createManifestLoader: () => createManifestLoader,
6622
- normalizeManifestExperiments: () => normalizeManifestExperiments,
6623
- resolveManifestLoader: () => resolveManifestLoader
6624
- });
6625
- var logger$3 = Logger.getInstance();
6710
+ var logger$2 = Logger.getInstance();
6626
6711
  /**
6627
6712
  * 把 manifest 里的实验定义归一化为 engine 内部用的 RuntimeExperimentConfig。
6628
6713
  * killed / paused / concluded 状态的实验:**weights 强制变成 [100, 0, 0, ...]**,
@@ -6681,7 +6766,7 @@ function createManifestLoader(options) {
6681
6766
  return;
6682
6767
  }
6683
6768
  state.current = normalizeManifestExperiments(json.experiments);
6684
- 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}`);
6685
6770
  } catch (err) {
6686
6771
  applyFallback(err instanceof Error ? err.message : String(err));
6687
6772
  }
@@ -6689,226 +6774,162 @@ function createManifestLoader(options) {
6689
6774
  function applyFallback(reason) {
6690
6775
  switch (fallbackOnError) {
6691
6776
  case "cache":
6692
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),沿用 cache 快照`);
6777
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),沿用 cache 快照`);
6693
6778
  break;
6694
6779
  case "static":
6695
6780
  state.current = { ...options.staticExperiments ?? {} };
6696
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),回退到 static 配置`);
6781
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),回退到 static 配置`);
6697
6782
  break;
6698
6783
  case "empty":
6699
6784
  state.current = {};
6700
- logger$3.warn(`[ManifestLoader] 拉取失败(${reason}),关闭所有实验`);
6785
+ logger$2.warn(`[ManifestLoader] 拉取失败(${reason}),关闭所有实验`);
6701
6786
  break;
6702
6787
  }
6703
6788
  }
6704
6789
  function schedulePoll() {
6705
- if (state.destroyed) return;
6706
- state.pollTimer = setTimeout(() => {
6707
- state.pollTimer = null;
6708
- pullOnce().finally(() => schedulePoll());
6709
- }, refreshIntervalMs);
6710
- state.pollTimer.unref?.();
6711
- }
6712
- return {
6713
- /** 立即拉一次(启动期同步等待 + 后续异步轮询) */
6714
- async init() {
6715
- await pullOnce();
6716
- schedulePoll();
6717
- },
6718
- /**
6719
- * 读取当前快照 —— 同步返回 ABVariantMiddleware 用。
6720
- * 永远返回非 null(最差是 empty);调用方不用 null 检查。
6721
- */
6722
- getCurrent() {
6723
- return state.current;
6724
- },
6725
- /** 销毁 loader(清定时器) */
6726
- destroy() {
6727
- state.destroyed = true;
6728
- if (state.pollTimer) {
6729
- clearTimeout(state.pollTimer);
6730
- state.pollTimer = null;
6731
- }
6732
- }
6733
- };
6734
- }
6735
- /**
6736
- * 解析配置,决定是否创建 loader 实例。配置缺失 / 无 endpoint 返回 null。
6737
- */
6738
- function resolveManifestLoader(config, staticExperiments, baseOrigin) {
6739
- if (!config?.endpoint) return null;
6740
- let endpoint = config.endpoint;
6741
- if (endpoint.startsWith("/")) {
6742
- if (!baseOrigin) {
6743
- logger$3.warn("[ManifestLoader] endpoint 是相对路径但没有 baseOrigin,跳过 manifest 拉取");
6744
- return null;
6745
- }
6746
- endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6747
- }
6748
- return createManifestLoader({
6749
- endpoint,
6750
- refreshIntervalMs: config.refreshIntervalMs,
6751
- fallbackOnError: config.fallbackOnError,
6752
- authHeader: config.authHeader,
6753
- staticExperiments
6754
- });
6755
- }
6756
- //#endregion
6757
- //#region src/experiments/ExposureQueue.ts
6758
- /**
6759
- * ExposureQueue —— 曝光事件批量上报队列
6760
- *
6761
- * 设计取舍:
6762
- * - **fire-and-forget**:业务渲染路径 push() 完立刻返回,不等任何 IO
6763
- * - **批量 flush**:减小 admin-server QPS(默认 100 条 / 1s 攒一批)
6764
- * - **不去重**:写入全量;分析期 COUNT(DISTINCT anon_id) 解(业界惯例,
6765
- * GrowthBook / Statsig / LinkedIn LiX 同款)
6766
- * - **不阻塞退出**:进程收到 SIGTERM 时同步 flush 一次最后批次再退出
6767
- * - **失败丢弃 + 警告日志**:业务不应该感知 exposure 失败
6768
- * - **采样**:sampleRate < 1 时随机丢弃,高 QPS 场景控制 admin-server 负载
6769
- *
6770
- * 不在本模块的事:
6771
- * - HTTP retry / backoff 走 fetch + 短暂 retry,admin-server 全挂时丢这一批
6772
- * - dedupe(写期不做)
6773
- * - schema 校验(admin-server 那边做)
6774
- */
6775
- var ExposureQueue_exports = /* @__PURE__ */ __exportAll({
6776
- createExposureQueue: () => createExposureQueue,
6777
- resolveExposureQueue: () => resolveExposureQueue
6778
- });
6779
- var logger$2 = Logger.getInstance();
6780
- /**
6781
- * 创建上报队列。同一进程整个 lifecycle 只创建一个;engine 入口保管 instance。
6782
- * 返回 push() / flush() / destroy() 三个方法。
6783
- */
6784
- function createExposureQueue(options) {
6785
- const batchSize = options.batchSize ?? 100;
6786
- const flushIntervalMs = options.flushIntervalMs ?? 1e3;
6787
- const sampleRate = options.sampleRate ?? 1;
6788
- const maxQueueSize = options.maxQueueSize ?? batchSize * 2;
6789
- const fetcher = options.fetcher ?? globalThis.fetch;
6790
- const endpoint = options.endpoint;
6791
- const state = {
6792
- events: [],
6793
- flushTimer: null,
6794
- destroyed: false
6795
- };
6796
- const shutdownHook = () => {
6797
- if (state.events.length > 0) flushNow().catch(() => {});
6798
- };
6799
- if (typeof process !== "undefined" && typeof process.on === "function") {
6800
- process.on("SIGTERM", shutdownHook);
6801
- process.on("SIGINT", shutdownHook);
6802
- process.on("beforeExit", shutdownHook);
6803
- }
6804
- function scheduleFlush() {
6805
- if (state.flushTimer || state.destroyed) return;
6806
- state.flushTimer = setTimeout(() => {
6807
- state.flushTimer = null;
6808
- flushNow().catch((err) => {
6809
- logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
6810
- });
6811
- }, flushIntervalMs);
6812
- state.flushTimer.unref?.();
6813
- }
6814
- const inFlight = /* @__PURE__ */ new Set();
6815
- function flushNow() {
6816
- const delivery = sendBatch();
6817
- inFlight.add(delivery);
6818
- delivery.finally(() => inFlight.delete(delivery));
6819
- return delivery;
6820
- }
6821
- async function sendBatch() {
6822
- if (state.events.length === 0) return;
6823
- const batch = state.events.splice(0, batchSize);
6824
- try {
6825
- const res = await fetcher(endpoint, {
6826
- method: "POST",
6827
- headers: { "content-type": "application/json" },
6828
- body: JSON.stringify({ events: batch }),
6829
- signal: AbortSignal.timeout(3e3)
6830
- });
6831
- if (!res.ok) logger$2.warn(`[ExposureQueue] admin-server 返回 ${res.status},丢弃 ${batch.length} 条曝光(不重试,业务无影响)`);
6832
- } catch (err) {
6833
- logger$2.warn(`[ExposureQueue] 上报失败,丢弃 ${batch.length} 条曝光(${err instanceof Error ? err.message : String(err)})`);
6834
- }
6835
- 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?.();
6836
6796
  }
6837
6797
  return {
6798
+ /** 立即拉一次(启动期同步等待 + 后续异步轮询) */
6799
+ async init() {
6800
+ await pullOnce();
6801
+ schedulePoll();
6802
+ },
6838
6803
  /**
6839
- * 入队一个曝光事件。完全同步、永远不抛错。
6840
- * - 队列满(maxQueueSize)→ 丢最早事件(FIFO)+ critical log
6841
- * - 采样未命中 → 直接丢弃
6804
+ * 读取当前快照 —— 同步返回 ABVariantMiddleware 用。
6805
+ * 永远返回非 null(最差是 empty);调用方不用 null 检查。
6842
6806
  */
6843
- push(event) {
6844
- if (state.destroyed) return;
6845
- if (sampleRate < 1 && Math.random() >= sampleRate) return;
6846
- if (state.events.length >= maxQueueSize) {
6847
- const dropped = state.events.shift();
6848
- logger$2.warn(`[ExposureQueue] 队列满(${maxQueueSize})丢弃最早事件,admin-server 可能下线`);
6849
- if (!dropped) return;
6850
- }
6851
- state.events.push(event);
6852
- if (state.events.length >= batchSize) {
6853
- if (state.flushTimer) {
6854
- clearTimeout(state.flushTimer);
6855
- state.flushTimer = null;
6856
- }
6857
- flushNow().catch((err) => {
6858
- logger$2.warn("[ExposureQueue] flush 异常(已吞):", err);
6859
- });
6860
- } else scheduleFlush();
6861
- },
6862
- /** 立即 flush 当前批次(测试 / 优雅退出用) */
6863
- async flush() {
6864
- do {
6865
- await flushNow();
6866
- await Promise.all([...inFlight]);
6867
- } while (state.events.length > 0 || inFlight.size > 0);
6807
+ getCurrent() {
6808
+ return state.current;
6868
6809
  },
6869
- /** 销毁队列(清定时器、丢残留);engine 关闭时调 */
6810
+ /** 销毁 loader(清定时器) */
6870
6811
  destroy() {
6871
6812
  state.destroyed = true;
6872
- process.removeListener("SIGTERM", shutdownHook);
6873
- process.removeListener("SIGINT", shutdownHook);
6874
- process.removeListener("beforeExit", shutdownHook);
6875
- if (state.flushTimer) {
6876
- clearTimeout(state.flushTimer);
6877
- state.flushTimer = null;
6813
+ if (state.pollTimer) {
6814
+ clearTimeout(state.pollTimer);
6815
+ state.pollTimer = null;
6878
6816
  }
6879
- state.events.length = 0;
6880
- },
6881
- /** 测试用:当前队列长度 */
6882
- get size() {
6883
- return state.events.length;
6884
6817
  }
6885
6818
  };
6886
6819
  }
6887
6820
  /**
6888
- * 解析配置,决定是否创建 queue 实例。配置缺失 / disabled / 无 endpoint 返回 null。
6889
- * services.api 或 services.telemetry origin 用于把相对路径补全为绝对 URL。
6821
+ * 解析配置,决定是否创建 loader 实例。配置缺失 / 无 endpoint 返回 null。
6890
6822
  */
6891
- function resolveExposureQueue(config, baseOrigin) {
6823
+ function resolveManifestLoader(config, staticExperiments, baseOrigin) {
6892
6824
  if (!config?.endpoint) return null;
6893
- if (config.enabled === false) return null;
6894
6825
  let endpoint = config.endpoint;
6895
6826
  if (endpoint.startsWith("/")) {
6896
6827
  if (!baseOrigin) {
6897
- logger$2.warn("[ExposureQueue] endpoint 是相对路径但没有 baseOrigin,跳过 exposure 上报");
6828
+ logger$2.warn("[ManifestLoader] endpoint 是相对路径但没有 baseOrigin,跳过 manifest 拉取");
6898
6829
  return null;
6899
6830
  }
6900
6831
  endpoint = baseOrigin.replace(/\/$/, "") + endpoint;
6901
6832
  }
6902
- return createExposureQueue({
6833
+ return createManifestLoader({
6903
6834
  endpoint,
6904
- batchSize: config.batchSize,
6905
- flushIntervalMs: config.flushIntervalMs,
6906
- sampleRate: config.sampleRate
6835
+ refreshIntervalMs: config.refreshIntervalMs,
6836
+ fallbackOnError: config.fallbackOnError,
6837
+ authHeader: config.authHeader,
6838
+ staticExperiments
6907
6839
  });
6908
6840
  }
6909
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
6910
6932
  //#region src/middlewares/LocaleRedirect.ts
6911
- var LocaleRedirect_exports = /* @__PURE__ */ __exportAll({ createLocaleRedirectMiddleware: () => createLocaleRedirectMiddleware });
6912
6933
  var FRAMEWORK_SKIP_PREFIXES = [
6913
6934
  "/api/",
6914
6935
  "/_rsc",
@@ -6958,635 +6979,1140 @@ function createLocaleRedirectMiddleware(options) {
6958
6979
  return;
6959
6980
  }
6960
6981
  }
6961
- const cookieLocale = readCookieLocale(typeof req.headers["cookie"] === "string" ? req.headers["cookie"] : "");
6962
- const target = (cookieLocale && localePrefixes.has(cookieLocale) ? cookieLocale : null) || negotiateLocale(typeof req.headers["accept-language"] === "string" ? req.headers["accept-language"] : null, i18n);
6963
- const prefix = localePrefixes.get(target);
6964
- if (!prefix) {
6965
- res.status(400).end();
6966
- return;
6967
- }
6968
- 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))
6969
7125
  };
6970
7126
  }
6971
- function readCookieLocale(header) {
6972
- if (!header) return null;
6973
- for (const part of header.split(";")) {
6974
- const trimmed = part.trim();
6975
- const eq = trimmed.indexOf("=");
6976
- if (eq <= 0) continue;
6977
- if (trimmed.slice(0, eq).trim() === "locale") try {
6978
- return decodeURIComponent(trimmed.slice(eq + 1).trim());
6979
- } catch {
6980
- return trimmed.slice(eq + 1).trim();
6981
- }
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 });
6982
7137
  }
6983
- return null;
7138
+ return manifest;
6984
7139
  }
6985
- //#endregion
6986
- //#region src/server/manager.ts
6987
- /**
6988
- * 服务器管理器
6989
- * 整合 Vite 开发服务器、HTTP 服务器和中间件
6990
- * ISREngine 唯一需要关心的服务器入口
6991
- */
6992
- var logger$1 = Logger.getInstance();
6993
- /** 服务器上下文 */
6994
- var serverContext = null;
6995
- var productionRuntime;
6996
- var starting;
6997
- var stopping;
6998
- var developmentCleanups = [];
6999
- async function closeDevelopmentResources() {
7000
- const owned = developmentCleanups.splice(0).reverse();
7001
- const failures = (await Promise.allSettled(owned.map((close) => Promise.resolve().then(close)))).filter((result) => result.status === "rejected");
7002
- 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");
7003
7161
  }
7004
- /** Retain the optional public ServerContext manifest for programmatic consumers. */
7005
- function loadProdManifest() {
7006
- for (const relativePath of [
7007
- "dist/.vite/manifest.json",
7008
- "dist/client/.vite/manifest.json",
7009
- "dist/manifest.json"
7010
- ]) {
7011
- const absolutePath = path.resolve(process.cwd(), relativePath);
7012
- if (!fs.existsSync(absolutePath)) continue;
7013
- try {
7014
- return JSON.parse(fs.readFileSync(absolutePath, "utf8"));
7015
- } catch {
7016
- logger$1.warn(`Manifest 解析失败: ${relativePath}`);
7017
- }
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);
7018
7172
  }
7019
- 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);
7020
7185
  }
7021
- /**
7022
- * 初始化开发模式服务器上下文
7023
- */
7024
- async function initDevContext(requestHandler, config) {
7025
- logger$1.info("🔧 初始化开发模式服务器...");
7026
- const viteDevMiddleware = await createViteDevServer();
7027
- bindRuntimeOpsConfig(requestHandler, getRuntimeOpsConfig(viteDevMiddleware) ?? resolveOpsConfig(config, "development"));
7186
+ function indexManifest(manifest, legacy) {
7028
7187
  return {
7029
- requestHandler,
7030
- viteDevMiddleware,
7031
- isDev: true,
7032
- manifest: null,
7033
- 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])]))
7034
7193
  };
7035
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
+ }
7036
7206
  /**
7037
- * 初始化服务器上下文(内部使用)
7207
+ * 从 ssr.config 路由表里提取要写入 sitemap 的路由(剔除通配符 / 内部 / API)
7208
+ * 导出以便单测覆盖(纯函数)
7038
7209
  */
7039
- async function initServerContext(config) {
7040
- if (serverContext) return serverContext;
7041
- serverContext = await initDevContext(express(), config);
7042
- developmentCleanups.push(closeViteDevServer);
7043
- applyBaseMiddlewaresWithOptions(serverContext);
7044
- const cookieDomain = config?.runtime?.cookieDomain;
7045
- serverContext.requestHandler.use((req, res, next) => {
7046
- const { data, needsAnonCookie } = createServerRequestContext(req);
7047
- if (needsAnonCookie) applyAnonCookie(res, data.anonId, cookieDomain);
7048
- requestContext.run(data, () => next());
7049
- });
7050
- if (config?.runtime?.i18n?.prefixDefault) {
7051
- const localeRedirect = createLocaleRedirectMiddleware({ i18n: resolveI18nConfig(config.runtime.i18n) });
7052
- 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);
7053
7217
  }
7054
- const hasStaticExps = config?.runtime?.experiments && Object.keys(config.runtime.experiments).length > 0;
7055
- const hasManifest = !!config?.runtime?.experimentManifest?.endpoint;
7056
- if (hasStaticExps || hasManifest) {
7057
- const baseOrigin = config?.runtime?.services?.api;
7058
- const manifestLoader = resolveManifestLoader(config?.runtime?.experimentManifest, config?.runtime?.experiments ?? {}, baseOrigin);
7059
- if (manifestLoader) {
7060
- developmentCleanups.push(() => manifestLoader.destroy());
7061
- 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;
7062
7268
  }
7063
- const exposureQueue = resolveExposureQueue(config?.runtime?.experimentTracking, baseOrigin);
7064
- if (exposureQueue) developmentCleanups.push(async () => {
7065
- try {
7066
- await exposureQueue.flush();
7067
- } finally {
7068
- exposureQueue.destroy();
7069
- }
7070
- });
7071
- serverContext.requestHandler.use(createABVariantMiddleware({
7072
- experiments: config?.runtime?.experiments ?? {},
7073
- manifestLoader,
7074
- exposureQueue
7075
- }));
7076
- const expKeys = manifestLoader ? Object.keys(manifestLoader.getCurrent()) : Object.keys(config?.runtime?.experiments ?? {});
7077
- logger$1.info(`🧪 A/B testing 已启用:${expKeys.join(", ") || "(empty)"}${manifestLoader ? " [manifest]" : " [static]"}${exposureQueue ? " + exposure tracking" : ""}`);
7078
7269
  }
7079
- logger$1.info(`✅ 服务器上下文已初始化 (${isDev() ? "开发" : "生产"}模式)`);
7080
- return serverContext;
7081
7270
  }
7082
- /**
7083
- * 启动服务器
7084
- * @returns 服务器上下文,包含 loadRenderFunction 等方法
7085
- */
7086
- function startAppServer(config, setupRoutes) {
7087
- if (stopping) return stopping.then(() => startAppServer(config, setupRoutes));
7088
- if (starting) return starting;
7089
- if (serverContext?.httpServer) return Promise.resolve(serverContext);
7090
- starting = startAppServerInternal(config, setupRoutes).finally(() => {
7091
- starting = void 0;
7092
- });
7093
- 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
+ };
7094
7281
  }
7095
- async function startAppServerInternal(config, setupRoutes) {
7096
- try {
7097
- return await createAndListenAppServer(config, setupRoutes);
7098
- } catch (error) {
7099
- if (serverContext?.isDev || developmentCleanups.length) {
7100
- const context = serverContext;
7101
- serverContext = null;
7102
- const rollback = await Promise.allSettled([context?.httpServer ? closeServer(context.httpServer) : Promise.resolve()]);
7103
- rollback.push(...await Promise.allSettled([closeDevelopmentResources()]));
7104
- for (const result of rollback) if (result.status === "rejected") logger$1.warn("Development startup cleanup failed", result.reason);
7105
- }
7106
- 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");
7107
7297
  }
7108
- }
7109
- async function createAndListenAppServer(config, setupRoutes) {
7110
- if (!isDev()) {
7111
- if (serverContext) return serverContext;
7112
- const runtime = await createProductionRuntime(config, { setupRoutes });
7113
- try {
7114
- const result = await startServer(runtime.app, config.server);
7115
- productionRuntime = runtime;
7116
- serverContext = {
7117
- requestHandler: runtime.app,
7118
- viteDevMiddleware: null,
7119
- httpServer: result.server,
7120
- url: result.url,
7121
- isDev: false,
7122
- manifest: loadProdManifest()
7123
- };
7124
- return serverContext;
7125
- } catch (error) {
7126
- try {
7127
- await runtime.close();
7128
- } catch (cleanupError) {
7129
- logger$1.warn("Production startup cleanup failed", cleanupError);
7130
- }
7131
- 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");
7132
7311
  }
7133
7312
  }
7134
- if (!serverContext) await initServerContext(config);
7135
- if (!serverContext) throw new Error("服务器上下文初始化失败");
7136
- setupRoutes(serverContext.requestHandler);
7137
- mountViteOrStatic(serverContext);
7138
- const serverConfig = {
7139
- port: config.server.port,
7140
- host: config.server.host,
7141
- 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;
7142
7317
  };
7143
- const result = await startServer(serverContext.requestHandler, serverConfig);
7144
- serverContext.httpServer = result.server;
7145
- serverContext.url = result.url;
7146
- logger$1.success(`🚀 ${isDev() ? "开发" : "生产"}服务器已启动: ${result.url}`);
7147
- return serverContext;
7148
- }
7149
- /**
7150
- * 关闭服务器
7151
- */
7152
- function shutdownServer() {
7153
- if (stopping) return stopping;
7154
- stopping = stopAppServer().finally(() => {
7155
- stopping = void 0;
7156
- });
7157
- return stopping;
7158
- }
7159
- async function stopAppServer() {
7160
- await starting?.catch(() => void 0);
7161
- if (!serverContext) return;
7162
- const context = serverContext;
7163
- const runtime = productionRuntime;
7164
- serverContext = null;
7165
- productionRuntime = void 0;
7166
- 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");
7167
- if (errors.length) throw new AggregateError(errors.map((result) => result.reason), "Server shutdown failed");
7168
- logger$1.success("✅ 服务器已完全关闭");
7169
- }
7170
- //#endregion
7171
- //#region src/isr/ISRRoutes.ts
7172
- var ISRRoutes = class {
7173
- engine;
7174
- logger;
7175
- defaultMode;
7176
- routes;
7177
- requestLimits;
7178
- constructor(engine, logger, config) {
7179
- this.engine = engine;
7180
- this.logger = logger;
7181
- this.defaultMode = config.renderMode;
7182
- this.routes = config.routes || {};
7183
- this.requestLimits = config.requestLimits;
7184
- }
7185
- setup(requestHandler) {
7186
- const seoLimiter = createRequestLimiter("seo", this.requestLimits?.seo);
7187
- const opsConfig = getRuntimeOpsConfig(requestHandler) ?? resolveOpsConfig({ server: { requestLimits: this.requestLimits } }, "development");
7188
- if (opsConfig.health.enabled) requestHandler.get("/health", getOpsRequestLimiter(opsConfig), createOpsAuthMiddleware("health", opsConfig), (_req, res) => {
7189
- res.json({
7190
- status: "healthy",
7191
- version: package_default.version,
7192
- mode: "plugin-rsc",
7193
- defaultRenderMode: this.defaultMode,
7194
- routes: Object.keys(this.routes).length,
7195
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
7196
- });
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());
7197
7351
  });
7198
- requestHandler.get("/sitemap.xml", seoLimiter, async (_req, res) => {
7199
- try {
7200
- const candidates = [
7201
- path.resolve(process.cwd(), "dist/client/sitemap.xml"),
7202
- path.resolve(process.cwd(), ".isr-hyou/ssg/sitemap.xml"),
7203
- path.resolve(process.cwd(), "public/sitemap.xml")
7204
- ];
7205
- for (const p of candidates) if (fs.existsSync(p)) {
7206
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7207
- res.send(await fs.promises.readFile(p, "utf-8"));
7208
- return;
7209
- }
7210
- await this.engine.generateSeo();
7211
- for (const p of candidates) if (fs.existsSync(p)) {
7212
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7213
- res.send(await fs.promises.readFile(p, "utf-8"));
7214
- return;
7215
- }
7216
- res.setHeader("Content-Type", "application/xml; charset=utf-8");
7217
- res.send(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>`);
7218
- } catch (error) {
7219
- this.logger.error("生成 sitemap 失败:", error);
7220
- 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();
7221
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
+ });
7222
7393
  });
7223
- 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;
7224
7400
  try {
7225
- const candidates = [
7226
- path.resolve(process.cwd(), "dist/client/robots.txt"),
7227
- path.resolve(process.cwd(), ".isr-hyou/ssg/robots.txt"),
7228
- path.resolve(process.cwd(), "public/robots.txt")
7229
- ];
7230
- for (const p of candidates) if (fs.existsSync(p)) {
7231
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
7232
- res.send(await fs.promises.readFile(p, "utf-8"));
7233
- return;
7234
- }
7235
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
7236
- res.send("User-agent: *\nAllow: /\nSitemap: /sitemap.xml\n");
7237
- } catch (error) {
7238
- this.logger.error("生成 robots.txt 失败:", error);
7239
- res.status(500).send("Internal Server Error");
7401
+ pathname = normalizeStaticAssetPathname(req.path).toLowerCase().replace(/\/$/, "");
7402
+ } catch {
7403
+ res.status(400).end();
7404
+ return;
7240
7405
  }
7406
+ if (pathname === "/sitemap.xml" || pathname === "/robots.txt") return seoLimiter(req, res, next);
7407
+ next();
7241
7408
  });
7242
- this.logger.debug("ISRRoutes: 已注册 ops 端点 (/health, /sitemap.xml, /robots.txt)");
7243
- }
7244
- };
7245
- //#endregion
7246
- //#region src/engine/seo/config.ts
7247
- /** 默认 SEO 配置 */
7248
- var DEFAULT_SEO_CONFIG = {
7249
- baseUrl: "",
7250
- siteName: "My App",
7251
- defaultLanguage: "zh",
7252
- supportedLanguages: ["zh", "en"],
7253
- defaultTitle: "My App",
7254
- defaultDescription: "",
7255
- titleTemplate: "%s | My App",
7256
- keywords: [],
7257
- author: "",
7258
- robots: "index,follow",
7259
- sitemap: {
7260
- priority: {
7261
- "/": 1,
7262
- "/blog/*": .7,
7263
- "*": .5
7264
- },
7265
- changeFreq: {
7266
- "/": "daily",
7267
- "/blog/*": "weekly",
7268
- "*": "monthly"
7269
- },
7270
- excludePatterns: ["/admin/*", "/api/*"],
7271
- cacheTimeout: 3600
7272
- },
7273
- openGraph: {
7274
- enabled: true,
7275
- locale: "zh_CN",
7276
- defaultImage: "/images/og-default.jpg"
7277
- },
7278
- twitter: {
7279
- enabled: true,
7280
- card: "summary_large_image",
7281
- site: ""
7282
- },
7283
- structuredData: {
7284
- enabled: true,
7285
- organizationLogo: ""
7286
- }
7287
- };
7288
- /** 深度合并配置 */
7289
- function mergeSEOConfig(base, override) {
7290
- return {
7291
- ...base,
7292
- ...override,
7293
- sitemap: {
7294
- ...base.sitemap,
7295
- ...override.sitemap
7296
- },
7297
- openGraph: {
7298
- ...base.openGraph,
7299
- ...override.openGraph
7300
- },
7301
- twitter: {
7302
- ...base.twitter,
7303
- ...override.twitter
7304
- },
7305
- structuredData: {
7306
- ...base.structuredData,
7307
- ...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";
7308
7423
  }
7309
- };
7310
- }
7311
- //#endregion
7312
- //#region src/engine/seo/SEOEngine.ts
7313
- /**
7314
- * SEO 引擎 - 单例模式
7315
- *
7316
- * 核心功能:
7317
- * - Meta 标签生成
7318
- * - 结构化数据(JSON-LD)生成
7319
- * - 站点地图生成
7320
- * - Open Graph / Twitter Cards
7321
- */
7322
- var SEOEngine_exports = /* @__PURE__ */ __exportAll({
7323
- SEOEngine: () => SEOEngine,
7324
- createSEOEngine: () => createSEOEngine
7325
- });
7326
- var SEOEngine = class SEOEngine {
7327
- static instance = null;
7328
- logger = Logger.getInstance();
7329
- config;
7330
- initialized = false;
7331
- pageDataCache = /* @__PURE__ */ new Map();
7332
- sitemapCache = null;
7333
- sitemapLastGenerated = 0;
7334
- constructor(config) {
7335
- this.config = config ? mergeSEOConfig(DEFAULT_SEO_CONFIG, config) : { ...DEFAULT_SEO_CONFIG };
7336
- }
7337
- /** 获取单例实例 */
7338
- static getInstance(config) {
7339
- if (!SEOEngine.instance) SEOEngine.instance = new SEOEngine(config);
7340
- return SEOEngine.instance;
7341
- }
7342
- /** 重置实例(仅用于测试) */
7343
- static resetInstance() {
7344
- SEOEngine.instance = null;
7345
- }
7346
- /** 更新配置 */
7347
- updateConfig(config) {
7348
- this.config = mergeSEOConfig(this.config, config);
7349
- this.clearCache();
7350
- }
7351
- /** 获取当前配置 */
7352
- getConfig() {
7353
- return this.config;
7354
- }
7355
- /** 初始化 */
7356
- async initialize() {
7357
- if (this.initialized) return;
7358
- this.logger.info("🎯 初始化 SEO 引擎...");
7359
- this.initialized = true;
7360
- this.logger.info("✅ SEO 引擎初始化完成");
7361
- }
7362
- /** 优化页面 SEO */
7363
- async optimizePage(url, context, result) {
7364
- const pageData = this.getOrCreatePageData(url, context);
7365
- const seoTags = this.generateAllTags(pageData);
7366
- const structuredData = this.generateStructuredData(pageData);
7367
- const html = this.insertSEOTags(result.html, seoTags, structuredData);
7368
- return {
7369
- ...result,
7370
- html,
7371
- seoScore: this.calculateScore(pageData),
7372
- meta: {
7373
- ...result.meta,
7374
- 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)}`);
7375
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
7376
7544
  };
7545
+ } catch (error) {
7546
+ await close().catch((cleanupError) => logger$8.error("[Server]", "Production initialization cleanup failed", cleanupError));
7547
+ throw error;
7377
7548
  }
7378
- /** 生成站点地图 */
7379
- async generateSitemap(routes) {
7380
- const now = Date.now();
7381
- if (this.sitemapCache && now - this.sitemapLastGenerated < this.config.sitemap.cacheTimeout * 1e3) return this.sitemapCache;
7382
- if (!this.config.baseUrl) throw new Error("SEO baseUrl 未配置,无法生成 sitemap。请设置 ssr.config.ts runtime.site。");
7383
- const sitemap = new SitemapStream({ hostname: this.config.baseUrl });
7384
- const urls = routes || Array.from(this.pageDataCache.keys());
7385
- const finalUrls = urls.length > 0 ? urls : ["/"];
7386
- for (const url of finalUrls) {
7387
- if (this.shouldExcludeUrl(url)) continue;
7388
- sitemap.write({
7389
- url,
7390
- priority: this.getUrlPriority(url),
7391
- changefreq: this.getUrlChangeFreq(url),
7392
- lastmod: (/* @__PURE__ */ new Date()).toISOString()
7393
- });
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));
7394
7556
  }
7395
- sitemap.end();
7396
- this.sitemapCache = (await streamToPromise(sitemap)).toString();
7397
- this.sitemapLastGenerated = now;
7398
- this.logger.info(`✅ 站点地图已生成: ${urls.length} 个页面`);
7399
- 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));
7400
7605
  }
7401
- /** 生成 Robots.txt */
7402
- generateRobotsTxt() {
7403
- return [
7404
- "User-agent: *",
7405
- "Allow: /",
7406
- "",
7407
- ...this.config.sitemap.excludePatterns.map((p) => `Disallow: ${p}`),
7408
- "",
7409
- `Sitemap: ${this.config.baseUrl}/sitemap.xml`
7410
- ].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";
7411
7615
  }
7412
- /** 清理缓存 */
7413
- clearCache() {
7414
- this.pageDataCache.clear();
7415
- this.sitemapCache = null;
7416
- 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]);
7417
7628
  }
7418
- /** 关闭引擎 */
7419
- async shutdown() {
7420
- this.clearCache();
7421
- this.initialized = false;
7422
- this.logger.debug("✅ SEO 引擎已关闭");
7629
+ if (!response.body) {
7630
+ res.end();
7631
+ return;
7423
7632
  }
7424
- getOrCreatePageData(url, context) {
7425
- const cached = this.pageDataCache.get(url);
7426
- if (cached) return cached;
7427
- const pageType = this.detectPageType(url);
7428
- const pageData = {
7429
- url: `${this.config.baseUrl}${url}`,
7430
- title: this.generateTitle(url),
7431
- description: this.generateDescription(url, pageType),
7432
- keywords: [...this.config.keywords, ...this.extractKeywordsFromUrl(url)],
7433
- image: this.config.openGraph.defaultImage,
7434
- type: pageType,
7435
- language: this.detectLanguage(url, context),
7436
- 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);
7437
7638
  };
7438
- this.pageDataCache.set(url, pageData);
7439
- return pageData;
7440
- }
7441
- generateAllTags(pageData) {
7442
- const tags = [];
7443
- tags.push(`<title>${pageData.title}</title>`);
7444
- tags.push(`<meta name="description" content="${pageData.description}">`);
7445
- if (pageData.keywords?.length) tags.push(`<meta name="keywords" content="${pageData.keywords.join(", ")}">`);
7446
- tags.push(`<meta name="author" content="${this.config.author}">`);
7447
- tags.push(`<meta name="robots" content="${this.config.robots}">`);
7448
- tags.push(`<link rel="canonical" href="${pageData.url}">`);
7449
- if (this.config.openGraph.enabled) {
7450
- tags.push(`<meta property="og:title" content="${pageData.title}">`);
7451
- tags.push(`<meta property="og:description" content="${pageData.description}">`);
7452
- tags.push(`<meta property="og:type" content="${pageData.type}">`);
7453
- tags.push(`<meta property="og:url" content="${pageData.url}">`);
7454
- tags.push(`<meta property="og:site_name" content="${this.config.siteName}">`);
7455
- tags.push(`<meta property="og:locale" content="${this.config.openGraph.locale}">`);
7456
- 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");
7457
7716
  }
7458
- if (this.config.twitter.enabled) {
7459
- tags.push(`<meta name="twitter:card" content="${this.config.twitter.card}">`);
7460
- tags.push(`<meta name="twitter:site" content="${this.config.twitter.site}">`);
7461
- tags.push(`<meta name="twitter:title" content="${pageData.title}">`);
7462
- tags.push(`<meta name="twitter:description" content="${pageData.description}">`);
7463
- 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;
7464
7725
  }
7465
- 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
+ };
7466
7767
  }
7467
- generateStructuredData(pageData) {
7468
- if (!this.config.structuredData.enabled) return "";
7469
- const data = [{
7470
- "@context": "https://schema.org",
7471
- "@type": "WebSite",
7472
- name: this.config.siteName,
7473
- url: this.config.baseUrl
7474
- }, {
7475
- "@context": "https://schema.org",
7476
- "@type": "Organization",
7477
- name: this.config.siteName,
7478
- url: this.config.baseUrl,
7479
- logo: this.config.structuredData.organizationLogo
7480
- }];
7481
- if (pageData.type === "article") data.push({
7482
- "@context": "https://schema.org",
7483
- "@type": "Article",
7484
- headline: pageData.title,
7485
- description: pageData.description,
7486
- url: pageData.url,
7487
- dateModified: pageData.modifiedTime,
7488
- author: {
7489
- "@type": "Person",
7490
- 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;
7491
7815
  }
7816
+ reject(error);
7492
7817
  });
7493
- return `<script type="application/ld+json">${JSON.stringify(data)}<\/script>`;
7494
- }
7495
- insertSEOTags(html, seoTags, structuredData) {
7496
- const headEndIndex = html.indexOf("</head>");
7497
- if (headEndIndex === -1) return html;
7498
- return html.slice(0, headEndIndex) + " " + seoTags + "\n " + structuredData + "\n" + html.slice(headEndIndex);
7499
- }
7500
- calculateScore(pageData) {
7501
- let score = 0;
7502
- if (pageData.title && pageData.title.length >= 30 && pageData.title.length <= 60) score += 25;
7503
- else if (pageData.title) score += 15;
7504
- if (pageData.description && pageData.description.length >= 100) score += 25;
7505
- else if (pageData.description) score += 15;
7506
- if (pageData.keywords && pageData.keywords.length >= 3) score += 20;
7507
- if (pageData.image) score += 15;
7508
- if (this.config.structuredData.enabled) score += 15;
7509
- return Math.min(score, 100);
7510
- }
7511
- detectPageType(url) {
7512
- if (url.includes("/blog/") || url.includes("/article/")) return "article";
7513
- if (url.includes("/product/") || url.includes("/shop/")) return "product";
7514
- return "website";
7515
- }
7516
- generateTitle(url) {
7517
- if (url === "/") return this.config.defaultTitle;
7518
- const title = url.split("/").filter(Boolean).map((s) => s.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())).join(" - ");
7519
- return this.config.titleTemplate.replace("%s", title);
7520
- }
7521
- generateDescription(url, pageType) {
7522
- if (url === "/") return this.config.defaultDescription;
7523
- const topic = url.split("/").pop()?.replace(/-/g, " ") || "";
7524
- if (pageType === "article") return `阅读关于 ${topic} 的最新文章。`;
7525
- if (pageType === "product") return `探索 ${topic} 的详细信息。`;
7526
- return `了解更多关于 ${topic} 的内容。`;
7527
- }
7528
- extractKeywordsFromUrl(url) {
7529
- return url.split("/").filter(Boolean).flatMap((s) => s.split("-"));
7530
- }
7531
- detectLanguage(url, _context) {
7532
- const pathLang = url.split("/")[1];
7533
- if (this.config.supportedLanguages.includes(pathLang)) return pathLang;
7534
- return this.config.defaultLanguage;
7535
- }
7536
- shouldExcludeUrl(url) {
7537
- return this.config.sitemap.excludePatterns.some((pattern) => new RegExp(pattern.replace(/\*/g, ".*")).test(url));
7538
- }
7539
- getUrlPriority(url) {
7540
- for (const [pattern, priority] of Object.entries(this.config.sitemap.priority)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return priority;
7541
- return .5;
7542
- }
7543
- getUrlChangeFreq(url) {
7544
- for (const [pattern, freq] of Object.entries(this.config.sitemap.changeFreq)) if (pattern === "*" || new RegExp(pattern.replace(/\*/g, ".*")).test(url)) return freq;
7545
- 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
+ }
7546
7888
  }
7547
- };
7548
- /** 创建 SEO 引擎实例(获取单例) */
7549
- function createSEOEngine(config) {
7550
- return SEOEngine.getInstance(config);
7889
+ return null;
7551
7890
  }
7552
- //#endregion
7553
- //#region src/engine/seo/resolveSeoConfig.ts
7554
7891
  /**
7555
- * SEO 配置解析器 —— 唯一的 baseUrl 解析入口
7556
- *
7557
- * 设计目标:
7558
- * - SEO 是 SSR/ISR 基础能力,始终启用,不暴露 enabled/sitemap/robots 开关
7559
- * - 用户在 ssr.config.ts 里只关心 prod 域名是什么
7560
- * - prod 只读 runtime.site,避免 SEO baseUrl 变成隐藏环境变量
7561
- * - dev 自动用 localhost,降低本地启动成本
7892
+ * 初始化开发模式服务器上下文
7562
7893
  */
7563
- var resolveSeoConfig_exports = /* @__PURE__ */ __exportAll({ resolveSeoConfig: () => resolveSeoConfig });
7564
- 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
+ }
7565
7906
  /**
7566
- * 按以下顺序解析 baseUrl:
7567
- * 1. runtime.site
7568
- * 2. dev 模式:`http://localhost:${server.port||3000}`
7569
- * 3. prod 且未配置:返回空串(SEOEngine 在调用 generateSitemap 时报错给出修复提示)
7907
+ * 初始化服务器上下文(内部使用)
7570
7908
  */
7571
- function resolveSeoConfig(config) {
7572
- let baseUrl = "";
7573
- let source = "unset";
7574
- if (config.runtime?.site) {
7575
- baseUrl = config.runtime.site;
7576
- source = "runtime.site";
7577
- } else if (isDev()) {
7578
- const envPort = process.env.PORT ? Number(process.env.PORT) : NaN;
7579
- baseUrl = `http://localhost:${config.server?.port ?? (Number.isFinite(envPort) ? envPort : 3e3)}`;
7580
- 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);
7581
7923
  }
7582
- if (!baseUrl) logger.warn("⚠️ SEO baseUrl 未配置:sitemap 端点将报错。请在 ssr.config.ts 设置 runtime.site。");
7583
- else logger.info(`🎯 SEO baseUrl=${baseUrl}(来源:${source})`);
7584
- return {
7585
- baseUrl,
7586
- 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
7587
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("✅ 服务器已完全关闭");
7588
8039
  }
7589
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
7590
8116
  //#region src/middlewares/MiddlewareComposer.ts
7591
8117
  var MiddlewareComposer = class MiddlewareComposer {
7592
8118
  static instance;
@@ -7849,6 +8375,6 @@ async function createISRApp(appOption) {
7849
8375
  };
7850
8376
  }
7851
8377
  //#endregion
7852
- 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 };
7853
8379
 
7854
- //# sourceMappingURL=createISRApp-GKE91WpD.js.map
8380
+ //# sourceMappingURL=createISRApp-rD8EUB--.js.map