isr-engine 2.6.21 → 3.1.0

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 (122) hide show
  1. package/README.md +97 -616
  2. package/dist/Logger-DqBS_3v8.cjs +184 -0
  3. package/dist/Logger-DqBS_3v8.cjs.map +1 -0
  4. package/dist/Logger-bg-doGwZ.js +174 -0
  5. package/dist/Logger-bg-doGwZ.js.map +1 -0
  6. package/dist/abVariantContext-BvAMuhjj.cjs +510 -0
  7. package/dist/abVariantContext-BvAMuhjj.cjs.map +1 -0
  8. package/dist/abVariantContext-Ud3aZ1yk.js +355 -0
  9. package/dist/abVariantContext-Ud3aZ1yk.js.map +1 -0
  10. package/dist/app/createISRApp.d.ts +2 -2
  11. package/dist/cli/cli.cjs +1 -1
  12. package/dist/cli/cli.js +1 -1
  13. package/dist/cli/start.d.ts +1 -1
  14. package/dist/config/loadConfig.d.ts +1 -1
  15. package/dist/config/normalizeEngineConfig.d.ts +1 -1
  16. package/dist/config/normalizeEngineConfig.d.ts.map +1 -1
  17. package/dist/config/resolveRuntimeRedis.d.ts +1 -1
  18. package/dist/{createCacheInspectorMiddleware-DYJ2WGYu.js → createCacheInspectorMiddleware-Bjku5v62.js} +10 -5
  19. package/dist/createCacheInspectorMiddleware-Bjku5v62.js.map +1 -0
  20. package/dist/{createCacheInspectorMiddleware-Byzz8ZlU.cjs → createCacheInspectorMiddleware-DG1_VLBS.cjs} +12 -5
  21. package/dist/createCacheInspectorMiddleware-DG1_VLBS.cjs.map +1 -0
  22. package/dist/{createISRApp-CylUYiIU.js → createISRApp-DYVU8ydT.js} +632 -100
  23. package/dist/createISRApp-DYVU8ydT.js.map +1 -0
  24. package/dist/{createISRApp-C9Bezuit.cjs → createISRApp-HX6X8UNb.cjs} +698 -129
  25. package/dist/createISRApp-HX6X8UNb.cjs.map +1 -0
  26. package/dist/{createImagePlugin-_ntL0DcT.js → createImagePlugin-BZJHOvN9.js} +67 -21
  27. package/dist/createImagePlugin-BZJHOvN9.js.map +1 -0
  28. package/dist/{createImagePlugin-birVNynL.cjs → createImagePlugin-Ca4t_WhM.cjs} +73 -21
  29. package/dist/createImagePlugin-Ca4t_WhM.cjs.map +1 -0
  30. package/dist/defaults/runtime/browserObservability.d.ts.map +1 -1
  31. package/dist/defaults/runtime/defineSiteHooks.cjs +2 -2
  32. package/dist/defaults/runtime/defineSiteHooks.js +2 -2
  33. package/dist/defaults/runtime/dev-style-resource-dispatcher.server.d.ts.map +1 -1
  34. package/dist/{defineSiteHooks-BeVy-qPH.js → defineSiteHooks-CV4tqHvB.js} +11 -5
  35. package/dist/{defineSiteHooks-BeVy-qPH.js.map → defineSiteHooks-CV4tqHvB.js.map} +1 -1
  36. package/dist/{defineSiteHooks-C3v3WLS8.cjs → defineSiteHooks-w2IrF5-D.cjs} +11 -5
  37. package/dist/{defineSiteHooks-C3v3WLS8.cjs.map → defineSiteHooks-w2IrF5-D.cjs.map} +1 -1
  38. package/dist/engine/ISREngine.d.ts +2 -2
  39. package/dist/engine/ISREngine.d.ts.map +1 -1
  40. package/dist/{i18n-CyJIoYJT.cjs → i18n-CS5QhOO0.cjs} +7 -30
  41. package/dist/i18n-CS5QhOO0.cjs.map +1 -0
  42. package/dist/{i18n-Dobe0Wxn.js → i18n-CnXYAgQE.js} +8 -25
  43. package/dist/i18n-CnXYAgQE.js.map +1 -0
  44. package/dist/index.d.ts +3 -3
  45. package/dist/isr/ISRRoutes.d.ts +5 -3
  46. package/dist/isr/ISRRoutes.d.ts.map +1 -1
  47. package/dist/isr-engine.cjs +619 -117
  48. package/dist/isr-engine.cjs.map +1 -1
  49. package/dist/isr-engine.js +609 -107
  50. package/dist/isr-engine.js.map +1 -1
  51. package/dist/logger/Logger.d.ts +6 -2
  52. package/dist/logger/Logger.d.ts.map +1 -1
  53. package/dist/logger/logRecord.d.ts +11 -0
  54. package/dist/logger/logRecord.d.ts.map +1 -0
  55. package/dist/logger/runtimeLogger.d.ts +6 -0
  56. package/dist/logger/runtimeLogger.d.ts.map +1 -0
  57. package/dist/metrics/PromMetrics.d.ts.map +1 -1
  58. package/dist/middlewares/LocaleRedirect.d.ts.map +1 -1
  59. package/dist/plugin/createCacheInspectorMiddleware.d.ts.map +1 -1
  60. package/dist/plugin/createDevCssHandoffPlugin.d.ts.map +1 -1
  61. package/dist/plugin/createFontPlugin.d.ts +1 -1
  62. package/dist/plugin/createFontPlugin.d.ts.map +1 -1
  63. package/dist/plugin/createIsrPlugin.d.ts.map +1 -1
  64. package/dist/plugin/googleFontAssets.d.ts +23 -0
  65. package/dist/plugin/googleFontAssets.d.ts.map +1 -0
  66. package/dist/plugin/isrCacheMiddleware.d.ts +5 -0
  67. package/dist/plugin/isrCacheMiddleware.d.ts.map +1 -1
  68. package/dist/plugin/remoteImageSource.d.ts +3 -3
  69. package/dist/plugin/remoteImageSource.d.ts.map +1 -1
  70. package/dist/rsc/ServerActions.d.ts.map +1 -1
  71. package/dist/rsc/cacheTag.d.ts.map +1 -1
  72. package/dist/rsc/index.cjs +8 -9
  73. package/dist/rsc/index.js +2 -3
  74. package/dist/rsc/revalidate.d.ts.map +1 -1
  75. package/dist/rsc/revalidationMetrics.d.ts +6 -0
  76. package/dist/rsc/revalidationMetrics.d.ts.map +1 -0
  77. package/dist/{rsc-lvWPTuVD.js → rsc-BJzB9s8U.js} +4 -6
  78. package/dist/rsc-BJzB9s8U.js.map +1 -0
  79. package/dist/{rsc-H7D_meHu.cjs → rsc-CYT6B6bf.cjs} +5 -7
  80. package/dist/rsc-CYT6B6bf.cjs.map +1 -0
  81. package/dist/server/manager.d.ts +1 -1
  82. package/dist/server/manager.d.ts.map +1 -1
  83. package/dist/server/opsConfig.d.ts +7 -1
  84. package/dist/server/opsConfig.d.ts.map +1 -1
  85. package/dist/server/productionRuntime.d.ts +3 -4
  86. package/dist/server/productionRuntime.d.ts.map +1 -1
  87. package/dist/server/requestLimits.d.ts +36 -0
  88. package/dist/server/requestLimits.d.ts.map +1 -0
  89. package/dist/server/safeRedirect.d.ts +6 -0
  90. package/dist/server/safeRedirect.d.ts.map +1 -0
  91. package/dist/server/types.d.ts +1 -1
  92. package/dist/ssg/spider.d.ts.map +1 -1
  93. package/dist/types/ISRConfig.d.ts +17 -0
  94. package/dist/types/ISRConfig.d.ts.map +1 -1
  95. package/dist/utils/cookie.d.ts.map +1 -1
  96. package/dist/utils/resolveFetchHandler.d.ts.map +1 -1
  97. package/package.json +30 -32
  98. package/src/defaults/runtime/browserObservability.ts +29 -13
  99. package/src/defaults/runtime/defineServerEntry.tsx +2 -2
  100. package/src/defaults/runtime/defineSiteHooks.ts +12 -7
  101. package/src/defaults/runtime/dev-style-resource-dispatcher.server.ts +2 -3
  102. package/src/types/ISRConfig.ts +21 -7
  103. package/src/utils/cookie.ts +5 -3
  104. package/src/utils/resolveFetchHandler.ts +1 -3
  105. package/dist/RequestContext-BVQ-rOmV.js +0 -58
  106. package/dist/RequestContext-BVQ-rOmV.js.map +0 -1
  107. package/dist/RequestContext-DgGEAxcW.cjs +0 -105
  108. package/dist/RequestContext-DgGEAxcW.cjs.map +0 -1
  109. package/dist/abVariantContext-CWCdRSdG.js +0 -549
  110. package/dist/abVariantContext-CWCdRSdG.js.map +0 -1
  111. package/dist/abVariantContext-Cqp-uxtd.cjs +0 -678
  112. package/dist/abVariantContext-Cqp-uxtd.cjs.map +0 -1
  113. package/dist/createCacheInspectorMiddleware-Byzz8ZlU.cjs.map +0 -1
  114. package/dist/createCacheInspectorMiddleware-DYJ2WGYu.js.map +0 -1
  115. package/dist/createISRApp-C9Bezuit.cjs.map +0 -1
  116. package/dist/createISRApp-CylUYiIU.js.map +0 -1
  117. package/dist/createImagePlugin-_ntL0DcT.js.map +0 -1
  118. package/dist/createImagePlugin-birVNynL.cjs.map +0 -1
  119. package/dist/i18n-CyJIoYJT.cjs.map +0 -1
  120. package/dist/i18n-Dobe0Wxn.js.map +0 -1
  121. package/dist/rsc-H7D_meHu.cjs.map +0 -1
  122. package/dist/rsc-lvWPTuVD.js.map +0 -1
