vinext 0.0.46 → 0.0.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -5
- package/dist/build/prerender.d.ts +2 -1
- package/dist/build/prerender.js +70 -14
- package/dist/build/prerender.js.map +1 -1
- package/dist/build/report.d.ts +1 -1
- package/dist/build/route-classification-injector.d.ts +35 -0
- package/dist/build/route-classification-injector.js +61 -0
- package/dist/build/route-classification-injector.js.map +1 -0
- package/dist/build/route-classification-manifest.d.ts +1 -1
- package/dist/build/static-export.d.ts +1 -1
- package/dist/cli-args.d.ts +31 -0
- package/dist/cli-args.js +104 -0
- package/dist/cli-args.js.map +1 -0
- package/dist/cli.js +2 -19
- package/dist/cli.js.map +1 -1
- package/dist/cloudflare/kv-cache-handler.js +29 -9
- package/dist/cloudflare/kv-cache-handler.js.map +1 -1
- package/dist/config/next-config.d.ts +4 -2
- package/dist/config/next-config.js +3 -0
- package/dist/config/next-config.js.map +1 -1
- package/dist/entries/app-rsc-entry.d.ts +4 -3
- package/dist/entries/app-rsc-entry.js +373 -854
- package/dist/entries/app-rsc-entry.js.map +1 -1
- package/dist/entries/app-rsc-manifest.d.ts +1 -1
- package/dist/entries/app-rsc-manifest.js +2 -0
- package/dist/entries/app-rsc-manifest.js.map +1 -1
- package/dist/entries/pages-server-entry.js +5 -2
- package/dist/entries/pages-server-entry.js.map +1 -1
- package/dist/index.js +28 -51
- package/dist/index.js.map +1 -1
- package/dist/plugins/fonts.js +54 -32
- package/dist/plugins/fonts.js.map +1 -1
- package/dist/plugins/rsc-client-shim-excludes.js +1 -0
- package/dist/plugins/rsc-client-shim-excludes.js.map +1 -1
- package/dist/routing/app-route-graph.d.ts +109 -0
- package/dist/routing/app-route-graph.js +819 -0
- package/dist/routing/app-route-graph.js.map +1 -0
- package/dist/routing/app-router.d.ts +2 -88
- package/dist/routing/app-router.js +6 -694
- package/dist/routing/app-router.js.map +1 -1
- package/dist/server/app-browser-entry.js +86 -252
- package/dist/server/app-browser-entry.js.map +1 -1
- package/dist/server/app-browser-error.d.ts +3 -4
- package/dist/server/app-browser-error.js +8 -4
- package/dist/server/app-browser-error.js.map +1 -1
- package/dist/server/app-browser-navigation-controller.d.ts +73 -0
- package/dist/server/app-browser-navigation-controller.js +282 -0
- package/dist/server/app-browser-navigation-controller.js.map +1 -0
- package/dist/server/app-browser-state.d.ts +1 -1
- package/dist/server/app-elements.js +1 -5
- package/dist/server/app-elements.js.map +1 -1
- package/dist/server/app-fallback-renderer.d.ts +57 -0
- package/dist/server/app-fallback-renderer.js +79 -0
- package/dist/server/app-fallback-renderer.js.map +1 -0
- package/dist/server/app-hook-warning-suppression.d.ts +7 -0
- package/dist/server/app-hook-warning-suppression.js +12 -0
- package/dist/server/app-hook-warning-suppression.js.map +1 -0
- package/dist/server/app-mounted-slots-header.d.ts +17 -0
- package/dist/server/app-mounted-slots-header.js +21 -0
- package/dist/server/app-mounted-slots-header.js.map +1 -0
- package/dist/server/app-page-boundary-render.d.ts +2 -2
- package/dist/server/app-page-boundary-render.js.map +1 -1
- package/dist/server/app-page-cache.d.ts +18 -4
- package/dist/server/app-page-cache.js +53 -10
- package/dist/server/app-page-cache.js.map +1 -1
- package/dist/server/app-page-dispatch.d.ts +7 -4
- package/dist/server/app-page-dispatch.js +24 -8
- package/dist/server/app-page-dispatch.js.map +1 -1
- package/dist/server/app-page-element-builder.d.ts +61 -0
- package/dist/server/app-page-element-builder.js +139 -0
- package/dist/server/app-page-element-builder.js.map +1 -0
- package/dist/server/app-page-params.d.ts +2 -1
- package/dist/server/app-page-params.js +3 -3
- package/dist/server/app-page-params.js.map +1 -1
- package/dist/server/app-page-render.d.ts +5 -1
- package/dist/server/app-page-render.js +80 -27
- package/dist/server/app-page-render.js.map +1 -1
- package/dist/server/app-page-request.d.ts +19 -4
- package/dist/server/app-page-request.js +51 -6
- package/dist/server/app-page-request.js.map +1 -1
- package/dist/server/app-page-response.d.ts +1 -0
- package/dist/server/app-page-response.js +3 -7
- package/dist/server/app-page-response.js.map +1 -1
- package/dist/server/app-page-route-wiring.d.ts +15 -2
- package/dist/server/app-page-route-wiring.js.map +1 -1
- package/dist/server/app-post-middleware-context.d.ts +16 -0
- package/dist/server/app-post-middleware-context.js +28 -0
- package/dist/server/app-post-middleware-context.js.map +1 -0
- package/dist/server/app-request-context.d.ts +22 -0
- package/dist/server/app-request-context.js +30 -0
- package/dist/server/app-request-context.js.map +1 -0
- package/dist/server/app-route-handler-cache.d.ts +1 -0
- package/dist/server/app-route-handler-cache.js +5 -1
- package/dist/server/app-route-handler-cache.js.map +1 -1
- package/dist/server/app-route-handler-dispatch.d.ts +1 -0
- package/dist/server/app-route-handler-dispatch.js +2 -0
- package/dist/server/app-route-handler-dispatch.js.map +1 -1
- package/dist/server/app-route-handler-execution.d.ts +2 -1
- package/dist/server/app-route-handler-execution.js +2 -2
- package/dist/server/app-route-handler-execution.js.map +1 -1
- package/dist/server/app-route-handler-response.d.ts +4 -2
- package/dist/server/app-route-handler-response.js +8 -7
- package/dist/server/app-route-handler-response.js.map +1 -1
- package/dist/server/app-rsc-error-handler.d.ts +21 -0
- package/dist/server/app-rsc-error-handler.js +30 -0
- package/dist/server/app-rsc-error-handler.js.map +1 -0
- package/dist/server/app-rsc-handler.d.ts +117 -0
- package/dist/server/app-rsc-handler.js +260 -0
- package/dist/server/app-rsc-handler.js.map +1 -0
- package/dist/server/app-rsc-request-normalization.d.ts +40 -0
- package/dist/server/app-rsc-request-normalization.js +63 -0
- package/dist/server/app-rsc-request-normalization.js.map +1 -0
- package/dist/server/app-rsc-response-finalizer.d.ts +30 -0
- package/dist/server/app-rsc-response-finalizer.js +38 -0
- package/dist/server/app-rsc-response-finalizer.js.map +1 -0
- package/dist/server/app-segment-config.d.ts +33 -0
- package/dist/server/app-segment-config.js +86 -0
- package/dist/server/app-segment-config.js.map +1 -0
- package/dist/server/app-server-action-execution.d.ts +2 -0
- package/dist/server/app-server-action-execution.js +2 -0
- package/dist/server/app-server-action-execution.js.map +1 -1
- package/dist/server/cache-control.d.ts +24 -0
- package/dist/server/cache-control.js +33 -0
- package/dist/server/cache-control.js.map +1 -0
- package/dist/server/dev-error-overlay-store.d.ts +23 -0
- package/dist/server/dev-error-overlay-store.js +67 -0
- package/dist/server/dev-error-overlay-store.js.map +1 -0
- package/dist/server/dev-error-overlay.d.ts +15 -0
- package/dist/server/dev-error-overlay.js +548 -0
- package/dist/server/dev-error-overlay.js.map +1 -0
- package/dist/server/instrumentation-runtime.d.ts +44 -0
- package/dist/server/instrumentation-runtime.js +29 -0
- package/dist/server/instrumentation-runtime.js.map +1 -0
- package/dist/server/isr-cache.d.ts +2 -7
- package/dist/server/isr-cache.js +7 -10
- package/dist/server/isr-cache.js.map +1 -1
- package/dist/server/pages-page-data.d.ts +2 -1
- package/dist/server/pages-page-data.js +6 -5
- package/dist/server/pages-page-data.js.map +1 -1
- package/dist/server/pages-page-response.d.ts +2 -1
- package/dist/server/pages-page-response.js +3 -2
- package/dist/server/pages-page-response.js.map +1 -1
- package/dist/server/rsc-stream-hints.d.ts +3 -1
- package/dist/server/rsc-stream-hints.js +4 -1
- package/dist/server/rsc-stream-hints.js.map +1 -1
- package/dist/server/seed-cache.js +19 -8
- package/dist/server/seed-cache.js.map +1 -1
- package/dist/shims/cache-runtime.js +28 -11
- package/dist/shims/cache-runtime.js.map +1 -1
- package/dist/shims/cache.d.ts +15 -3
- package/dist/shims/cache.js +42 -15
- package/dist/shims/cache.js.map +1 -1
- package/dist/shims/error-boundary.d.ts +17 -1
- package/dist/shims/error-boundary.js +31 -1
- package/dist/shims/error-boundary.js.map +1 -1
- package/dist/shims/fetch-cache.d.ts +4 -1
- package/dist/shims/fetch-cache.js +55 -13
- package/dist/shims/fetch-cache.js.map +1 -1
- package/dist/shims/image.js +93 -5
- package/dist/shims/image.js.map +1 -1
- package/dist/shims/request-state-types.d.ts +1 -1
- package/dist/shims/unified-request-context.d.ts +1 -1
- package/dist/shims/unified-request-context.js +1 -0
- package/dist/shims/unified-request-context.js.map +1 -1
- package/dist/shims/use-merged-ref.d.ts +7 -0
- package/dist/shims/use-merged-ref.js +40 -0
- package/dist/shims/use-merged-ref.js.map +1 -0
- package/dist/utils/cache-control-metadata.d.ts +6 -0
- package/dist/utils/cache-control-metadata.js +16 -0
- package/dist/utils/cache-control-metadata.js.map +1 -0
- package/package.json +1 -1
package/dist/plugins/fonts.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { validateGoogleFontOptions } from "../build/google-fonts/validate.js";
|
|
2
2
|
import { getFontAxes } from "../build/google-fonts/get-axes.js";
|
|
3
3
|
import { buildGoogleFontsUrl } from "../build/google-fonts/build-url.js";
|
|
4
|
+
import { CONTENT_TYPES } from "../server/static-file-cache.js";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { parseAst } from "vite";
|
|
@@ -406,16 +407,39 @@ function _findCallEnd(code, objEnd) {
|
|
|
406
407
|
return i + 1;
|
|
407
408
|
}
|
|
408
409
|
function createGoogleFontsPlugin(fontGoogleShimPath, shimsDir) {
|
|
409
|
-
let isBuild = false;
|
|
410
410
|
const fontCache = /* @__PURE__ */ new Map();
|
|
411
411
|
let cacheDir = "";
|
|
412
412
|
return {
|
|
413
413
|
name: "vinext:google-fonts",
|
|
414
414
|
enforce: "pre",
|
|
415
415
|
configResolved(config) {
|
|
416
|
-
isBuild = config.command === "build";
|
|
417
416
|
cacheDir = path.join(config.root, ".vinext", "fonts");
|
|
418
417
|
},
|
|
418
|
+
configureServer(server) {
|
|
419
|
+
if (!cacheDir) return;
|
|
420
|
+
const urlPrefix = `/${server.environments?.client?.config?.build?.assetsDir ?? server.config?.build?.assetsDir ?? DEFAULT_ASSETS_DIR}/${VINEXT_FONT_URL_NAMESPACE}/`;
|
|
421
|
+
server.middlewares.use((req, res, next) => {
|
|
422
|
+
const url = req.url;
|
|
423
|
+
if (!url || !url.startsWith(urlPrefix)) return next();
|
|
424
|
+
const rawPath = url.slice(urlPrefix.length).split("?")[0];
|
|
425
|
+
let decoded;
|
|
426
|
+
try {
|
|
427
|
+
decoded = decodeURIComponent(rawPath);
|
|
428
|
+
} catch {
|
|
429
|
+
return next();
|
|
430
|
+
}
|
|
431
|
+
const filePath = path.resolve(cacheDir, decoded);
|
|
432
|
+
if (filePath !== cacheDir && !filePath.startsWith(cacheDir + path.sep)) return next();
|
|
433
|
+
fs.stat(filePath, (err, stat) => {
|
|
434
|
+
if (err || !stat.isFile()) return next();
|
|
435
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
436
|
+
res.setHeader("Content-Type", CONTENT_TYPES[ext] ?? "application/octet-stream");
|
|
437
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
438
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
439
|
+
fs.createReadStream(filePath).pipe(res);
|
|
440
|
+
});
|
|
441
|
+
});
|
|
442
|
+
},
|
|
419
443
|
transform: {
|
|
420
444
|
filter: {
|
|
421
445
|
id: { include: /\.(tsx?|jsx?|mjs)$/ },
|
|
@@ -520,36 +544,34 @@ function createGoogleFontsPlugin(fontGoogleShimPath, shimsDir) {
|
|
|
520
544
|
overwrittenRanges.push([callStart, callEnd]);
|
|
521
545
|
hasChanges = true;
|
|
522
546
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
await injectSelfHostedCss(callStart, callEnd, optionsStr, propertyNameToGoogleFontFamily(propName), `${objectName}.${propName}`);
|
|
552
|
-
}
|
|
547
|
+
const namedCallRe = /\b([A-Za-z_$][A-Za-z0-9_$]*)\s*\(\s*(?=\{)/g;
|
|
548
|
+
let namedCallMatch;
|
|
549
|
+
while ((namedCallMatch = namedCallRe.exec(code)) !== null) {
|
|
550
|
+
const [fullMatch, localName] = namedCallMatch;
|
|
551
|
+
const importedName = fontLocals.get(localName);
|
|
552
|
+
if (!importedName) continue;
|
|
553
|
+
const callStart = namedCallMatch.index;
|
|
554
|
+
const objRange = _findBalancedObject(code, callStart + fullMatch.length);
|
|
555
|
+
if (!objRange) continue;
|
|
556
|
+
const optionsStr = code.slice(objRange[0], objRange[1]);
|
|
557
|
+
const callEnd = _findCallEnd(code, objRange[1]);
|
|
558
|
+
if (callEnd === null) continue;
|
|
559
|
+
if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) continue;
|
|
560
|
+
await injectSelfHostedCss(callStart, callEnd, optionsStr, importedName.replace(/_/g, " "), localName);
|
|
561
|
+
}
|
|
562
|
+
const memberCallRe = /\b([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)\s*\(\s*(?=\{)/g;
|
|
563
|
+
let memberCallMatch;
|
|
564
|
+
while ((memberCallMatch = memberCallRe.exec(code)) !== null) {
|
|
565
|
+
const [fullMatch, objectName, propName] = memberCallMatch;
|
|
566
|
+
if (!proxyObjectLocals.has(objectName)) continue;
|
|
567
|
+
const callStart = memberCallMatch.index;
|
|
568
|
+
const objRange = _findBalancedObject(code, callStart + fullMatch.length);
|
|
569
|
+
if (!objRange) continue;
|
|
570
|
+
const optionsStr = code.slice(objRange[0], objRange[1]);
|
|
571
|
+
const callEnd = _findCallEnd(code, objRange[1]);
|
|
572
|
+
if (callEnd === null) continue;
|
|
573
|
+
if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) continue;
|
|
574
|
+
await injectSelfHostedCss(callStart, callEnd, optionsStr, propertyNameToGoogleFontFamily(propName), `${objectName}.${propName}`);
|
|
553
575
|
}
|
|
554
576
|
if (!hasChanges) return null;
|
|
555
577
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fonts.js","names":[],"sources":["../../src/plugins/fonts.ts"],"sourcesContent":["/**\n * vinext font plugins\n *\n * Exports two Vite plugins:\n *\n * `createGoogleFontsPlugin` — vinext:google-fonts\n * 1. Rewrites named `next/font/google` imports/exports to tiny virtual modules\n * that export only the requested fonts plus any utility exports. This lets us\n * delete the generated ~1,900-line runtime catalog while keeping ESM import\n * semantics intact.\n * 2. During production builds, fetches Google Fonts CSS + font files, caches\n * them locally under `.vinext/fonts/`, and injects `_selfHostedCSS` into\n * statically analyzable font loader calls so fonts are served from the\n * deployed origin rather than fonts.googleapis.com.\n *\n * `createLocalFontsPlugin` — vinext:local-fonts\n * When a source file calls localFont({ src: \"./font.woff2\" }) or\n * localFont({ src: [{ path: \"./font.woff2\" }] }), the relative paths\n * won't resolve in the browser because the CSS is injected at runtime.\n * This plugin rewrites those path strings into Vite asset import references\n * so that both dev (/@fs/...) and prod (/assets/font-xxx.woff2) URLs are\n * correct.\n */\n\nimport type { Plugin } from \"vite\";\nimport { parseAst } from \"vite\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport MagicString from \"magic-string\";\nimport { validateGoogleFontOptions } from \"../build/google-fonts/validate.js\";\nimport { getFontAxes } from \"../build/google-fonts/get-axes.js\";\nimport { buildGoogleFontsUrl } from \"../build/google-fonts/build-url.js\";\n\n/**\n * Thrown when Google Fonts returns a non-2xx response. Distinct from a raw\n * `fetch` rejection (network error, DNS failure, AbortError) so the call\n * site can decide whether to surface as a build error or fall through to\n * the runtime CDN path.\n */\nclass GoogleFontsHttpError extends Error {\n constructor(\n public readonly url: string,\n public readonly status: number,\n public readonly responseBody: string,\n ) {\n super(`Google Fonts returned HTTP ${status} for ${url}`);\n this.name = \"GoogleFontsHttpError\";\n }\n}\n\n// ── Virtual module IDs ────────────────────────────────────────────────────────\n\nexport const VIRTUAL_GOOGLE_FONTS = \"virtual:vinext-google-fonts\";\nexport const RESOLVED_VIRTUAL_GOOGLE_FONTS = \"\\0\" + VIRTUAL_GOOGLE_FONTS;\n\n// ── Constants ─────────────────────────────────────────────────────────────────\n\n// IMPORTANT: keep this set in sync with the non-default exports from\n// packages/vinext/src/shims/font-google.ts (and its re-export barrel).\nconst GOOGLE_FONT_UTILITY_EXPORTS = new Set([\n \"buildGoogleFontsUrl\",\n \"getSSRFontLinks\",\n \"getSSRFontStyles\",\n \"getSSRFontPreloads\",\n \"createFontLoader\",\n]);\n\n/**\n * Served URL prefix for self-hosted Google Font files.\n *\n * `fetchAndCacheFont()` downloads .woff2 files into `<root>/.vinext/fonts/`\n * and writes an `@font-face` CSS snippet whose `src: url(...)` references\n * the files by absolute filesystem path — convenient for disk, unusable at\n * runtime because browsers resolve relative to the origin. Before the CSS\n * is embedded in the bundle as `_selfHostedCSS`, the filesystem prefix is\n * rewritten to this URL prefix by `_rewriteCachedFontCssToServedUrls()`,\n * and the matching `writeBundle` hook in `createGoogleFontsPlugin` copies\n * the font files into `<clientOutDir>/<assetsDir>/_vinext_fonts/` so the\n * rewritten URL actually resolves against the origin at request time.\n *\n * The leading `_` keeps the namespace distinct from Vite's content-hashed\n * asset names (which are emitted flat into `<assetsDir>/`) and from any\n * user-provided public files.\n */\nconst VINEXT_FONT_URL_NAMESPACE = \"_vinext_fonts\";\nconst MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH = 500;\n\nfunction formatGoogleFontsErrorBody(body: string): string {\n const trimmed = body.trim();\n if (!trimmed) return \"(empty response body)\";\n if (trimmed.length <= MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH) return trimmed;\n const omitted = trimmed.length - MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH;\n return `${trimmed.slice(0, MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH)}\\n... (truncated ${omitted} characters)`;\n}\n\n/**\n * Rewrite absolute filesystem paths in cached Google Fonts CSS so the\n * `@font-face { src: url(...) }` references point at the served URL the\n * plugin's `writeBundle` hook copies the font files to.\n *\n * This is called once per transform, before the CSS string is embedded in\n * the bundle as `_selfHostedCSS`. Every downstream consumer reads from the\n * same rewritten CSS: the injected `<style data-vinext-fonts>` block, the\n * HTML body's `<link rel=\"preload\">` tags (via `collectFontPreloadsFromCSS`\n * in `shims/font-google-base.ts`), and the HTTP `Link:` response header\n * (via `buildAppPageFontLinkHeader` in `server/app-page-execution.ts`).\n *\n * Without this rewrite, all three emit the dev-machine filesystem path\n * (e.g. `/home/user/project/.vinext/fonts/geist-<hash>/geist-<hash>.woff2`)\n * and any production request fetches `<origin>/home/user/...` → 404.\n *\n * `assetsDir` must match whatever Vite has resolved for\n * `build.assetsDir` on the client environment — otherwise the embedded\n * CSS URLs and the files emitted by the `writeBundle` hook would diverge\n * and a user who customizes `build.assetsDir` (e.g. to `\"static\"`) would\n * see 404s on every preload. The call site in `injectSelfHostedCss`\n * passes the resolved value through from plugin state. The default is\n * kept only so the exported helper can be driven directly from unit\n * tests without synthesizing a full plugin context.\n *\n * Uses split/join rather than regex because `cacheDir` is an absolute\n * filesystem path that may contain regex metacharacters on unusual\n * filesystems.\n */\nexport function _rewriteCachedFontCssToServedUrls(\n css: string,\n cacheDir: string,\n assetsDir: string = DEFAULT_ASSETS_DIR,\n): string {\n if (!cacheDir || !css.includes(cacheDir)) return css;\n const prefix = assetsDir || DEFAULT_ASSETS_DIR;\n return css.split(cacheDir).join(`/${prefix}/${VINEXT_FONT_URL_NAMESPACE}`);\n}\n\n/**\n * Default Vite `build.assetsDir` — mirrors Vite's own default. Used as\n * the fallback for the `assetsDir` parameter of\n * `_rewriteCachedFontCssToServedUrls` so the exported helper can be unit\n * tested without synthesizing plugin state. Production call sites thread\n * the real `envConfig.build.assetsDir` resolved by Vite through so that\n * the embedded CSS URLs always match the directory the `writeBundle`\n * hook copies the font files into.\n */\nconst DEFAULT_ASSETS_DIR = \"assets\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\ntype GoogleFontNamedSpecifier = {\n imported: string;\n local: string;\n isType: boolean;\n raw: string;\n};\n\n// ── Helpers shared with index.ts ──────────────────────────────────────────────\n\n/**\n * Safely parse a static JS object literal string into a plain object.\n * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.\n * Returns null if the expression contains anything dynamic (function calls,\n * template literals, identifiers, computed properties, etc.).\n *\n * Supports: string literals, numeric literals, boolean literals,\n * arrays of the above, and nested object literals.\n */\nexport function parseStaticObjectLiteral(objectStr: string): Record<string, unknown> | null {\n let ast: ReturnType<typeof parseAst>;\n try {\n // Wrap in parens so the parser treats `{…}` as an expression, not a block\n ast = parseAst(`(${objectStr})`);\n } catch {\n return null;\n }\n\n // The AST should be: Program > ExpressionStatement > ObjectExpression\n const body = ast.body;\n if (body.length !== 1 || body[0].type !== \"ExpressionStatement\") return null;\n\n const expr = body[0].expression;\n if (expr.type !== \"ObjectExpression\") return null;\n\n const result = extractStaticValue(expr);\n return result === undefined ? null : (result as Record<string, unknown>);\n}\n\n/**\n * Recursively extract a static value from an ESTree AST node.\n * Returns undefined (not null) if the node contains any dynamic expression.\n *\n * Uses `any` for the node parameter because Rollup's internal ESTree types\n * (estree.Expression, estree.ObjectExpression, etc.) aren't re-exported by Vite,\n * and the recursive traversal touches many different node shapes.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractStaticValue(node: any): unknown {\n switch (node.type) {\n case \"Literal\":\n // String, number, boolean, null\n return node.value;\n\n case \"UnaryExpression\":\n // Handle negative numbers: -1, -3.14\n if (\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\"\n ) {\n return -node.argument.value;\n }\n return undefined;\n\n case \"ArrayExpression\": {\n const arr: unknown[] = [];\n for (const elem of node.elements) {\n if (!elem) return undefined; // sparse array\n const val = extractStaticValue(elem);\n if (val === undefined) return undefined;\n arr.push(val);\n }\n return arr;\n }\n\n case \"ObjectExpression\": {\n const obj: Record<string, unknown> = {};\n for (const prop of node.properties) {\n if (prop.type !== \"Property\") return undefined; // SpreadElement etc.\n if (prop.computed) return undefined; // [expr]: val\n\n // Key can be Identifier (unquoted) or Literal (quoted)\n let key: string;\n if (prop.key.type === \"Identifier\") {\n key = prop.key.name;\n } else if (prop.key.type === \"Literal\" && typeof prop.key.value === \"string\") {\n key = prop.key.value;\n } else {\n return undefined;\n }\n\n const val = extractStaticValue(prop.value);\n if (val === undefined) return undefined;\n obj[key] = val;\n }\n return obj;\n }\n\n default:\n // TemplateLiteral, CallExpression, Identifier, etc. — reject\n return undefined;\n }\n}\n\n// ── Virtual module encoding/decoding ─────────────────────────────────────────\n\nfunction encodeGoogleFontsVirtualId(payload: {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n}): string {\n const params = new URLSearchParams();\n if (payload.hasDefault) params.set(\"default\", \"1\");\n if (payload.fonts.length > 0) params.set(\"fonts\", payload.fonts.join(\",\"));\n if (payload.utilities.length > 0) params.set(\"utilities\", payload.utilities.join(\",\"));\n return `${VIRTUAL_GOOGLE_FONTS}?${params.toString()}`;\n}\n\nfunction parseGoogleFontsVirtualId(id: string): {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n} | null {\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n if (!cleanId.startsWith(VIRTUAL_GOOGLE_FONTS)) return null;\n const queryIndex = cleanId.indexOf(\"?\");\n const params = new URLSearchParams(queryIndex === -1 ? \"\" : cleanId.slice(queryIndex + 1));\n return {\n hasDefault: params.get(\"default\") === \"1\",\n fonts:\n params\n .get(\"fonts\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n utilities:\n params\n .get(\"utilities\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n };\n}\n\nexport function generateGoogleFontsVirtualModule(\n id: string,\n fontGoogleShimPath: string,\n): string | null {\n const payload = parseGoogleFontsVirtualId(id);\n if (!payload) return null;\n\n const utilities = Array.from(new Set(payload.utilities));\n const fonts = Array.from(new Set(payload.fonts));\n const lines: string[] = [];\n\n lines.push(`import { createFontLoader } from ${JSON.stringify(fontGoogleShimPath)};`);\n\n const reExports: string[] = [];\n if (payload.hasDefault) reExports.push(\"default\");\n reExports.push(...utilities);\n if (reExports.length > 0) {\n lines.push(`export { ${reExports.join(\", \")} } from ${JSON.stringify(fontGoogleShimPath)};`);\n }\n\n for (const fontName of fonts) {\n const family = fontName.replace(/_/g, \" \");\n lines.push(\n `export const ${fontName} = /*#__PURE__*/ createFontLoader(${JSON.stringify(family)});`,\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ── Import clause parsers ─────────────────────────────────────────────────────\n\nfunction parseGoogleFontNamedSpecifiers(\n specifiersStr: string,\n forceType = false,\n): GoogleFontNamedSpecifier[] {\n return specifiersStr\n .split(\",\")\n .map((spec) => spec.trim())\n .filter(Boolean)\n .map((raw) => {\n const isType = forceType || raw.startsWith(\"type \");\n const valueSpec = isType ? raw.replace(/^type\\s+/, \"\") : raw;\n const asParts = valueSpec.split(/\\s+as\\s+/);\n const imported = asParts[0]?.trim() ?? \"\";\n const local = (asParts[1] || asParts[0] || \"\").trim();\n return { imported, local, isType, raw };\n })\n .filter((spec) => spec.imported.length > 0 && spec.local.length > 0);\n}\n\nfunction parseGoogleFontImportClause(clause: string): {\n defaultLocal: string | null;\n namespaceLocal: string | null;\n named: GoogleFontNamedSpecifier[];\n} {\n const trimmed = clause.trim();\n\n if (trimmed.startsWith(\"type \")) {\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart === -1 || braceEnd === -1) {\n return { defaultLocal: null, namespaceLocal: null, named: [] };\n }\n return {\n defaultLocal: null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd), true),\n };\n }\n\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart !== -1 && braceEnd !== -1) {\n const beforeNamed = trimmed.slice(0, braceStart).trim().replace(/,\\s*$/, \"\").trim();\n return {\n defaultLocal: beforeNamed || null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd)),\n };\n }\n\n const commaIndex = trimmed.indexOf(\",\");\n if (commaIndex !== -1) {\n const defaultLocal = trimmed.slice(0, commaIndex).trim() || null;\n const rest = trimmed.slice(commaIndex + 1).trim();\n if (rest.startsWith(\"* as \")) {\n return {\n defaultLocal,\n namespaceLocal: rest.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n }\n\n if (trimmed.startsWith(\"* as \")) {\n return {\n defaultLocal: null,\n namespaceLocal: trimmed.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n\n return {\n defaultLocal: trimmed || null,\n namespaceLocal: null,\n named: [],\n };\n}\n\nfunction propertyNameToGoogleFontFamily(prop: string): string {\n return prop.replace(/_/g, \" \").replace(/([a-z])([A-Z])/g, \"$1 $2\");\n}\n\n// ── Font fetching and caching ─────────────────────────────────────────────────\n\n/**\n * Fetch Google Fonts CSS, download .woff2 files, cache locally, and return\n * @font-face CSS with local file references.\n *\n * Cache dir structure: .vinext/fonts/<family-hash>/\n * - style.css (the rewritten @font-face CSS)\n * - *.woff2 (downloaded font files)\n */\nasync function fetchAndCacheFont(\n cssUrl: string,\n family: string,\n cacheDir: string,\n): Promise<string> {\n // Use a hash of the URL for the cache key\n const { createHash } = await import(\"node:crypto\");\n const urlHash = createHash(\"md5\").update(cssUrl).digest(\"hex\").slice(0, 12);\n const fontDir = path.join(cacheDir, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${urlHash}`);\n\n // Check if already cached\n const cachedCSSPath = path.join(fontDir, \"style.css\");\n if (fs.existsSync(cachedCSSPath)) {\n return fs.readFileSync(cachedCSSPath, \"utf-8\");\n }\n\n // Fetch CSS from Google Fonts (woff2 user-agent gives woff2 URLs)\n const cssResponse = await fetch(cssUrl, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n },\n });\n if (!cssResponse.ok) {\n // Include the response body when Google rejected the request so the\n // caller can see why (the body usually contains a one-line CSS comment\n // identifying the bad axis or family).\n const body = await cssResponse.text().catch(() => \"\");\n throw new GoogleFontsHttpError(cssUrl, cssResponse.status, body);\n }\n let css = await cssResponse.text();\n\n // Extract all font file URLs\n const urlRe = /url\\((https:\\/\\/fonts\\.gstatic\\.com\\/[^)]+)\\)/g;\n const urls = new Map<string, string>(); // original URL -> local filename\n let urlMatch;\n while ((urlMatch = urlRe.exec(css)) !== null) {\n const fontUrl = urlMatch[1];\n if (!urls.has(fontUrl)) {\n const ext = fontUrl.includes(\".woff2\")\n ? \".woff2\"\n : fontUrl.includes(\".woff\")\n ? \".woff\"\n : \".ttf\";\n const fileHash = createHash(\"md5\").update(fontUrl).digest(\"hex\").slice(0, 8);\n urls.set(fontUrl, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${fileHash}${ext}`);\n }\n }\n\n // Download font files\n fs.mkdirSync(fontDir, { recursive: true });\n for (const [fontUrl, filename] of urls) {\n const filePath = path.join(fontDir, filename);\n if (!fs.existsSync(filePath)) {\n const fontResponse = await fetch(fontUrl);\n if (fontResponse.ok) {\n const buffer = Buffer.from(await fontResponse.arrayBuffer());\n fs.writeFileSync(filePath, buffer);\n }\n }\n // Rewrite every remote Google Fonts CDN URL in the cached CSS to the\n // absolute filesystem path of the locally-downloaded font file. This\n // cache file is read back by the plugin and then run through\n // `_rewriteCachedFontCssToServedUrls()` at embed time, which replaces\n // the absolute `cacheDir` prefix with the served URL namespace under\n // `/<assetsDir>/_vinext_fonts/`. The filesystem path is only the\n // on-disk intermediate form — it must never reach the bundle, the\n // injected `<style data-vinext-fonts>` block, the HTML `<link\n // rel=\"preload\">` tags, or the HTTP `Link:` response header. An\n // earlier version of this code claimed \"Vite will resolve /@fs/ for\n // dev, or asset for build\", which was never true: the CSS is\n // embedded as a JavaScript string literal and Vite's asset pipeline\n // does not scan string literals. Do not resurrect that assumption.\n css = css.split(fontUrl).join(filePath.replaceAll(\"\\\\\", \"/\"));\n }\n\n // Cache the rewritten CSS\n fs.writeFileSync(cachedCSSPath, css);\n return css;\n}\n\n// ── Plugin factories ──────────────────────────────────────────────────────────\n\n/**\n * Create the `vinext:google-fonts` Vite plugin.\n *\n * @param fontGoogleShimPath - Absolute path to the font-google shim module\n * (either `.ts` in source or `.js` in built packages). Resolved by the caller\n * so the plugin file has no dependency on `__dirname`.\n * @param shimsDir - Absolute path to the shims directory. Used to skip shim\n * files from transform (they contain `next/font/google` references that must\n * not be rewritten).\n */\n\n/**\n * Scan `code` forward from `searchStart` for a `{...}` object literal that\n * may contain arbitrarily nested braces. Returns `[objStart, objEnd]` where\n * `code[objStart] === '{'` and `code[objEnd - 1] === '}'`, or `null` if no\n * balanced object is found.\n *\n * String literals (single-quoted, double-quoted, and backtick template\n * literals including `${...}` interpolations) are fully skipped so that brace\n * characters inside string values do not affect the depth count.\n */\nexport function _findBalancedObject(code: string, searchStart: number): [number, number] | null {\n let i = searchStart;\n // Skip leading whitespace before the opening brace\n while (\n i < code.length &&\n (code[i] === \" \" || code[i] === \"\\t\" || code[i] === \"\\n\" || code[i] === \"\\r\")\n ) {\n i++;\n }\n if (i >= code.length || code[i] !== \"{\") return null;\n const objStart = i;\n let depth = 0;\n while (i < code.length) {\n const ch = code[i];\n if (ch === '\"' || ch === \"'\") {\n // Skip a single- or double-quoted string literal, respecting backslash escapes.\n const quote = ch;\n i++;\n while (i < code.length) {\n const sc = code[i];\n if (sc === \"\\\\\") {\n i += 2; // skip escaped character\n } else if (sc === quote) {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else if (ch === \"`\") {\n // Skip a template literal, including ${...} interpolation blocks.\n // We need to track brace depth inside interpolations so that a `}`\n // that closes an interpolation isn't mistaken for closing the object.\n i++; // consume the opening backtick\n while (i < code.length) {\n const tc = code[i];\n if (tc === \"\\\\\") {\n i += 2; // skip escape sequence\n } else if (tc === \"`\") {\n i++; // end of template literal\n break;\n } else if (tc === \"$\" && code[i + 1] === \"{\") {\n // Enter a ${...} interpolation: scan forward tracking nested braces.\n i += 2; // consume '${'\n let exprDepth = 1;\n while (i < code.length && exprDepth > 0) {\n const ec = code[i];\n if (ec === \"{\") {\n exprDepth++;\n i++;\n } else if (ec === \"}\") {\n exprDepth--;\n i++;\n } else if (ec === '\"' || ec === \"'\") {\n // Quoted string inside interpolation — skip it\n const q = ec;\n i++;\n while (i < code.length) {\n if (code[i] === \"\\\\\") {\n i += 2;\n } else if (code[i] === q) {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else if (ec === \"`\") {\n // Nested template literal inside interpolation — skip it\n // (simple depth-1 skip; deeply nested templates are rare in font options)\n i++;\n while (i < code.length) {\n if (code[i] === \"\\\\\") {\n i += 2;\n } else if (code[i] === \"`\") {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else {\n i++;\n }\n }\n } else {\n i++;\n }\n }\n } else if (ch === \"{\") {\n depth++;\n i++;\n } else if (ch === \"}\") {\n depth--;\n i++;\n if (depth === 0) return [objStart, i];\n } else {\n i++;\n }\n }\n return null; // unbalanced\n}\n\n/**\n * Given the index just past the closing `}` of an options object, skip\n * optional whitespace and return the index after the closing `)`.\n * Returns `null` if the next non-whitespace character is not `)`.\n */\nexport function _findCallEnd(code: string, objEnd: number): number | null {\n let i = objEnd;\n while (\n i < code.length &&\n (code[i] === \" \" || code[i] === \"\\t\" || code[i] === \"\\n\" || code[i] === \"\\r\")\n ) {\n i++;\n }\n if (i >= code.length || code[i] !== \")\") return null;\n return i + 1;\n}\n\nexport function createGoogleFontsPlugin(fontGoogleShimPath: string, shimsDir: string): Plugin {\n // Vite does not bind `this` to the plugin object when calling hooks, so\n // plugin state must be held in closure variables rather than as properties.\n let isBuild = false;\n const fontCache = new Map<string, string>(); // url -> local @font-face CSS\n let cacheDir = \"\";\n\n return {\n name: \"vinext:google-fonts\",\n enforce: \"pre\",\n\n configResolved(config) {\n isBuild = config.command === \"build\";\n cacheDir = path.join(config.root, \".vinext\", \"fonts\");\n },\n\n transform: {\n // Hook filter: only invoke JS when code contains 'next/font/google'.\n // This still eliminates nearly all Rust-to-JS calls since very few files\n // import from next/font/google.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n },\n code: \"next/font/google\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/google\")) return null;\n if (id.startsWith(shimsDir)) return null;\n\n // Read the resolved `build.assetsDir` from the current Vite\n // environment so it can be closed over by the inner\n // `injectSelfHostedCss` helper (a plain function declaration\n // where `this` is untyped). Captured at the top of the hook so\n // a single handler invocation always threads one consistent\n // value through every font-loader call site it rewrites.\n const transformAssetsDir = this.environment?.config?.build?.assetsDir ?? DEFAULT_ASSETS_DIR;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let proxyImportCounter = 0;\n const overwrittenRanges: Array<[number, number]> = [];\n const fontLocals = new Map<string, string>();\n const proxyObjectLocals = new Set<string>();\n\n // The clause is a sequence of either a brace block (`\\{[^}]*?\\}` —\n // newlines allowed inside, but `[^}]` keeps it from spanning past\n // the matching close brace) or a single non-`;` non-`\\n` char.\n // Effect: multi-line bracket imports (Prettier wraps past\n // `printWidth`) match, but a preceding semicolon-less line\n // (e.g. `import type { Metadata } from 'next'`) can't be swallowed\n // into the clause via newline crossings. Both shapes used to fail\n // silently — the rewrite was skipped because the resulting clause\n // wasn't a valid single import.\n const importRe =\n /^[ \\t]*import\\s+((?:\\{[^}]*?\\}|[^;\\n])+?)\\s+from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let importMatch;\n while ((importMatch = importRe.exec(code)) !== null) {\n const [fullMatch, clause] = importMatch;\n const matchStart = importMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const parsed = parseGoogleFontImportClause(clause);\n const utilityImports = parsed.named.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontImports = parsed.named.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n\n if (parsed.defaultLocal) {\n proxyObjectLocals.add(parsed.defaultLocal);\n }\n for (const fontImport of fontImports) {\n fontLocals.set(fontImport.local, fontImport.imported);\n }\n\n if (fontImports.length > 0) {\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: Boolean(parsed.defaultLocal),\n fonts: Array.from(new Set(fontImports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityImports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `import ${clause} from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n continue;\n }\n\n if (parsed.namespaceLocal) {\n const proxyImportName = `__vinext_google_fonts_proxy_${proxyImportCounter++}`;\n const replacementLines = [\n `import ${proxyImportName} from ${JSON.stringify(fontGoogleShimPath)};`,\n ];\n if (parsed.defaultLocal) {\n replacementLines.push(`var ${parsed.defaultLocal} = ${proxyImportName};`);\n }\n replacementLines.push(`var ${parsed.namespaceLocal} = ${proxyImportName};`);\n s.overwrite(matchStart, matchEnd, replacementLines.join(\"\\n\"));\n overwrittenRanges.push([matchStart, matchEnd]);\n proxyObjectLocals.add(parsed.namespaceLocal);\n hasChanges = true;\n }\n }\n\n const exportRe = /^[ \\t]*export\\s*\\{([^}]+)\\}\\s*from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let exportMatch;\n while ((exportMatch = exportRe.exec(code)) !== null) {\n const [fullMatch, specifiers] = exportMatch;\n const matchStart = exportMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const namedExports = parseGoogleFontNamedSpecifiers(specifiers);\n const utilityExports = namedExports.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontExports = namedExports.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n if (fontExports.length === 0) continue;\n\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: false,\n fonts: Array.from(new Set(fontExports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityExports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `export { ${specifiers.trim()} } from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n }\n\n async function injectSelfHostedCss(\n callStart: number,\n callEnd: number,\n optionsStr: string,\n family: string,\n calleeSource: string,\n ) {\n // Parse options safely via AST — no eval/new Function\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let options: Record<string, any> = {};\n try {\n const parsed = parseStaticObjectLiteral(optionsStr);\n if (!parsed) return; // Contains dynamic expressions, skip\n options = parsed as Record<string, unknown>;\n } catch {\n return; // Can't parse options statically, skip\n }\n\n // Validate the call against the bundled Google Fonts metadata\n // and resolve the actual axis values. This replaces an earlier\n // inline URL builder that hardcoded `:wght@100..900` regardless\n // of the font's real `wght` axis range, which produced HTTP 400\n // for fonts whose axis is narrower (Sen 400..800, Anton 400).\n // See issue #885.\n let validated;\n try {\n validated = validateGoogleFontOptions(family, options);\n } catch (err) {\n // Validation errors are programmer errors (unknown family,\n // missing required weight on a static font, etc.). Re-throw\n // with the file path attached so Vite reports the offending\n // call site instead of a generic plugin error.\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`[vinext:google-fonts] ${id}: ${message}`);\n }\n const axes = getFontAxes(\n family,\n validated.weights,\n validated.styles,\n validated.selectedVariableAxes,\n );\n const cssUrl = buildGoogleFontsUrl(family, axes, validated.display);\n\n // Check cache\n let localCSS = fontCache.get(cssUrl);\n if (!localCSS) {\n try {\n localCSS = await fetchAndCacheFont(cssUrl, family, cacheDir);\n fontCache.set(cssUrl, localCSS);\n } catch (err) {\n if (err instanceof GoogleFontsHttpError) {\n // HTTP 4xx/5xx from Google means the URL is malformed or\n // the family/axis combination is invalid. Surface as a\n // build error so the user sees the failing URL plus\n // Google's response body, rather than silently falling\n // through to a CDN URL that ships the same bad request\n // to the browser.\n throw new Error(\n `[vinext:google-fonts] ${id}: Google Fonts returned HTTP ${err.status} for ${err.url}.\\n${formatGoogleFontsErrorBody(err.responseBody)}`,\n );\n }\n // Network errors (offline, DNS, AbortError) are recoverable;\n // skip self-hosting and let the runtime CDN path handle it.\n return;\n }\n }\n\n // Rewrite absolute `.vinext/fonts/` filesystem paths in the cached\n // CSS to served URLs under `/<assetsDir>/_vinext_fonts/` so the\n // embedded `_selfHostedCSS` string has origin-relative URLs that\n // the browser can actually resolve. The plugin's writeBundle hook\n // copies the referenced font files to the matching location under\n // the client output directory so the URLs serve 200s, not 404s.\n //\n // `transformAssetsDir` is captured at the top of the outer\n // transform handler (where `this.environment` is bound by\n // Rollup to the plugin context) and closed over here. This\n // keeps the embedded URL prefix in lockstep with the directory\n // the writeBundle hook copies files into, so a user who\n // customizes `build.assetsDir` (e.g. to `\"static\"`) sees both\n // the CSS and the copy target move together — otherwise the\n // rewritten URLs would 404 in production.\n const servedCSS = _rewriteCachedFontCssToServedUrls(\n localCSS,\n cacheDir,\n transformAssetsDir,\n );\n\n // Inject _selfHostedCSS into the options object\n const escapedCSS = JSON.stringify(servedCSS);\n const closingBrace = optionsStr.lastIndexOf(\"}\");\n const beforeBrace = optionsStr.slice(0, closingBrace).trim();\n // Determine the separator to insert before the new property:\n // - Empty string if the object is empty ({ is the last non-whitespace char)\n // - Empty string if there's already a trailing comma (avoid double comma)\n // - \", \" otherwise (before the new property)\n const separator = beforeBrace.endsWith(\"{\") || beforeBrace.endsWith(\",\") ? \"\" : \", \";\n const optionsWithCSS =\n optionsStr.slice(0, closingBrace) +\n separator +\n `_selfHostedCSS: ${escapedCSS}` +\n optionsStr.slice(closingBrace);\n\n const replacement = `${calleeSource}(${optionsWithCSS})`;\n s.overwrite(callStart, callEnd, replacement);\n overwrittenRanges.push([callStart, callEnd]);\n hasChanges = true;\n }\n\n if (isBuild) {\n // Match: Identifier( — where the argument starts with {\n // The regex intentionally does NOT capture the options object; we use\n // _findBalancedObject() to handle nested braces correctly.\n const namedCallRe = /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(?=\\{)/g;\n let namedCallMatch;\n while ((namedCallMatch = namedCallRe.exec(code)) !== null) {\n const [fullMatch, localName] = namedCallMatch;\n const importedName = fontLocals.get(localName);\n if (!importedName) continue;\n\n const callStart = namedCallMatch.index;\n // The regex consumed up to (but not including) the '{' due to the\n // lookahead — find the balanced object starting at the lookahead pos.\n const openParenEnd = callStart + fullMatch.length;\n const objRange = _findBalancedObject(code, openParenEnd);\n if (!objRange) continue;\n const optionsStr = code.slice(objRange[0], objRange[1]);\n const callEnd = _findCallEnd(code, objRange[1]);\n if (callEnd === null) continue;\n\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n importedName.replace(/_/g, \" \"),\n localName,\n );\n }\n\n // Match: Identifier.Identifier( — where the argument starts with {\n const memberCallRe =\n /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(?=\\{)/g;\n let memberCallMatch;\n while ((memberCallMatch = memberCallRe.exec(code)) !== null) {\n const [fullMatch, objectName, propName] = memberCallMatch;\n if (!proxyObjectLocals.has(objectName)) continue;\n\n const callStart = memberCallMatch.index;\n const openParenEnd = callStart + fullMatch.length;\n const objRange = _findBalancedObject(code, openParenEnd);\n if (!objRange) continue;\n const optionsStr = code.slice(objRange[0], objRange[1]);\n const callEnd = _findCallEnd(code, objRange[1]);\n if (callEnd === null) continue;\n\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n propertyNameToGoogleFontFamily(propName),\n `${objectName}.${propName}`,\n );\n }\n }\n\n if (!hasChanges) return null;\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n\n // Copy cached Google Font files into the client output so the served\n // URLs produced by `_rewriteCachedFontCssToServedUrls` resolve against\n // the origin. Runs once, at the end of the client environment's build.\n //\n // `fetchAndCacheFont` downloads files into `<root>/.vinext/fonts/` and\n // leaves them there — nothing else copies them. Without this hook, the\n // rewritten `/assets/_vinext_fonts/...` URLs would 404 in production.\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(outputOptions: { dir?: string }) {\n // Only copy on the client build — the server/SSR environments\n // don't serve static assets.\n //\n // Optional chaining on `this.environment` matches the convention\n // used by the other build-time plugins in `src/index.ts` (the\n // `vinext:precompress` and `vinext:cloudflare-build` plugins both\n // guard on `this.environment?.name !== \"client\"`). Vite 6+ always\n // populates `this.environment` inside writeBundle, but keeping\n // the guard makes the hook safely no-op if the code is ever\n // executed in a context where Rollup invokes it without a bound\n // environment (e.g. a thin unit test harness that invokes the\n // hook directly). Concretely: under normal Vite builds this\n // always resolves, the early-return is never taken.\n if (this.environment?.name !== \"client\") return;\n if (!cacheDir || !fs.existsSync(cacheDir)) return;\n const outDir = outputOptions.dir;\n if (!outDir) return;\n\n // Read the resolved `build.assetsDir` from the same environment\n // that the transform-time rewrite read it from, so the embedded\n // URL prefix and the physical copy location cannot diverge even\n // if a user customizes `build.assetsDir`.\n const assetsDir = this.environment.config?.build?.assetsDir ?? DEFAULT_ASSETS_DIR;\n const targetRoot = path.join(outDir, assetsDir, VINEXT_FONT_URL_NAMESPACE);\n\n // Recursive copy of every cached font file. Skip the companion\n // `style.css` artifact — that is only read by the build plugin\n // itself, never served at runtime.\n const stack: string[] = [cacheDir];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const src = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(src);\n continue;\n }\n if (!/\\.(woff2?|ttf|otf|eot)$/i.test(entry.name)) continue;\n const relative = path.relative(cacheDir, src);\n const dest = path.join(targetRoot, relative);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.copyFileSync(src, dest);\n }\n }\n },\n },\n } satisfies Plugin;\n}\n\n/**\n * Create the `vinext:local-fonts` Vite plugin.\n *\n * Rewrites relative font file paths in `next/font/local` calls into Vite\n * asset import references so that both dev (/@fs/...) and prod\n * (/assets/font-xxx.woff2) URLs resolve correctly.\n */\nexport function createLocalFontsPlugin(): Plugin {\n return {\n name: \"vinext:local-fonts\",\n enforce: \"pre\",\n\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"next/font/local\",\n },\n handler(code, id) {\n // Defensive guards — duplicate filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/local\")) return null;\n // Skip vinext's own font-local shim — it contains example paths\n // in comments that would be incorrectly rewritten.\n if (id.includes(\"font-local\")) return null;\n\n // Verify there's actually an import from next/font/local\n const importRe = /import\\s+\\w+\\s+from\\s*['\"]next\\/font\\/local['\"]/;\n if (!importRe.test(code)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let fontImportCounter = 0;\n const imports: string[] = [];\n\n // Match font file paths in `path: \"...\"` or `src: \"...\"` properties.\n // Captures: (1) property+colon prefix, (2) quote char, (3) the path.\n const fontPathRe = /((?:path|src)\\s*:\\s*)(['\"])([^'\"]+\\.(?:woff2?|ttf|otf|eot))\\2/g;\n\n let match;\n while ((match = fontPathRe.exec(code)) !== null) {\n const [fullMatch, prefix, _quote, fontPath] = match;\n const varName = `__vinext_local_font_${fontImportCounter++}`;\n\n // Add an import for this font file — Vite resolves it as a static\n // asset and returns the correct URL for both dev and prod.\n imports.push(`import ${varName} from ${JSON.stringify(fontPath)};`);\n\n // Replace: path: \"./font.woff2\" -> path: __vinext_local_font_0\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n s.overwrite(matchStart, matchEnd, `${prefix}${varName}`);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n // Prepend the asset imports at the top of the file\n s.prepend(imports.join(\"\\n\") + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } satisfies Plugin;\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,IAAM,uBAAN,cAAmC,MAAM;CACvC,YACE,KACA,QACA,cACA;AACA,QAAM,8BAA8B,OAAO,OAAO,MAAM;AAJxC,OAAA,MAAA;AACA,OAAA,SAAA;AACA,OAAA,eAAA;AAGhB,OAAK,OAAO;;;AAMhB,MAAa,uBAAuB;AACpC,MAAa,gCAAgC,OAAO;AAMpD,MAAM,8BAA8B,IAAI,IAAI;CAC1C;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;;;;;;;;;;AAmBF,MAAM,4BAA4B;AAClC,MAAM,qCAAqC;AAE3C,SAAS,2BAA2B,MAAsB;CACxD,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,QAAQ,UAAU,mCAAoC,QAAO;CACjE,MAAM,UAAU,QAAQ,SAAS;AACjC,QAAO,GAAG,QAAQ,MAAM,GAAG,mCAAmC,CAAC,mBAAmB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC5F,SAAgB,kCACd,KACA,UACA,YAAoB,oBACZ;AACR,KAAI,CAAC,YAAY,CAAC,IAAI,SAAS,SAAS,CAAE,QAAO;CACjD,MAAM,SAAS,aAAa;AAC5B,QAAO,IAAI,MAAM,SAAS,CAAC,KAAK,IAAI,OAAO,GAAG,4BAA4B;;;;;;;;;;;AAY5E,MAAM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
|
|
1
|
+
{"version":3,"file":"fonts.js","names":[],"sources":["../../src/plugins/fonts.ts"],"sourcesContent":["/**\n * vinext font plugins\n *\n * Exports two Vite plugins:\n *\n * `createGoogleFontsPlugin` — vinext:google-fonts\n * 1. Rewrites named `next/font/google` imports/exports to tiny virtual modules\n * that export only the requested fonts plus any utility exports. This lets us\n * delete the generated ~1,900-line runtime catalog while keeping ESM import\n * semantics intact.\n * 2. During production builds, fetches Google Fonts CSS + font files, caches\n * them locally under `.vinext/fonts/`, and injects `_selfHostedCSS` into\n * statically analyzable font loader calls so fonts are served from the\n * deployed origin rather than fonts.googleapis.com.\n *\n * `createLocalFontsPlugin` — vinext:local-fonts\n * When a source file calls localFont({ src: \"./font.woff2\" }) or\n * localFont({ src: [{ path: \"./font.woff2\" }] }), the relative paths\n * won't resolve in the browser because the CSS is injected at runtime.\n * This plugin rewrites those path strings into Vite asset import references\n * so that both dev (/@fs/...) and prod (/assets/font-xxx.woff2) URLs are\n * correct.\n */\n\nimport type { Plugin } from \"vite\";\nimport { parseAst } from \"vite\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport MagicString from \"magic-string\";\nimport { validateGoogleFontOptions } from \"../build/google-fonts/validate.js\";\nimport { getFontAxes } from \"../build/google-fonts/get-axes.js\";\nimport { buildGoogleFontsUrl } from \"../build/google-fonts/build-url.js\";\nimport { CONTENT_TYPES } from \"../server/static-file-cache.js\";\n\n/**\n * Thrown when Google Fonts returns a non-2xx response. Distinct from a raw\n * `fetch` rejection (network error, DNS failure, AbortError) so the call\n * site can decide whether to surface as a build error or fall through to\n * the runtime CDN path.\n */\nclass GoogleFontsHttpError extends Error {\n constructor(\n public readonly url: string,\n public readonly status: number,\n public readonly responseBody: string,\n ) {\n super(`Google Fonts returned HTTP ${status} for ${url}`);\n this.name = \"GoogleFontsHttpError\";\n }\n}\n\n// ── Virtual module IDs ────────────────────────────────────────────────────────\n\nexport const VIRTUAL_GOOGLE_FONTS = \"virtual:vinext-google-fonts\";\nexport const RESOLVED_VIRTUAL_GOOGLE_FONTS = \"\\0\" + VIRTUAL_GOOGLE_FONTS;\n\n// ── Constants ─────────────────────────────────────────────────────────────────\n\n// IMPORTANT: keep this set in sync with the non-default exports from\n// packages/vinext/src/shims/font-google.ts (and its re-export barrel).\nconst GOOGLE_FONT_UTILITY_EXPORTS = new Set([\n \"buildGoogleFontsUrl\",\n \"getSSRFontLinks\",\n \"getSSRFontStyles\",\n \"getSSRFontPreloads\",\n \"createFontLoader\",\n]);\n\n/**\n * Served URL prefix for self-hosted Google Font files.\n *\n * `fetchAndCacheFont()` downloads .woff2 files into `<root>/.vinext/fonts/`\n * and writes an `@font-face` CSS snippet whose `src: url(...)` references\n * the files by absolute filesystem path — convenient for disk, unusable at\n * runtime because browsers resolve relative to the origin. Before the CSS\n * is embedded in the bundle as `_selfHostedCSS`, the filesystem prefix is\n * rewritten to this URL prefix by `_rewriteCachedFontCssToServedUrls()`,\n * and the matching `writeBundle` hook in `createGoogleFontsPlugin` copies\n * the font files into `<clientOutDir>/<assetsDir>/_vinext_fonts/` so the\n * rewritten URL actually resolves against the origin at request time.\n *\n * The leading `_` keeps the namespace distinct from Vite's content-hashed\n * asset names (which are emitted flat into `<assetsDir>/`) and from any\n * user-provided public files.\n */\nconst VINEXT_FONT_URL_NAMESPACE = \"_vinext_fonts\";\nconst MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH = 500;\n\nfunction formatGoogleFontsErrorBody(body: string): string {\n const trimmed = body.trim();\n if (!trimmed) return \"(empty response body)\";\n if (trimmed.length <= MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH) return trimmed;\n const omitted = trimmed.length - MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH;\n return `${trimmed.slice(0, MAX_GOOGLE_FONTS_ERROR_BODY_LENGTH)}\\n... (truncated ${omitted} characters)`;\n}\n\n/**\n * Rewrite absolute filesystem paths in cached Google Fonts CSS so the\n * `@font-face { src: url(...) }` references point at the served URL the\n * plugin's `writeBundle` hook copies the font files to.\n *\n * This is called once per transform, before the CSS string is embedded in\n * the bundle as `_selfHostedCSS`. Every downstream consumer reads from the\n * same rewritten CSS: the injected `<style data-vinext-fonts>` block, the\n * HTML body's `<link rel=\"preload\">` tags (via `collectFontPreloadsFromCSS`\n * in `shims/font-google-base.ts`), and the HTTP `Link:` response header\n * (via `buildAppPageFontLinkHeader` in `server/app-page-execution.ts`).\n *\n * Without this rewrite, all three emit the dev-machine filesystem path\n * (e.g. `/home/user/project/.vinext/fonts/geist-<hash>/geist-<hash>.woff2`)\n * and any production request fetches `<origin>/home/user/...` → 404.\n *\n * `assetsDir` must match whatever Vite has resolved for\n * `build.assetsDir` on the client environment — otherwise the embedded\n * CSS URLs and the files emitted by the `writeBundle` hook would diverge\n * and a user who customizes `build.assetsDir` (e.g. to `\"static\"`) would\n * see 404s on every preload. The call site in `injectSelfHostedCss`\n * passes the resolved value through from plugin state. The default is\n * kept only so the exported helper can be driven directly from unit\n * tests without synthesizing a full plugin context.\n *\n * Uses split/join rather than regex because `cacheDir` is an absolute\n * filesystem path that may contain regex metacharacters on unusual\n * filesystems.\n */\nexport function _rewriteCachedFontCssToServedUrls(\n css: string,\n cacheDir: string,\n assetsDir: string = DEFAULT_ASSETS_DIR,\n): string {\n if (!cacheDir || !css.includes(cacheDir)) return css;\n const prefix = assetsDir || DEFAULT_ASSETS_DIR;\n return css.split(cacheDir).join(`/${prefix}/${VINEXT_FONT_URL_NAMESPACE}`);\n}\n\n/**\n * Default Vite `build.assetsDir` — mirrors Vite's own default. Used as\n * the fallback for the `assetsDir` parameter of\n * `_rewriteCachedFontCssToServedUrls` so the exported helper can be unit\n * tested without synthesizing plugin state. Production call sites thread\n * the real `envConfig.build.assetsDir` resolved by Vite through so that\n * the embedded CSS URLs always match the directory the `writeBundle`\n * hook copies the font files into.\n */\nconst DEFAULT_ASSETS_DIR = \"assets\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\ntype GoogleFontNamedSpecifier = {\n imported: string;\n local: string;\n isType: boolean;\n raw: string;\n};\n\n// ── Helpers shared with index.ts ──────────────────────────────────────────────\n\n/**\n * Safely parse a static JS object literal string into a plain object.\n * Uses Vite's parseAst (Rollup/acorn) so no code is ever evaluated.\n * Returns null if the expression contains anything dynamic (function calls,\n * template literals, identifiers, computed properties, etc.).\n *\n * Supports: string literals, numeric literals, boolean literals,\n * arrays of the above, and nested object literals.\n */\nexport function parseStaticObjectLiteral(objectStr: string): Record<string, unknown> | null {\n let ast: ReturnType<typeof parseAst>;\n try {\n // Wrap in parens so the parser treats `{…}` as an expression, not a block\n ast = parseAst(`(${objectStr})`);\n } catch {\n return null;\n }\n\n // The AST should be: Program > ExpressionStatement > ObjectExpression\n const body = ast.body;\n if (body.length !== 1 || body[0].type !== \"ExpressionStatement\") return null;\n\n const expr = body[0].expression;\n if (expr.type !== \"ObjectExpression\") return null;\n\n const result = extractStaticValue(expr);\n return result === undefined ? null : (result as Record<string, unknown>);\n}\n\n/**\n * Recursively extract a static value from an ESTree AST node.\n * Returns undefined (not null) if the node contains any dynamic expression.\n *\n * Uses `any` for the node parameter because Rollup's internal ESTree types\n * (estree.Expression, estree.ObjectExpression, etc.) aren't re-exported by Vite,\n * and the recursive traversal touches many different node shapes.\n */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractStaticValue(node: any): unknown {\n switch (node.type) {\n case \"Literal\":\n // String, number, boolean, null\n return node.value;\n\n case \"UnaryExpression\":\n // Handle negative numbers: -1, -3.14\n if (\n node.operator === \"-\" &&\n node.argument?.type === \"Literal\" &&\n typeof node.argument.value === \"number\"\n ) {\n return -node.argument.value;\n }\n return undefined;\n\n case \"ArrayExpression\": {\n const arr: unknown[] = [];\n for (const elem of node.elements) {\n if (!elem) return undefined; // sparse array\n const val = extractStaticValue(elem);\n if (val === undefined) return undefined;\n arr.push(val);\n }\n return arr;\n }\n\n case \"ObjectExpression\": {\n const obj: Record<string, unknown> = {};\n for (const prop of node.properties) {\n if (prop.type !== \"Property\") return undefined; // SpreadElement etc.\n if (prop.computed) return undefined; // [expr]: val\n\n // Key can be Identifier (unquoted) or Literal (quoted)\n let key: string;\n if (prop.key.type === \"Identifier\") {\n key = prop.key.name;\n } else if (prop.key.type === \"Literal\" && typeof prop.key.value === \"string\") {\n key = prop.key.value;\n } else {\n return undefined;\n }\n\n const val = extractStaticValue(prop.value);\n if (val === undefined) return undefined;\n obj[key] = val;\n }\n return obj;\n }\n\n default:\n // TemplateLiteral, CallExpression, Identifier, etc. — reject\n return undefined;\n }\n}\n\n// ── Virtual module encoding/decoding ─────────────────────────────────────────\n\nfunction encodeGoogleFontsVirtualId(payload: {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n}): string {\n const params = new URLSearchParams();\n if (payload.hasDefault) params.set(\"default\", \"1\");\n if (payload.fonts.length > 0) params.set(\"fonts\", payload.fonts.join(\",\"));\n if (payload.utilities.length > 0) params.set(\"utilities\", payload.utilities.join(\",\"));\n return `${VIRTUAL_GOOGLE_FONTS}?${params.toString()}`;\n}\n\nfunction parseGoogleFontsVirtualId(id: string): {\n hasDefault: boolean;\n fonts: string[];\n utilities: string[];\n} | null {\n const cleanId = id.startsWith(\"\\0\") ? id.slice(1) : id;\n if (!cleanId.startsWith(VIRTUAL_GOOGLE_FONTS)) return null;\n const queryIndex = cleanId.indexOf(\"?\");\n const params = new URLSearchParams(queryIndex === -1 ? \"\" : cleanId.slice(queryIndex + 1));\n return {\n hasDefault: params.get(\"default\") === \"1\",\n fonts:\n params\n .get(\"fonts\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n utilities:\n params\n .get(\"utilities\")\n ?.split(\",\")\n .map((value) => value.trim())\n .filter(Boolean) ?? [],\n };\n}\n\nexport function generateGoogleFontsVirtualModule(\n id: string,\n fontGoogleShimPath: string,\n): string | null {\n const payload = parseGoogleFontsVirtualId(id);\n if (!payload) return null;\n\n const utilities = Array.from(new Set(payload.utilities));\n const fonts = Array.from(new Set(payload.fonts));\n const lines: string[] = [];\n\n lines.push(`import { createFontLoader } from ${JSON.stringify(fontGoogleShimPath)};`);\n\n const reExports: string[] = [];\n if (payload.hasDefault) reExports.push(\"default\");\n reExports.push(...utilities);\n if (reExports.length > 0) {\n lines.push(`export { ${reExports.join(\", \")} } from ${JSON.stringify(fontGoogleShimPath)};`);\n }\n\n for (const fontName of fonts) {\n const family = fontName.replace(/_/g, \" \");\n lines.push(\n `export const ${fontName} = /*#__PURE__*/ createFontLoader(${JSON.stringify(family)});`,\n );\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ── Import clause parsers ─────────────────────────────────────────────────────\n\nfunction parseGoogleFontNamedSpecifiers(\n specifiersStr: string,\n forceType = false,\n): GoogleFontNamedSpecifier[] {\n return specifiersStr\n .split(\",\")\n .map((spec) => spec.trim())\n .filter(Boolean)\n .map((raw) => {\n const isType = forceType || raw.startsWith(\"type \");\n const valueSpec = isType ? raw.replace(/^type\\s+/, \"\") : raw;\n const asParts = valueSpec.split(/\\s+as\\s+/);\n const imported = asParts[0]?.trim() ?? \"\";\n const local = (asParts[1] || asParts[0] || \"\").trim();\n return { imported, local, isType, raw };\n })\n .filter((spec) => spec.imported.length > 0 && spec.local.length > 0);\n}\n\nfunction parseGoogleFontImportClause(clause: string): {\n defaultLocal: string | null;\n namespaceLocal: string | null;\n named: GoogleFontNamedSpecifier[];\n} {\n const trimmed = clause.trim();\n\n if (trimmed.startsWith(\"type \")) {\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart === -1 || braceEnd === -1) {\n return { defaultLocal: null, namespaceLocal: null, named: [] };\n }\n return {\n defaultLocal: null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd), true),\n };\n }\n\n const braceStart = trimmed.indexOf(\"{\");\n const braceEnd = trimmed.lastIndexOf(\"}\");\n if (braceStart !== -1 && braceEnd !== -1) {\n const beforeNamed = trimmed.slice(0, braceStart).trim().replace(/,\\s*$/, \"\").trim();\n return {\n defaultLocal: beforeNamed || null,\n namespaceLocal: null,\n named: parseGoogleFontNamedSpecifiers(trimmed.slice(braceStart + 1, braceEnd)),\n };\n }\n\n const commaIndex = trimmed.indexOf(\",\");\n if (commaIndex !== -1) {\n const defaultLocal = trimmed.slice(0, commaIndex).trim() || null;\n const rest = trimmed.slice(commaIndex + 1).trim();\n if (rest.startsWith(\"* as \")) {\n return {\n defaultLocal,\n namespaceLocal: rest.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n }\n\n if (trimmed.startsWith(\"* as \")) {\n return {\n defaultLocal: null,\n namespaceLocal: trimmed.slice(\"* as \".length).trim() || null,\n named: [],\n };\n }\n\n return {\n defaultLocal: trimmed || null,\n namespaceLocal: null,\n named: [],\n };\n}\n\nfunction propertyNameToGoogleFontFamily(prop: string): string {\n return prop.replace(/_/g, \" \").replace(/([a-z])([A-Z])/g, \"$1 $2\");\n}\n\n// ── Font fetching and caching ─────────────────────────────────────────────────\n\n/**\n * Fetch Google Fonts CSS, download .woff2 files, cache locally, and return\n * @font-face CSS with local file references.\n *\n * Cache dir structure: .vinext/fonts/<family-hash>/\n * - style.css (the rewritten @font-face CSS)\n * - *.woff2 (downloaded font files)\n */\nasync function fetchAndCacheFont(\n cssUrl: string,\n family: string,\n cacheDir: string,\n): Promise<string> {\n // Use a hash of the URL for the cache key\n const { createHash } = await import(\"node:crypto\");\n const urlHash = createHash(\"md5\").update(cssUrl).digest(\"hex\").slice(0, 12);\n const fontDir = path.join(cacheDir, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${urlHash}`);\n\n // Check if already cached\n const cachedCSSPath = path.join(fontDir, \"style.css\");\n if (fs.existsSync(cachedCSSPath)) {\n return fs.readFileSync(cachedCSSPath, \"utf-8\");\n }\n\n // Fetch CSS from Google Fonts (woff2 user-agent gives woff2 URLs)\n const cssResponse = await fetch(cssUrl, {\n headers: {\n \"User-Agent\":\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n },\n });\n if (!cssResponse.ok) {\n // Include the response body when Google rejected the request so the\n // caller can see why (the body usually contains a one-line CSS comment\n // identifying the bad axis or family).\n const body = await cssResponse.text().catch(() => \"\");\n throw new GoogleFontsHttpError(cssUrl, cssResponse.status, body);\n }\n let css = await cssResponse.text();\n\n // Extract all font file URLs\n const urlRe = /url\\((https:\\/\\/fonts\\.gstatic\\.com\\/[^)]+)\\)/g;\n const urls = new Map<string, string>(); // original URL -> local filename\n let urlMatch;\n while ((urlMatch = urlRe.exec(css)) !== null) {\n const fontUrl = urlMatch[1];\n if (!urls.has(fontUrl)) {\n const ext = fontUrl.includes(\".woff2\")\n ? \".woff2\"\n : fontUrl.includes(\".woff\")\n ? \".woff\"\n : \".ttf\";\n const fileHash = createHash(\"md5\").update(fontUrl).digest(\"hex\").slice(0, 8);\n urls.set(fontUrl, `${family.toLowerCase().replace(/\\s+/g, \"-\")}-${fileHash}${ext}`);\n }\n }\n\n // Download font files\n fs.mkdirSync(fontDir, { recursive: true });\n for (const [fontUrl, filename] of urls) {\n const filePath = path.join(fontDir, filename);\n if (!fs.existsSync(filePath)) {\n const fontResponse = await fetch(fontUrl);\n if (fontResponse.ok) {\n const buffer = Buffer.from(await fontResponse.arrayBuffer());\n fs.writeFileSync(filePath, buffer);\n }\n }\n // Rewrite every remote Google Fonts CDN URL in the cached CSS to the\n // absolute filesystem path of the locally-downloaded font file. This\n // cache file is read back by the plugin and then run through\n // `_rewriteCachedFontCssToServedUrls()` at embed time, which replaces\n // the absolute `cacheDir` prefix with the served URL namespace under\n // `/<assetsDir>/_vinext_fonts/`. The filesystem path is only the\n // on-disk intermediate form — it must never reach the bundle, the\n // injected `<style data-vinext-fonts>` block, the HTML `<link\n // rel=\"preload\">` tags, or the HTTP `Link:` response header. An\n // earlier version of this code claimed \"Vite will resolve /@fs/ for\n // dev, or asset for build\", which was never true: the CSS is\n // embedded as a JavaScript string literal and Vite's asset pipeline\n // does not scan string literals. Do not resurrect that assumption.\n css = css.split(fontUrl).join(filePath.replaceAll(\"\\\\\", \"/\"));\n }\n\n // Cache the rewritten CSS\n fs.writeFileSync(cachedCSSPath, css);\n return css;\n}\n\n// ── Plugin factories ──────────────────────────────────────────────────────────\n\n/**\n * Create the `vinext:google-fonts` Vite plugin.\n *\n * @param fontGoogleShimPath - Absolute path to the font-google shim module\n * (either `.ts` in source or `.js` in built packages). Resolved by the caller\n * so the plugin file has no dependency on `__dirname`.\n * @param shimsDir - Absolute path to the shims directory. Used to skip shim\n * files from transform (they contain `next/font/google` references that must\n * not be rewritten).\n */\n\n/**\n * Scan `code` forward from `searchStart` for a `{...}` object literal that\n * may contain arbitrarily nested braces. Returns `[objStart, objEnd]` where\n * `code[objStart] === '{'` and `code[objEnd - 1] === '}'`, or `null` if no\n * balanced object is found.\n *\n * String literals (single-quoted, double-quoted, and backtick template\n * literals including `${...}` interpolations) are fully skipped so that brace\n * characters inside string values do not affect the depth count.\n */\nexport function _findBalancedObject(code: string, searchStart: number): [number, number] | null {\n let i = searchStart;\n // Skip leading whitespace before the opening brace\n while (\n i < code.length &&\n (code[i] === \" \" || code[i] === \"\\t\" || code[i] === \"\\n\" || code[i] === \"\\r\")\n ) {\n i++;\n }\n if (i >= code.length || code[i] !== \"{\") return null;\n const objStart = i;\n let depth = 0;\n while (i < code.length) {\n const ch = code[i];\n if (ch === '\"' || ch === \"'\") {\n // Skip a single- or double-quoted string literal, respecting backslash escapes.\n const quote = ch;\n i++;\n while (i < code.length) {\n const sc = code[i];\n if (sc === \"\\\\\") {\n i += 2; // skip escaped character\n } else if (sc === quote) {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else if (ch === \"`\") {\n // Skip a template literal, including ${...} interpolation blocks.\n // We need to track brace depth inside interpolations so that a `}`\n // that closes an interpolation isn't mistaken for closing the object.\n i++; // consume the opening backtick\n while (i < code.length) {\n const tc = code[i];\n if (tc === \"\\\\\") {\n i += 2; // skip escape sequence\n } else if (tc === \"`\") {\n i++; // end of template literal\n break;\n } else if (tc === \"$\" && code[i + 1] === \"{\") {\n // Enter a ${...} interpolation: scan forward tracking nested braces.\n i += 2; // consume '${'\n let exprDepth = 1;\n while (i < code.length && exprDepth > 0) {\n const ec = code[i];\n if (ec === \"{\") {\n exprDepth++;\n i++;\n } else if (ec === \"}\") {\n exprDepth--;\n i++;\n } else if (ec === '\"' || ec === \"'\") {\n // Quoted string inside interpolation — skip it\n const q = ec;\n i++;\n while (i < code.length) {\n if (code[i] === \"\\\\\") {\n i += 2;\n } else if (code[i] === q) {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else if (ec === \"`\") {\n // Nested template literal inside interpolation — skip it\n // (simple depth-1 skip; deeply nested templates are rare in font options)\n i++;\n while (i < code.length) {\n if (code[i] === \"\\\\\") {\n i += 2;\n } else if (code[i] === \"`\") {\n i++;\n break;\n } else {\n i++;\n }\n }\n } else {\n i++;\n }\n }\n } else {\n i++;\n }\n }\n } else if (ch === \"{\") {\n depth++;\n i++;\n } else if (ch === \"}\") {\n depth--;\n i++;\n if (depth === 0) return [objStart, i];\n } else {\n i++;\n }\n }\n return null; // unbalanced\n}\n\n/**\n * Given the index just past the closing `}` of an options object, skip\n * optional whitespace and return the index after the closing `)`.\n * Returns `null` if the next non-whitespace character is not `)`.\n */\nexport function _findCallEnd(code: string, objEnd: number): number | null {\n let i = objEnd;\n while (\n i < code.length &&\n (code[i] === \" \" || code[i] === \"\\t\" || code[i] === \"\\n\" || code[i] === \"\\r\")\n ) {\n i++;\n }\n if (i >= code.length || code[i] !== \")\") return null;\n return i + 1;\n}\n\nexport function createGoogleFontsPlugin(fontGoogleShimPath: string, shimsDir: string): Plugin {\n // Vite does not bind `this` to the plugin object when calling hooks, so\n // plugin state must be held in closure variables rather than as properties.\n const fontCache = new Map<string, string>(); // url -> local @font-face CSS\n let cacheDir = \"\";\n\n return {\n name: \"vinext:google-fonts\",\n enforce: \"pre\",\n\n configResolved(config) {\n cacheDir = path.join(config.root, \".vinext\", \"fonts\");\n },\n\n // Dev-mode equivalent of the production `writeBundle` copy step. In dev\n // there is no client output directory to copy files into, so the cached\n // .vinext/fonts/ tree is served directly under the same URL prefix that\n // `_rewriteCachedFontCssToServedUrls()` embeds into the @font-face CSS\n // (`/<assetsDir>/_vinext_fonts/...`). Without this hook the rewritten\n // URLs 404 — and once `_selfHostedCSS` is injected, the shim no longer\n // emits the fonts.googleapis.com `<link>`, so a 404 here means no\n // glyphs render at all (no CDN fallback path).\n configureServer(server) {\n if (!cacheDir) return;\n const assetsDir =\n server.environments?.client?.config?.build?.assetsDir ??\n server.config?.build?.assetsDir ??\n DEFAULT_ASSETS_DIR;\n const urlPrefix = `/${assetsDir}/${VINEXT_FONT_URL_NAMESPACE}/`;\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (!url || !url.startsWith(urlPrefix)) return next();\n const rawPath = url.slice(urlPrefix.length).split(\"?\")[0];\n let decoded: string;\n try {\n decoded = decodeURIComponent(rawPath);\n } catch {\n return next();\n }\n const filePath = path.resolve(cacheDir, decoded);\n // Path traversal guard — `decoded` came from the URL, so refuse\n // anything that escapes the cache root (e.g. `..%2F..%2Fetc/passwd`).\n if (filePath !== cacheDir && !filePath.startsWith(cacheDir + path.sep)) {\n return next();\n }\n fs.stat(filePath, (err, stat) => {\n if (err || !stat.isFile()) return next();\n const ext = path.extname(filePath).toLowerCase();\n // CONTENT_TYPES is the same map prod-server uses, so fonts get\n // identical MIME types in dev and prod. fetchAndCacheFont only\n // ever writes .woff2/.woff/.ttf, all of which are covered.\n res.setHeader(\"Content-Type\", CONTENT_TYPES[ext] ?? \"application/octet-stream\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Access-Control-Allow-Origin\", \"*\");\n fs.createReadStream(filePath).pipe(res);\n });\n });\n },\n\n transform: {\n // Hook filter: only invoke JS when code contains 'next/font/google'.\n // This still eliminates nearly all Rust-to-JS calls since very few files\n // import from next/font/google.\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n },\n code: \"next/font/google\",\n },\n async handler(code, id) {\n // Defensive guard — duplicates filter logic\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/google\")) return null;\n if (id.startsWith(shimsDir)) return null;\n\n // Read the resolved `build.assetsDir` from the current Vite\n // environment so it can be closed over by the inner\n // `injectSelfHostedCss` helper (a plain function declaration\n // where `this` is untyped). Captured at the top of the hook so\n // a single handler invocation always threads one consistent\n // value through every font-loader call site it rewrites.\n const transformAssetsDir = this.environment?.config?.build?.assetsDir ?? DEFAULT_ASSETS_DIR;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let proxyImportCounter = 0;\n const overwrittenRanges: Array<[number, number]> = [];\n const fontLocals = new Map<string, string>();\n const proxyObjectLocals = new Set<string>();\n\n // The clause is a sequence of either a brace block (`\\{[^}]*?\\}` —\n // newlines allowed inside, but `[^}]` keeps it from spanning past\n // the matching close brace) or a single non-`;` non-`\\n` char.\n // Effect: multi-line bracket imports (Prettier wraps past\n // `printWidth`) match, but a preceding semicolon-less line\n // (e.g. `import type { Metadata } from 'next'`) can't be swallowed\n // into the clause via newline crossings. Both shapes used to fail\n // silently — the rewrite was skipped because the resulting clause\n // wasn't a valid single import.\n const importRe =\n /^[ \\t]*import\\s+((?:\\{[^}]*?\\}|[^;\\n])+?)\\s+from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let importMatch;\n while ((importMatch = importRe.exec(code)) !== null) {\n const [fullMatch, clause] = importMatch;\n const matchStart = importMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const parsed = parseGoogleFontImportClause(clause);\n const utilityImports = parsed.named.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontImports = parsed.named.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n\n if (parsed.defaultLocal) {\n proxyObjectLocals.add(parsed.defaultLocal);\n }\n for (const fontImport of fontImports) {\n fontLocals.set(fontImport.local, fontImport.imported);\n }\n\n if (fontImports.length > 0) {\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: Boolean(parsed.defaultLocal),\n fonts: Array.from(new Set(fontImports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityImports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `import ${clause} from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n continue;\n }\n\n if (parsed.namespaceLocal) {\n const proxyImportName = `__vinext_google_fonts_proxy_${proxyImportCounter++}`;\n const replacementLines = [\n `import ${proxyImportName} from ${JSON.stringify(fontGoogleShimPath)};`,\n ];\n if (parsed.defaultLocal) {\n replacementLines.push(`var ${parsed.defaultLocal} = ${proxyImportName};`);\n }\n replacementLines.push(`var ${parsed.namespaceLocal} = ${proxyImportName};`);\n s.overwrite(matchStart, matchEnd, replacementLines.join(\"\\n\"));\n overwrittenRanges.push([matchStart, matchEnd]);\n proxyObjectLocals.add(parsed.namespaceLocal);\n hasChanges = true;\n }\n }\n\n const exportRe = /^[ \\t]*export\\s*\\{([^}]+)\\}\\s*from\\s*([\"'])next\\/font\\/google\\2\\s*;?/gm;\n let exportMatch;\n while ((exportMatch = exportRe.exec(code)) !== null) {\n const [fullMatch, specifiers] = exportMatch;\n const matchStart = exportMatch.index;\n const matchEnd = matchStart + fullMatch.length;\n const namedExports = parseGoogleFontNamedSpecifiers(specifiers);\n const utilityExports = namedExports.filter(\n (spec) => !spec.isType && GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n const fontExports = namedExports.filter(\n (spec) => !spec.isType && !GOOGLE_FONT_UTILITY_EXPORTS.has(spec.imported),\n );\n if (fontExports.length === 0) continue;\n\n const virtualId = encodeGoogleFontsVirtualId({\n hasDefault: false,\n fonts: Array.from(new Set(fontExports.map((spec) => spec.imported))),\n utilities: Array.from(new Set(utilityExports.map((spec) => spec.imported))),\n });\n s.overwrite(\n matchStart,\n matchEnd,\n `export { ${specifiers.trim()} } from ${JSON.stringify(virtualId)};`,\n );\n overwrittenRanges.push([matchStart, matchEnd]);\n hasChanges = true;\n }\n\n async function injectSelfHostedCss(\n callStart: number,\n callEnd: number,\n optionsStr: string,\n family: string,\n calleeSource: string,\n ) {\n // Parse options safely via AST — no eval/new Function\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let options: Record<string, any> = {};\n try {\n const parsed = parseStaticObjectLiteral(optionsStr);\n if (!parsed) return; // Contains dynamic expressions, skip\n options = parsed as Record<string, unknown>;\n } catch {\n return; // Can't parse options statically, skip\n }\n\n // Validate the call against the bundled Google Fonts metadata\n // and resolve the actual axis values. This replaces an earlier\n // inline URL builder that hardcoded `:wght@100..900` regardless\n // of the font's real `wght` axis range, which produced HTTP 400\n // for fonts whose axis is narrower (Sen 400..800, Anton 400).\n // See issue #885.\n let validated;\n try {\n validated = validateGoogleFontOptions(family, options);\n } catch (err) {\n // Validation errors are programmer errors (unknown family,\n // missing required weight on a static font, etc.). Re-throw\n // with the file path attached so Vite reports the offending\n // call site instead of a generic plugin error.\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`[vinext:google-fonts] ${id}: ${message}`);\n }\n const axes = getFontAxes(\n family,\n validated.weights,\n validated.styles,\n validated.selectedVariableAxes,\n );\n const cssUrl = buildGoogleFontsUrl(family, axes, validated.display);\n\n // Check cache\n let localCSS = fontCache.get(cssUrl);\n if (!localCSS) {\n try {\n localCSS = await fetchAndCacheFont(cssUrl, family, cacheDir);\n fontCache.set(cssUrl, localCSS);\n } catch (err) {\n if (err instanceof GoogleFontsHttpError) {\n // HTTP 4xx/5xx from Google means the URL is malformed or\n // the family/axis combination is invalid. Surface as a\n // build error so the user sees the failing URL plus\n // Google's response body, rather than silently falling\n // through to a CDN URL that ships the same bad request\n // to the browser.\n throw new Error(\n `[vinext:google-fonts] ${id}: Google Fonts returned HTTP ${err.status} for ${err.url}.\\n${formatGoogleFontsErrorBody(err.responseBody)}`,\n );\n }\n // Network errors (offline, DNS, AbortError) are recoverable;\n // skip self-hosting and let the runtime CDN path handle it.\n return;\n }\n }\n\n // Rewrite absolute `.vinext/fonts/` filesystem paths in the cached\n // CSS to served URLs under `/<assetsDir>/_vinext_fonts/` so the\n // embedded `_selfHostedCSS` string has origin-relative URLs that\n // the browser can actually resolve. The plugin's writeBundle hook\n // copies the referenced font files to the matching location under\n // the client output directory so the URLs serve 200s, not 404s.\n //\n // `transformAssetsDir` is captured at the top of the outer\n // transform handler (where `this.environment` is bound by\n // Rollup to the plugin context) and closed over here. This\n // keeps the embedded URL prefix in lockstep with the directory\n // the writeBundle hook copies files into, so a user who\n // customizes `build.assetsDir` (e.g. to `\"static\"`) sees both\n // the CSS and the copy target move together — otherwise the\n // rewritten URLs would 404 in production.\n const servedCSS = _rewriteCachedFontCssToServedUrls(\n localCSS,\n cacheDir,\n transformAssetsDir,\n );\n\n // Inject _selfHostedCSS into the options object\n const escapedCSS = JSON.stringify(servedCSS);\n const closingBrace = optionsStr.lastIndexOf(\"}\");\n const beforeBrace = optionsStr.slice(0, closingBrace).trim();\n // Determine the separator to insert before the new property:\n // - Empty string if the object is empty ({ is the last non-whitespace char)\n // - Empty string if there's already a trailing comma (avoid double comma)\n // - \", \" otherwise (before the new property)\n const separator = beforeBrace.endsWith(\"{\") || beforeBrace.endsWith(\",\") ? \"\" : \", \";\n const optionsWithCSS =\n optionsStr.slice(0, closingBrace) +\n separator +\n `_selfHostedCSS: ${escapedCSS}` +\n optionsStr.slice(closingBrace);\n\n const replacement = `${calleeSource}(${optionsWithCSS})`;\n s.overwrite(callStart, callEnd, replacement);\n overwrittenRanges.push([callStart, callEnd]);\n hasChanges = true;\n }\n\n // Self-host injection runs in both dev and build. In dev, the\n // companion `configureServer` hook serves the cached files\n // directly from `.vinext/fonts/` so the rewritten URLs resolve\n // against the dev origin; in build, the `writeBundle` hook copies\n // them into the client output directory.\n\n // Match: Identifier( — where the argument starts with {\n // The regex intentionally does NOT capture the options object; we use\n // _findBalancedObject() to handle nested braces correctly.\n const namedCallRe = /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(?=\\{)/g;\n let namedCallMatch;\n while ((namedCallMatch = namedCallRe.exec(code)) !== null) {\n const [fullMatch, localName] = namedCallMatch;\n const importedName = fontLocals.get(localName);\n if (!importedName) continue;\n\n const callStart = namedCallMatch.index;\n // The regex consumed up to (but not including) the '{' due to the\n // lookahead — find the balanced object starting at the lookahead pos.\n const openParenEnd = callStart + fullMatch.length;\n const objRange = _findBalancedObject(code, openParenEnd);\n if (!objRange) continue;\n const optionsStr = code.slice(objRange[0], objRange[1]);\n const callEnd = _findCallEnd(code, objRange[1]);\n if (callEnd === null) continue;\n\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n importedName.replace(/_/g, \" \"),\n localName,\n );\n }\n\n // Match: Identifier.Identifier( — where the argument starts with {\n const memberCallRe =\n /\\b([A-Za-z_$][A-Za-z0-9_$]*)\\.([A-Za-z_$][A-Za-z0-9_$]*)\\s*\\(\\s*(?=\\{)/g;\n let memberCallMatch;\n while ((memberCallMatch = memberCallRe.exec(code)) !== null) {\n const [fullMatch, objectName, propName] = memberCallMatch;\n if (!proxyObjectLocals.has(objectName)) continue;\n\n const callStart = memberCallMatch.index;\n const openParenEnd = callStart + fullMatch.length;\n const objRange = _findBalancedObject(code, openParenEnd);\n if (!objRange) continue;\n const optionsStr = code.slice(objRange[0], objRange[1]);\n const callEnd = _findCallEnd(code, objRange[1]);\n if (callEnd === null) continue;\n\n if (overwrittenRanges.some(([start, end]) => callStart < end && callEnd > start)) {\n continue;\n }\n\n await injectSelfHostedCss(\n callStart,\n callEnd,\n optionsStr,\n propertyNameToGoogleFontFamily(propName),\n `${objectName}.${propName}`,\n );\n }\n\n if (!hasChanges) return null;\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n\n // Copy cached Google Font files into the client output so the served\n // URLs produced by `_rewriteCachedFontCssToServedUrls` resolve against\n // the origin. Runs once, at the end of the client environment's build.\n //\n // `fetchAndCacheFont` downloads files into `<root>/.vinext/fonts/` and\n // leaves them there — nothing else copies them. Without this hook, the\n // rewritten `/assets/_vinext_fonts/...` URLs would 404 in production.\n writeBundle: {\n sequential: true,\n order: \"post\" as const,\n handler(outputOptions: { dir?: string }) {\n // Only copy on the client build — the server/SSR environments\n // don't serve static assets.\n //\n // Optional chaining on `this.environment` matches the convention\n // used by the other build-time plugins in `src/index.ts` (the\n // `vinext:precompress` and `vinext:cloudflare-build` plugins both\n // guard on `this.environment?.name !== \"client\"`). Vite 6+ always\n // populates `this.environment` inside writeBundle, but keeping\n // the guard makes the hook safely no-op if the code is ever\n // executed in a context where Rollup invokes it without a bound\n // environment (e.g. a thin unit test harness that invokes the\n // hook directly). Concretely: under normal Vite builds this\n // always resolves, the early-return is never taken.\n if (this.environment?.name !== \"client\") return;\n if (!cacheDir || !fs.existsSync(cacheDir)) return;\n const outDir = outputOptions.dir;\n if (!outDir) return;\n\n // Read the resolved `build.assetsDir` from the same environment\n // that the transform-time rewrite read it from, so the embedded\n // URL prefix and the physical copy location cannot diverge even\n // if a user customizes `build.assetsDir`.\n const assetsDir = this.environment.config?.build?.assetsDir ?? DEFAULT_ASSETS_DIR;\n const targetRoot = path.join(outDir, assetsDir, VINEXT_FONT_URL_NAMESPACE);\n\n // Recursive copy of every cached font file. Skip the companion\n // `style.css` artifact — that is only read by the build plugin\n // itself, never served at runtime.\n const stack: string[] = [cacheDir];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n const src = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(src);\n continue;\n }\n if (!/\\.(woff2?|ttf|otf|eot)$/i.test(entry.name)) continue;\n const relative = path.relative(cacheDir, src);\n const dest = path.join(targetRoot, relative);\n fs.mkdirSync(path.dirname(dest), { recursive: true });\n fs.copyFileSync(src, dest);\n }\n }\n },\n },\n } satisfies Plugin;\n}\n\n/**\n * Create the `vinext:local-fonts` Vite plugin.\n *\n * Rewrites relative font file paths in `next/font/local` calls into Vite\n * asset import references so that both dev (/@fs/...) and prod\n * (/assets/font-xxx.woff2) URLs resolve correctly.\n */\nexport function createLocalFontsPlugin(): Plugin {\n return {\n name: \"vinext:local-fonts\",\n enforce: \"pre\",\n\n transform: {\n filter: {\n id: {\n include: /\\.(tsx?|jsx?|mjs)$/,\n exclude: /node_modules/,\n },\n code: \"next/font/local\",\n },\n handler(code, id) {\n // Defensive guards — duplicate filter logic\n if (id.includes(\"node_modules\")) return null;\n if (id.startsWith(\"\\0\")) return null;\n if (!id.match(/\\.(tsx?|jsx?|mjs)$/)) return null;\n if (!code.includes(\"next/font/local\")) return null;\n // Skip vinext's own font-local shim — it contains example paths\n // in comments that would be incorrectly rewritten.\n if (id.includes(\"font-local\")) return null;\n\n // Verify there's actually an import from next/font/local\n const importRe = /import\\s+\\w+\\s+from\\s*['\"]next\\/font\\/local['\"]/;\n if (!importRe.test(code)) return null;\n\n const s = new MagicString(code);\n let hasChanges = false;\n let fontImportCounter = 0;\n const imports: string[] = [];\n\n // Match font file paths in `path: \"...\"` or `src: \"...\"` properties.\n // Captures: (1) property+colon prefix, (2) quote char, (3) the path.\n const fontPathRe = /((?:path|src)\\s*:\\s*)(['\"])([^'\"]+\\.(?:woff2?|ttf|otf|eot))\\2/g;\n\n let match;\n while ((match = fontPathRe.exec(code)) !== null) {\n const [fullMatch, prefix, _quote, fontPath] = match;\n const varName = `__vinext_local_font_${fontImportCounter++}`;\n\n // Add an import for this font file — Vite resolves it as a static\n // asset and returns the correct URL for both dev and prod.\n imports.push(`import ${varName} from ${JSON.stringify(fontPath)};`);\n\n // Replace: path: \"./font.woff2\" -> path: __vinext_local_font_0\n const matchStart = match.index;\n const matchEnd = matchStart + fullMatch.length;\n s.overwrite(matchStart, matchEnd, `${prefix}${varName}`);\n hasChanges = true;\n }\n\n if (!hasChanges) return null;\n\n // Prepend the asset imports at the top of the file\n s.prepend(imports.join(\"\\n\") + \"\\n\");\n\n return {\n code: s.toString(),\n map: s.generateMap({ hires: \"boundary\" }),\n };\n },\n },\n } satisfies Plugin;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,IAAM,uBAAN,cAAmC,MAAM;CACvC,YACE,KACA,QACA,cACA;AACA,QAAM,8BAA8B,OAAO,OAAO,MAAM;AAJxC,OAAA,MAAA;AACA,OAAA,SAAA;AACA,OAAA,eAAA;AAGhB,OAAK,OAAO;;;AAMhB,MAAa,uBAAuB;AACpC,MAAa,gCAAgC,OAAO;AAMpD,MAAM,8BAA8B,IAAI,IAAI;CAC1C;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;;;;;;;;;;;;;AAmBF,MAAM,4BAA4B;AAClC,MAAM,qCAAqC;AAE3C,SAAS,2BAA2B,MAAsB;CACxD,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,CAAC,QAAS,QAAO;AACrB,KAAI,QAAQ,UAAU,mCAAoC,QAAO;CACjE,MAAM,UAAU,QAAQ,SAAS;AACjC,QAAO,GAAG,QAAQ,MAAM,GAAG,mCAAmC,CAAC,mBAAmB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC5F,SAAgB,kCACd,KACA,UACA,YAAoB,oBACZ;AACR,KAAI,CAAC,YAAY,CAAC,IAAI,SAAS,SAAS,CAAE,QAAO;CACjD,MAAM,SAAS,aAAa;AAC5B,QAAO,IAAI,MAAM,SAAS,CAAC,KAAK,IAAI,OAAO,GAAG,4BAA4B;;;;;;;;;;;AAY5E,MAAM,qBAAqB;;;;;;;;;;AAsB3B,SAAgB,yBAAyB,WAAmD;CAC1F,IAAI;AACJ,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AkB,CAAE,QAAO;AAG9C,QAAI,GAAG,SAAS,aAAa,CAAE,QAAO;AAItC,QAAI,CADa,kDACH,KAAK,KAAK,CAAE,QAAO;IAEjC,MAAM,IAAI,IAAI,YAAY,KAAK;IAC/B,IAAI,aAAa;IACjB,IAAI,oBAAoB;IACxB,MAAM,UAAoB,EAAE;IAI5B,MAAM,aAAa;IAEnB,IAAI;AACJ,YAAQ,QAAQ,WAAW,KAAK,KAAK,MAAM,MAAM;KAC/C,MAAM,CAAC,WAAW,QAAQ,QAAQ,YAAY;KAC9C,MAAM,UAAU,uBAAuB;AAIvC,aAAQ,KAAK,UAAU,QAAQ,QAAQ,KAAK,UAAU,SAAS,CAAC,GAAG;KAGnE,MAAM,aAAa,MAAM;KACzB,MAAM,WAAW,aAAa,UAAU;AACxC,OAAE,UAAU,YAAY,UAAU,GAAG,SAAS,UAAU;AACxD,kBAAa;;AAGf,QAAI,CAAC,WAAY,QAAO;AAGxB,MAAE,QAAQ,QAAQ,KAAK,KAAK,GAAG,KAAK;AAEpC,WAAO;KACL,MAAM,EAAE,UAAU;KAClB,KAAK,EAAE,YAAY,EAAE,OAAO,YAAY,CAAC;KAC1C;;GAEJ;EACF"}
|
|
@@ -11,6 +11,7 @@ const RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([
|
|
|
11
11
|
const VINEXT_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([
|
|
12
12
|
"vinext",
|
|
13
13
|
"@vercel/og",
|
|
14
|
+
"private-next-instrumentation-client",
|
|
14
15
|
...RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE
|
|
15
16
|
]);
|
|
16
17
|
function mergeOptimizeDepsExclude(...excludeGroups) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rsc-client-shim-excludes.js","names":[],"sources":["../../src/plugins/rsc-client-shim-excludes.ts"],"sourcesContent":["const RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([\n // @vitejs/plugin-rsc tracks package client references by the original\n // bare source. If Vite pre-bundles these known client shims, the generated\n // client-package proxy can lose the matching export metadata in dev.\n \"vinext/shims/error-boundary\",\n \"vinext/shims/form\",\n \"vinext/shims/layout-segment-context\",\n \"vinext/shims/link\",\n \"vinext/shims/script\",\n \"vinext/shims/slot\",\n \"vinext/shims/offline\",\n]);\n\nexport const VINEXT_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([\n \"vinext\",\n \"@vercel/og\",\n ...RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE,\n]);\n\nexport function mergeOptimizeDepsExclude(\n ...excludeGroups: readonly (readonly string[])[]\n): string[] {\n const seen = new Set<string>();\n\n for (const group of excludeGroups) {\n for (const entry of group) {\n if (seen.has(entry)) continue;\n seen.add(entry);\n }\n }\n\n return [...seen];\n}\n"],"mappings":";AAAA,MAAM,wCAAwC,OAAO,OAAO;CAI1D;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAa,+BAA+B,OAAO,OAAO;CACxD;CACA;CACA,GAAG;CACJ,CAAC;AAEF,SAAgB,yBACd,GAAG,eACO;CACV,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,cAClB,MAAK,MAAM,SAAS,OAAO;AACzB,MAAI,KAAK,IAAI,MAAM,CAAE;AACrB,OAAK,IAAI,MAAM;;AAInB,QAAO,CAAC,GAAG,KAAK"}
|
|
1
|
+
{"version":3,"file":"rsc-client-shim-excludes.js","names":[],"sources":["../../src/plugins/rsc-client-shim-excludes.ts"],"sourcesContent":["const RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([\n // @vitejs/plugin-rsc tracks package client references by the original\n // bare source. If Vite pre-bundles these known client shims, the generated\n // client-package proxy can lose the matching export metadata in dev.\n \"vinext/shims/error-boundary\",\n \"vinext/shims/form\",\n \"vinext/shims/layout-segment-context\",\n \"vinext/shims/link\",\n \"vinext/shims/script\",\n \"vinext/shims/slot\",\n \"vinext/shims/offline\",\n]);\n\nexport const VINEXT_OPTIMIZE_DEPS_EXCLUDE = Object.freeze([\n \"vinext\",\n \"@vercel/og\",\n // Aliased to the user's instrumentation-client source file (or an empty\n // shim). Not a real npm dep, so pre-bundling it would break HMR and cause\n // a \"new dependencies optimized\" reload on the first request.\n \"private-next-instrumentation-client\",\n ...RSC_CLIENT_SHIM_OPTIMIZE_DEPS_EXCLUDE,\n]);\n\nexport function mergeOptimizeDepsExclude(\n ...excludeGroups: readonly (readonly string[])[]\n): string[] {\n const seen = new Set<string>();\n\n for (const group of excludeGroups) {\n for (const entry of group) {\n if (seen.has(entry)) continue;\n seen.add(entry);\n }\n }\n\n return [...seen];\n}\n"],"mappings":";AAAA,MAAM,wCAAwC,OAAO,OAAO;CAI1D;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAa,+BAA+B,OAAO,OAAO;CACxD;CACA;CAIA;CACA,GAAG;CACJ,CAAC;AAEF,SAAgB,yBACd,GAAG,eACO;CACV,MAAM,uBAAO,IAAI,KAAa;AAE9B,MAAK,MAAM,SAAS,cAClB,MAAK,MAAM,SAAS,OAAO;AACzB,MAAI,KAAK,IAAI,MAAM,CAAE;AACrB,OAAK,IAAI,MAAM;;AAInB,QAAO,CAAC,GAAG,KAAK"}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { ValidFileMatcher } from "./file-matcher.js";
|
|
2
|
+
|
|
3
|
+
//#region src/routing/app-route-graph.d.ts
|
|
4
|
+
type InterceptingRoute = {
|
|
5
|
+
/** The interception convention: "." | ".." | "../.." | "..." */convention: string; /** The URL pattern this intercepts (e.g. "/photos/:id") */
|
|
6
|
+
targetPattern: string; /** Absolute path to the intercepting page component */
|
|
7
|
+
pagePath: string; /** Absolute layout paths inside the intercepting route tree, outermost to innermost */
|
|
8
|
+
layoutPaths: string[]; /** Parameter names for dynamic segments */
|
|
9
|
+
params: string[];
|
|
10
|
+
};
|
|
11
|
+
type ParallelSlot = {
|
|
12
|
+
/** Stable slot identity (name + owning directory), used for route serialization keys. */key: string; /** Slot name (e.g. "team" from @team) */
|
|
13
|
+
name: string; /** Absolute path to the @slot directory that owns this slot. Internal routing metadata. */
|
|
14
|
+
ownerDir: string; /** Absolute path to the slot's page component */
|
|
15
|
+
pagePath: string | null; /** Absolute path to the slot's default.tsx fallback */
|
|
16
|
+
defaultPath: string | null; /** Absolute path to the slot's layout component (wraps slot content) */
|
|
17
|
+
layoutPath: string | null; /** Absolute path to the slot's loading component */
|
|
18
|
+
loadingPath: string | null; /** Absolute path to the slot's error component */
|
|
19
|
+
errorPath: string | null; /** Intercepting routes within this slot */
|
|
20
|
+
interceptingRoutes: InterceptingRoute[];
|
|
21
|
+
/**
|
|
22
|
+
* The layout index (0-based, in route.layouts[]) that this slot belongs to.
|
|
23
|
+
* Slots are passed as props to the layout at their directory level, not
|
|
24
|
+
* necessarily the innermost layout. -1 means "innermost" (legacy default).
|
|
25
|
+
*/
|
|
26
|
+
layoutIndex: number;
|
|
27
|
+
/**
|
|
28
|
+
* Filesystem segments from the slot's root directory to its active page.
|
|
29
|
+
* Used at render time to compute segments for useSelectedLayoutSegment(slotName).
|
|
30
|
+
* For a page at the slot root (@team/page.tsx), this is [].
|
|
31
|
+
* For a sub-page (@team/members/page.tsx), this is ["members"].
|
|
32
|
+
* null when the slot has no active page (showing default.tsx fallback).
|
|
33
|
+
*/
|
|
34
|
+
routeSegments: string[] | null;
|
|
35
|
+
/**
|
|
36
|
+
* Full URL pattern parts for the slot's active page (owner prefix +
|
|
37
|
+
* slot-relative pattern). Set when an inherited slot mirrors a sub-page
|
|
38
|
+
* whose param names may differ from the route's. The runtime matches the
|
|
39
|
+
* request URL against these parts to extract slot-specific params.
|
|
40
|
+
*/
|
|
41
|
+
slotPatternParts?: string[];
|
|
42
|
+
/**
|
|
43
|
+
* Param names captured by `slotPatternParts`, in order of appearance.
|
|
44
|
+
* Used at runtime to decide whether to extract slot-specific params or
|
|
45
|
+
* reuse the route's matched params.
|
|
46
|
+
*/
|
|
47
|
+
slotParamNames?: string[];
|
|
48
|
+
};
|
|
49
|
+
type AppRoute = {
|
|
50
|
+
/** URL pattern, e.g. "/" or "/about" or "/blog/:slug" */pattern: string; /** Absolute file path to the page component */
|
|
51
|
+
pagePath: string | null; /** Absolute file path to the route handler (route.ts) */
|
|
52
|
+
routePath: string | null; /** Ordered list of layout files from root to leaf */
|
|
53
|
+
layouts: string[]; /** Ordered list of all discovered template files from root to leaf (not necessarily aligned 1:1 with layouts) */
|
|
54
|
+
templates: string[]; /** Parallel route slots (from @slot directories at the route's directory level) */
|
|
55
|
+
parallelSlots: ParallelSlot[]; /** Loading component path */
|
|
56
|
+
loadingPath: string | null; /** Error component path (leaf directory only) */
|
|
57
|
+
errorPath: string | null;
|
|
58
|
+
/**
|
|
59
|
+
* Per-layout error boundary paths, aligned with the layouts array.
|
|
60
|
+
* Each entry is the error.tsx at the same directory level as the
|
|
61
|
+
* corresponding layout (or null if that level has no error.tsx).
|
|
62
|
+
* Used to interleave ErrorBoundary components with layouts so that
|
|
63
|
+
* ancestor error boundaries catch errors from descendant segments.
|
|
64
|
+
*/
|
|
65
|
+
layoutErrorPaths: (string | null)[]; /** Not-found component path (nearest, walking up from page dir) */
|
|
66
|
+
notFoundPath: string | null;
|
|
67
|
+
/**
|
|
68
|
+
* Not-found component paths per layout level (aligned with layouts array).
|
|
69
|
+
* Each entry is the not-found.tsx at that layout's directory, or null.
|
|
70
|
+
* Used to create per-layout NotFoundBoundary so that notFound() thrown from
|
|
71
|
+
* a layout is caught by the parent layout's boundary (matching Next.js behavior).
|
|
72
|
+
*/
|
|
73
|
+
notFoundPaths: (string | null)[];
|
|
74
|
+
/**
|
|
75
|
+
* Forbidden component paths per layout level (aligned with layouts array).
|
|
76
|
+
* Each entry is the forbidden.tsx at that layout's directory, or null.
|
|
77
|
+
* Used to create per-layout ForbiddenBoundary.
|
|
78
|
+
*/
|
|
79
|
+
forbiddenPaths: (string | null)[]; /** Forbidden component path (403) at the route's directory level */
|
|
80
|
+
forbiddenPath: string | null; /** Unauthorized component path (401) at the route's directory level */
|
|
81
|
+
unauthorizedPath: string | null; /** Unauthorized component paths per layout level (aligned with layouts array). */
|
|
82
|
+
unauthorizedPaths: (string | null)[];
|
|
83
|
+
/**
|
|
84
|
+
* Filesystem segments from app/ root to the route's directory.
|
|
85
|
+
* Includes route groups and dynamic segments (as template strings like "[id]").
|
|
86
|
+
* Used at render time to compute the child segments for useSelectedLayoutSegments().
|
|
87
|
+
*/
|
|
88
|
+
routeSegments: string[]; /** Tree position (directory depth from app/ root) for each template. */
|
|
89
|
+
templateTreePositions?: number[];
|
|
90
|
+
/**
|
|
91
|
+
* Tree position (directory depth from app/ root) for each layout.
|
|
92
|
+
* Used to slice routeSegments and determine which segments are below each layout.
|
|
93
|
+
* For example, root layout = 0, a layout at app/blog/ = 1, app/blog/(group)/ = 2.
|
|
94
|
+
* Unlike the old layoutSegmentDepths, this counts ALL directory levels including
|
|
95
|
+
* route groups and parallel slots.
|
|
96
|
+
*/
|
|
97
|
+
layoutTreePositions: number[]; /** Whether this is a dynamic route */
|
|
98
|
+
isDynamic: boolean; /** Parameter names for dynamic segments */
|
|
99
|
+
params: string[]; /** Dynamic parameter names captured by the route's root layout. */
|
|
100
|
+
rootParamNames?: string[]; /** Pre-split pattern segments (computed once at scan time, reused per request) */
|
|
101
|
+
patternParts: string[];
|
|
102
|
+
};
|
|
103
|
+
declare function buildAppRouteGraph(appDir: string, matcher: ValidFileMatcher): Promise<{
|
|
104
|
+
routes: AppRoute[];
|
|
105
|
+
}>;
|
|
106
|
+
declare function computeRootParamNames(routeSegments: readonly string[], layoutTreePositions: readonly number[]): string[];
|
|
107
|
+
//#endregion
|
|
108
|
+
export { AppRoute, InterceptingRoute, ParallelSlot, buildAppRouteGraph, computeRootParamNames };
|
|
109
|
+
//# sourceMappingURL=app-route-graph.d.ts.map
|