@@ -1,20 +1,21 @@
1
- import { $ as CacheCleanup, A as FallbackChain, B as scanComponents, C as loadConfig, D as getRouteFallbackChain, E as getFallbackChain, F as logger$1, G as parseRouteFromFile, H as scanRoutes, J as isTestFile, K as parseRoutes, M as RenderModes, N as extractSsgRoutes, O as matchRoutePattern, P as spiderSsgRoutes, Q as getEnv, R as resolveFetchHandler, T as createMemoryCacheStore, U as parseComponentFromFile, V as scanProject, W as parseComponents, X as isDev, Y as readDirRecursive, Z as isProd, _ as RedisInvalidationBus, a as DEFAULT_SEO_CONFIG, b as createCoherentCacheStore, c as startAppServer, et as assertDistinctHtmlRouteIdentities, g as createIsrCacheMiddleware, h as createIsrCacheHandler, i as createSEOEngine, j as InternalStrategies, k as resolveRenderMode, l as createABVariantMiddleware, m as generateStaticCspManifest, n as ISREngine, o as mergeSEOConfig, q as isCodeFile, r as SEOEngine, s as shutdownServer, t as createISRApp, tt as resolveImageOptions, v as RedisCacheAdapter, w as createHybridCacheStore, x as createDevAssetRequestMiddleware, y as MemoryCacheAdapter, z as DEFAULT_SCAN_CONFIG } from "./createISRApp-CylUYiIU.js";
2
- import { c as requestContext, i as getRequestContext } from "./RequestContext-BVQ-rOmV.js";
3
- import { _ as invalidatorRunsTotal, b as recordHttpRequest, c as RevalidationError, d as revalidateTag, g as invalidatorFailuresTotal, h as createPrometheusMetricsMiddleware, l as registerInvalidator, n as cacheTag, r as collectTags, s as runWithTagStore, t as getVariant, u as revalidatePath, x as Logger, y as promRegistry } from "./abVariantContext-CWCdRSdG.js";
4
- import { c as parseCookieHeader, l as readCookie, o as trimTrailingSlashes, s as getCookieHeader } from "./i18n-Dobe0Wxn.js";
1
+ import { $ as isCodeFile, A as createHybridCacheStore, B as spiderSsgRoutes, D as invalidatorRunsTotal, E as invalidatorFailuresTotal, F as resolveRenderMode, G as DEFAULT_SCAN_CONFIG, I as FallbackChain, J as scanRoutes, K as scanComponents, L as InternalStrategies, M as getFallbackChain, N as getRouteFallbackChain, O as promRegistry, P as matchRoutePattern, Q as parseRoutes, R as RenderModes, T as createPrometheusMetricsMiddleware, V as logger$1, W as resolveFetchHandler, X as parseComponents, Y as parseComponentFromFile, Z as parseRouteFromFile, _ as RedisInvalidationBus, a as DEFAULT_SEO_CONFIG, at as CacheCleanup, b as createCoherentCacheStore, c as startAppServer, et as isTestFile, g as createIsrCacheMiddleware, h as createIsrCacheHandler, i as createSEOEngine, it as getEnv, j as createMemoryCacheStore, k as recordHttpRequest, l as createABVariantMiddleware, m as generateStaticCspManifest, n as ISREngine, nt as isDev, o as mergeSEOConfig, ot as assertDistinctHtmlRouteIdentities, q as scanProject, r as SEOEngine, rt as isProd, s as shutdownServer, st as resolveImageOptions, t as createISRApp, tt as readDirRecursive, v as RedisCacheAdapter, w as loadConfig, x as createDevAssetRequestMiddleware, y as MemoryCacheAdapter, z as extractSsgRoutes } from "./createISRApp-DYVU8ydT.js";
2
+ import { E as requestContext, S as getRequestContext, c as RevalidationError, d as revalidateTag, l as registerInvalidator, n as cacheTag, r as collectTags, s as runWithTagStore, t as getVariant, u as revalidatePath } from "./abVariantContext-Ud3aZ1yk.js";
3
+ import { t as Logger } from "./Logger-bg-doGwZ.js";
4
+ import { a as trimTrailingSlashes, c as readCookie, o as getCookieHeader, s as parseCookieHeader } from "./i18n-CnXYAgQE.js";
5
5
  import { defineIsrConfig, defineRuntimeConfig } from "./config/defineConfig.js";
6
- import { n as createImagePlugin, t as createImageMiddleware } from "./createImagePlugin-_ntL0DcT.js";
7
- import { a as defineSiteHooks, i as defineAdminSiteHooks, n as createAdminIntlLoader, o as createCachedFetcher, r as createAdminSeoLoader, t as applyRuntimeToServerHooks } from "./defineSiteHooks-BeVy-qPH.js";
8
- import { a as LEGACY_SERVER_ACTION_ENDPOINT, d as createServerAction, f as serverActionsRegistry, i as getI18nLocale, o as SERVER_ACTION_ENDPOINT, r as getI18n, u as ServerActionUtils } from "./rsc-lvWPTuVD.js";
6
+ import { i as requestPinnedImage, n as createImagePlugin, t as createImageMiddleware } from "./createImagePlugin-BZJHOvN9.js";
7
+ import { a as defineSiteHooks, i as defineAdminSiteHooks, n as createAdminIntlLoader, o as createCachedFetcher, r as createAdminSeoLoader, t as applyRuntimeToServerHooks } from "./defineSiteHooks-CV4tqHvB.js";
8
+ import { a as LEGACY_SERVER_ACTION_ENDPOINT, d as createServerAction, f as serverActionsRegistry, i as getI18nLocale, o as SERVER_ACTION_ENDPOINT, r as getI18n, u as ServerActionUtils } from "./rsc-BJzB9s8U.js";
9
9
  import fs, { existsSync, promises, readFileSync, realpathSync } from "node:fs";
10
10
  import path from "node:path";
11
- import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "fs";
12
11
  import { resolve as resolve$1 } from "path";
12
+ import { existsSync as existsSync$1, readFileSync as readFileSync$1 } from "fs";
13
13
  import ts from "typescript";
14
14
  import { normalizePath, version } from "vite";
15
15
  import { createHash } from "node:crypto";
16
16
  import { fileURLToPath, pathToFileURL } from "node:url";
17
- import { parse, walk } from "css-tree";
17
+ import { generate, parse, walk } from "css-tree";
18
+ import { brotliDecompress } from "node:zlib";
18
19
  import { createRequire } from "node:module";
19
20
  import vitePluginRsc from "@vitejs/plugin-rsc";
20
21
  import * as ReactDOM from "react-dom";
@@ -518,6 +519,416 @@ var CacheManager = class {
518
519
  }
519
520
  };
520
521
  //#endregion
522
+ //#region src/plugin/googleFontAssets.ts
523
+ var MAX_CSS_BYTES = 2 * 1024 * 1024;
524
+ var MAX_FONT_BYTES = 16 * 1024 * 1024;
525
+ var MAX_DECODED_BYTES = 32 * 1024 * 1024;
526
+ var MAX_TOTAL_BYTES = 64 * 1024 * 1024;
527
+ var MAX_ASSETS = 512;
528
+ var MAX_FACES = 512;
529
+ var REQUEST_TIMEOUT = 1e4;
530
+ var BATCH_TIMEOUT = 6e4;
531
+ function invalid(message) {
532
+ throw new Error(`Google font ${message}`);
533
+ }
534
+ function isControlCharacter(character) {
535
+ const code = character.charCodeAt(0);
536
+ return code < 32 || code >= 127 && code <= 159;
537
+ }
538
+ function normalizeFontOutDir(value) {
539
+ const directory = value.replace(/\/$/, "");
540
+ if (!directory || directory.length > 256 || directory.split("/").some((part) => !/^[A-Za-z0-9_.-]+$/.test(part) || part === "." || part === "..")) invalid("outDir must be a relative asset directory without traversal");
541
+ return directory;
542
+ }
543
+ function validateOptions(families, weights) {
544
+ if (families.length > 32 || families.some((family) => !family || family.length > 128 || family.trim() !== family || Array.from(family).some(isControlCharacter))) invalid("family list is invalid or too large");
545
+ if (!weights.length || weights.length > 16 || weights.some((weight) => {
546
+ const match = /^([1-9]\d{0,3})(?:\.\.([1-9]\d{0,3}))?$/.exec(weight);
547
+ return !match || Number(match[1]) > 1e3 || match[2] !== void 0 && (Number(match[2]) > 1e3 || Number(match[2]) < Number(match[1]));
548
+ })) invalid("weights must be bounded numeric weights or ranges");
549
+ }
550
+ /** Fixed trusted host selection is separate from the untrusted stylesheet's URL components. */
551
+ function googleTarget(source, kind) {
552
+ const host = kind === "css" ? "fonts.googleapis.com" : "fonts.gstatic.com";
553
+ let url;
554
+ try {
555
+ url = new URL(source);
556
+ } catch {
557
+ return invalid("URL is invalid");
558
+ }
559
+ if (url.protocol !== "https:" || url.hostname !== host || url.port || url.username || url.password || url.hash) invalid("origin is not allowed");
560
+ return url;
561
+ }
562
+ async function download(source, kind, parent) {
563
+ const controller = new AbortController();
564
+ const abort = () => controller.abort(parent.reason);
565
+ if (parent.aborted) abort();
566
+ else parent.addEventListener("abort", abort, { once: true });
567
+ const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Google font request timed out")), REQUEST_TIMEOUT);
568
+ const limit = kind === "css" ? MAX_CSS_BYTES : MAX_FONT_BYTES;
569
+ const allow = /* @__PURE__ */ new Set([kind === "css" ? "fonts.googleapis.com:443" : "fonts.gstatic.com:443"]);
570
+ try {
571
+ let url = googleTarget(source, kind);
572
+ for (let hop = 0; hop <= 5; hop++) {
573
+ controller.signal.throwIfAborted();
574
+ const response = await requestPinnedImage(url, allow, controller.signal, kind === "css" ? "text/css" : "font/woff2", kind === "css" ? "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36" : void 0);
575
+ try {
576
+ if ([
577
+ 301,
578
+ 302,
579
+ 303,
580
+ 307,
581
+ 308
582
+ ].includes(response.statusCode ?? 0)) {
583
+ if (!response.headers.location || hop === 5) invalid("redirect limit exceeded");
584
+ url = googleTarget(new URL(response.headers.location, url).href, kind);
585
+ continue;
586
+ }
587
+ if ((response.statusCode ?? 0) < 200 || (response.statusCode ?? 0) >= 300) invalid("download failed");
588
+ if (response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity") invalid("unexpected response encoding");
589
+ if (Number(response.headers["content-length"]) > limit) invalid("response is too large");
590
+ const chunks = [];
591
+ let size = 0;
592
+ for await (const chunk of response) {
593
+ controller.signal.throwIfAborted();
594
+ const bytes = Buffer.from(chunk);
595
+ size += bytes.length;
596
+ if (size > limit) invalid("response is too large");
597
+ chunks.push(bytes);
598
+ }
599
+ if (!response.complete) invalid("response is incomplete");
600
+ return Buffer.concat(chunks, size);
601
+ } finally {
602
+ response.destroy();
603
+ }
604
+ }
605
+ return invalid("redirect limit exceeded");
606
+ } catch (error) {
607
+ if (controller.signal.aborted) throw controller.signal.reason;
608
+ throw error;
609
+ } finally {
610
+ clearTimeout(timeout);
611
+ parent.removeEventListener("abort", abort);
612
+ }
613
+ }
614
+ function declarations(rule) {
615
+ const values = /* @__PURE__ */ new Map();
616
+ const allowed = /* @__PURE__ */ new Set([
617
+ "font-family",
618
+ "font-style",
619
+ "font-weight",
620
+ "font-stretch",
621
+ "font-display",
622
+ "src",
623
+ "unicode-range"
624
+ ]);
625
+ if (rule.prelude || !rule.block) invalid("stylesheet contains an invalid font-face rule");
626
+ rule.block.children.forEach((declaration) => {
627
+ if (declaration.type !== "Declaration" || declaration.important || declaration.value.type !== "Value") invalid("stylesheet contains an invalid font descriptor");
628
+ const property = declaration.property.toLowerCase();
629
+ if (!allowed.has(property) || values.has(property)) invalid("stylesheet contains an unsupported font descriptor");
630
+ values.set(property, declaration.value);
631
+ });
632
+ return values;
633
+ }
634
+ function unicodeRange(value) {
635
+ const ranges = value.toUpperCase().split(",");
636
+ if (ranges.length > 256 || ranges.some((part) => {
637
+ const match = /^U\+([0-9A-F?]{1,6})(?:-([0-9A-F]{1,6}))?$/.exec(part.trim());
638
+ if (!match) return true;
639
+ if (match[1].includes("?") && (match[2] || !/^[0-9A-F]*\?+$/.test(match[1]))) return true;
640
+ const low = Number.parseInt(match[1].replaceAll("?", "0"), 16);
641
+ const high = Number.parseInt(match[2] ?? match[1].replaceAll("?", "F"), 16);
642
+ return high > 1114111 || low > high;
643
+ })) return invalid("unicode range is invalid");
644
+ return ranges.map((part) => part.trim()).join(", ");
645
+ }
646
+ function parseFaces(css, family) {
647
+ let stylesheet;
648
+ try {
649
+ stylesheet = parse(css, { onParseError: () => invalid("stylesheet cannot be parsed") });
650
+ } catch {
651
+ return invalid("stylesheet cannot be parsed");
652
+ }
653
+ if (stylesheet.type !== "StyleSheet") return invalid("stylesheet is invalid");
654
+ const faces = [];
655
+ stylesheet.children.forEach((rule) => {
656
+ if (rule.type !== "Atrule" || rule.name.toLowerCase() !== "font-face") invalid("stylesheet contains a non-font rule");
657
+ const values = declarations(rule);
658
+ const familyNode = values.get("font-family");
659
+ if (familyNode?.type !== "Value" || familyNode.children.size !== 1) invalid("family descriptor is invalid");
660
+ const name = familyNode.children.first;
661
+ if (name?.type !== "String" || name.value !== family) invalid("family descriptor does not match the requested family");
662
+ const style = values.has("font-style") ? generate(values.get("font-style")).toLowerCase() : "normal";
663
+ if (![
664
+ "normal",
665
+ "italic",
666
+ "oblique"
667
+ ].includes(style)) invalid("style descriptor is invalid");
668
+ let weight = values.has("font-weight") ? generate(values.get("font-weight")) : "400";
669
+ if (weight === "normal") weight = "400";
670
+ if (weight === "bold") weight = "700";
671
+ const weights = weight.split(/\s+/);
672
+ if (weights.length > 2 || weights.some((value) => !/^\d{1,4}$/.test(value) || Number(value) < 1 || Number(value) > 1e3) || weights.length === 2 && Number(weights[0]) > Number(weights[1])) invalid("weight descriptor is invalid");
673
+ const stretch = values.has("font-stretch") ? generate(values.get("font-stretch")).toLowerCase() : void 0;
674
+ if (stretch !== void 0 && !/^(?:normal|(?:ultra-|extra-|semi-)?(?:condensed|expanded)|\d{1,3}(?:\.\d+)?%(?: \d{1,3}(?:\.\d+)?%)?)$/.test(stretch)) invalid("stretch descriptor is invalid");
675
+ const display = values.get("font-display");
676
+ if (display && ![
677
+ "auto",
678
+ "block",
679
+ "swap",
680
+ "fallback",
681
+ "optional"
682
+ ].includes(generate(display))) invalid("display descriptor is invalid");
683
+ const src = values.get("src");
684
+ if (src?.type !== "Value") invalid("source descriptor is missing");
685
+ const parts = src.children.toArray();
686
+ const url = parts[0];
687
+ const format = parts[1];
688
+ if (url?.type !== "Url" || parts.length > 2 || format && (format.type !== "Function" || format.name.toLowerCase() !== "format" || format.children.size !== 1 || format.children.first?.type !== "String" || format.children.first.value !== "woff2")) invalid("source descriptor must contain one WOFF2 URL");
689
+ const source = googleTarget(url.value, "font").href;
690
+ const range = values.get("unicode-range");
691
+ faces.push({
692
+ family,
693
+ style,
694
+ weight,
695
+ stretch,
696
+ unicodeRange: range ? unicodeRange(generate(range)) : void 0,
697
+ source
698
+ });
699
+ });
700
+ if (!faces.length || faces.length > MAX_FACES) invalid("stylesheet has an invalid number of font faces");
701
+ return faces;
702
+ }
703
+ function decompress(bytes, limit) {
704
+ return new Promise((resolve, reject) => {
705
+ brotliDecompress(bytes, { maxOutputLength: limit }, (error, result) => {
706
+ if (error) reject(/* @__PURE__ */ new Error("Google font WOFF2 compressed data is invalid"));
707
+ else resolve(result);
708
+ });
709
+ });
710
+ }
711
+ var TABLE_TAGS = [
712
+ "cmap",
713
+ "head",
714
+ "hhea",
715
+ "hmtx",
716
+ "maxp",
717
+ "name",
718
+ "OS/2",
719
+ "post",
720
+ "cvt ",
721
+ "fpgm",
722
+ "glyf",
723
+ "loca",
724
+ "prep",
725
+ "CFF ",
726
+ "VORG",
727
+ "EBDT",
728
+ "EBLC",
729
+ "gasp",
730
+ "hdmx",
731
+ "kern",
732
+ "LTSH",
733
+ "PCLT",
734
+ "VDMX",
735
+ "vhea",
736
+ "vmtx",
737
+ "BASE",
738
+ "GDEF",
739
+ "GPOS",
740
+ "GSUB",
741
+ "EBSC",
742
+ "JSTF",
743
+ "MATH",
744
+ "CBDT",
745
+ "CBLC",
746
+ "COLR",
747
+ "CPAL",
748
+ "SVG ",
749
+ "sbix",
750
+ "acnt",
751
+ "avar",
752
+ "bdat",
753
+ "bloc",
754
+ "bsln",
755
+ "cvar",
756
+ "fdsc",
757
+ "feat",
758
+ "fmtx",
759
+ "fvar",
760
+ "gvar",
761
+ "hsty",
762
+ "just",
763
+ "lcar",
764
+ "mort",
765
+ "morx",
766
+ "opbd",
767
+ "prop",
768
+ "trak",
769
+ "Zapf",
770
+ "Silf",
771
+ "Glat",
772
+ "Gloc",
773
+ "Feat",
774
+ "Sill"
775
+ ];
776
+ /**
777
+ * Admit bounded single-font WOFF2 containers, not arbitrary network bytes or collections.
778
+ * Directory/Brotli validation follows https://www.w3.org/TR/WOFF2/ sections 3–5.
779
+ * This does not replace the browser's semantic OpenType/glyph validation.
780
+ */
781
+ async function validateWoff2(font) {
782
+ const fail = () => invalid("WOFF2 container is invalid or too large");
783
+ if (font.length < 50 || font.length > MAX_FONT_BYTES || font.readUInt32BE(0) !== 2001684018) fail();
784
+ const flavor = font.readUInt32BE(4);
785
+ const tables = font.readUInt16BE(12);
786
+ const sfntSize = font.readUInt32BE(16);
787
+ const compressedSize = font.readUInt32BE(20);
788
+ if (![65536, 1330926671].includes(flavor) || font.readUInt32BE(8) !== font.length || !tables || tables > 256 || font.readUInt16BE(14) !== 0 || sfntSize < 12 + tables * 16 || sfntSize > MAX_DECODED_BYTES || !compressedSize) fail();
789
+ let cursor = 48;
790
+ const byte = () => {
791
+ if (cursor >= font.length) return fail();
792
+ return font[cursor++];
793
+ };
794
+ const base128 = () => {
795
+ let value = 0;
796
+ for (let index = 0; index < 5; index++) {
797
+ const next = byte();
798
+ if (index === 0 && next === 128 || value > 33554431) return fail();
799
+ value = value * 128 + (next & 127);
800
+ if (!(next & 128)) return value;
801
+ }
802
+ return fail();
803
+ };
804
+ const tags = /* @__PURE__ */ new Set();
805
+ let decodedSize = 0;
806
+ let originalSize = 12 + tables * 16;
807
+ let previousTransformedGlyf = false;
808
+ for (let index = 0; index < tables; index++) {
809
+ const flags = byte();
810
+ const tag = (flags & 63) === 63 ? String.fromCharCode(byte(), byte(), byte(), byte()) : TABLE_TAGS[flags & 63];
811
+ if (!tag || tags.has(tag) || !/^[\x20-\x7e]{4}$/.test(tag)) fail();
812
+ tags.add(tag);
813
+ const version = flags >> 6;
814
+ const glyfOrLoca = tag === "glyf" || tag === "loca";
815
+ if (glyfOrLoca ? version !== 0 && version !== 3 : version !== 0 && !(tag === "hmtx" && version === 1)) fail();
816
+ const transformed = glyfOrLoca ? version === 0 : version !== 0;
817
+ const original = base128();
818
+ const length = transformed ? base128() : original;
819
+ if (tag === "loca" && transformed && length !== 0) fail();
820
+ if (previousTransformedGlyf !== (tag === "loca" && transformed)) fail();
821
+ previousTransformedGlyf = tag === "glyf" && transformed;
822
+ decodedSize += length;
823
+ originalSize += Math.ceil(original / 4) * 4;
824
+ if (decodedSize > MAX_DECODED_BYTES || originalSize > MAX_DECODED_BYTES) fail();
825
+ }
826
+ if (previousTransformedGlyf || !decodedSize || ![
827
+ "cmap",
828
+ "head",
829
+ "hhea",
830
+ "hmtx",
831
+ "maxp",
832
+ "name",
833
+ "OS/2",
834
+ "post"
835
+ ].every((tag) => tags.has(tag))) fail();
836
+ const compressedStart = cursor;
837
+ cursor += compressedSize;
838
+ if (cursor > font.length) fail();
839
+ const metaOffset = font.readUInt32BE(28);
840
+ const metaLength = font.readUInt32BE(32);
841
+ const metaOriginal = font.readUInt32BE(36);
842
+ const privateOffset = font.readUInt32BE(40);
843
+ const privateLength = font.readUInt32BE(44);
844
+ const advance = (offset, length) => {
845
+ if (!length || offset % 4 || offset < cursor || offset - cursor > 3 || offset + length > font.length) fail();
846
+ while (cursor < offset) if (font[cursor++] !== 0) fail();
847
+ cursor += length;
848
+ };
849
+ if (metaOffset) {
850
+ if (!metaOriginal || metaOriginal > 1024 * 1024 || metaLength > 1024 * 1024) fail();
851
+ advance(metaOffset, metaLength);
852
+ } else if (metaLength || metaOriginal) fail();
853
+ if (privateOffset) {
854
+ if (privateLength > 1024 * 1024) fail();
855
+ advance(privateOffset, privateLength);
856
+ } else if (privateLength) fail();
857
+ if (font.length - cursor > 3) fail();
858
+ while (cursor < font.length) if (font[cursor++] !== 0) fail();
859
+ if ((await decompress(font.subarray(compressedStart, compressedStart + compressedSize), MAX_DECODED_BYTES)).length !== decodedSize) fail();
860
+ if (metaOffset && (await decompress(font.subarray(metaOffset, metaOffset + metaLength), 1024 * 1024)).length !== metaOriginal) fail();
861
+ }
862
+ async function loadGoogleFontAssets(families, weights, outDir, shutdown) {
863
+ validateOptions(families, weights);
864
+ const directory = normalizeFontOutDir(outDir);
865
+ const controller = new AbortController();
866
+ const abort = () => controller.abort(shutdown.reason);
867
+ if (shutdown.aborted) abort();
868
+ else shutdown.addEventListener("abort", abort, { once: true });
869
+ const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Google font batch timed out")), BATCH_TIMEOUT);
870
+ const bundle = {
871
+ assets: /* @__PURE__ */ new Map(),
872
+ faces: []
873
+ };
874
+ const downloaded = /* @__PURE__ */ new Map();
875
+ let total = 0;
876
+ try {
877
+ for (const family of [...new Set(families)]) {
878
+ controller.signal.throwIfAborted();
879
+ const bytes = await download("https://fonts.googleapis.com/css2?family=" + encodeURIComponent(family).replace(/%20/g, "+") + `:wght@${weights.join(";")}&display=swap`, "css", controller.signal);
880
+ total += bytes.length;
881
+ if (total > MAX_TOTAL_BYTES) invalid("total download byte budget exceeded");
882
+ let css;
883
+ try {
884
+ css = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
885
+ } catch {
886
+ return invalid("stylesheet encoding is invalid");
887
+ }
888
+ const faces = parseFaces(css, family);
889
+ if (bundle.faces.length + faces.length > MAX_FACES) invalid("face budget exceeded");
890
+ for (const face of faces) {
891
+ controller.signal.throwIfAborted();
892
+ let fileName = downloaded.get(face.source);
893
+ if (!fileName) {
894
+ if (downloaded.size >= MAX_ASSETS) invalid("asset count budget exceeded");
895
+ const font = await download(face.source, "font", controller.signal);
896
+ total += font.length;
897
+ if (total > MAX_TOTAL_BYTES) invalid("total download byte budget exceeded");
898
+ await validateWoff2(font);
899
+ controller.signal.throwIfAborted();
900
+ fileName = `${directory}/${createHash("sha256").update(font).digest("hex")}.woff2`;
901
+ if (!bundle.assets.has(fileName)) bundle.assets.set(fileName, font);
902
+ downloaded.set(face.source, fileName);
903
+ }
904
+ bundle.faces.push({
905
+ family: face.family,
906
+ style: face.style,
907
+ weight: face.weight,
908
+ stretch: face.stretch,
909
+ unicodeRange: face.unicodeRange,
910
+ fileName
911
+ });
912
+ }
913
+ }
914
+ return bundle;
915
+ } finally {
916
+ clearTimeout(timeout);
917
+ shutdown.removeEventListener("abort", abort);
918
+ }
919
+ }
920
+ /** CSS strings are escaped for both the CSS parser and an HTML raw-text style element. */
921
+ function cssString(value) {
922
+ let output = "\"";
923
+ for (const character of value) if (isControlCharacter(character) || "\\\"<>".includes(character)) output += `\\${character.charCodeAt(0).toString(16)} `;
924
+ else output += character;
925
+ return output + "\"";
926
+ }
927
+ function renderGoogleFontCss(bundle, assetUrl) {
928
+ return bundle.faces.map((face) => `@font-face {
929
+ font-family: ${cssString(face.family)};\n font-style: ${face.style};\n font-weight: ${face.weight};\n` + (face.stretch ? ` font-stretch: ${face.stretch};\n` : "") + ` font-display: swap;\n src: url(${cssString(assetUrl(face.fileName))}) format("woff2");\n` + (face.unicodeRange ? ` unicode-range: ${face.unicodeRange};\n` : "") + "}").join("\n");
930
+ }
931
+ //#endregion
521
932
  //#region src/plugin/createFontPlugin.ts
522
933
  /**
523
934
  * createFontPlugin —— 字体优化 Vite 插件(构建时 + dev)
@@ -528,7 +939,7 @@ var CacheManager = class {
528
939
  * 2. **CLS**:自上而下扫 CSS 的 @font-face 链接,注入 <link rel="preload">
529
940
  * 到 transformIndexHtml(让浏览器在 HTML parse 时就拉字体)
530
941
  * 3. **Google Fonts → 自托管**:可选 `google: ['Inter', 'Noto Sans SC']`
531
- * 构建时下载到 `public/_/fonts/`,避免运行时第三方阻塞 + GDPR 问题
942
+ * 构建时输出字体资源、开发时从内存提供,避免运行时第三方阻塞
532
943
  *
533
944
  * 业界对标:next/font 的子集(不做 size-adjust 推算 fallback metrics —— 那是
534
945
  * Capsize 的活,可作为后续增强;当前覆盖 80% 收益场景)。
@@ -546,34 +957,121 @@ function fontTypeFromUrl(url) {
546
957
  otf: "font/otf"
547
958
  }[ext] : void 0;
548
959
  }
960
+ function createSession(config) {
961
+ return {
962
+ config,
963
+ preloadUrls: /* @__PURE__ */ new Set(),
964
+ shutdown: new AbortController(),
965
+ devAssets: /* @__PURE__ */ new Map(),
966
+ starts: /* @__PURE__ */ new Map()
967
+ };
968
+ }
549
969
  function createFontPlugin(options = {}) {
550
970
  const injectSwap = options.injectSwap !== false;
551
971
  const injectPreload = options.injectPreload !== false;
552
- const weights = options.weights ?? ["400", "700"];
553
- const outRel = options.outDir ?? "_/fonts";
554
- let resolved;
555
- /** 跨文件聚合 —— transform 阶段抓取,transformIndexHtml 注入 preload */
556
- const preloadUrls = /* @__PURE__ */ new Set();
557
- const generatedCss = [];
972
+ const weights = [...options.weights ?? ["400", "700"]];
973
+ const families = [...options.google ?? []];
974
+ const outRel = normalizeFontOutDir(options.outDir ?? "_/fonts");
975
+ const sessions = /* @__PURE__ */ new WeakMap();
976
+ let current = createSession();
977
+ function sessionFor(config) {
978
+ return (config ? sessions.get(config) : void 0) ?? current;
979
+ }
980
+ function environmentSession(environment) {
981
+ return sessionFor(environment?.getTopLevelConfig?.());
982
+ }
983
+ function assetUrl(session, fileName, htmlPath = "/index.html") {
984
+ const base = session.config?.base ?? "/";
985
+ if (base === "./" || base === "") {
986
+ let entry = htmlPath.split(/[?#]/, 1)[0].replace(/^\/+/, "");
987
+ if (!entry || entry.endsWith("/")) entry += "index.html";
988
+ const relative = path.posix.relative(path.posix.dirname(entry), fileName);
989
+ return relative.startsWith(".") ? relative : `./${relative}`;
990
+ }
991
+ return `${base.endsWith("/") ? base : `${base}/`}${fileName}`;
992
+ }
993
+ function ensureAssets(session) {
994
+ session.shutdown.signal.throwIfAborted();
995
+ return session.downloading ??= loadGoogleFontAssets(families, weights, outRel, session.shutdown.signal).then((bundle) => {
996
+ session.shutdown.signal.throwIfAborted();
997
+ session.assets = bundle;
998
+ if (session.config?.command === "serve") for (const [fileName, bytes] of bundle.assets) session.devAssets.set(new URL(assetUrl(session, fileName), "http://font-assets.invalid").pathname, bytes);
999
+ return bundle;
1000
+ }).catch((error) => {
1001
+ session.downloading = void 0;
1002
+ throw error;
1003
+ });
1004
+ }
1005
+ function dispose(session) {
1006
+ session.shutdown.abort(/* @__PURE__ */ new Error("Google font asset session closed"));
1007
+ session.assets = void 0;
1008
+ session.downloading = void 0;
1009
+ session.devAssets.clear();
1010
+ session.starts.clear();
1011
+ session.preloadUrls.clear();
1012
+ }
558
1013
  return {
559
1014
  name: "isr-engine:font-optimization",
560
1015
  enforce: "post",
1016
+ sharedDuringBuild: true,
561
1017
  configResolved(c) {
562
- resolved = c;
1018
+ current = createSession(c);
1019
+ sessions.set(c, current);
563
1020
  },
564
- /** 构建启动前:下载 Google Fonts 到 public/<outDir>/ + 生成本地 @font-face CSS */
1021
+ /** Share validated downloads across environments; only client outputs own browser assets. */
565
1022
  async buildStart() {
566
- if (!options.google || options.google.length === 0) return;
567
- const publicDir = resolved.publicDir || path.resolve(resolved.root, "public");
568
- const fontsDir = path.join(publicDir, outRel);
569
- await promises.mkdir(fontsDir, { recursive: true });
570
- for (const family of options.google) {
571
- const css = await downloadGoogleFontFamily(family, weights, fontsDir, outRel);
572
- if (css) generatedCss.push(css);
1023
+ const session = environmentSession(this.environment);
1024
+ if (!families.length || session.config?.command === "build" && this.environment?.config.consumer === "server") return;
1025
+ const key = this.environment ?? this;
1026
+ let pending = session.starts.get(key);
1027
+ if (!pending) {
1028
+ pending = (async () => {
1029
+ const bundle = await ensureAssets(session);
1030
+ session.shutdown.signal.throwIfAborted();
1031
+ if (session.config?.command === "build") for (const [fileName, source] of bundle.assets) this.emitFile({
1032
+ type: "asset",
1033
+ fileName,
1034
+ source
1035
+ });
1036
+ })();
1037
+ session.starts.set(key, pending);
1038
+ }
1039
+ try {
1040
+ await pending;
1041
+ } finally {
1042
+ if (session.starts.get(key) === pending) session.starts.delete(key);
573
1043
  }
574
1044
  },
1045
+ configureServer(server) {
1046
+ const session = sessionFor(server.config);
1047
+ server.httpServer?.once("close", () => dispose(session));
1048
+ server.middlewares.use((req, res, next) => {
1049
+ const bytes = session.devAssets.get((req.url ?? "").split(/[?#]/, 1)[0]);
1050
+ if (!bytes) return next();
1051
+ if (req.method !== "GET" && req.method !== "HEAD") {
1052
+ res.statusCode = 405;
1053
+ res.setHeader("allow", "GET, HEAD");
1054
+ res.end();
1055
+ return;
1056
+ }
1057
+ res.setHeader("content-type", "font/woff2");
1058
+ res.setHeader("x-content-type-options", "nosniff");
1059
+ res.setHeader("content-length", bytes.length);
1060
+ res.setHeader("cache-control", "public, max-age=31536000, immutable");
1061
+ res.end(req.method === "HEAD" ? void 0 : bytes);
1062
+ });
1063
+ },
1064
+ closeBundle() {
1065
+ const session = environmentSession(this.environment);
1066
+ if (session.config?.command === "serve") dispose(session);
1067
+ },
1068
+ closeWatcher() {
1069
+ const session = environmentSession(this.environment);
1070
+ if (session.config?.command === "build" && this.environment?.config.consumer !== "server") dispose(session);
1071
+ },
575
1072
  /** 任何 CSS 文件经过 transform:注入 swap + 收集 preload url */
576
1073
  transform(code, id) {
1074
+ const session = environmentSession(this.environment);
577
1075
  if (!/\.(css|scss|less|sass|styl)(\?|$)/.test(id)) return null;
578
1076
  let stylesheet;
579
1077
  try {
@@ -599,7 +1097,7 @@ function createFontPlugin(options = {}) {
599
1097
  }
600
1098
  });
601
1099
  });
602
- if (firstUrl && injectPreload) preloadUrls.add(firstUrl);
1100
+ if (firstUrl && injectPreload) session.preloadUrls.add(firstUrl);
603
1101
  const close = rule.block.loc ? rule.block.loc.end.offset - 1 : -1;
604
1102
  if (injectSwap && !hasDisplay && code[close] === "}") insertions.push(close);
605
1103
  }
@@ -618,64 +1116,36 @@ function createFontPlugin(options = {}) {
618
1116
  };
619
1117
  },
620
1118
  /** HTML 注入:preload 标签 + 自托管 google fonts 的 @font-face 块 */
621
- transformIndexHtml(html) {
622
- const tags = [];
623
- if (generatedCss.length > 0) tags.push({
624
- tag: "style",
625
- attrs: { "data-isr-engine-font": "google" },
626
- injectTo: "head"
627
- });
628
- for (const url of preloadUrls) tags.push({
629
- tag: "link",
630
- attrs: {
631
- rel: "preload",
632
- href: url,
633
- as: "font",
634
- type: fontTypeFromUrl(url) ?? "font/woff2",
635
- crossorigin: "anonymous"
636
- },
637
- injectTo: "head"
638
- });
639
- if (tags.length === 0) return html;
640
- const inject = `${tags.filter((t) => t.tag === "link").map((t) => `<link ${Object.entries(t.attrs ?? {}).map(([k, v]) => `${k}="${escapeHtmlAttribute(v)}"`).join(" ")}>`).join("\n ")}\n ${generatedCss.length > 0 ? `<style data-isr-engine-font="google">${generatedCss.join("\n")}</style>` : ""}\n`;
641
- return html.replace("</head>", ` ${inject}</head>`);
1119
+ transformIndexHtml(html, context) {
1120
+ const session = sessionFor(context?.server?.config);
1121
+ const render = () => {
1122
+ const generatedCss = session.assets ? renderGoogleFontCss(session.assets, (fileName) => assetUrl(session, fileName, context?.path)) : "";
1123
+ const tags = [];
1124
+ if (generatedCss) tags.push({
1125
+ tag: "style",
1126
+ attrs: { "data-isr-engine-font": "google" },
1127
+ injectTo: "head"
1128
+ });
1129
+ for (const url of session.preloadUrls) tags.push({
1130
+ tag: "link",
1131
+ attrs: {
1132
+ rel: "preload",
1133
+ href: url,
1134
+ as: "font",
1135
+ type: fontTypeFromUrl(url) ?? "font/woff2",
1136
+ crossorigin: "anonymous"
1137
+ },
1138
+ injectTo: "head"
1139
+ });
1140
+ if (tags.length === 0) return html;
1141
+ const inject = `${tags.filter((t) => t.tag === "link").map((t) => `<link ${Object.entries(t.attrs ?? {}).map(([k, v]) => `${k}="${escapeHtmlAttribute(v)}"`).join(" ")}>`).join("\n ")}\n ${generatedCss ? `<style data-isr-engine-font="google">${generatedCss}</style>` : ""}\n`;
1142
+ return html.replace("</head>", ` ${inject}</head>`);
1143
+ };
1144
+ if (families.length && !session.assets) return ensureAssets(session).then(render);
1145
+ return render();
642
1146
  }
643
1147
  };
644
1148
  }
645
- /**
646
- * Google Fonts 家族下载 —— 通过 css2 API 拉 CSS,再下载里面所有 url(.woff2)
647
- *
648
- * 不用第三方 SDK:直接 HTTP,避开 GDPR + 锁版本风险
649
- */
650
- async function downloadGoogleFontFamily(family, weights, outDir, publicRel) {
651
- const cssUrl = "https://fonts.googleapis.com/css2?family=" + encodeURIComponent(family).replace(/%20/g, "+") + `:wght@${weights.join(";")}&display=swap`;
652
- try {
653
- const cssRes = await fetch(cssUrl, { headers: { "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36" } });
654
- if (!cssRes.ok) {
655
- console.warn(`[font-plugin] Google Fonts ${family} 拉取失败: ${cssRes.status}`);
656
- return null;
657
- }
658
- let css = await cssRes.text();
659
- const urls = Array.from(css.matchAll(/url\((https:\/\/[^)]+)\)/g)).map((m) => m[1]);
660
- for (const u of urls) {
661
- const r = await fetch(u);
662
- if (!r.ok) continue;
663
- const ab = await r.arrayBuffer();
664
- const buf = Buffer.from(ab);
665
- const ext = u.split(".").pop()?.split("?")[0] || "woff2";
666
- const hash = createHash("sha1").update(buf).digest("hex").slice(0, 10);
667
- const fname = `${family.replace(/\s+/g, "-")}-${hash}.${ext}`;
668
- const localPath = path.join(outDir, fname);
669
- await promises.writeFile(localPath, buf);
670
- const publicUrl = `/${publicRel}/${fname}`;
671
- css = css.replace(u, publicUrl);
672
- }
673
- return css;
674
- } catch (err) {
675
- console.warn(`[font-plugin] ${family} 下载异常`, err);
676
- return null;
677
- }
678
- }
679
1149
  //#endregion
680
1150
  //#region src/runtime/telemetry.ts
681
1151
  var currentHandle = null;
@@ -777,6 +1247,7 @@ function createEndpointAnalyticsClient(options, getUser) {
777
1247
  sampleRate: analyticsOptions?.sampleRate ?? 1,
778
1248
  key: "isr_engine_builtin_analytics"
779
1249
  }, getUser);
1250
+ if (!base) return null;
780
1251
  return {
781
1252
  track(name, properties, trackOptions) {
782
1253
  base.enqueue({
@@ -833,6 +1304,7 @@ function createEndpointErrorReporter(options, getUser) {
833
1304
  sampleRate: errorOptions?.sampleRate ?? 1,
834
1305
  key: "isr_engine_builtin_errors"
835
1306
  }, getUser);
1307
+ if (!base) return null;
836
1308
  const captureException = (error, context = {}) => {
837
1309
  const normalized = normalizeError(error);
838
1310
  base.enqueue({
@@ -899,6 +1371,7 @@ function createEndpointQueue(options, baseOptions, getUser) {
899
1371
  const queue = [];
900
1372
  const sessionId = readOrCreateBrowserId(`${baseOptions.key}_session`);
901
1373
  const anonymousId = readOrCreateBrowserId(`${baseOptions.key}_anonymous`);
1374
+ if (!sessionId || !anonymousId) return null;
902
1375
  let timer = null;
903
1376
  let retryTimer = null;
904
1377
  let inFlight = false;
@@ -934,8 +1407,10 @@ function createEndpointQueue(options, baseOptions, getUser) {
934
1407
  const enqueue = (payload) => {
935
1408
  if (baseOptions.sampleRate <= 0) return;
936
1409
  if (baseOptions.sampleRate < 1 && Math.random() > baseOptions.sampleRate) return;
1410
+ const id = createId(baseOptions.key.includes("errors") ? "err" : "evt");
1411
+ if (!id) return;
937
1412
  queue.push({
938
- id: createId(baseOptions.key.includes("errors") ? "err" : "evt"),
1413
+ id,
939
1414
  app: options.app,
940
1415
  ts: Date.now(),
941
1416
  release: options.release,
@@ -1178,19 +1653,26 @@ function isBrowser() {
1178
1653
  return typeof window !== "undefined" && typeof document !== "undefined";
1179
1654
  }
1180
1655
  function createId(prefix) {
1181
- return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1656
+ try {
1657
+ if (typeof globalThis.crypto?.getRandomValues !== "function") return null;
1658
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
1659
+ return `${prefix}_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1660
+ } catch {
1661
+ return null;
1662
+ }
1182
1663
  }
1183
1664
  function readOrCreateBrowserId(key) {
1184
1665
  if (!isBrowser()) return createId("runtime");
1185
1666
  try {
1186
1667
  const existing = window.localStorage.getItem(key);
1187
- if (existing) return existing;
1188
- const next = createId("runtime");
1668
+ if (existing && /^runtime_[0-9a-f]{32}$/.test(existing)) return existing;
1669
+ } catch {}
1670
+ const next = createId("runtime");
1671
+ if (!next) return null;
1672
+ try {
1189
1673
  window.localStorage.setItem(key, next);
1190
- return next;
1191
- } catch {
1192
- return createId("runtime");
1193
- }
1674
+ } catch {}
1675
+ return next;
1194
1676
  }
1195
1677
  /** 解析 ignoreSourcePatterns 选项 —— false 关闭过滤;数组与默认合并;缺省走默认。 */
1196
1678
  function resolveIgnorePatterns(custom) {
@@ -1572,7 +2054,7 @@ function transformDevCssModule(code, id, registryId, browserStyleId) {
1572
2054
  }
1573
2055
  //#endregion
1574
2056
  //#region src/defaults/runtime/dev-style-resource-dispatcher.server.ts
1575
- var PINNED_REACT_DOM_VERSION = "19.3.0-canary-bd6ea412-20260824";
2057
+ var PINNED_REACT_DOM_VERSION = "19.3.1";
1576
2058
  function pinnedResourceDispatcher() {
1577
2059
  const module = ReactDOM;
1578
2060
  const dispatcher = module.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE?.d;
@@ -1670,7 +2152,7 @@ function hasUseClientDirective$1(code, id) {
1670
2152
  return false;
1671
2153
  }
1672
2154
  function unsupportedClientProxy(id) {
1673
- return /* @__PURE__ */ new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc client reference proxy shape in ${id}. Expected the pinned 0.5.34 registerClientReference wrapper.`);
2155
+ return /* @__PURE__ */ new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc client reference proxy shape in ${id}. Expected the pinned 0.5.39 registerClientReference wrapper.`);
1674
2156
  }
1675
2157
  function isPinnedRscServerRuntime(value) {
1676
2158
  try {
@@ -1916,10 +2398,11 @@ function isCreateElementCall(node, reactBinding, argumentCount) {
1916
2398
  return ts.isCallExpression(node) && node.arguments.length === argumentCount && isPropertyPath(node.expression, reactBinding, "createElement");
1917
2399
  }
1918
2400
  function isPinnedLinkProps(node, hrefBinding, precedenceBinding) {
1919
- if (!ts.isObjectLiteralExpression(node) || node.properties.length !== 5) return false;
1920
- const [key, rel, precedence, href, dataHref] = node.properties;
2401
+ if (!ts.isObjectLiteralExpression(node) || node.properties.length !== 6) return false;
2402
+ const [key, rel, crossOrigin, precedence, href, dataHref] = node.properties;
1921
2403
  if (!key || !ts.isPropertyAssignment(key) || propertyName(key.name) !== "key" || !ts.isBinaryExpression(key.initializer) || key.initializer.operatorToken.kind !== ts.SyntaxKind.PlusToken || !stringIs(key.initializer.left, "css:") || !identifierIs(key.initializer.right, hrefBinding)) return false;
1922
2404
  if (!rel || !ts.isPropertyAssignment(rel) || propertyName(rel.name) !== "rel" || !stringIs(rel.initializer, "stylesheet")) return false;
2405
+ if (!crossOrigin || !ts.isPropertyAssignment(crossOrigin) || propertyName(crossOrigin.name) !== "crossOrigin" || !stringIs(crossOrigin.initializer, "anonymous")) return false;
1923
2406
  if (!precedence || !ts.isSpreadAssignment(precedence)) return false;
1924
2407
  const condition = precedence.expression;
1925
2408
  if (!ts.isConditionalExpression(condition) || !identifierIs(condition.condition, precedenceBinding) || !ts.isObjectLiteralExpression(condition.whenTrue) || condition.whenTrue.properties.length !== 1 || !ts.isShorthandPropertyAssignment(condition.whenTrue.properties[0]) || condition.whenTrue.properties[0].name.text !== precedenceBinding || !ts.isObjectLiteralExpression(condition.whenFalse) || condition.whenFalse.properties.length !== 0) return false;
@@ -1936,13 +2419,17 @@ function isPinnedResourcesFactory(factory) {
1936
2419
  if (factory.parameters.length !== parameterNames.length || !factory.parameters.every((parameter, index) => {
1937
2420
  const expected = parameterNames[index];
1938
2421
  return expected !== void 0 && identifierIs(parameter.name, expected);
1939
- }) || !ts.isBlock(factory.body) || factory.body.statements.length !== 1) return false;
1940
- const factoryReturn = factory.body.statements[0];
2422
+ }) || !ts.isBlock(factory.body) || factory.body.statements.length !== 2) return false;
2423
+ const [element, factoryReturn] = factory.body.statements;
2424
+ if (!element || !ts.isVariableStatement(element) || (element.declarationList.flags & ts.NodeFlags.Const) === 0 || element.declarationList.declarations.length !== 1) return false;
2425
+ const declaration = element.declarationList.declarations[0];
2426
+ if (!declaration || !identifierIs(declaration.name, "element")) return false;
1941
2427
  if (!factoryReturn || !ts.isReturnStatement(factoryReturn) || !factoryReturn.expression || !ts.isFunctionExpression(factoryReturn.expression) || !identifierIs(factoryReturn.expression.name, "Resources") || factoryReturn.expression.parameters.length !== 0 || factoryReturn.expression.body.statements.length !== 1) return false;
1942
2428
  const resourcesReturn = factoryReturn.expression.body.statements[0];
1943
- const resourcesCall = resourcesReturn && ts.isReturnStatement(resourcesReturn) && resourcesReturn.expression && isCreateElementCall(resourcesReturn.expression, "React", 3) ? resourcesReturn.expression : void 0;
1944
- const [fragment, nullValue, children] = resourcesCall?.arguments ?? [];
1945
- if (!resourcesCall || !fragment || !isPropertyPath(fragment, "React", "Fragment") || nullValue?.kind !== ts.SyntaxKind.NullKeyword || !children || !ts.isArrayLiteralExpression(children) || children.elements.length !== 2) return false;
2429
+ const resourcesCall = declaration.initializer;
2430
+ if (!resourcesReturn || !ts.isReturnStatement(resourcesReturn) || !identifierIs(resourcesReturn.expression, "element") || !resourcesCall || !isCreateElementCall(resourcesCall, "React", 3)) return false;
2431
+ const [fragment, nullValue, children] = resourcesCall.arguments;
2432
+ if (!fragment || !isPropertyPath(fragment, "React", "Fragment") || nullValue?.kind !== ts.SyntaxKind.NullKeyword || !children || !ts.isArrayLiteralExpression(children) || children.elements.length !== 2) return false;
1946
2433
  const [linksSpread, cleanup] = children.elements;
1947
2434
  if (!linksSpread || !ts.isSpreadElement(linksSpread) || !ts.isCallExpression(linksSpread.expression)) return false;
1948
2435
  const mapCall = linksSpread.expression;
@@ -1995,7 +2482,7 @@ function instrumentDevRscStylesheetModule(code, id, declarationsUrl) {
1995
2482
  const reactBinding = defaultImportBinding(source.statements[0], "react");
1996
2483
  const cleanupBinding = defaultImportBinding(source.statements[1], VITE_RSC_REMOVE_DUPLICATE_CSS_ID);
1997
2484
  const depsArgument = initializer && ts.isCallExpression(initializer) ? initializer.arguments[1] : void 0;
1998
- if (source.statements.length !== 3 || reactBinding === void 0 || cleanupBinding === void 0 || source.statements[2] !== resourcesStatement || !resourcesStatement || resourcesStatement.modifiers?.length !== 1 || resourcesStatement.modifiers[0]?.kind !== ts.SyntaxKind.ExportKeyword || (resourcesStatement.declarationList.flags & ts.NodeFlags.Const) === 0 || resourcesStatement.declarationList.declarations.length !== 1 || !initializer || !ts.isCallExpression(initializer) || initializer.arguments.length !== 4 || factory === void 0 || !ts.isArrowFunction(factory) && !ts.isFunctionExpression(factory) || !isPinnedResourcesFactory(factory) || !identifierIs(initializer.arguments[0], reactBinding) || !depsArgument || !isPinnedDependencies(depsArgument) || !identifierIs(initializer.arguments[2], cleanupBinding) || !(stringIs(initializer.arguments[3], "vite-rsc/importer-resources") || identifierIs(initializer.arguments[3], "undefined"))) throw new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc server stylesheet resource shape in ${id}. Expected the pinned 0.5.34 Resources factory.`);
2485
+ if (source.statements.length !== 3 || reactBinding === void 0 || cleanupBinding === void 0 || source.statements[2] !== resourcesStatement || !resourcesStatement || resourcesStatement.modifiers?.length !== 1 || resourcesStatement.modifiers[0]?.kind !== ts.SyntaxKind.ExportKeyword || (resourcesStatement.declarationList.flags & ts.NodeFlags.Const) === 0 || resourcesStatement.declarationList.declarations.length !== 1 || !initializer || !ts.isCallExpression(initializer) || initializer.arguments.length !== 4 || factory === void 0 || !ts.isArrowFunction(factory) && !ts.isFunctionExpression(factory) || !isPinnedResourcesFactory(factory) || !identifierIs(initializer.arguments[0], reactBinding) || !depsArgument || !isPinnedDependencies(depsArgument) || !identifierIs(initializer.arguments[2], cleanupBinding) || !(stringIs(initializer.arguments[3], "vite-rsc/importer-resources") || identifierIs(initializer.arguments[3], "undefined"))) throw new Error(`[isr-engine] Unsupported @vitejs/plugin-rsc server stylesheet resource shape in ${id}. Expected the pinned 0.5.39 Resources factory.`);
1999
2486
  const reactCode = code.slice(initializer.arguments[0].getStart(source), initializer.arguments[0].getEnd());
2000
2487
  const depsCode = code.slice(initializer.arguments[1].getStart(source), initializer.arguments[1].getEnd());
2001
2488
  const replacement = `
@@ -2625,6 +3112,26 @@ async function resolveClientRuntimeConfigModule(root, inlineConfig) {
2625
3112
  function createAppAliasPlugin(root) {
2626
3113
  const userSrc = path.resolve(root, "src");
2627
3114
  const defaultsDir = resolveEngineDefaultsDir();
3115
+ const requireFromEngine = createRequire(path.resolve(defaultsDir, "../../package.json"));
3116
+ const transportAliases = ["client", "server"].map((entry) => {
3117
+ const find = `rsc-html-stream/${entry}`;
3118
+ return {
3119
+ find,
3120
+ replacement: requireFromEngine.resolve(find)
3121
+ };
3122
+ });
3123
+ for (const entry of [
3124
+ "client.browser",
3125
+ "client.edge",
3126
+ "server.edge",
3127
+ "static.edge"
3128
+ ]) {
3129
+ const find = `@vitejs/plugin-rsc/vendor/react-server-dom/${entry}`;
3130
+ transportAliases.push({
3131
+ find,
3132
+ replacement: requireFromEngine.resolve(find)
3133
+ });
3134
+ }
2628
3135
  const emptyConfig = path.resolve(defaultsDir, "runtime/empty-config.ts");
2629
3136
  const emptyRoutes = path.resolve(defaultsDir, "runtime/empty-routes.ts");
2630
3137
  const appEntry = path.resolve(userSrc, "app.tsx");
@@ -2640,7 +3147,7 @@ function createAppAliasPlugin(root) {
2640
3147
  const clientReferenceDeps = detectClientReferenceDependencies(root);
2641
3148
  return {
2642
3149
  resolve: {
2643
- alias: [
3150
+ alias: [...[
2644
3151
  {
2645
3152
  find: "@app/_entry",
2646
3153
  replacement: appEntry
@@ -2665,13 +3172,8 @@ function createAppAliasPlugin(root) {
2665
3172
  find: /^@app\/(.*)$/,
2666
3173
  replacement: `${userSrc}/$1`
2667
3174
  }
2668
- ],
2669
- dedupe: [
2670
- "react",
2671
- "react-dom",
2672
- "react-server-dom-webpack",
2673
- "rsc-html-stream"
2674
- ]
3175
+ ], ...transportAliases],
3176
+ dedupe: ["react", "react-dom"]
2675
3177
  },
2676
3178
  optimizeDeps: {
2677
3179
  entries: ["src/**/*.{js,jsx,ts,tsx}"],