veryfront 0.1.1203 → 0.1.1205
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/esm/deno.js +1 -1
- package/esm/src/config/declarative-evaluator.d.ts.map +1 -1
- package/esm/src/config/declarative-evaluator.js +8 -0
- package/esm/src/html/hydration-script-builder/hydration-runtime.generated.js +1 -1
- package/esm/src/html/styles-builder/candidate-tokenizer.d.ts.map +1 -1
- package/esm/src/html/styles-builder/candidate-tokenizer.js +32 -1
- package/esm/src/html/styles-builder/css-import-extraction.d.ts +15 -1
- package/esm/src/html/styles-builder/css-import-extraction.d.ts.map +1 -1
- package/esm/src/html/styles-builder/css-import-extraction.js +29 -4
- package/esm/src/html/styles-builder/tailwind-compiler.d.ts.map +1 -1
- package/esm/src/html/styles-builder/tailwind-compiler.js +26 -6
- package/esm/src/platform/compat/http/pinned-fetch.d.ts +1 -1
- package/esm/src/release-assets/build-executor.d.ts.map +1 -1
- package/esm/src/release-assets/build-executor.js +30 -22
- package/esm/src/server/runtime-handler/adapter-factory.d.ts +12 -0
- package/esm/src/server/runtime-handler/adapter-factory.d.ts.map +1 -1
- package/esm/src/server/runtime-handler/adapter-factory.js +72 -13
- package/esm/src/server/shared/renderer/adapter.d.ts.map +1 -1
- package/esm/src/server/shared/renderer/adapter.js +44 -5
- package/esm/src/transforms/esm/http-cache.d.ts.map +1 -1
- package/esm/src/transforms/esm/http-cache.js +3 -3
- package/esm/src/utils/version-constant.d.ts +1 -1
- package/esm/src/utils/version-constant.js +1 -1
- package/package.json +8 -8
package/esm/deno.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"declarative-evaluator.d.ts","sourceRoot":"","sources":["../../../src/src/config/declarative-evaluator.ts"],"names":[],"mappings":"AAcA,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,eAAe,CAAC;AA2CvB,qEAAqE;AACrE,MAAM,MAAM,yBAAyB,GACjC,qBAAqB,GACrB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AAE,gCAAgC,EACjD,QAAQ,GAAE,yBAAwD,GACjE,sCAAsC,CAmGxC;AAuuED;;;;;;;;;GASG;AACH,wBAAsB,mCAAmC,CACvD,OAAO,EAAE,kCAAkC,EAC3C,MAAM,EAAE,OAAO,GACd,OAAO,CAAC,oBAAoB,CAAC,CAG/B;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,kCAAkC,GAC1C,OAAO,CAAC,oBAAoB,CAAC,CAG/B"}
|
|
@@ -2009,6 +2009,14 @@ async function evaluateCapturedInput(input, parser) {
|
|
|
2009
2009
|
const { source, fileName, preparedState } = input;
|
|
2010
2010
|
let parsedAst;
|
|
2011
2011
|
try {
|
|
2012
|
+
// The name is not reliably the file we are holding: VERYFRONT_CONFIG_FILES
|
|
2013
|
+
// is ordered `.js, .ts, .mjs`, and in production a project's
|
|
2014
|
+
// veryfront.config.ts was evaluated under the `.js` name. pickPlugins now
|
|
2015
|
+
// enables TypeScript regardless of extension, so the name only selects JSX.
|
|
2016
|
+
//
|
|
2017
|
+
// The mislabeling itself is a separate defect and is still unfixed:
|
|
2018
|
+
// readHostedConfigSource returns the candidate it actually loaded, so the
|
|
2019
|
+
// substitution happens downstream of it on the API-backed path.
|
|
2012
2020
|
parsedAst = await parser.parse({
|
|
2013
2021
|
code: source,
|
|
2014
2022
|
filePath: fileName,
|
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
* `deno task generate` to regenerate.
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
-
export const HYDRATION_RUNTIME_BUNDLE = '// src/html/hydration-script-builder/runtime/main.ts\nimport * as React from "react";\nimport { createRoot } from "react-dom/client";\nimport { RouterProvider, useRouter as useRouterFromModule } from "veryfront/router";\nimport * as RouterRuntime from "veryfront/router";\nimport { PageContextProvider } from "veryfront/context";\n\n// src/routing/flatten-route-params.ts\nfunction flattenRouteParams(params) {\n if (!params) return {};\n const flat = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === void 0) continue;\n flat[key] = Array.isArray(value) ? value.join("/") : value;\n }\n return flat;\n}\n\n// src/html/hydration-script-builder/runtime/shared.ts\nfunction moduleServerUrl(window) {\n return window.location.origin + "/_vf_modules";\n}\nfunction createLogging(window) {\n const DEBUG = Boolean(\n window.__VERYFRONT_DEBUG__ || new URLSearchParams(window.location.search).has("vf_debug")\n );\n const log = DEBUG ? console.log.bind(console, "[Veryfront]") : () => {\n };\n const logError = console.error.bind(console, "[Veryfront]");\n function logBackgroundFetchFailure(reason, path, error) {\n const message = error?.message ?? String(error);\n log(reason + " failed:", path, message);\n }\n const perfTimers = /* @__PURE__ */ new Map();\n const perfStart = DEBUG ? (label) => {\n perfTimers.set(label, performance.now());\n } : () => {\n };\n const perfEnd = DEBUG ? (label) => {\n const start = perfTimers.get(label);\n if (start === void 0) return 0;\n const duration = performance.now() - start;\n perfTimers.delete(label);\n console.log(\n "[Veryfront Perf] %c" + label + ": %c" + duration.toFixed(2) + "ms",\n "color: #888",\n duration > 100 ? "color: #f00; font-weight: bold" : "color: #0a0"\n );\n return duration;\n } : () => 0;\n return { DEBUG, log, logError, logBackgroundFetchFailure, perfStart, perfEnd };\n}\nfunction isAbortError(error) {\n return error?.name === "AbortError";\n}\nfunction resolveDocumentNavigationUrl(target, origin) {\n try {\n const url = new URL(target, origin);\n if (url.protocol === "http:" || url.protocol === "https:") return url.href;\n } catch (_) {\n }\n return null;\n}\nfunction getDocumentNonce(document2) {\n const element = document2.querySelector("script[nonce], style[nonce], link[nonce]");\n if (!element) return void 0;\n return element.nonce || element.getAttribute("nonce") || void 0;\n}\n\n// src/html/hydration-data-element.ts\nvar HYDRATION_DATA_ELEMENT_ID = "veryfront-hydration-data";\nfunction findServerHydrationDataElement(document2) {\n try {\n const matches = [...document2.querySelectorAll(`[id="${HYDRATION_DATA_ELEMENT_ID}"]`)];\n if (matches.length !== 1) return null;\n const body = document2.body;\n if (!body) return null;\n const element = matches[0];\n if (body.firstElementChild !== element && element.parentElement !== body) return null;\n if (element.tagName?.toLowerCase() !== "script") return null;\n if (element.getAttribute("type")?.trim().toLowerCase() !== "application/json") return null;\n return element;\n } catch {\n return null;\n }\n}\n\n// src/html/hydration-script-builder/runtime/hydration-data.ts\nfunction readInitialHydrationData(document2) {\n try {\n const element = findServerHydrationDataElement(document2);\n return JSON.parse(element && element.textContent ? element.textContent : "{}") || {};\n } catch (_) {\n return {};\n }\n}\nfunction readDocumentDependencyPinningCacheKey(initialHydrationData2) {\n return typeof initialHydrationData2.dependencyPinningCacheKey === "string" && initialHydrationData2.dependencyPinningCacheKey.startsWith("on:") ? initialHydrationData2.dependencyPinningCacheKey : null;\n}\n\n// src/html/hydration-script-builder/runtime/snapshot-modules.ts\nvar RECOVERY_STATE_KEY = "__VF_DEPENDENCY_SNAPSHOT_RECOVERY_STARTED__";\nasync function isDependencySnapshotConflictResponse(response) {\n if (!response || response.status !== 409) return false;\n try {\n const clone = response.clone?.() ?? response;\n const body = (await clone.text?.() ?? "").trim();\n return body === "Unknown dependency snapshot" || body === "export default null; // Unknown dependency snapshot";\n } catch (_) {\n return false;\n }\n}\nfunction createSnapshotModuleImporter(deps) {\n async function recoverFromSnapshotBoundModuleFailure(moduleUrl, allowDocumentReload = true) {\n try {\n const parsedUrl = new URL(moduleUrl, "http://veryfront.local");\n const snapshotKeys = parsedUrl.searchParams.getAll("pins");\n const pathMatch = parsedUrl.pathname.match(\n /^\\/_vf_modules\\/_pins\\/([^/]+)(?:\\/|$)/\n );\n if (pathMatch) {\n try {\n snapshotKeys.push(decodeURIComponent(pathMatch[1]));\n } catch (_) {\n return false;\n }\n }\n if (snapshotKeys.length !== 1 || !/^on:[A-Za-z0-9._-]+$/.test(snapshotKeys[0])) return false;\n const response = await deps.fetchModule(moduleUrl, { cache: "no-store" });\n if (!await isDependencySnapshotConflictResponse(response)) return false;\n if (!allowDocumentReload) return true;\n if (deps.recoveryState[RECOVERY_STATE_KEY] === true) return true;\n deps.recoveryState[RECOVERY_STATE_KEY] = true;\n try {\n deps.reloadDocument();\n } catch (_) {\n delete deps.recoveryState[RECOVERY_STATE_KEY];\n return false;\n }\n return true;\n } catch (_) {\n return false;\n }\n }\n async function importSnapshotBoundModule(moduleUrl, allowDocumentReload = true) {\n try {\n return await deps.importModule(moduleUrl);\n } catch (error) {\n const snapshotConflict = await recoverFromSnapshotBoundModuleFailure(\n moduleUrl,\n allowDocumentReload\n );\n if (snapshotConflict && !allowDocumentReload) {\n const conflictError = new Error(\n "Dependency snapshot is unavailable during speculative module prefetch"\n );\n conflictError.name = "DependencySnapshotConflictError";\n conflictError.dependencySnapshotConflict = true;\n conflictError.cause = error;\n throw conflictError;\n }\n throw error;\n }\n }\n return { importSnapshotBoundModule, recoverFromSnapshotBoundModuleFailure };\n}\nfunction isDependencySnapshotConflict(error) {\n return Boolean(error?.dependencySnapshotConflict);\n}\n\n// src/utils/version-constant.ts\nvar VERSION = "0.1.1203";\n\n// src/html/hydration-script-builder/runtime/module-urls.ts\nfunction appendQueryParam(url, key, value) {\n return url + (url.includes("?") ? "&" : "?") + key + "=" + value;\n}\nfunction appendDependencyPinningVersion(url, moduleData) {\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n if (typeof pinKey !== "string" || !pinKey.startsWith("on:")) return url;\n const hashIndex = url.indexOf("#");\n const hash = hashIndex >= 0 ? url.slice(hashIndex) : "";\n const withoutHash = hashIndex >= 0 ? url.slice(0, hashIndex) : url;\n const queryIndex = withoutHash.indexOf("?");\n const base = queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash;\n const params = new URLSearchParams(queryIndex >= 0 ? withoutHash.slice(queryIndex + 1) : "");\n const modulePrefix = "/_vf_modules/";\n const prefixIndex = base.indexOf(modulePrefix);\n const origin = prefixIndex >= 0 ? base.slice(0, prefixIndex) : "";\n if (prefixIndex >= 0 && (origin === "" || /^https?:\\/\\/[^/]+$/i.test(origin))) {\n const pathStart = prefixIndex + modulePrefix.length;\n let modulePath = base.slice(pathStart);\n if (modulePath.startsWith("_pins/")) {\n const existingKeyEnd = modulePath.indexOf("/", "_pins/".length);\n const encodedExistingKey = existingKeyEnd < 0 ? modulePath.slice("_pins/".length) : modulePath.slice("_pins/".length, existingKeyEnd);\n let existingKey;\n try {\n existingKey = decodeURIComponent(encodedExistingKey);\n } catch {\n existingKey = void 0;\n }\n if (existingKey && /^on:[A-Za-z0-9._-]+$/.test(existingKey)) {\n if (existingKeyEnd < 0) return url;\n modulePath = modulePath.slice(existingKeyEnd + 1);\n }\n }\n params.delete("pins");\n const query = params.toString();\n return base.slice(0, pathStart) + "_pins/" + encodeURIComponent(pinKey) + "/" + modulePath + (query ? "?" + query : "") + hash;\n }\n params.set("pins", pinKey);\n return base + "?" + params.toString() + hash;\n}\nfunction componentCacheKey(path, moduleData) {\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n return typeof pinKey === "string" && pinKey.startsWith("on:") ? path + "|vf_pins|" + pinKey : path;\n}\nfunction normalizeReleaseAssetModulePath(path) {\n return String(path || "").replace(/^\\/?_vf_modules\\//, "").replace(/^\\/+/, "").replace(/[?#].*$/, "");\n}\nfunction buildPinnedRscModuleUrl(path, moduleData) {\n let moduleUrl = "/_veryfront/rsc/module?rel=" + encodeURIComponent(path);\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n if (typeof pinKey === "string" && pinKey.startsWith("on:")) {\n moduleUrl += "&pins=" + encodeURIComponent(pinKey);\n }\n return moduleUrl;\n}\nfunction buildPageDataEndpoint(path, origin) {\n const targetUrl = new URL(path, origin);\n const normalizedPath = targetUrl.pathname === "/" ? "" : targetUrl.pathname.replace(/^\\//, "");\n const endpointUrl = new URL(\n "/_veryfront/page-data/" + normalizedPath + ".json",\n origin\n );\n endpointUrl.search = targetUrl.search;\n return endpointUrl.pathname + endpointUrl.search;\n}\nfunction pageDataCacheIdentity(path, documentDependencyPinningCacheKey2) {\n return documentDependencyPinningCacheKey2 ? documentDependencyPinningCacheKey2 + "|path:" + path : path;\n}\nfunction assertPageDataMatchesDocumentSnapshot(path, data, documentDependencyPinningCacheKey2) {\n if (!documentDependencyPinningCacheKey2) return data;\n if (data && data.dependencyPinningCacheKey === documentDependencyPinningCacheKey2) {\n return data;\n }\n const error = new Error("Page data dependency snapshot does not match the document");\n error.status = 409;\n error.dependencySnapshotMismatch = true;\n error.path = path;\n throw error;\n}\n\n// src/html/hydration-script-builder/runtime/component-loader.ts\nvar VERYFRONT_RUNTIME_VERSION = VERSION;\nfunction createComponentLoader(deps) {\n const { window, moduleServerUrl: moduleServerUrl2 } = deps;\n const { DEBUG, log, logError } = deps.logging;\n const componentCache = /* @__PURE__ */ new Map();\n const loadingPromises = /* @__PURE__ */ new Map();\n let releaseId = null;\n let releaseAssetModules = null;\n let studioEmbed = false;\n let hmrRefreshTimestamp = null;\n function clearComponentCache(path) {\n if (!path) {\n componentCache.clear();\n loadingPromises.clear();\n log("Cleared all component caches");\n return;\n }\n for (const key of componentCache.keys()) {\n if (key === path || key.startsWith(path + "|vf_pins|")) {\n componentCache.delete(key);\n }\n }\n for (const key of loadingPromises.keys()) {\n if (key === path || key.startsWith(path + "|vf_pins|")) {\n loadingPromises.delete(key);\n }\n }\n log("Cleared component cache for:", path);\n }\n function setReleaseId(value) {\n releaseId = typeof value === "string" && value ? value : null;\n window.__veryfrontReleaseId = releaseId;\n }\n function appendReleaseModuleVersion(url) {\n if (!releaseId || url.includes("vf_release=")) return url;\n let versionedUrl = appendQueryParam(url, "vf_release", encodeURIComponent(releaseId));\n versionedUrl = appendQueryParam(\n versionedUrl,\n "vf_runtime",\n encodeURIComponent(VERYFRONT_RUNTIME_VERSION)\n );\n return versionedUrl;\n }\n function setReleaseAssetModules(value) {\n releaseAssetModules = value && typeof value === "object" && !Array.isArray(value) ? value : null;\n window.__veryfrontReleaseAssetModules = releaseAssetModules;\n }\n function resolveReleaseAssetModuleUrl(path) {\n if (!releaseAssetModules || studioEmbed || hmrRefreshTimestamp) return null;\n const key = normalizeReleaseAssetModulePath(path);\n if (releaseAssetModules[key]) return releaseAssetModules[key];\n const withoutExt = key.replace(/\\.(tsx|ts|jsx|mdx|js|mjs)$/, "");\n const extensions = [".tsx", ".ts", ".jsx", ".mdx", ".js"];\n for (const ext of extensions) {\n const candidate = withoutExt + ext;\n if (releaseAssetModules[candidate]) return releaseAssetModules[candidate];\n }\n return null;\n }\n function pathToModuleUrl(path, embedInStudio, moduleData) {\n const releaseAssetUrl = resolveReleaseAssetModuleUrl(path);\n if (releaseAssetUrl) return releaseAssetUrl;\n const pattern = /(pages|components|app|lib|layouts|shared|features)\\/(.+)\\.(tsx|ts|jsx|mdx)$/;\n const match = path.match(new RegExp("/" + pattern.source)) || path.match(new RegExp("^" + pattern.source));\n let url;\n if (match) {\n url = moduleServerUrl2 + "/" + match[1] + "/" + match[2] + ".js";\n } else {\n const hasKnownExt = /\\.(tsx|ts|jsx|mdx|js|mjs)$/.test(path);\n url = moduleServerUrl2 + "/" + (hasKnownExt ? path.replace(/\\.(tsx|ts|jsx|mdx)$/, ".js") : path + ".js");\n }\n if (embedInStudio) url = appendQueryParam(url, "studio_embed", "true");\n if (hmrRefreshTimestamp) url = appendQueryParam(url, "t", hmrRefreshTimestamp);\n if (!embedInStudio && !hmrRefreshTimestamp) url = appendReleaseModuleVersion(url);\n url = appendDependencyPinningVersion(url, moduleData);\n return url;\n }\n function setStudioEmbed(value) {\n studioEmbed = value;\n window.__veryfrontStudioEmbed = value;\n }\n function setHMRRefreshTimestamp(timestamp) {\n hmrRefreshTimestamp = timestamp;\n window.__veryfrontHMRRefreshTimestamp = timestamp;\n }\n async function loadComponent(path, moduleData, options = {}) {\n if (!path) return null;\n const cacheKey = componentCacheKey(path, moduleData);\n if (componentCache.has(cacheKey)) {\n log("Component cached:", path);\n return componentCache.get(cacheKey);\n }\n const existingPromise = loadingPromises.get(cacheKey);\n if (existingPromise) return existingPromise;\n const loadPromise = (async () => {\n try {\n const moduleUrl = pathToModuleUrl(path, studioEmbed, moduleData);\n const start = DEBUG ? performance.now() : 0;\n log("Loading component:", moduleUrl);\n const module = await deps.snapshotModules.importSnapshotBoundModule(\n moduleUrl,\n options.allowDocumentReload !== false\n );\n const component = module.MDXLayout || module.MainLayout || module.default || module;\n if (DEBUG) {\n const duration = performance.now() - start;\n console.log(\n "[Veryfront Perf] %cimport:" + path.split("/").pop() + ": %c" + duration.toFixed(2) + "ms",\n "color: #888",\n duration > 50 ? "color: #f00; font-weight: bold" : "color: #0a0"\n );\n }\n componentCache.set(cacheKey, component);\n return component;\n } catch (error) {\n if (isDependencySnapshotConflict(error)) throw error;\n logError("Failed to load component:", path, error);\n return null;\n } finally {\n loadingPromises.delete(cacheKey);\n }\n })();\n loadingPromises.set(cacheKey, loadPromise);\n return loadPromise;\n }\n return {\n loadComponent,\n pathToModuleUrl,\n clearComponentCache,\n setStudioEmbed,\n setReleaseId,\n setReleaseAssetModules,\n setHMRRefreshTimestamp\n };\n}\n\n// src/html/hydration-script-builder/runtime/route-timing.ts\nvar MAX_ROUTE_TIMINGS = 100;\nvar MAX_SERVER_TIMING_LENGTH = 1024;\nfunction routeTimingNow() {\n return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();\n}\nfunction sanitizeServerTimingMetricName(name) {\n return String(name || "").trim().replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 128);\n}\nfunction sanitizeServerTimingHeader(value) {\n if (!value) return null;\n const metrics = [];\n const printable = String(value).replace(/[^\\x20-\\x7E]/g, " ").trim();\n if (!printable) return null;\n for (const item of printable.split(",")) {\n const segments = item.split(";").map((segment) => segment.trim()).filter(Boolean);\n const name = sanitizeServerTimingMetricName(segments[0]);\n if (!name) continue;\n for (const segment of segments.slice(1)) {\n const [key, rawValue = ""] = segment.split("=");\n if ((key ?? "").trim().toLowerCase() !== "dur") continue;\n const duration = Number(rawValue.trim().replace(/^"|"$/g, ""));\n if (!Number.isFinite(duration) || duration < 0) continue;\n metrics.push(name + ";dur=" + (Math.round(duration * 100) / 100).toFixed(2));\n break;\n }\n }\n const sanitized = metrics.join(", ");\n return sanitized ? sanitized.slice(0, MAX_SERVER_TIMING_LENGTH) : null;\n}\nfunction parseServerTimingMetrics(value) {\n const header = sanitizeServerTimingHeader(value);\n if (!header) return null;\n const metrics = {};\n for (const item of header.split(",")) {\n const segments = item.split(";").map((segment) => segment.trim()).filter(Boolean);\n const name = sanitizeServerTimingMetricName(segments[0]);\n if (!name) continue;\n for (const segment of segments.slice(1)) {\n const [key, rawValue = ""] = segment.split("=");\n if ((key ?? "").trim().toLowerCase() !== "dur") continue;\n const duration = Number(rawValue.trim().replace(/^"|"$/g, ""));\n if (Number.isFinite(duration) && duration >= 0) {\n metrics[name] = Math.round(duration * 100) / 100;\n }\n }\n }\n return Object.keys(metrics).length ? metrics : null;\n}\nfunction readResponseServerTiming(response) {\n try {\n return sanitizeServerTimingHeader(response.headers?.get("server-timing"));\n } catch (_) {\n return null;\n }\n}\nfunction roundRouteTimingValue(value) {\n return Math.round(value * 100) / 100;\n}\nfunction extractResourceTiming(entry) {\n const fields = [\n "startTime",\n "requestStart",\n "responseStart",\n "responseEnd",\n "duration",\n "transferSize",\n "encodedBodySize",\n "decodedBodySize"\n ];\n const timing = {};\n for (const field of fields) {\n const value = entry?.[field];\n if (typeof value === "number" && Number.isFinite(value) && value >= 0) {\n timing[field] = roundRouteTimingValue(value);\n }\n }\n return Object.keys(timing).length ? timing : null;\n}\nfunction createRouteTimingRecorder(window, logging2) {\n const { log } = logging2;\n function emitRouteTiming(phase, path, startedAt, detail = {}) {\n const entry = {\n phase,\n path,\n duration: Math.max(0, routeTimingNow() - startedAt),\n timestamp: Date.now(),\n ...detail\n };\n const timings = Array.isArray(window.__veryfrontRouteTimings) ? window.__veryfrontRouteTimings : [];\n timings.push(entry);\n if (timings.length > MAX_ROUTE_TIMINGS) {\n timings.splice(0, timings.length - MAX_ROUTE_TIMINGS);\n }\n window.__veryfrontRouteTimings = timings;\n try {\n window.dispatchEvent(new CustomEvent("veryfront:route-timing", { detail: entry }));\n } catch (_) {\n }\n log("Route timing:", entry);\n return entry;\n }\n function getPageDataResourceTiming(endpoint, fetchStartedAt) {\n try {\n if (typeof performance === "undefined" || typeof performance.getEntriesByName !== "function") {\n return null;\n }\n const href = new URL(endpoint, window.location.href).href;\n const entries = performance.getEntriesByName(href, "resource");\n if (!entries.length) return null;\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index];\n const responseEnd = entry?.responseEnd;\n if (typeof responseEnd === "number" && Number.isFinite(responseEnd) && responseEnd + 1 >= fetchStartedAt) {\n return extractResourceTiming(entry);\n }\n }\n return null;\n } catch (_) {\n return null;\n }\n }\n function buildPageDataTimingDetail(response, endpoint, fetchStartedAt, source) {\n const detail = { source, status: response.status };\n const serverTiming = readResponseServerTiming(response);\n if (serverTiming) {\n detail.serverTiming = serverTiming;\n const serverTimingMetrics = parseServerTimingMetrics(serverTiming);\n if (serverTimingMetrics) detail.serverTimingMetrics = serverTimingMetrics;\n }\n const resourceTiming = getPageDataResourceTiming(response.url || endpoint, fetchStartedAt);\n if (resourceTiming) detail.resourceTiming = resourceTiming;\n return detail;\n }\n return { emitRouteTiming, buildPageDataTimingDetail };\n}\n\n// src/html/managed-head-protocol.ts\nvar HEAD_PROVENANCE_ATTRIBUTE = "data-vf-head";\nvar HEAD_LEGACY_MANAGED_ATTRIBUTE = "data-veryfront-managed";\nvar HEAD_CONTENT_HASH_ATTRIBUTE = "data-vf-hash";\nvar HEAD_REACT_MANAGED_ATTRIBUTE = "data-vf-react-head";\nvar HEAD_REACT_OWNER_ATTRIBUTE = "data-vf-react-head-owner";\nvar HEAD_ROUTE_MANAGED_ATTRIBUTE = "data-vf-route-head";\nvar HEAD_SERVER_COMMIT_ATTRIBUTE = "data-vf-server-head-commit";\nvar HEAD_SHELL_PROVENANCE_ATTRIBUTE = "data-vf-shell-head";\nvar HEAD_SSR_PAYLOAD_ATTRIBUTE = "data-vf-ssr-head";\nvar MAX_MANAGED_HEAD_BYTES = 2 * 1024 * 1024;\nvar MAX_MANAGED_HEAD_PAYLOAD_BYTES = MAX_MANAGED_HEAD_BYTES * 2;\nvar SINGLETON_META_KEYS = /* @__PURE__ */ new Set([\n "description",\n "robots",\n "viewport",\n "referrer",\n "color-scheme",\n "application-name",\n "generator",\n "og:title",\n "og:description",\n "og:url",\n "og:type",\n "og:site_name",\n "og:locale",\n "twitter:card",\n "twitter:site",\n "twitter:creator",\n "twitter:title",\n "twitter:description",\n "twitter:image",\n "twitter:image:alt"\n]);\nvar SINGLETON_LINK_RELS = /* @__PURE__ */ new Set([\n "canonical",\n "manifest",\n "amphtml"\n]);\nvar MAX_HEAD_ATTRIBUTE_VALUE_BYTES = 64 * 1024;\nvar MAX_HEAD_ATTRIBUTE_BYTES = 1024 * 1024;\nvar MAX_HEAD_CONTENT_BYTES = 1024 * 1024;\nvar headTextEncoder = new TextEncoder();\nvar BOOLEAN_HEAD_ATTRIBUTES = /* @__PURE__ */ new Set([\n "async",\n "defer",\n "disabled",\n "itemscope",\n "nomodule"\n]);\nfunction isHeadFrameworkAttribute(name) {\n switch (name.toLowerCase()) {\n case HEAD_PROVENANCE_ATTRIBUTE:\n case HEAD_LEGACY_MANAGED_ATTRIBUTE:\n case HEAD_CONTENT_HASH_ATTRIBUTE:\n case HEAD_REACT_MANAGED_ATTRIBUTE:\n case HEAD_REACT_OWNER_ATTRIBUTE:\n case HEAD_ROUTE_MANAGED_ATTRIBUTE:\n case HEAD_SERVER_COMMIT_ATTRIBUTE:\n case HEAD_SHELL_PROVENANCE_ATTRIBUTE:\n case HEAD_SSR_PAYLOAD_ATTRIBUTE:\n return true;\n default:\n return false;\n }\n}\nfunction normalizeHeadIdentityValue(value) {\n const normalized = value?.trim().toLowerCase();\n return normalized || void 0;\n}\nfunction readOwnString(record, key) {\n try {\n const descriptor = Reflect.getOwnPropertyDescriptor(record, key);\n return descriptor && !descriptor.get && !descriptor.set && "value" in descriptor && typeof descriptor.value === "string" ? descriptor.value : void 0;\n } catch {\n return void 0;\n }\n}\nfunction headMetaSingletonKeyFromRecord(meta) {\n if (readOwnString(meta, "charset") !== void 0) return "meta:charset";\n const key = normalizeHeadIdentityValue(\n readOwnString(meta, "property") ?? readOwnString(meta, "name")\n );\n if (!key) return void 0;\n if (key === "theme-color") {\n return `meta:theme-color:${readOwnString(meta, "media")?.trim() ?? ""}`;\n }\n return SINGLETON_META_KEYS.has(key) ? `meta:${key}` : void 0;\n}\nfunction headLinkSingletonKeyFromRecord(link) {\n const rel = normalizeHeadIdentityValue(readOwnString(link, "rel"));\n return rel && SINGLETON_LINK_RELS.has(rel) ? `link:${rel}` : void 0;\n}\n\n// src/html/client-head-manager.ts\nvar HEAD_MANAGER_STATE_SYMBOL = /* @__PURE__ */ Symbol.for(\n "veryfront.client-head-manager.v2"\n);\nvar CROSS_PAGE_PRESERVED_SINGLETON_KEYS = /* @__PURE__ */ new Set([\n "meta:viewport",\n "link:manifest"\n]);\nfunction getClientHeadManagerState() {\n const globalState = globalThis;\n return globalState[HEAD_MANAGER_STATE_SYMBOL] ?? (globalState[HEAD_MANAGER_STATE_SYMBOL] = {\n documents: /* @__PURE__ */ new WeakMap()\n });\n}\nfunction readElementAttributes(element) {\n const attributes = [];\n for (const attribute of element.attributes) {\n const name = attribute.name.toLowerCase();\n if (isHeadFrameworkAttribute(name)) continue;\n const nonce = name === "nonce" && "nonce" in element ? element.nonce : "";\n const value = BOOLEAN_HEAD_ATTRIBUTES.has(name) ? "" : nonce || attribute.value;\n attributes.push([name, value]);\n }\n return attributes.sort(([left], [right]) => left.localeCompare(right));\n}\nfunction elementSingletonKey(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName === "title") return "title";\n const attributes = Object.fromEntries(readElementAttributes(element));\n if (tagName === "meta") return headMetaSingletonKeyFromRecord(attributes);\n if (tagName === "link") return headLinkSingletonKeyFromRecord(attributes);\n return void 0;\n}\nfunction promoteToShellHeadBaseline(element) {\n for (const attribute of [...element.attributes]) {\n if (isHeadFrameworkAttribute(attribute.name)) {\n element.removeAttribute(attribute.name);\n }\n }\n element.setAttribute(HEAD_SHELL_PROVENANCE_ATTRIBUTE, "true");\n}\nfunction isCrossPagePreservedSingleton(element, singletonKey = elementSingletonKey(element)) {\n return element.parentElement !== null && singletonKey !== void 0 && CROSS_PAGE_PRESERVED_SINGLETON_KEYS.has(singletonKey);\n}\nfunction isFrameworkOwnedHeadElement(element) {\n return element.getAttribute(HEAD_PROVENANCE_ATTRIBUTE) === "true" || element.getAttribute(HEAD_REACT_MANAGED_ATTRIBUTE) === "true" || element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1" || element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true" || element.getAttribute(HEAD_SHELL_PROVENANCE_ATTRIBUTE) === "true";\n}\nfunction retireFrameworkHeadElement(element) {\n if (isCrossPagePreservedSingleton(element)) {\n promoteToShellHeadBaseline(element);\n return;\n }\n element.remove();\n}\nfunction retireClientHeadOwnership(targetDocument) {\n const manager = getClientHeadManagerState().documents.get(targetDocument);\n if (manager) {\n manager.retire();\n return;\n }\n for (const element of [...targetDocument.head?.children ?? []]) {\n if (isFrameworkOwnedHeadElement(element)) retireFrameworkHeadElement(element);\n }\n}\n\n// src/html/client-route-head.ts\nfunction updateRouteTitle(title, targetDocument = document) {\n if (typeof title !== "string" || !title) return;\n const titles = [...targetDocument.head.querySelectorAll("title")];\n if (titles.some((element) => element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1")) {\n return;\n }\n let titleElement = titles.find(\n (element) => element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true"\n );\n for (const element of titles) {\n if (element !== titleElement) element.remove();\n }\n if (!titleElement) {\n titleElement = targetDocument.createElement("title");\n titleElement.setAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE, "true");\n targetDocument.head.appendChild(titleElement);\n }\n titleElement.textContent = title;\n}\nfunction updateRouteMetaTag(targetDocument, selector, attributeName, attributeValue, content) {\n const matches = [...targetDocument.head.querySelectorAll(selector)];\n if (matches.some((element) => element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1")) {\n return;\n }\n let metaTag = matches.find(\n (element) => element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true"\n );\n if (!metaTag) {\n metaTag = targetDocument.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n metaTag.setAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE, "true");\n targetDocument.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction updateRouteMetaTags(metadata, targetDocument = document) {\n if (typeof metadata.description === "string" && metadata.description) {\n updateRouteMetaTag(\n targetDocument,\n \'meta[name="description"]\',\n "name",\n "description",\n metadata.description\n );\n }\n if (typeof metadata.ogTitle === "string" && metadata.ogTitle) {\n updateRouteMetaTag(\n targetDocument,\n \'meta[property="og:title"]\',\n "property",\n "og:title",\n metadata.ogTitle\n );\n }\n}\nfunction handoffClientRouteMetadata(metadata, targetDocument = document) {\n const retainedTitle = targetDocument.title;\n retireClientHeadOwnership(targetDocument);\n updateRouteTitle(\n typeof metadata.title === "string" && metadata.title ? metadata.title : retainedTitle,\n targetDocument\n );\n updateRouteMetaTags(metadata, targetDocument);\n}\n\n// src/html/hydration-script-builder/runtime/router.ts\nvar FETCH_TIMEOUT_MS = 1e4;\nvar MAX_RETRIES = 2;\nvar MAX_CACHE_SIZE = 50;\nvar CACHE_TTL_MS = 5 * 60 * 1e3;\nvar BACKGROUND_REFRESH_INTERVAL_MS = 30 * 1e3;\nvar PREFETCH_DELAY_MS = 100;\nvar MAX_PREFETCH_PATHS = 100;\nvar IDLE_PREFETCH_DELAY_MS = 1200;\nvar IDLE_PREFETCH_MAX_LINKS = 4;\nvar VIEWPORT_PREFETCH_MAX_LINKS = 8;\nvar PAGE_DATA_PREFETCH_CONCURRENCY = 2;\nvar VIEWPORT_PREFETCH_ROOT_MARGIN = "200px";\nvar MAX_SCROLL_POSITIONS = 100;\nfunction createRouterRuntime(deps) {\n const { env: env2, logging: logging2, routeTiming: routeTiming2, componentLoader: componentLoader2, snapshotModules: snapshotModules2 } = deps;\n const { window, document: document2, React: React2, RouterProvider: RouterProvider2, PageContextProvider: PageContextProvider2 } = env2;\n const { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = env2;\n const { log, logError, logBackgroundFetchFailure, perfStart, perfEnd } = logging2;\n const { emitRouteTiming, buildPageDataTimingDetail } = routeTiming2;\n const { loadComponent } = componentLoader2;\n const documentPinKey = deps.documentDependencyPinningCacheKey;\n let hydrationResolve;\n let hydrationReject;\n const hydrationPromise = new Promise((resolve, reject) => {\n hydrationResolve = resolve;\n hydrationReject = reject;\n });\n let hydrationCompleted = false;\n let hydrationFailed = false;\n function signalHydrationComplete() {\n hydrationCompleted = true;\n hydrationResolve();\n log("Hydration complete signal received");\n }\n function signalHydrationFailed(error) {\n hydrationFailed = true;\n hydrationReject(error);\n logError("Hydration failed signal received:", error);\n }\n window.__veryfrontHydrationComplete = signalHydrationComplete;\n window.__veryfrontHydrationFailed = signalHydrationFailed;\n function pageDataCacheIdentity2(path) {\n return pageDataCacheIdentity(path, documentPinKey);\n }\n function navigateDocument(target) {\n const safeUrl = resolveDocumentNavigationUrl(target, window.location.origin);\n if (safeUrl) {\n window.location.href = safeUrl;\n return;\n }\n logError("Refusing an unsafe document navigation:", target);\n window.location.reload();\n }\n let clientBuildVersion = null;\n function checkVersionMismatch(newVersion) {\n if (!clientBuildVersion) {\n clientBuildVersion = newVersion;\n log("Build version initialized:", newVersion);\n return false;\n }\n if (newVersion.serverStart !== clientBuildVersion.serverStart) {\n log("Server restarted, reloading...", {\n old: clientBuildVersion.serverStart,\n new: newVersion.serverStart\n });\n return true;\n }\n if (newVersion.framework !== clientBuildVersion.framework) {\n log("Framework version changed, reloading...", {\n old: clientBuildVersion.framework,\n new: newVersion.framework\n });\n return true;\n }\n if (newVersion.projectUpdated && clientBuildVersion.projectUpdated && newVersion.projectUpdated !== clientBuildVersion.projectUpdated) {\n log("Project content updated, reloading...", {\n old: clientBuildVersion.projectUpdated,\n new: newVersion.projectUpdated\n });\n return true;\n }\n return false;\n }\n const pageDataCache = /* @__PURE__ */ new Map();\n const pendingPageDataFetches = /* @__PURE__ */ new Map();\n const backgroundRefreshTimestamps = /* @__PURE__ */ new Map();\n function getCachedPageData(path) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const entry = pageDataCache.get(cacheIdentity);\n if (!entry) return null;\n if (Date.now() - entry.timestamp < CACHE_TTL_MS) return entry.data;\n pageDataCache.delete(cacheIdentity);\n backgroundRefreshTimestamps.delete(cacheIdentity);\n return null;\n }\n function setCachedPageData(path, data) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n if (pageDataCache.size >= MAX_CACHE_SIZE) {\n const oldest = pageDataCache.keys().next().value;\n if (oldest) {\n pageDataCache.delete(oldest);\n backgroundRefreshTimestamps.delete(oldest);\n }\n }\n pageDataCache.set(cacheIdentity, { data, timestamp: Date.now() });\n }\n const scrollPositions = /* @__PURE__ */ new Map();\n function saveScrollPosition(path) {\n if (scrollPositions.size >= MAX_SCROLL_POSITIONS) {\n const oldest = scrollPositions.keys().next().value;\n if (oldest) scrollPositions.delete(oldest);\n }\n scrollPositions.set(path, window.scrollY);\n }\n function restoreScrollPosition(path) {\n const savedY = scrollPositions.get(path);\n if (savedY === void 0) return false;\n requestAnimationFrame(() => window.scrollTo(0, savedY));\n return true;\n }\n let progressBar = null;\n let progressTimeout = null;\n function showNavigationProgress() {\n if (!progressBar) {\n progressBar = document2.createElement("div");\n progressBar.id = "vf-nav-progress";\n progressBar.style.cssText = "position:fixed;top:0;left:0;height:3px;width:0;background:linear-gradient(90deg,#0066ff,#00aaff);z-index:99999;transition:width 0.3s ease-out,opacity 0.2s;opacity:1;";\n document2.body.prepend(progressBar);\n }\n progressBar.style.opacity = "1";\n progressBar.style.width = "30%";\n progressTimeout = setTimeout2(() => {\n if (progressBar?.style) progressBar.style.width = "70%";\n }, 300);\n document2.body.setAttribute("aria-busy", "true");\n }\n function hideNavigationProgress() {\n if (progressTimeout) {\n clearTimeout2(progressTimeout);\n progressTimeout = null;\n }\n if (progressBar) {\n progressBar.style.width = "100%";\n setTimeout2(() => {\n if (!progressBar) return;\n progressBar.style.opacity = "0";\n setTimeout2(() => {\n if (progressBar) progressBar.style.width = "0";\n }, 200);\n }, 150);\n }\n document2.body.removeAttribute("aria-busy");\n }\n let currentAbortController = null;\n function sleep(ms) {\n return new Promise((resolve) => setTimeout2(resolve, ms));\n }\n async function fetchWithRetry(url, options, maxRetries = MAX_RETRIES) {\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController();\n const callerSignal = options.signal;\n const abortFromCaller = () => controller.abort();\n if (callerSignal?.aborted) controller.abort();\n callerSignal?.addEventListener("abort", abortFromCaller, { once: true });\n const timeout = setTimeout2(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n const response = await env2.fetch(url, { ...options, signal: controller.signal });\n clearTimeout2(timeout);\n callerSignal?.removeEventListener("abort", abortFromCaller);\n if (response.ok) return response;\n if (response.status >= 500 && attempt < maxRetries) {\n log("Server error, retrying...", response.status);\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n return response;\n } catch (error) {\n clearTimeout2(timeout);\n callerSignal?.removeEventListener("abort", abortFromCaller);\n if (error.name === "AbortError" && callerSignal?.aborted) throw error;\n if (attempt === maxRetries) throw error;\n log("Fetch failed, retrying...", error.message);\n await sleep(Math.pow(2, attempt) * 500);\n }\n }\n throw new Error("Failed to fetch page data");\n }\n async function fetchPageDataFresh(path, signal, options = {}) {\n const {\n triggerReloadOnVersionMismatch = false,\n recordRouteTiming = false,\n timingSource = "network"\n } = options;\n const endpoint = buildPageDataEndpoint(path, window.location.origin);\n const startedAt = recordRouteTiming ? routeTimingNow() : 0;\n log("Fetching page data:", path);\n perfStart("fetch:" + path);\n const headers = options.prefetch ? { "X-Veryfront-Prefetch": "1" } : { "X-Veryfront-Navigation": "spa" };\n if (documentPinKey) {\n headers["X-Veryfront-Dependency-Pins"] = documentPinKey;\n }\n const response = await fetchWithRetry(endpoint, {\n headers,\n signal\n }, options.prefetch ? 0 : MAX_RETRIES);\n if (!response.ok) {\n perfEnd("fetch:" + path);\n if (recordRouteTiming) {\n emitRouteTiming(\n "page-data",\n path,\n startedAt,\n buildPageDataTimingDetail(response, endpoint, startedAt, timingSource)\n );\n }\n const error = new Error("Failed to fetch page data: " + response.status);\n error.status = response.status;\n throw error;\n }\n perfStart("parse:" + path);\n const data = assertPageDataMatchesDocumentSnapshot(\n path,\n await response.json(),\n documentPinKey\n );\n perfEnd("parse:" + path);\n perfEnd("fetch:" + path);\n if (recordRouteTiming) {\n emitRouteTiming(\n "page-data",\n path,\n startedAt,\n buildPageDataTimingDetail(response, endpoint, startedAt, timingSource)\n );\n }\n if (triggerReloadOnVersionMismatch) {\n const checkedData = handlePageDataVersionMismatch(path, data);\n if (checkedData !== data) return checkedData;\n }\n setCachedPageData(path, data);\n return data;\n }\n function handlePageDataVersionMismatch(path, data) {\n if (data.buildVersion && checkVersionMismatch(data.buildVersion)) {\n log("Version mismatch detected, performing full page reload to:", path);\n navigateDocument(path);\n return new Promise(() => {\n });\n }\n return data;\n }\n function startPageDataFetch(path, signal, options = {}) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const request = fetchPageDataFresh(path, signal, options).finally(() => {\n if (options.trackPending !== false && pendingPageDataFetches.get(cacheIdentity) === request) {\n pendingPageDataFetches.delete(cacheIdentity);\n }\n });\n if (options.trackPending !== false) {\n pendingPageDataFetches.set(cacheIdentity, request);\n }\n return request;\n }\n function fetchPageDataDeduped(path) {\n const pending = pendingPageDataFetches.get(pageDataCacheIdentity2(path));\n if (pending) return pending;\n return startPageDataFetch(path, null);\n }\n function refreshPageDataInBackground(path) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const lastRefreshAt = backgroundRefreshTimestamps.get(cacheIdentity) || 0;\n const now = Date.now();\n if (now - lastRefreshAt < BACKGROUND_REFRESH_INTERVAL_MS) return;\n backgroundRefreshTimestamps.set(cacheIdentity, now);\n fetchPageDataDeduped(path).catch((error) => {\n logBackgroundFetchFailure("Stale page data refresh", path, error);\n });\n }\n async function fetchPageDataForNavigation(path, signal) {\n const startedAt = routeTimingNow();\n const cached = getCachedPageData(path);\n if (cached) {\n log("Using cached page data:", path);\n refreshPageDataInBackground(path);\n emitRouteTiming("page-data", path, startedAt, { source: "cache" });\n return cached;\n }\n const pending = pendingPageDataFetches.get(pageDataCacheIdentity2(path));\n if (pending) {\n log("Reusing pending page data fetch for navigation:", path);\n const data = await pending;\n emitRouteTiming("page-data", path, startedAt, { source: "deduped" });\n return handlePageDataVersionMismatch(path, data);\n }\n return startPageDataFetch(path, signal, {\n triggerReloadOnVersionMismatch: true,\n recordRouteTiming: true,\n timingSource: "network"\n });\n }\n function fetchPageDataForPrefetch(path, signal) {\n if (getCachedPageData(path)) return Promise.resolve();\n return startPageDataFetch(path, signal, { prefetch: true, trackPending: false }).then((data) => preloadModulesForPageData(data, path)).catch((error) => {\n if (!isAbortError(error)) {\n logBackgroundFetchFailure("Page data prefetch", path, error);\n }\n throw error;\n });\n }\n let currentPath = window.location.pathname;\n let isNavigating = false;\n async function navigateSPA(href, historyMode = "push", restoreScroll = false) {\n currentAbortController?.abort();\n if (isNavigating) return;\n isNavigating = true;\n const [navigationPath] = href.split("#");\n removeQueuedPrefetch(navigationPath || href);\n abortActiveSpeculativePrefetches();\n currentAbortController = new AbortController();\n const signal = currentAbortController.signal;\n const navigationStartedAt = routeTimingNow();\n showNavigationProgress();\n perfStart("nav:total:" + href);\n try {\n log("SPA navigating to:", href);\n saveScrollPosition(currentPath);\n const [path, hash] = href.split("#");\n const targetPath = path || currentPath;\n perfStart("nav:fetchData:" + href);\n const pageData = await fetchPageDataForNavigation(targetPath, signal);\n perfEnd("nav:fetchData:" + href);\n if (signal.aborted) return;\n if (pageData && pageData.redirect && typeof pageData.redirect.destination === "string") {\n const redirectUrl = resolveDocumentNavigationUrl(\n pageData.redirect.destination,\n window.location.origin\n );\n if (redirectUrl) {\n log("SPA navigation redirect -> " + redirectUrl);\n window.location.href = redirectUrl;\n return;\n }\n }\n if (historyMode === "push") {\n window.history.pushState({ pageData, scrollY: 0 }, "", href);\n } else if (historyMode === "replace") {\n window.history.replaceState({ pageData, scrollY: 0 }, "", href);\n }\n currentPath = targetPath;\n router.pathname = targetPath;\n router.query = Object.fromEntries(new URLSearchParams(window.location.search));\n router.params = flattenRouteParams(pageData.params);\n perfStart("nav:render:" + href);\n await renderPageFromData(pageData, targetPath);\n perfEnd("nav:render:" + href);\n if (restoreScroll) {\n restoreScrollPosition(targetPath);\n } else if (hash) {\n requestAnimationFrame(() => {\n const target = document2.getElementById(hash);\n if (target) {\n target.scrollIntoView({ behavior: "smooth" });\n return;\n }\n window.scrollTo(0, 0);\n });\n } else {\n window.scrollTo(0, 0);\n }\n hideNavigationProgress();\n perfEnd("nav:total:" + href);\n emitRouteTiming("total", targetPath, navigationStartedAt, {\n href,\n historyMode,\n restoreScroll\n });\n log("SPA navigation complete");\n } catch (error) {\n hideNavigationProgress();\n if (error.name === "AbortError") {\n log("Navigation aborted");\n return;\n }\n logError("SPA navigation failed:", error.message);\n if (error.status === 404) {\n logError("Page not found:", href);\n }\n navigateDocument(href);\n } finally {\n isNavigating = false;\n currentAbortController = null;\n processPageDataPrefetchQueue();\n }\n }\n async function loadPageDataComponent(pageData, path, options = {}) {\n if (!pageData.isolatedClientPage) return loadComponent(path, pageData, options);\n const moduleUrl = buildPinnedRscModuleUrl(path, pageData);\n const module = await snapshotModules2.importSnapshotBoundModule(\n moduleUrl,\n options.allowDocumentReload !== false\n );\n return module.MDXLayout || module.MainLayout || module.default || module;\n }\n async function renderPageFromData(pageData, targetPath) {\n if (pageData.requiresFullDocumentNavigation) {\n throw new Error("Server layout requires full document navigation");\n }\n if (window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(pageData.releaseId || null);\n }\n if (window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(pageData.releaseAssetModules || null);\n }\n perfStart("render:loadAll");\n const allPaths = getPageDataModulePaths(pageData);\n const modulesStartedAt = routeTimingNow();\n const components = await Promise.all(\n allPaths.map((path) => loadPageDataComponent(pageData, path))\n );\n emitRouteTiming("modules", targetPath, modulesStartedAt, { count: allPaths.length });\n perfEnd("render:loadAll");\n const [PageComponent, ...rest] = components;\n const ErrorComponent = pageData.errorPath ? rest.pop() : null;\n const AppComponent = pageData.appPath ? rest.pop() : null;\n const LayoutComponents = rest;\n if (!PageComponent) {\n throw new Error("Failed to load page component: " + pageData.pagePath);\n }\n handoffClientRouteMetadata(\n pageData.frontmatter ?? {},\n document2\n );\n if (pageData.css) {\n const existingStyle = document2.getElementById("veryfront-spa-css");\n if (existingStyle) {\n existingStyle.textContent = pageData.css;\n } else {\n const styleEl = document2.createElement("style");\n const nonce = getDocumentNonce(document2);\n if (nonce) styleEl.setAttribute("nonce", nonce);\n styleEl.id = "veryfront-spa-css";\n styleEl.textContent = pageData.css;\n document2.head.appendChild(styleEl);\n }\n log("Injected CSS for SPA navigation", { cssLength: pageData.css.length });\n } else if (pageData.cssAction === "clear") {\n const existingStyle = document2.getElementById("veryfront-spa-css");\n if (existingStyle) {\n existingStyle.remove();\n log("Cleared SPA CSS for release stylesheet navigation");\n }\n }\n const normalizedParams = flattenRouteParams(pageData.params);\n let tree = React2.createElement(PageComponent, {\n ...pageData.props,\n params: normalizedParams\n });\n if (pageData.layouts?.length) {\n for (let i = pageData.layouts.length - 1; i >= 0; i--) {\n const layout = pageData.layouts[i];\n const LayoutComponent = LayoutComponents[i];\n if (!LayoutComponent || !layout) continue;\n const layoutProps = pageData.layoutProps?.[layout.path] || {};\n tree = React2.createElement(LayoutComponent, { ...layoutProps, children: tree });\n }\n }\n if (AppComponent) {\n tree = React2.createElement(AppComponent, { children: tree });\n log("Wrapped with App component for SPA navigation");\n }\n if (ErrorComponent) {\n class AppRouterErrorBoundary extends React2.Component {\n constructor(props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n static getDerivedStateFromError(error) {\n return { hasError: true, error };\n }\n render() {\n if (this.state.hasError) {\n return React2.createElement(ErrorComponent, {\n error: this.state.error,\n reset: () => this.setState({ hasError: false, error: null })\n });\n }\n return this.props.children;\n }\n }\n tree = React2.createElement(AppRouterErrorBoundary, null, tree);\n }\n const headingsArray = pageData.headings || [];\n const pageContext = {\n slug: pageData.slug || "",\n path: pageData.pagePath || targetPath,\n params: normalizedParams,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n frontmatter: pageData.frontmatter || {},\n data: pageData.props || {},\n headings: headingsArray,\n mdxHeadings: headingsArray\n };\n tree = React2.createElement(PageContextProvider2, { pageContext, children: tree });\n tree = React2.createElement(RouterProvider2, { router, children: tree });\n const container = pageData.isolatedClientPage ? document2.getElementById("veryfront-page-island") : document2.getElementById("root");\n if (!hydrationCompleted && !hydrationFailed) {\n log("Waiting for hydration to complete before SPA render...");\n try {\n await Promise.race([\n hydrationPromise,\n new Promise(\n (_, reject) => setTimeout2(() => reject(new Error("Hydration timeout")), 1e4)\n )\n ]);\n } catch (waitError) {\n log("Hydration wait failed:", waitError.message);\n }\n }\n if (container?.__reactRoot) {\n perfStart("render:reactRender");\n container.__reactRoot.render(tree);\n perfEnd("render:reactRender");\n log("Page re-rendered via SPA");\n scheduleRoutePrefetchRefresh();\n return;\n }\n if (hydrationFailed) {\n throw new Error(\n "React root not found - hydration failed, falling back to full page navigation"\n );\n }\n throw new Error("React root not found");\n }\n let prefetchTimeout = null;\n let currentHoverLink = null;\n let routePrefetchRefreshPending = false;\n let viewportPrefetchObserver = null;\n const observedPrefetchLinks = /* @__PURE__ */ new WeakSet();\n const prefetchedPaths = /* @__PURE__ */ new Set();\n const inFlightPrefetches = /* @__PURE__ */ new Set();\n const queuedPrefetchPaths = /* @__PURE__ */ new Set();\n const pageDataPrefetchQueue = [];\n const activePageDataPrefetchControllers = /* @__PURE__ */ new Map();\n function cancelScheduledPrefetch() {\n if (prefetchTimeout) {\n clearTimeout2(prefetchTimeout);\n prefetchTimeout = null;\n }\n currentHoverLink = null;\n }\n function getPageDataModulePaths(pageData) {\n const layoutPaths = (pageData.layouts || []).map((l) => l.path).filter(Boolean);\n const allPaths = [pageData.pagePath, ...layoutPaths].filter(Boolean);\n if (pageData.appPath) allPaths.push(pageData.appPath);\n if (pageData.errorPath) allPaths.push(pageData.errorPath);\n return allPaths;\n }\n function getCurrentRouteHref() {\n return window.location.pathname + window.location.search;\n }\n function getInternalRouteHrefFromLink(link) {\n if (!link || link.target === "_blank" || link.hasAttribute("download") || link.getAttribute("data-prefetch") === "false") {\n return null;\n }\n const href = link.getAttribute("href");\n if (!href || href.startsWith("#") || href.startsWith("//") || !href.startsWith("/")) {\n return null;\n }\n try {\n const url = new URL(href, window.location.origin);\n if (url.origin !== window.location.origin) return null;\n const routeHref = url.pathname + url.search;\n return routeHref === getCurrentRouteHref() ? null : routeHref;\n } catch (_) {\n return null;\n }\n }\n function getEligiblePrefetchLinks(limit) {\n const links = [];\n const seenHrefs = /* @__PURE__ */ new Set();\n for (const link of document2.querySelectorAll("a[href]")) {\n const href = getInternalRouteHrefFromLink(link);\n if (!href || seenHrefs.has(href)) continue;\n seenHrefs.add(href);\n links.push({ link, href });\n if (links.length >= limit) break;\n }\n return links;\n }\n async function preloadModulesForPageData(pageData, path) {\n if (!pageData || pageData.requiresFullDocumentNavigation) return;\n if (pageData.releaseId && window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(pageData.releaseId);\n }\n if (pageData.releaseAssetModules && window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(pageData.releaseAssetModules);\n }\n const modulePaths = getPageDataModulePaths(pageData);\n if (modulePaths.length === 0) return;\n try {\n await Promise.all(\n modulePaths.map(\n (modulePath) => loadPageDataComponent(pageData, modulePath, { allowDocumentReload: false })\n )\n );\n } catch (error) {\n if (isDependencySnapshotConflict(error)) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n pageDataCache.delete(cacheIdentity);\n backgroundRefreshTimestamps.delete(cacheIdentity);\n prefetchedPaths.delete(path);\n throw error;\n }\n logBackgroundFetchFailure("Module prefetch", path, error);\n }\n }\n function removeQueuedPrefetch(path) {\n queuedPrefetchPaths.delete(path);\n for (let i = pageDataPrefetchQueue.length - 1; i >= 0; i--) {\n if (pageDataPrefetchQueue[i] === path) pageDataPrefetchQueue.splice(i, 1);\n }\n }\n function abortActiveSpeculativePrefetches() {\n for (const controller of activePageDataPrefetchControllers.values()) {\n controller.abort();\n }\n }\n function processPageDataPrefetchQueue() {\n if (isNavigating) return;\n while (activePageDataPrefetchControllers.size < PAGE_DATA_PREFETCH_CONCURRENCY && pageDataPrefetchQueue.length > 0) {\n const href = pageDataPrefetchQueue.shift();\n queuedPrefetchPaths.delete(href);\n if (prefetchedPaths.has(href) || inFlightPrefetches.has(href) || getCachedPageData(href)) {\n continue;\n }\n if (prefetchedPaths.size >= MAX_PREFETCH_PATHS) {\n const oldest = prefetchedPaths.values().next().value;\n if (oldest) prefetchedPaths.delete(oldest);\n }\n const controller = new AbortController();\n prefetchedPaths.add(href);\n inFlightPrefetches.add(href);\n activePageDataPrefetchControllers.set(href, controller);\n fetchPageDataForPrefetch(href, controller.signal).catch((error) => {\n prefetchedPaths.delete(href);\n if (isDependencySnapshotConflict(error)) {\n logBackgroundFetchFailure("Module prefetch", href, error);\n }\n }).finally(() => {\n inFlightPrefetches.delete(href);\n activePageDataPrefetchControllers.delete(href);\n processPageDataPrefetchQueue();\n });\n }\n }\n function prefetchPage(href) {\n if (isNavigating) return;\n if (prefetchedPaths.has(href) || inFlightPrefetches.has(href) || queuedPrefetchPaths.has(href)) return;\n const cachedPageData = getCachedPageData(href);\n if (cachedPageData) {\n preloadModulesForPageData(cachedPageData, href).catch((error) => {\n logBackgroundFetchFailure("Module prefetch", href, error);\n });\n return;\n }\n queuedPrefetchPaths.add(href);\n pageDataPrefetchQueue.push(href);\n processPageDataPrefetchQueue();\n }\n function prefetchEligibleRouteLinks(limit) {\n for (const { href } of getEligiblePrefetchLinks(limit)) {\n prefetchPage(href);\n }\n }\n function ensureViewportPrefetchObserver() {\n if (viewportPrefetchObserver || typeof IntersectionObserver !== "function") {\n return viewportPrefetchObserver;\n }\n viewportPrefetchObserver = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n viewportPrefetchObserver?.unobserve(entry.target);\n const href = getInternalRouteHrefFromLink(\n entry.target\n );\n if (href) prefetchPage(href);\n }\n }, { rootMargin: VIEWPORT_PREFETCH_ROOT_MARGIN });\n return viewportPrefetchObserver;\n }\n function observeViewportPrefetchLinks() {\n const observer = ensureViewportPrefetchObserver();\n if (!observer) return;\n for (const { link } of getEligiblePrefetchLinks(VIEWPORT_PREFETCH_MAX_LINKS)) {\n if (observedPrefetchLinks.has(link)) continue;\n observedPrefetchLinks.add(link);\n observer.observe(link);\n }\n }\n function runRoutePrefetchRefresh() {\n routePrefetchRefreshPending = false;\n prefetchEligibleRouteLinks(IDLE_PREFETCH_MAX_LINKS);\n observeViewportPrefetchLinks();\n }\n function scheduleRoutePrefetchRefresh() {\n if (routePrefetchRefreshPending) return;\n routePrefetchRefreshPending = true;\n setTimeout2(() => {\n if (typeof requestIdleCallback === "function") {\n requestIdleCallback(runRoutePrefetchRefresh, { timeout: IDLE_PREFETCH_DELAY_MS });\n return;\n }\n runRoutePrefetchRefresh();\n }, IDLE_PREFETCH_DELAY_MS);\n }\n const router = {\n domain: window.location.origin,\n path: window.location.pathname,\n push: (path) => {\n void navigateSPA(path, "push");\n },\n replace: (path) => {\n void navigateSPA(path, "replace");\n },\n back: () => {\n window.history.back();\n },\n forward: () => {\n window.history.forward();\n },\n prefetch: (path) => {\n prefetchPage(path);\n },\n pathname: window.location.pathname,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n // Seed route params from the hydration data (issue #2741). Catch-all\n // segments arrive as arrays and are joined so no path info is lost.\n params: flattenRouteParams(deps.initialHydrationData.params || {}),\n isPreview: false,\n isMounted: true,\n navigate: (path) => navigateSPA(path, "push"),\n reload: () => window.location.reload()\n };\n window.__veryfrontRouter = router;\n if (deps.navigationStoreUsesRegistryFallback) {\n log("Router runtime does not export getNavigationStore; using shared v1 registry fallback");\n }\n if (typeof deps.getNavigationStore === "function") {\n deps.getNavigationStore().setNavigator((href, options) => {\n const mode = options && options.history;\n const historyMode = mode === "replace" ? "replace" : mode === "none" ? "none" : "push";\n return navigateSPA(href, historyMode);\n });\n }\n window.addEventListener("popstate", async (e) => {\n const path = window.location.pathname;\n log("Popstate:", path);\n saveScrollPosition(currentPath);\n if (!e.state?.pageData) {\n await navigateSPA(path, "none", true);\n return;\n }\n showNavigationProgress();\n try {\n currentPath = path;\n router.pathname = path;\n router.query = Object.fromEntries(new URLSearchParams(window.location.search));\n router.params = flattenRouteParams(e.state.pageData.params);\n await renderPageFromData(e.state.pageData, path);\n restoreScrollPosition(path);\n hideNavigationProgress();\n } catch (error) {\n hideNavigationProgress();\n logError("Popstate render failed:", error.message);\n window.location.reload();\n }\n });\n document2.addEventListener("click", (e) => {\n const link = e.target?.closest("a[href]");\n if (!link) return;\n const href = link.getAttribute("href");\n if (!href) return;\n if (href.startsWith("#")) {\n const target = document2.getElementById(href.slice(1));\n if (!target) return;\n e.preventDefault();\n target.scrollIntoView({ behavior: "smooth" });\n window.history.pushState(null, "", href);\n return;\n }\n if (link.target === "_blank" || link.hasAttribute("download") || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !href.startsWith("/") || href.startsWith("//")) {\n return;\n }\n e.preventDefault();\n cancelScheduledPrefetch();\n void navigateSPA(href, "push");\n });\n document2.addEventListener(\n "mouseenter",\n (e) => {\n if (!e.target || typeof e.target.closest !== "function") return;\n const link = e.target.closest("a[href]");\n if (!link) return;\n const href = getInternalRouteHrefFromLink(link);\n if (!href) return;\n if (currentHoverLink === link) return;\n if (prefetchTimeout) {\n clearTimeout2(prefetchTimeout);\n prefetchTimeout = null;\n }\n currentHoverLink = link;\n prefetchTimeout = setTimeout2(() => {\n prefetchPage(href);\n prefetchTimeout = null;\n }, PREFETCH_DELAY_MS);\n },\n true\n );\n document2.addEventListener(\n "mouseleave",\n (e) => {\n if (!e.target || typeof e.target.closest !== "function") return;\n const relatedTarget = e.relatedTarget;\n if (currentHoverLink && relatedTarget && currentHoverLink.contains(relatedTarget)) return;\n cancelScheduledPrefetch();\n },\n true\n );\n if (document2.readyState === "loading") {\n document2.addEventListener("DOMContentLoaded", scheduleRoutePrefetchRefresh, { once: true });\n } else {\n scheduleRoutePrefetchRefresh();\n }\n window.useRouter = () => {\n try {\n return env2.useRouterFromModule();\n } catch (_) {\n return window.__veryfrontRouter;\n }\n };\n return {\n router,\n navigateSPA,\n renderPageFromData,\n prefetchPage,\n signalHydrationComplete,\n signalHydrationFailed\n };\n}\n\n// src/html/hydration-script-builder/runtime/renderer.ts\nfunction isModuleNotFoundError(error) {\n if (!error) return false;\n if (error instanceof SyntaxError) return false;\n const message = String(error.message || error);\n return /(?:dynamically imported module|Importing a module script failed|Failed to load module script)/i.test(message);\n}\nfunction preferReachedModuleError(earlier, later) {\n if (!earlier) return later;\n if (!later) return earlier;\n if (isModuleNotFoundError(earlier) && !isModuleNotFoundError(later)) return later;\n return earlier;\n}\nasync function loadPageModuleWithIndexFallback(basePath, pageSlug, pageModuleError, importModule) {\n try {\n return await importModule(basePath + ".js");\n } catch (error) {\n const routeError = preferReachedModuleError(pageModuleError, error);\n if (pageSlug === "index" || pageSlug.endsWith("/index")) throw routeError;\n try {\n return await importModule(basePath + "/index.js");\n } catch (indexError) {\n throw preferReachedModuleError(routeError, indexError);\n }\n }\n}\nfunction isAppRouterPath(path, appRouterRoot) {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n return normalizedPath === appRouterRoot || normalizedPath.startsWith(appRouterRoot + "/");\n}\nfunction isRootAppLayoutPath(path, appRouterRoot) {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n const pathWithoutExtension = normalizedPath.replace(/\\.(?:tsx|jsx|ts|js)$/, "");\n return pathWithoutExtension === appRouterRoot + "/layout";\n}\nfunction unwrapAppRouterDocumentLayout(LayoutComponent, React2) {\n return function AppRouterDocumentLayout(props) {\n const element = LayoutComponent(props);\n const asElement = element;\n if (!React2.isValidElement(element) || asElement.type !== "html") {\n return element;\n }\n const body = React2.Children.toArray(asElement.props?.children).find(\n (child) => React2.isValidElement(child) && child.type === "body"\n );\n return body?.props?.children ?? props.children;\n };\n}\nfunction createHydrationRenderer(deps) {\n const { env: env2, logging: logging2, componentLoader: componentLoader2, snapshotModules: snapshotModules2, moduleServerUrl: moduleServerUrl2 } = deps;\n const { window, document: document2, React: React2, RouterProvider: RouterProvider2, PageContextProvider: PageContextProvider2 } = env2;\n const { DEBUG, log, logError } = logging2;\n const { loadComponent, pathToModuleUrl } = componentLoader2;\n const { importSnapshotBoundModule } = snapshotModules2;\n async function renderPage(pathname) {\n const resolvedPathname = (() => {\n const input = typeof pathname === "string" ? pathname : window.location.pathname;\n try {\n return new URL(input, window.location.origin).pathname || "/";\n } catch (_) {\n const [pathOnly] = String(input || "/").split(/[?#]/);\n return pathOnly || "/";\n }\n })();\n const dataScript = findServerHydrationDataElement(document2);\n if (!dataScript) {\n logError("Hydration data not found");\n return;\n }\n let data = {};\n try {\n data = JSON.parse(dataScript.textContent || "{}");\n } catch (parseError) {\n logError("Failed to parse hydration data:", parseError);\n return;\n }\n log("Hydration data:", data);\n if (data.studioEmbed && window.__veryfrontSetStudioEmbed) {\n window.__veryfrontSetStudioEmbed(true);\n }\n if (window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(data.releaseId || null);\n }\n if (data.releaseAssetModules && window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(data.releaseAssetModules);\n }\n try {\n let pageModule;\n const pagePath = typeof data.pagePath === "string" ? data.pagePath : "";\n const normalizedPagePath = pagePath.replace(/^\\/+/, "");\n const normalizedAppRouterRoot = typeof data.appRouterRoot === "string" && data.appRouterRoot.replace(/^\\/+|\\/+$/g, "") ? data.appRouterRoot.replace(/^\\/+|\\/+$/g, "") : "app";\n const hasReleaseAssetModules = data.releaseAssetModules && Object.keys(data.releaseAssetModules).length > 0;\n const shouldRenderRscClientPage = data.clientModuleStrategy === "rsc-module" && !hasReleaseAssetModules && isAppRouterPath(normalizedPagePath, normalizedAppRouterRoot);\n const isolatedClientPage = data.isolatedClientPage === true;\n const loadHydrationComponent = async (path, preferRscModule) => {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n if (preferRscModule && isAppRouterPath(normalizedPath, normalizedAppRouterRoot)) {\n const moduleUrl = buildPinnedRscModuleUrl(path, data);\n log("Loading App Router component from RSC module:", moduleUrl);\n const module = await importSnapshotBoundModule(moduleUrl);\n return module.default || module;\n }\n return loadComponent(path, data);\n };\n let pageModuleError = null;\n if (data.pagePath) {\n const moduleUrl = shouldRenderRscClientPage ? buildPinnedRscModuleUrl(data.pagePath, data) : pathToModuleUrl(data.pagePath, data.studioEmbed, data);\n log("Loading page from hydration data:", moduleUrl);\n try {\n pageModule = await importSnapshotBoundModule(moduleUrl);\n } catch (error) {\n pageModuleError = error;\n logError("Failed to load page from hydration data:", error);\n }\n }\n if (!pageModule) {\n const pageSlug = resolvedPathname === "/" ? "index" : resolvedPathname.slice(1);\n log("Falling back to Pages Router pattern:", pageSlug);\n const prefix = pageSlug.startsWith("@/") ? "" : "/pages";\n const basePath = moduleServerUrl2 + prefix + "/" + pageSlug;\n pageModule = await loadPageModuleWithIndexFallback(\n basePath,\n pageSlug,\n pageModuleError,\n (moduleUrl) => importSnapshotBoundModule(appendDependencyPinningVersion(moduleUrl, data))\n );\n }\n if (!pageModule) {\n logError("Page module failed to load");\n return;\n }\n const PageComponent = pageModule.default || pageModule;\n if (!PageComponent) {\n logError("Page component not found");\n return;\n }\n const normalizedParams = flattenRouteParams(data.params);\n const pageProps = { ...data.props || {}, params: normalizedParams };\n let tree = React2.createElement(PageComponent, pageProps);\n const layouts = data.layouts;\n if (layouts?.length) {\n for (let i = layouts.length - 1; i >= 0; i--) {\n const layout = layouts[i];\n if (!layout) continue;\n const LayoutComponent = await loadHydrationComponent(\n layout.path,\n shouldRenderRscClientPage\n );\n if (LayoutComponent) {\n const WrappedLayoutComponent = shouldRenderRscClientPage && isRootAppLayoutPath(layout.path, normalizedAppRouterRoot) ? unwrapAppRouterDocumentLayout(LayoutComponent, React2) : LayoutComponent;\n const layoutProps = data.layoutProps?.[layout.path] || {};\n tree = React2.createElement(\n WrappedLayoutComponent,\n { ...layoutProps, children: tree }\n );\n }\n }\n }\n if (data.appPath && !isolatedClientPage) {\n const AppComponent = await loadHydrationComponent(data.appPath, shouldRenderRscClientPage);\n if (AppComponent) {\n tree = React2.createElement(AppComponent, { children: tree });\n }\n }\n if (data.errorPath) {\n const ErrorComponent = await loadHydrationComponent(\n data.errorPath,\n shouldRenderRscClientPage\n );\n if (ErrorComponent) {\n class AppRouterErrorBoundary extends React2.Component {\n constructor(props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n static getDerivedStateFromError(error) {\n return { hasError: true, error };\n }\n render() {\n if (this.state.hasError) {\n return React2.createElement(ErrorComponent, {\n error: this.state.error,\n reset: () => this.setState({ hasError: false, error: null })\n });\n }\n return this.props.children;\n }\n }\n tree = React2.createElement(AppRouterErrorBoundary, null, tree);\n }\n }\n const headings = data.headings || [];\n const pageContext = {\n slug: data.slug || "",\n path: data.pagePath || resolvedPathname,\n params: normalizedParams,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n frontmatter: data.frontmatter || {},\n data: data.props || {},\n headings,\n mdxHeadings: headings\n // Alias for backwards compatibility\n };\n tree = React2.createElement(PageContextProvider2, { pageContext, children: tree });\n tree = React2.createElement(RouterProvider2, { router: deps.router, children: tree });\n const container = isolatedClientPage ? document2.getElementById("veryfront-page-island") : document2.getElementById("root");\n if (!container) {\n if (isolatedClientPage) {\n throw new Error("Isolated client page root not found");\n }\n return;\n }\n if (container.__reactRoot) {\n container.__reactRoot.render(tree);\n log("Page re-rendered");\n return;\n }\n if (shouldRenderRscClientPage) {\n container.__reactRoot = env2.createRoot(container);\n container.__reactRoot.render(tree);\n log("Client-side React app rendered successfully");\n } else {\n const { hydrateRoot } = await import("react-dom/client");\n const options = {\n identifierPrefix: "vf",\n onRecoverableError: (error) => {\n if (data.dev && DEBUG) {\n log("Hydration mismatch (suppressed):", error.message);\n }\n }\n };\n container.__reactRoot = hydrateRoot(container, tree, options);\n log("Client-side React app hydrated successfully");\n }\n if (window.__veryfrontHydrationComplete) {\n window.__veryfrontHydrationComplete();\n }\n } catch (error) {\n logError("Client initialization error:", error);\n if (window.__veryfrontHydrationFailed) {\n window.__veryfrontHydrationFailed(error);\n }\n }\n }\n function start() {\n window.__veryfrontRenderPage = renderPage;\n void renderPage(window.location.pathname);\n const initialDataScript = findServerHydrationDataElement(document2);\n if (initialDataScript) {\n try {\n const pageData = JSON.parse(initialDataScript.textContent || "{}");\n if (pageData.pagePath) {\n window.history.replaceState({ pageData, scrollY: 0 }, "", window.location.href);\n log("Stored initial page data in history state");\n }\n } catch (_) {\n }\n }\n }\n return { renderPage, start };\n}\n\n// src/html/hydration-script-builder/runtime/navigation-store.ts\nvar NAVIGATION_STORE_REGISTRY_KEY = "veryfront.navigation.store.v1";\nfunction resolveNavigationStore(RouterRuntime2) {\n const usesRegistryFallback2 = typeof RouterRuntime2.getNavigationStore !== "function";\n if (!usesRegistryFallback2) {\n return {\n usesRegistryFallback: usesRegistryFallback2,\n getNavigationStore: RouterRuntime2.getNavigationStore\n };\n }\n return {\n usesRegistryFallback: usesRegistryFallback2,\n getNavigationStore: () => {\n const storeKey = Symbol.for(NAVIGATION_STORE_REGISTRY_KEY);\n const registry = globalThis;\n const existing = registry[storeKey];\n if (existing) return existing;\n const listeners = /* @__PURE__ */ new Set();\n let navigator = null;\n const store = {\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n getHref() {\n const loc = globalThis.location;\n return loc ? loc.pathname + loc.search + loc.hash : "/";\n },\n notify() {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n }\n }\n },\n navigate(href, options) {\n if (navigator) return navigator(href, options);\n globalThis.location?.assign(href);\n return Promise.resolve();\n },\n setNavigator(next) {\n navigator = next;\n }\n };\n registry[storeKey] = store;\n return store;\n }\n };\n}\n\n// src/html/hydration-script-builder/runtime/main.ts\nvar runtimeWindow = globalThis;\nvar runtimeDocument = globalThis.document;\nvar env = {\n window: runtimeWindow,\n document: runtimeDocument,\n fetch: (url, init) => fetch(url, init),\n React,\n RouterProvider,\n PageContextProvider,\n createRoot: (container) => createRoot(container),\n importModule: (moduleUrl) => import(moduleUrl),\n useRouterFromModule,\n setTimeout: (handler, timeout) => setTimeout(handler, timeout),\n clearTimeout: (id) => clearTimeout(id)\n};\nvar logging = createLogging(runtimeWindow);\nvar initialHydrationData = readInitialHydrationData(runtimeDocument);\nvar documentDependencyPinningCacheKey = readDocumentDependencyPinningCacheKey(\n initialHydrationData\n);\nvar routeTiming = createRouteTimingRecorder(runtimeWindow, logging);\nvar snapshotModules = createSnapshotModuleImporter({\n importModule: env.importModule,\n fetchModule: env.fetch,\n reloadDocument: () => runtimeWindow.location.reload(),\n recoveryState: runtimeWindow\n});\nvar componentLoader = createComponentLoader({\n window: runtimeWindow,\n logging,\n moduleServerUrl: moduleServerUrl(runtimeWindow),\n snapshotModules\n});\nruntimeWindow.__veryfrontClearComponentCache = componentLoader.clearComponentCache;\nruntimeWindow.__veryfrontSetStudioEmbed = componentLoader.setStudioEmbed;\nruntimeWindow.__veryfrontSetReleaseId = componentLoader.setReleaseId;\nruntimeWindow.__veryfrontSetReleaseAssetModules = componentLoader.setReleaseAssetModules;\nruntimeWindow.__veryfrontSetHMRRefreshTimestamp = componentLoader.setHMRRefreshTimestamp;\nvar { usesRegistryFallback, getNavigationStore } = resolveNavigationStore(RouterRuntime);\nvar routerRuntime = createRouterRuntime({\n env,\n logging,\n routeTiming,\n componentLoader,\n snapshotModules,\n initialHydrationData,\n documentDependencyPinningCacheKey,\n getNavigationStore,\n navigationStoreUsesRegistryFallback: usesRegistryFallback\n});\ncreateHydrationRenderer({\n env,\n logging,\n componentLoader,\n snapshotModules,\n moduleServerUrl: moduleServerUrl(runtimeWindow),\n router: routerRuntime.router\n}).start();\n';
|
|
9
|
+
export const HYDRATION_RUNTIME_BUNDLE = '// src/html/hydration-script-builder/runtime/main.ts\nimport * as React from "react";\nimport { createRoot } from "react-dom/client";\nimport { RouterProvider, useRouter as useRouterFromModule } from "veryfront/router";\nimport * as RouterRuntime from "veryfront/router";\nimport { PageContextProvider } from "veryfront/context";\n\n// src/routing/flatten-route-params.ts\nfunction flattenRouteParams(params) {\n if (!params) return {};\n const flat = {};\n for (const [key, value] of Object.entries(params)) {\n if (value === void 0) continue;\n flat[key] = Array.isArray(value) ? value.join("/") : value;\n }\n return flat;\n}\n\n// src/html/hydration-script-builder/runtime/shared.ts\nfunction moduleServerUrl(window) {\n return window.location.origin + "/_vf_modules";\n}\nfunction createLogging(window) {\n const DEBUG = Boolean(\n window.__VERYFRONT_DEBUG__ || new URLSearchParams(window.location.search).has("vf_debug")\n );\n const log = DEBUG ? console.log.bind(console, "[Veryfront]") : () => {\n };\n const logError = console.error.bind(console, "[Veryfront]");\n function logBackgroundFetchFailure(reason, path, error) {\n const message = error?.message ?? String(error);\n log(reason + " failed:", path, message);\n }\n const perfTimers = /* @__PURE__ */ new Map();\n const perfStart = DEBUG ? (label) => {\n perfTimers.set(label, performance.now());\n } : () => {\n };\n const perfEnd = DEBUG ? (label) => {\n const start = perfTimers.get(label);\n if (start === void 0) return 0;\n const duration = performance.now() - start;\n perfTimers.delete(label);\n console.log(\n "[Veryfront Perf] %c" + label + ": %c" + duration.toFixed(2) + "ms",\n "color: #888",\n duration > 100 ? "color: #f00; font-weight: bold" : "color: #0a0"\n );\n return duration;\n } : () => 0;\n return { DEBUG, log, logError, logBackgroundFetchFailure, perfStart, perfEnd };\n}\nfunction isAbortError(error) {\n return error?.name === "AbortError";\n}\nfunction resolveDocumentNavigationUrl(target, origin) {\n try {\n const url = new URL(target, origin);\n if (url.protocol === "http:" || url.protocol === "https:") return url.href;\n } catch (_) {\n }\n return null;\n}\nfunction getDocumentNonce(document2) {\n const element = document2.querySelector("script[nonce], style[nonce], link[nonce]");\n if (!element) return void 0;\n return element.nonce || element.getAttribute("nonce") || void 0;\n}\n\n// src/html/hydration-data-element.ts\nvar HYDRATION_DATA_ELEMENT_ID = "veryfront-hydration-data";\nfunction findServerHydrationDataElement(document2) {\n try {\n const matches = [...document2.querySelectorAll(`[id="${HYDRATION_DATA_ELEMENT_ID}"]`)];\n if (matches.length !== 1) return null;\n const body = document2.body;\n if (!body) return null;\n const element = matches[0];\n if (body.firstElementChild !== element && element.parentElement !== body) return null;\n if (element.tagName?.toLowerCase() !== "script") return null;\n if (element.getAttribute("type")?.trim().toLowerCase() !== "application/json") return null;\n return element;\n } catch {\n return null;\n }\n}\n\n// src/html/hydration-script-builder/runtime/hydration-data.ts\nfunction readInitialHydrationData(document2) {\n try {\n const element = findServerHydrationDataElement(document2);\n return JSON.parse(element && element.textContent ? element.textContent : "{}") || {};\n } catch (_) {\n return {};\n }\n}\nfunction readDocumentDependencyPinningCacheKey(initialHydrationData2) {\n return typeof initialHydrationData2.dependencyPinningCacheKey === "string" && initialHydrationData2.dependencyPinningCacheKey.startsWith("on:") ? initialHydrationData2.dependencyPinningCacheKey : null;\n}\n\n// src/html/hydration-script-builder/runtime/snapshot-modules.ts\nvar RECOVERY_STATE_KEY = "__VF_DEPENDENCY_SNAPSHOT_RECOVERY_STARTED__";\nasync function isDependencySnapshotConflictResponse(response) {\n if (!response || response.status !== 409) return false;\n try {\n const clone = response.clone?.() ?? response;\n const body = (await clone.text?.() ?? "").trim();\n return body === "Unknown dependency snapshot" || body === "export default null; // Unknown dependency snapshot";\n } catch (_) {\n return false;\n }\n}\nfunction createSnapshotModuleImporter(deps) {\n async function recoverFromSnapshotBoundModuleFailure(moduleUrl, allowDocumentReload = true) {\n try {\n const parsedUrl = new URL(moduleUrl, "http://veryfront.local");\n const snapshotKeys = parsedUrl.searchParams.getAll("pins");\n const pathMatch = parsedUrl.pathname.match(\n /^\\/_vf_modules\\/_pins\\/([^/]+)(?:\\/|$)/\n );\n if (pathMatch) {\n try {\n snapshotKeys.push(decodeURIComponent(pathMatch[1]));\n } catch (_) {\n return false;\n }\n }\n if (snapshotKeys.length !== 1 || !/^on:[A-Za-z0-9._-]+$/.test(snapshotKeys[0])) return false;\n const response = await deps.fetchModule(moduleUrl, { cache: "no-store" });\n if (!await isDependencySnapshotConflictResponse(response)) return false;\n if (!allowDocumentReload) return true;\n if (deps.recoveryState[RECOVERY_STATE_KEY] === true) return true;\n deps.recoveryState[RECOVERY_STATE_KEY] = true;\n try {\n deps.reloadDocument();\n } catch (_) {\n delete deps.recoveryState[RECOVERY_STATE_KEY];\n return false;\n }\n return true;\n } catch (_) {\n return false;\n }\n }\n async function importSnapshotBoundModule(moduleUrl, allowDocumentReload = true) {\n try {\n return await deps.importModule(moduleUrl);\n } catch (error) {\n const snapshotConflict = await recoverFromSnapshotBoundModuleFailure(\n moduleUrl,\n allowDocumentReload\n );\n if (snapshotConflict && !allowDocumentReload) {\n const conflictError = new Error(\n "Dependency snapshot is unavailable during speculative module prefetch"\n );\n conflictError.name = "DependencySnapshotConflictError";\n conflictError.dependencySnapshotConflict = true;\n conflictError.cause = error;\n throw conflictError;\n }\n throw error;\n }\n }\n return { importSnapshotBoundModule, recoverFromSnapshotBoundModuleFailure };\n}\nfunction isDependencySnapshotConflict(error) {\n return Boolean(error?.dependencySnapshotConflict);\n}\n\n// src/utils/version-constant.ts\nvar VERSION = "0.1.1205";\n\n// src/html/hydration-script-builder/runtime/module-urls.ts\nfunction appendQueryParam(url, key, value) {\n return url + (url.includes("?") ? "&" : "?") + key + "=" + value;\n}\nfunction appendDependencyPinningVersion(url, moduleData) {\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n if (typeof pinKey !== "string" || !pinKey.startsWith("on:")) return url;\n const hashIndex = url.indexOf("#");\n const hash = hashIndex >= 0 ? url.slice(hashIndex) : "";\n const withoutHash = hashIndex >= 0 ? url.slice(0, hashIndex) : url;\n const queryIndex = withoutHash.indexOf("?");\n const base = queryIndex >= 0 ? withoutHash.slice(0, queryIndex) : withoutHash;\n const params = new URLSearchParams(queryIndex >= 0 ? withoutHash.slice(queryIndex + 1) : "");\n const modulePrefix = "/_vf_modules/";\n const prefixIndex = base.indexOf(modulePrefix);\n const origin = prefixIndex >= 0 ? base.slice(0, prefixIndex) : "";\n if (prefixIndex >= 0 && (origin === "" || /^https?:\\/\\/[^/]+$/i.test(origin))) {\n const pathStart = prefixIndex + modulePrefix.length;\n let modulePath = base.slice(pathStart);\n if (modulePath.startsWith("_pins/")) {\n const existingKeyEnd = modulePath.indexOf("/", "_pins/".length);\n const encodedExistingKey = existingKeyEnd < 0 ? modulePath.slice("_pins/".length) : modulePath.slice("_pins/".length, existingKeyEnd);\n let existingKey;\n try {\n existingKey = decodeURIComponent(encodedExistingKey);\n } catch {\n existingKey = void 0;\n }\n if (existingKey && /^on:[A-Za-z0-9._-]+$/.test(existingKey)) {\n if (existingKeyEnd < 0) return url;\n modulePath = modulePath.slice(existingKeyEnd + 1);\n }\n }\n params.delete("pins");\n const query = params.toString();\n return base.slice(0, pathStart) + "_pins/" + encodeURIComponent(pinKey) + "/" + modulePath + (query ? "?" + query : "") + hash;\n }\n params.set("pins", pinKey);\n return base + "?" + params.toString() + hash;\n}\nfunction componentCacheKey(path, moduleData) {\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n return typeof pinKey === "string" && pinKey.startsWith("on:") ? path + "|vf_pins|" + pinKey : path;\n}\nfunction normalizeReleaseAssetModulePath(path) {\n return String(path || "").replace(/^\\/?_vf_modules\\//, "").replace(/^\\/+/, "").replace(/[?#].*$/, "");\n}\nfunction buildPinnedRscModuleUrl(path, moduleData) {\n let moduleUrl = "/_veryfront/rsc/module?rel=" + encodeURIComponent(path);\n const pinKey = moduleData && moduleData.dependencyPinningCacheKey;\n if (typeof pinKey === "string" && pinKey.startsWith("on:")) {\n moduleUrl += "&pins=" + encodeURIComponent(pinKey);\n }\n return moduleUrl;\n}\nfunction buildPageDataEndpoint(path, origin) {\n const targetUrl = new URL(path, origin);\n const normalizedPath = targetUrl.pathname === "/" ? "" : targetUrl.pathname.replace(/^\\//, "");\n const endpointUrl = new URL(\n "/_veryfront/page-data/" + normalizedPath + ".json",\n origin\n );\n endpointUrl.search = targetUrl.search;\n return endpointUrl.pathname + endpointUrl.search;\n}\nfunction pageDataCacheIdentity(path, documentDependencyPinningCacheKey2) {\n return documentDependencyPinningCacheKey2 ? documentDependencyPinningCacheKey2 + "|path:" + path : path;\n}\nfunction assertPageDataMatchesDocumentSnapshot(path, data, documentDependencyPinningCacheKey2) {\n if (!documentDependencyPinningCacheKey2) return data;\n if (data && data.dependencyPinningCacheKey === documentDependencyPinningCacheKey2) {\n return data;\n }\n const error = new Error("Page data dependency snapshot does not match the document");\n error.status = 409;\n error.dependencySnapshotMismatch = true;\n error.path = path;\n throw error;\n}\n\n// src/html/hydration-script-builder/runtime/component-loader.ts\nvar VERYFRONT_RUNTIME_VERSION = VERSION;\nfunction createComponentLoader(deps) {\n const { window, moduleServerUrl: moduleServerUrl2 } = deps;\n const { DEBUG, log, logError } = deps.logging;\n const componentCache = /* @__PURE__ */ new Map();\n const loadingPromises = /* @__PURE__ */ new Map();\n let releaseId = null;\n let releaseAssetModules = null;\n let studioEmbed = false;\n let hmrRefreshTimestamp = null;\n function clearComponentCache(path) {\n if (!path) {\n componentCache.clear();\n loadingPromises.clear();\n log("Cleared all component caches");\n return;\n }\n for (const key of componentCache.keys()) {\n if (key === path || key.startsWith(path + "|vf_pins|")) {\n componentCache.delete(key);\n }\n }\n for (const key of loadingPromises.keys()) {\n if (key === path || key.startsWith(path + "|vf_pins|")) {\n loadingPromises.delete(key);\n }\n }\n log("Cleared component cache for:", path);\n }\n function setReleaseId(value) {\n releaseId = typeof value === "string" && value ? value : null;\n window.__veryfrontReleaseId = releaseId;\n }\n function appendReleaseModuleVersion(url) {\n if (!releaseId || url.includes("vf_release=")) return url;\n let versionedUrl = appendQueryParam(url, "vf_release", encodeURIComponent(releaseId));\n versionedUrl = appendQueryParam(\n versionedUrl,\n "vf_runtime",\n encodeURIComponent(VERYFRONT_RUNTIME_VERSION)\n );\n return versionedUrl;\n }\n function setReleaseAssetModules(value) {\n releaseAssetModules = value && typeof value === "object" && !Array.isArray(value) ? value : null;\n window.__veryfrontReleaseAssetModules = releaseAssetModules;\n }\n function resolveReleaseAssetModuleUrl(path) {\n if (!releaseAssetModules || studioEmbed || hmrRefreshTimestamp) return null;\n const key = normalizeReleaseAssetModulePath(path);\n if (releaseAssetModules[key]) return releaseAssetModules[key];\n const withoutExt = key.replace(/\\.(tsx|ts|jsx|mdx|js|mjs)$/, "");\n const extensions = [".tsx", ".ts", ".jsx", ".mdx", ".js"];\n for (const ext of extensions) {\n const candidate = withoutExt + ext;\n if (releaseAssetModules[candidate]) return releaseAssetModules[candidate];\n }\n return null;\n }\n function pathToModuleUrl(path, embedInStudio, moduleData) {\n const releaseAssetUrl = resolveReleaseAssetModuleUrl(path);\n if (releaseAssetUrl) return releaseAssetUrl;\n const pattern = /(pages|components|app|lib|layouts|shared|features)\\/(.+)\\.(tsx|ts|jsx|mdx)$/;\n const match = path.match(new RegExp("/" + pattern.source)) || path.match(new RegExp("^" + pattern.source));\n let url;\n if (match) {\n url = moduleServerUrl2 + "/" + match[1] + "/" + match[2] + ".js";\n } else {\n const hasKnownExt = /\\.(tsx|ts|jsx|mdx|js|mjs)$/.test(path);\n url = moduleServerUrl2 + "/" + (hasKnownExt ? path.replace(/\\.(tsx|ts|jsx|mdx)$/, ".js") : path + ".js");\n }\n if (embedInStudio) url = appendQueryParam(url, "studio_embed", "true");\n if (hmrRefreshTimestamp) url = appendQueryParam(url, "t", hmrRefreshTimestamp);\n if (!embedInStudio && !hmrRefreshTimestamp) url = appendReleaseModuleVersion(url);\n url = appendDependencyPinningVersion(url, moduleData);\n return url;\n }\n function setStudioEmbed(value) {\n studioEmbed = value;\n window.__veryfrontStudioEmbed = value;\n }\n function setHMRRefreshTimestamp(timestamp) {\n hmrRefreshTimestamp = timestamp;\n window.__veryfrontHMRRefreshTimestamp = timestamp;\n }\n async function loadComponent(path, moduleData, options = {}) {\n if (!path) return null;\n const cacheKey = componentCacheKey(path, moduleData);\n if (componentCache.has(cacheKey)) {\n log("Component cached:", path);\n return componentCache.get(cacheKey);\n }\n const existingPromise = loadingPromises.get(cacheKey);\n if (existingPromise) return existingPromise;\n const loadPromise = (async () => {\n try {\n const moduleUrl = pathToModuleUrl(path, studioEmbed, moduleData);\n const start = DEBUG ? performance.now() : 0;\n log("Loading component:", moduleUrl);\n const module = await deps.snapshotModules.importSnapshotBoundModule(\n moduleUrl,\n options.allowDocumentReload !== false\n );\n const component = module.MDXLayout || module.MainLayout || module.default || module;\n if (DEBUG) {\n const duration = performance.now() - start;\n console.log(\n "[Veryfront Perf] %cimport:" + path.split("/").pop() + ": %c" + duration.toFixed(2) + "ms",\n "color: #888",\n duration > 50 ? "color: #f00; font-weight: bold" : "color: #0a0"\n );\n }\n componentCache.set(cacheKey, component);\n return component;\n } catch (error) {\n if (isDependencySnapshotConflict(error)) throw error;\n logError("Failed to load component:", path, error);\n return null;\n } finally {\n loadingPromises.delete(cacheKey);\n }\n })();\n loadingPromises.set(cacheKey, loadPromise);\n return loadPromise;\n }\n return {\n loadComponent,\n pathToModuleUrl,\n clearComponentCache,\n setStudioEmbed,\n setReleaseId,\n setReleaseAssetModules,\n setHMRRefreshTimestamp\n };\n}\n\n// src/html/hydration-script-builder/runtime/route-timing.ts\nvar MAX_ROUTE_TIMINGS = 100;\nvar MAX_SERVER_TIMING_LENGTH = 1024;\nfunction routeTimingNow() {\n return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();\n}\nfunction sanitizeServerTimingMetricName(name) {\n return String(name || "").trim().replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 128);\n}\nfunction sanitizeServerTimingHeader(value) {\n if (!value) return null;\n const metrics = [];\n const printable = String(value).replace(/[^\\x20-\\x7E]/g, " ").trim();\n if (!printable) return null;\n for (const item of printable.split(",")) {\n const segments = item.split(";").map((segment) => segment.trim()).filter(Boolean);\n const name = sanitizeServerTimingMetricName(segments[0]);\n if (!name) continue;\n for (const segment of segments.slice(1)) {\n const [key, rawValue = ""] = segment.split("=");\n if ((key ?? "").trim().toLowerCase() !== "dur") continue;\n const duration = Number(rawValue.trim().replace(/^"|"$/g, ""));\n if (!Number.isFinite(duration) || duration < 0) continue;\n metrics.push(name + ";dur=" + (Math.round(duration * 100) / 100).toFixed(2));\n break;\n }\n }\n const sanitized = metrics.join(", ");\n return sanitized ? sanitized.slice(0, MAX_SERVER_TIMING_LENGTH) : null;\n}\nfunction parseServerTimingMetrics(value) {\n const header = sanitizeServerTimingHeader(value);\n if (!header) return null;\n const metrics = {};\n for (const item of header.split(",")) {\n const segments = item.split(";").map((segment) => segment.trim()).filter(Boolean);\n const name = sanitizeServerTimingMetricName(segments[0]);\n if (!name) continue;\n for (const segment of segments.slice(1)) {\n const [key, rawValue = ""] = segment.split("=");\n if ((key ?? "").trim().toLowerCase() !== "dur") continue;\n const duration = Number(rawValue.trim().replace(/^"|"$/g, ""));\n if (Number.isFinite(duration) && duration >= 0) {\n metrics[name] = Math.round(duration * 100) / 100;\n }\n }\n }\n return Object.keys(metrics).length ? metrics : null;\n}\nfunction readResponseServerTiming(response) {\n try {\n return sanitizeServerTimingHeader(response.headers?.get("server-timing"));\n } catch (_) {\n return null;\n }\n}\nfunction roundRouteTimingValue(value) {\n return Math.round(value * 100) / 100;\n}\nfunction extractResourceTiming(entry) {\n const fields = [\n "startTime",\n "requestStart",\n "responseStart",\n "responseEnd",\n "duration",\n "transferSize",\n "encodedBodySize",\n "decodedBodySize"\n ];\n const timing = {};\n for (const field of fields) {\n const value = entry?.[field];\n if (typeof value === "number" && Number.isFinite(value) && value >= 0) {\n timing[field] = roundRouteTimingValue(value);\n }\n }\n return Object.keys(timing).length ? timing : null;\n}\nfunction createRouteTimingRecorder(window, logging2) {\n const { log } = logging2;\n function emitRouteTiming(phase, path, startedAt, detail = {}) {\n const entry = {\n phase,\n path,\n duration: Math.max(0, routeTimingNow() - startedAt),\n timestamp: Date.now(),\n ...detail\n };\n const timings = Array.isArray(window.__veryfrontRouteTimings) ? window.__veryfrontRouteTimings : [];\n timings.push(entry);\n if (timings.length > MAX_ROUTE_TIMINGS) {\n timings.splice(0, timings.length - MAX_ROUTE_TIMINGS);\n }\n window.__veryfrontRouteTimings = timings;\n try {\n window.dispatchEvent(new CustomEvent("veryfront:route-timing", { detail: entry }));\n } catch (_) {\n }\n log("Route timing:", entry);\n return entry;\n }\n function getPageDataResourceTiming(endpoint, fetchStartedAt) {\n try {\n if (typeof performance === "undefined" || typeof performance.getEntriesByName !== "function") {\n return null;\n }\n const href = new URL(endpoint, window.location.href).href;\n const entries = performance.getEntriesByName(href, "resource");\n if (!entries.length) return null;\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index];\n const responseEnd = entry?.responseEnd;\n if (typeof responseEnd === "number" && Number.isFinite(responseEnd) && responseEnd + 1 >= fetchStartedAt) {\n return extractResourceTiming(entry);\n }\n }\n return null;\n } catch (_) {\n return null;\n }\n }\n function buildPageDataTimingDetail(response, endpoint, fetchStartedAt, source) {\n const detail = { source, status: response.status };\n const serverTiming = readResponseServerTiming(response);\n if (serverTiming) {\n detail.serverTiming = serverTiming;\n const serverTimingMetrics = parseServerTimingMetrics(serverTiming);\n if (serverTimingMetrics) detail.serverTimingMetrics = serverTimingMetrics;\n }\n const resourceTiming = getPageDataResourceTiming(response.url || endpoint, fetchStartedAt);\n if (resourceTiming) detail.resourceTiming = resourceTiming;\n return detail;\n }\n return { emitRouteTiming, buildPageDataTimingDetail };\n}\n\n// src/html/managed-head-protocol.ts\nvar HEAD_PROVENANCE_ATTRIBUTE = "data-vf-head";\nvar HEAD_LEGACY_MANAGED_ATTRIBUTE = "data-veryfront-managed";\nvar HEAD_CONTENT_HASH_ATTRIBUTE = "data-vf-hash";\nvar HEAD_REACT_MANAGED_ATTRIBUTE = "data-vf-react-head";\nvar HEAD_REACT_OWNER_ATTRIBUTE = "data-vf-react-head-owner";\nvar HEAD_ROUTE_MANAGED_ATTRIBUTE = "data-vf-route-head";\nvar HEAD_SERVER_COMMIT_ATTRIBUTE = "data-vf-server-head-commit";\nvar HEAD_SHELL_PROVENANCE_ATTRIBUTE = "data-vf-shell-head";\nvar HEAD_SSR_PAYLOAD_ATTRIBUTE = "data-vf-ssr-head";\nvar MAX_MANAGED_HEAD_BYTES = 2 * 1024 * 1024;\nvar MAX_MANAGED_HEAD_PAYLOAD_BYTES = MAX_MANAGED_HEAD_BYTES * 2;\nvar SINGLETON_META_KEYS = /* @__PURE__ */ new Set([\n "description",\n "robots",\n "viewport",\n "referrer",\n "color-scheme",\n "application-name",\n "generator",\n "og:title",\n "og:description",\n "og:url",\n "og:type",\n "og:site_name",\n "og:locale",\n "twitter:card",\n "twitter:site",\n "twitter:creator",\n "twitter:title",\n "twitter:description",\n "twitter:image",\n "twitter:image:alt"\n]);\nvar SINGLETON_LINK_RELS = /* @__PURE__ */ new Set([\n "canonical",\n "manifest",\n "amphtml"\n]);\nvar MAX_HEAD_ATTRIBUTE_VALUE_BYTES = 64 * 1024;\nvar MAX_HEAD_ATTRIBUTE_BYTES = 1024 * 1024;\nvar MAX_HEAD_CONTENT_BYTES = 1024 * 1024;\nvar headTextEncoder = new TextEncoder();\nvar BOOLEAN_HEAD_ATTRIBUTES = /* @__PURE__ */ new Set([\n "async",\n "defer",\n "disabled",\n "itemscope",\n "nomodule"\n]);\nfunction isHeadFrameworkAttribute(name) {\n switch (name.toLowerCase()) {\n case HEAD_PROVENANCE_ATTRIBUTE:\n case HEAD_LEGACY_MANAGED_ATTRIBUTE:\n case HEAD_CONTENT_HASH_ATTRIBUTE:\n case HEAD_REACT_MANAGED_ATTRIBUTE:\n case HEAD_REACT_OWNER_ATTRIBUTE:\n case HEAD_ROUTE_MANAGED_ATTRIBUTE:\n case HEAD_SERVER_COMMIT_ATTRIBUTE:\n case HEAD_SHELL_PROVENANCE_ATTRIBUTE:\n case HEAD_SSR_PAYLOAD_ATTRIBUTE:\n return true;\n default:\n return false;\n }\n}\nfunction normalizeHeadIdentityValue(value) {\n const normalized = value?.trim().toLowerCase();\n return normalized || void 0;\n}\nfunction readOwnString(record, key) {\n try {\n const descriptor = Reflect.getOwnPropertyDescriptor(record, key);\n return descriptor && !descriptor.get && !descriptor.set && "value" in descriptor && typeof descriptor.value === "string" ? descriptor.value : void 0;\n } catch {\n return void 0;\n }\n}\nfunction headMetaSingletonKeyFromRecord(meta) {\n if (readOwnString(meta, "charset") !== void 0) return "meta:charset";\n const key = normalizeHeadIdentityValue(\n readOwnString(meta, "property") ?? readOwnString(meta, "name")\n );\n if (!key) return void 0;\n if (key === "theme-color") {\n return `meta:theme-color:${readOwnString(meta, "media")?.trim() ?? ""}`;\n }\n return SINGLETON_META_KEYS.has(key) ? `meta:${key}` : void 0;\n}\nfunction headLinkSingletonKeyFromRecord(link) {\n const rel = normalizeHeadIdentityValue(readOwnString(link, "rel"));\n return rel && SINGLETON_LINK_RELS.has(rel) ? `link:${rel}` : void 0;\n}\n\n// src/html/client-head-manager.ts\nvar HEAD_MANAGER_STATE_SYMBOL = /* @__PURE__ */ Symbol.for(\n "veryfront.client-head-manager.v2"\n);\nvar CROSS_PAGE_PRESERVED_SINGLETON_KEYS = /* @__PURE__ */ new Set([\n "meta:viewport",\n "link:manifest"\n]);\nfunction getClientHeadManagerState() {\n const globalState = globalThis;\n return globalState[HEAD_MANAGER_STATE_SYMBOL] ?? (globalState[HEAD_MANAGER_STATE_SYMBOL] = {\n documents: /* @__PURE__ */ new WeakMap()\n });\n}\nfunction readElementAttributes(element) {\n const attributes = [];\n for (const attribute of element.attributes) {\n const name = attribute.name.toLowerCase();\n if (isHeadFrameworkAttribute(name)) continue;\n const nonce = name === "nonce" && "nonce" in element ? element.nonce : "";\n const value = BOOLEAN_HEAD_ATTRIBUTES.has(name) ? "" : nonce || attribute.value;\n attributes.push([name, value]);\n }\n return attributes.sort(([left], [right]) => left.localeCompare(right));\n}\nfunction elementSingletonKey(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName === "title") return "title";\n const attributes = Object.fromEntries(readElementAttributes(element));\n if (tagName === "meta") return headMetaSingletonKeyFromRecord(attributes);\n if (tagName === "link") return headLinkSingletonKeyFromRecord(attributes);\n return void 0;\n}\nfunction promoteToShellHeadBaseline(element) {\n for (const attribute of [...element.attributes]) {\n if (isHeadFrameworkAttribute(attribute.name)) {\n element.removeAttribute(attribute.name);\n }\n }\n element.setAttribute(HEAD_SHELL_PROVENANCE_ATTRIBUTE, "true");\n}\nfunction isCrossPagePreservedSingleton(element, singletonKey = elementSingletonKey(element)) {\n return element.parentElement !== null && singletonKey !== void 0 && CROSS_PAGE_PRESERVED_SINGLETON_KEYS.has(singletonKey);\n}\nfunction isFrameworkOwnedHeadElement(element) {\n return element.getAttribute(HEAD_PROVENANCE_ATTRIBUTE) === "true" || element.getAttribute(HEAD_REACT_MANAGED_ATTRIBUTE) === "true" || element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1" || element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true" || element.getAttribute(HEAD_SHELL_PROVENANCE_ATTRIBUTE) === "true";\n}\nfunction retireFrameworkHeadElement(element) {\n if (isCrossPagePreservedSingleton(element)) {\n promoteToShellHeadBaseline(element);\n return;\n }\n element.remove();\n}\nfunction retireClientHeadOwnership(targetDocument) {\n const manager = getClientHeadManagerState().documents.get(targetDocument);\n if (manager) {\n manager.retire();\n return;\n }\n for (const element of [...targetDocument.head?.children ?? []]) {\n if (isFrameworkOwnedHeadElement(element)) retireFrameworkHeadElement(element);\n }\n}\n\n// src/html/client-route-head.ts\nfunction updateRouteTitle(title, targetDocument = document) {\n if (typeof title !== "string" || !title) return;\n const titles = [...targetDocument.head.querySelectorAll("title")];\n if (titles.some((element) => element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1")) {\n return;\n }\n let titleElement = titles.find(\n (element) => element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true"\n );\n for (const element of titles) {\n if (element !== titleElement) element.remove();\n }\n if (!titleElement) {\n titleElement = targetDocument.createElement("title");\n titleElement.setAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE, "true");\n targetDocument.head.appendChild(titleElement);\n }\n titleElement.textContent = title;\n}\nfunction updateRouteMetaTag(targetDocument, selector, attributeName, attributeValue, content) {\n const matches = [...targetDocument.head.querySelectorAll(selector)];\n if (matches.some((element) => element.getAttribute(HEAD_LEGACY_MANAGED_ATTRIBUTE) === "1")) {\n return;\n }\n let metaTag = matches.find(\n (element) => element.getAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE) === "true"\n );\n if (!metaTag) {\n metaTag = targetDocument.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n metaTag.setAttribute(HEAD_ROUTE_MANAGED_ATTRIBUTE, "true");\n targetDocument.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction updateRouteMetaTags(metadata, targetDocument = document) {\n if (typeof metadata.description === "string" && metadata.description) {\n updateRouteMetaTag(\n targetDocument,\n \'meta[name="description"]\',\n "name",\n "description",\n metadata.description\n );\n }\n if (typeof metadata.ogTitle === "string" && metadata.ogTitle) {\n updateRouteMetaTag(\n targetDocument,\n \'meta[property="og:title"]\',\n "property",\n "og:title",\n metadata.ogTitle\n );\n }\n}\nfunction handoffClientRouteMetadata(metadata, targetDocument = document) {\n const retainedTitle = targetDocument.title;\n retireClientHeadOwnership(targetDocument);\n updateRouteTitle(\n typeof metadata.title === "string" && metadata.title ? metadata.title : retainedTitle,\n targetDocument\n );\n updateRouteMetaTags(metadata, targetDocument);\n}\n\n// src/html/hydration-script-builder/runtime/router.ts\nvar FETCH_TIMEOUT_MS = 1e4;\nvar MAX_RETRIES = 2;\nvar MAX_CACHE_SIZE = 50;\nvar CACHE_TTL_MS = 5 * 60 * 1e3;\nvar BACKGROUND_REFRESH_INTERVAL_MS = 30 * 1e3;\nvar PREFETCH_DELAY_MS = 100;\nvar MAX_PREFETCH_PATHS = 100;\nvar IDLE_PREFETCH_DELAY_MS = 1200;\nvar IDLE_PREFETCH_MAX_LINKS = 4;\nvar VIEWPORT_PREFETCH_MAX_LINKS = 8;\nvar PAGE_DATA_PREFETCH_CONCURRENCY = 2;\nvar VIEWPORT_PREFETCH_ROOT_MARGIN = "200px";\nvar MAX_SCROLL_POSITIONS = 100;\nfunction createRouterRuntime(deps) {\n const { env: env2, logging: logging2, routeTiming: routeTiming2, componentLoader: componentLoader2, snapshotModules: snapshotModules2 } = deps;\n const { window, document: document2, React: React2, RouterProvider: RouterProvider2, PageContextProvider: PageContextProvider2 } = env2;\n const { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = env2;\n const { log, logError, logBackgroundFetchFailure, perfStart, perfEnd } = logging2;\n const { emitRouteTiming, buildPageDataTimingDetail } = routeTiming2;\n const { loadComponent } = componentLoader2;\n const documentPinKey = deps.documentDependencyPinningCacheKey;\n let hydrationResolve;\n let hydrationReject;\n const hydrationPromise = new Promise((resolve, reject) => {\n hydrationResolve = resolve;\n hydrationReject = reject;\n });\n let hydrationCompleted = false;\n let hydrationFailed = false;\n function signalHydrationComplete() {\n hydrationCompleted = true;\n hydrationResolve();\n log("Hydration complete signal received");\n }\n function signalHydrationFailed(error) {\n hydrationFailed = true;\n hydrationReject(error);\n logError("Hydration failed signal received:", error);\n }\n window.__veryfrontHydrationComplete = signalHydrationComplete;\n window.__veryfrontHydrationFailed = signalHydrationFailed;\n function pageDataCacheIdentity2(path) {\n return pageDataCacheIdentity(path, documentPinKey);\n }\n function navigateDocument(target) {\n const safeUrl = resolveDocumentNavigationUrl(target, window.location.origin);\n if (safeUrl) {\n window.location.href = safeUrl;\n return;\n }\n logError("Refusing an unsafe document navigation:", target);\n window.location.reload();\n }\n let clientBuildVersion = null;\n function checkVersionMismatch(newVersion) {\n if (!clientBuildVersion) {\n clientBuildVersion = newVersion;\n log("Build version initialized:", newVersion);\n return false;\n }\n if (newVersion.serverStart !== clientBuildVersion.serverStart) {\n log("Server restarted, reloading...", {\n old: clientBuildVersion.serverStart,\n new: newVersion.serverStart\n });\n return true;\n }\n if (newVersion.framework !== clientBuildVersion.framework) {\n log("Framework version changed, reloading...", {\n old: clientBuildVersion.framework,\n new: newVersion.framework\n });\n return true;\n }\n if (newVersion.projectUpdated && clientBuildVersion.projectUpdated && newVersion.projectUpdated !== clientBuildVersion.projectUpdated) {\n log("Project content updated, reloading...", {\n old: clientBuildVersion.projectUpdated,\n new: newVersion.projectUpdated\n });\n return true;\n }\n return false;\n }\n const pageDataCache = /* @__PURE__ */ new Map();\n const pendingPageDataFetches = /* @__PURE__ */ new Map();\n const backgroundRefreshTimestamps = /* @__PURE__ */ new Map();\n function getCachedPageData(path) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const entry = pageDataCache.get(cacheIdentity);\n if (!entry) return null;\n if (Date.now() - entry.timestamp < CACHE_TTL_MS) return entry.data;\n pageDataCache.delete(cacheIdentity);\n backgroundRefreshTimestamps.delete(cacheIdentity);\n return null;\n }\n function setCachedPageData(path, data) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n if (pageDataCache.size >= MAX_CACHE_SIZE) {\n const oldest = pageDataCache.keys().next().value;\n if (oldest) {\n pageDataCache.delete(oldest);\n backgroundRefreshTimestamps.delete(oldest);\n }\n }\n pageDataCache.set(cacheIdentity, { data, timestamp: Date.now() });\n }\n const scrollPositions = /* @__PURE__ */ new Map();\n function saveScrollPosition(path) {\n if (scrollPositions.size >= MAX_SCROLL_POSITIONS) {\n const oldest = scrollPositions.keys().next().value;\n if (oldest) scrollPositions.delete(oldest);\n }\n scrollPositions.set(path, window.scrollY);\n }\n function restoreScrollPosition(path) {\n const savedY = scrollPositions.get(path);\n if (savedY === void 0) return false;\n requestAnimationFrame(() => window.scrollTo(0, savedY));\n return true;\n }\n let progressBar = null;\n let progressTimeout = null;\n function showNavigationProgress() {\n if (!progressBar) {\n progressBar = document2.createElement("div");\n progressBar.id = "vf-nav-progress";\n progressBar.style.cssText = "position:fixed;top:0;left:0;height:3px;width:0;background:linear-gradient(90deg,#0066ff,#00aaff);z-index:99999;transition:width 0.3s ease-out,opacity 0.2s;opacity:1;";\n document2.body.prepend(progressBar);\n }\n progressBar.style.opacity = "1";\n progressBar.style.width = "30%";\n progressTimeout = setTimeout2(() => {\n if (progressBar?.style) progressBar.style.width = "70%";\n }, 300);\n document2.body.setAttribute("aria-busy", "true");\n }\n function hideNavigationProgress() {\n if (progressTimeout) {\n clearTimeout2(progressTimeout);\n progressTimeout = null;\n }\n if (progressBar) {\n progressBar.style.width = "100%";\n setTimeout2(() => {\n if (!progressBar) return;\n progressBar.style.opacity = "0";\n setTimeout2(() => {\n if (progressBar) progressBar.style.width = "0";\n }, 200);\n }, 150);\n }\n document2.body.removeAttribute("aria-busy");\n }\n let currentAbortController = null;\n function sleep(ms) {\n return new Promise((resolve) => setTimeout2(resolve, ms));\n }\n async function fetchWithRetry(url, options, maxRetries = MAX_RETRIES) {\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController();\n const callerSignal = options.signal;\n const abortFromCaller = () => controller.abort();\n if (callerSignal?.aborted) controller.abort();\n callerSignal?.addEventListener("abort", abortFromCaller, { once: true });\n const timeout = setTimeout2(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n const response = await env2.fetch(url, { ...options, signal: controller.signal });\n clearTimeout2(timeout);\n callerSignal?.removeEventListener("abort", abortFromCaller);\n if (response.ok) return response;\n if (response.status >= 500 && attempt < maxRetries) {\n log("Server error, retrying...", response.status);\n await sleep(Math.pow(2, attempt) * 500);\n continue;\n }\n return response;\n } catch (error) {\n clearTimeout2(timeout);\n callerSignal?.removeEventListener("abort", abortFromCaller);\n if (error.name === "AbortError" && callerSignal?.aborted) throw error;\n if (attempt === maxRetries) throw error;\n log("Fetch failed, retrying...", error.message);\n await sleep(Math.pow(2, attempt) * 500);\n }\n }\n throw new Error("Failed to fetch page data");\n }\n async function fetchPageDataFresh(path, signal, options = {}) {\n const {\n triggerReloadOnVersionMismatch = false,\n recordRouteTiming = false,\n timingSource = "network"\n } = options;\n const endpoint = buildPageDataEndpoint(path, window.location.origin);\n const startedAt = recordRouteTiming ? routeTimingNow() : 0;\n log("Fetching page data:", path);\n perfStart("fetch:" + path);\n const headers = options.prefetch ? { "X-Veryfront-Prefetch": "1" } : { "X-Veryfront-Navigation": "spa" };\n if (documentPinKey) {\n headers["X-Veryfront-Dependency-Pins"] = documentPinKey;\n }\n const response = await fetchWithRetry(endpoint, {\n headers,\n signal\n }, options.prefetch ? 0 : MAX_RETRIES);\n if (!response.ok) {\n perfEnd("fetch:" + path);\n if (recordRouteTiming) {\n emitRouteTiming(\n "page-data",\n path,\n startedAt,\n buildPageDataTimingDetail(response, endpoint, startedAt, timingSource)\n );\n }\n const error = new Error("Failed to fetch page data: " + response.status);\n error.status = response.status;\n throw error;\n }\n perfStart("parse:" + path);\n const data = assertPageDataMatchesDocumentSnapshot(\n path,\n await response.json(),\n documentPinKey\n );\n perfEnd("parse:" + path);\n perfEnd("fetch:" + path);\n if (recordRouteTiming) {\n emitRouteTiming(\n "page-data",\n path,\n startedAt,\n buildPageDataTimingDetail(response, endpoint, startedAt, timingSource)\n );\n }\n if (triggerReloadOnVersionMismatch) {\n const checkedData = handlePageDataVersionMismatch(path, data);\n if (checkedData !== data) return checkedData;\n }\n setCachedPageData(path, data);\n return data;\n }\n function handlePageDataVersionMismatch(path, data) {\n if (data.buildVersion && checkVersionMismatch(data.buildVersion)) {\n log("Version mismatch detected, performing full page reload to:", path);\n navigateDocument(path);\n return new Promise(() => {\n });\n }\n return data;\n }\n function startPageDataFetch(path, signal, options = {}) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const request = fetchPageDataFresh(path, signal, options).finally(() => {\n if (options.trackPending !== false && pendingPageDataFetches.get(cacheIdentity) === request) {\n pendingPageDataFetches.delete(cacheIdentity);\n }\n });\n if (options.trackPending !== false) {\n pendingPageDataFetches.set(cacheIdentity, request);\n }\n return request;\n }\n function fetchPageDataDeduped(path) {\n const pending = pendingPageDataFetches.get(pageDataCacheIdentity2(path));\n if (pending) return pending;\n return startPageDataFetch(path, null);\n }\n function refreshPageDataInBackground(path) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n const lastRefreshAt = backgroundRefreshTimestamps.get(cacheIdentity) || 0;\n const now = Date.now();\n if (now - lastRefreshAt < BACKGROUND_REFRESH_INTERVAL_MS) return;\n backgroundRefreshTimestamps.set(cacheIdentity, now);\n fetchPageDataDeduped(path).catch((error) => {\n logBackgroundFetchFailure("Stale page data refresh", path, error);\n });\n }\n async function fetchPageDataForNavigation(path, signal) {\n const startedAt = routeTimingNow();\n const cached = getCachedPageData(path);\n if (cached) {\n log("Using cached page data:", path);\n refreshPageDataInBackground(path);\n emitRouteTiming("page-data", path, startedAt, { source: "cache" });\n return cached;\n }\n const pending = pendingPageDataFetches.get(pageDataCacheIdentity2(path));\n if (pending) {\n log("Reusing pending page data fetch for navigation:", path);\n const data = await pending;\n emitRouteTiming("page-data", path, startedAt, { source: "deduped" });\n return handlePageDataVersionMismatch(path, data);\n }\n return startPageDataFetch(path, signal, {\n triggerReloadOnVersionMismatch: true,\n recordRouteTiming: true,\n timingSource: "network"\n });\n }\n function fetchPageDataForPrefetch(path, signal) {\n if (getCachedPageData(path)) return Promise.resolve();\n return startPageDataFetch(path, signal, { prefetch: true, trackPending: false }).then((data) => preloadModulesForPageData(data, path)).catch((error) => {\n if (!isAbortError(error)) {\n logBackgroundFetchFailure("Page data prefetch", path, error);\n }\n throw error;\n });\n }\n let currentPath = window.location.pathname;\n let isNavigating = false;\n async function navigateSPA(href, historyMode = "push", restoreScroll = false) {\n currentAbortController?.abort();\n if (isNavigating) return;\n isNavigating = true;\n const [navigationPath] = href.split("#");\n removeQueuedPrefetch(navigationPath || href);\n abortActiveSpeculativePrefetches();\n currentAbortController = new AbortController();\n const signal = currentAbortController.signal;\n const navigationStartedAt = routeTimingNow();\n showNavigationProgress();\n perfStart("nav:total:" + href);\n try {\n log("SPA navigating to:", href);\n saveScrollPosition(currentPath);\n const [path, hash] = href.split("#");\n const targetPath = path || currentPath;\n perfStart("nav:fetchData:" + href);\n const pageData = await fetchPageDataForNavigation(targetPath, signal);\n perfEnd("nav:fetchData:" + href);\n if (signal.aborted) return;\n if (pageData && pageData.redirect && typeof pageData.redirect.destination === "string") {\n const redirectUrl = resolveDocumentNavigationUrl(\n pageData.redirect.destination,\n window.location.origin\n );\n if (redirectUrl) {\n log("SPA navigation redirect -> " + redirectUrl);\n window.location.href = redirectUrl;\n return;\n }\n }\n if (historyMode === "push") {\n window.history.pushState({ pageData, scrollY: 0 }, "", href);\n } else if (historyMode === "replace") {\n window.history.replaceState({ pageData, scrollY: 0 }, "", href);\n }\n currentPath = targetPath;\n router.pathname = targetPath;\n router.query = Object.fromEntries(new URLSearchParams(window.location.search));\n router.params = flattenRouteParams(pageData.params);\n perfStart("nav:render:" + href);\n await renderPageFromData(pageData, targetPath);\n perfEnd("nav:render:" + href);\n if (restoreScroll) {\n restoreScrollPosition(targetPath);\n } else if (hash) {\n requestAnimationFrame(() => {\n const target = document2.getElementById(hash);\n if (target) {\n target.scrollIntoView({ behavior: "smooth" });\n return;\n }\n window.scrollTo(0, 0);\n });\n } else {\n window.scrollTo(0, 0);\n }\n hideNavigationProgress();\n perfEnd("nav:total:" + href);\n emitRouteTiming("total", targetPath, navigationStartedAt, {\n href,\n historyMode,\n restoreScroll\n });\n log("SPA navigation complete");\n } catch (error) {\n hideNavigationProgress();\n if (error.name === "AbortError") {\n log("Navigation aborted");\n return;\n }\n logError("SPA navigation failed:", error.message);\n if (error.status === 404) {\n logError("Page not found:", href);\n }\n navigateDocument(href);\n } finally {\n isNavigating = false;\n currentAbortController = null;\n processPageDataPrefetchQueue();\n }\n }\n async function loadPageDataComponent(pageData, path, options = {}) {\n if (!pageData.isolatedClientPage) return loadComponent(path, pageData, options);\n const moduleUrl = buildPinnedRscModuleUrl(path, pageData);\n const module = await snapshotModules2.importSnapshotBoundModule(\n moduleUrl,\n options.allowDocumentReload !== false\n );\n return module.MDXLayout || module.MainLayout || module.default || module;\n }\n async function renderPageFromData(pageData, targetPath) {\n if (pageData.requiresFullDocumentNavigation) {\n throw new Error("Server layout requires full document navigation");\n }\n if (window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(pageData.releaseId || null);\n }\n if (window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(pageData.releaseAssetModules || null);\n }\n perfStart("render:loadAll");\n const allPaths = getPageDataModulePaths(pageData);\n const modulesStartedAt = routeTimingNow();\n const components = await Promise.all(\n allPaths.map((path) => loadPageDataComponent(pageData, path))\n );\n emitRouteTiming("modules", targetPath, modulesStartedAt, { count: allPaths.length });\n perfEnd("render:loadAll");\n const [PageComponent, ...rest] = components;\n const ErrorComponent = pageData.errorPath ? rest.pop() : null;\n const AppComponent = pageData.appPath ? rest.pop() : null;\n const LayoutComponents = rest;\n if (!PageComponent) {\n throw new Error("Failed to load page component: " + pageData.pagePath);\n }\n handoffClientRouteMetadata(\n pageData.frontmatter ?? {},\n document2\n );\n if (pageData.css) {\n const existingStyle = document2.getElementById("veryfront-spa-css");\n if (existingStyle) {\n existingStyle.textContent = pageData.css;\n } else {\n const styleEl = document2.createElement("style");\n const nonce = getDocumentNonce(document2);\n if (nonce) styleEl.setAttribute("nonce", nonce);\n styleEl.id = "veryfront-spa-css";\n styleEl.textContent = pageData.css;\n document2.head.appendChild(styleEl);\n }\n log("Injected CSS for SPA navigation", { cssLength: pageData.css.length });\n } else if (pageData.cssAction === "clear") {\n const existingStyle = document2.getElementById("veryfront-spa-css");\n if (existingStyle) {\n existingStyle.remove();\n log("Cleared SPA CSS for release stylesheet navigation");\n }\n }\n const normalizedParams = flattenRouteParams(pageData.params);\n let tree = React2.createElement(PageComponent, {\n ...pageData.props,\n params: normalizedParams\n });\n if (pageData.layouts?.length) {\n for (let i = pageData.layouts.length - 1; i >= 0; i--) {\n const layout = pageData.layouts[i];\n const LayoutComponent = LayoutComponents[i];\n if (!LayoutComponent || !layout) continue;\n const layoutProps = pageData.layoutProps?.[layout.path] || {};\n tree = React2.createElement(LayoutComponent, { ...layoutProps, children: tree });\n }\n }\n if (AppComponent) {\n tree = React2.createElement(AppComponent, { children: tree });\n log("Wrapped with App component for SPA navigation");\n }\n if (ErrorComponent) {\n class AppRouterErrorBoundary extends React2.Component {\n constructor(props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n static getDerivedStateFromError(error) {\n return { hasError: true, error };\n }\n render() {\n if (this.state.hasError) {\n return React2.createElement(ErrorComponent, {\n error: this.state.error,\n reset: () => this.setState({ hasError: false, error: null })\n });\n }\n return this.props.children;\n }\n }\n tree = React2.createElement(AppRouterErrorBoundary, null, tree);\n }\n const headingsArray = pageData.headings || [];\n const pageContext = {\n slug: pageData.slug || "",\n path: pageData.pagePath || targetPath,\n params: normalizedParams,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n frontmatter: pageData.frontmatter || {},\n data: pageData.props || {},\n headings: headingsArray,\n mdxHeadings: headingsArray\n };\n tree = React2.createElement(PageContextProvider2, { pageContext, children: tree });\n tree = React2.createElement(RouterProvider2, { router, children: tree });\n const container = pageData.isolatedClientPage ? document2.getElementById("veryfront-page-island") : document2.getElementById("root");\n if (!hydrationCompleted && !hydrationFailed) {\n log("Waiting for hydration to complete before SPA render...");\n try {\n await Promise.race([\n hydrationPromise,\n new Promise(\n (_, reject) => setTimeout2(() => reject(new Error("Hydration timeout")), 1e4)\n )\n ]);\n } catch (waitError) {\n log("Hydration wait failed:", waitError.message);\n }\n }\n if (container?.__reactRoot) {\n perfStart("render:reactRender");\n container.__reactRoot.render(tree);\n perfEnd("render:reactRender");\n log("Page re-rendered via SPA");\n scheduleRoutePrefetchRefresh();\n return;\n }\n if (hydrationFailed) {\n throw new Error(\n "React root not found - hydration failed, falling back to full page navigation"\n );\n }\n throw new Error("React root not found");\n }\n let prefetchTimeout = null;\n let currentHoverLink = null;\n let routePrefetchRefreshPending = false;\n let viewportPrefetchObserver = null;\n const observedPrefetchLinks = /* @__PURE__ */ new WeakSet();\n const prefetchedPaths = /* @__PURE__ */ new Set();\n const inFlightPrefetches = /* @__PURE__ */ new Set();\n const queuedPrefetchPaths = /* @__PURE__ */ new Set();\n const pageDataPrefetchQueue = [];\n const activePageDataPrefetchControllers = /* @__PURE__ */ new Map();\n function cancelScheduledPrefetch() {\n if (prefetchTimeout) {\n clearTimeout2(prefetchTimeout);\n prefetchTimeout = null;\n }\n currentHoverLink = null;\n }\n function getPageDataModulePaths(pageData) {\n const layoutPaths = (pageData.layouts || []).map((l) => l.path).filter(Boolean);\n const allPaths = [pageData.pagePath, ...layoutPaths].filter(Boolean);\n if (pageData.appPath) allPaths.push(pageData.appPath);\n if (pageData.errorPath) allPaths.push(pageData.errorPath);\n return allPaths;\n }\n function getCurrentRouteHref() {\n return window.location.pathname + window.location.search;\n }\n function getInternalRouteHrefFromLink(link) {\n if (!link || link.target === "_blank" || link.hasAttribute("download") || link.getAttribute("data-prefetch") === "false") {\n return null;\n }\n const href = link.getAttribute("href");\n if (!href || href.startsWith("#") || href.startsWith("//") || !href.startsWith("/")) {\n return null;\n }\n try {\n const url = new URL(href, window.location.origin);\n if (url.origin !== window.location.origin) return null;\n const routeHref = url.pathname + url.search;\n return routeHref === getCurrentRouteHref() ? null : routeHref;\n } catch (_) {\n return null;\n }\n }\n function getEligiblePrefetchLinks(limit) {\n const links = [];\n const seenHrefs = /* @__PURE__ */ new Set();\n for (const link of document2.querySelectorAll("a[href]")) {\n const href = getInternalRouteHrefFromLink(link);\n if (!href || seenHrefs.has(href)) continue;\n seenHrefs.add(href);\n links.push({ link, href });\n if (links.length >= limit) break;\n }\n return links;\n }\n async function preloadModulesForPageData(pageData, path) {\n if (!pageData || pageData.requiresFullDocumentNavigation) return;\n if (pageData.releaseId && window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(pageData.releaseId);\n }\n if (pageData.releaseAssetModules && window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(pageData.releaseAssetModules);\n }\n const modulePaths = getPageDataModulePaths(pageData);\n if (modulePaths.length === 0) return;\n try {\n await Promise.all(\n modulePaths.map(\n (modulePath) => loadPageDataComponent(pageData, modulePath, { allowDocumentReload: false })\n )\n );\n } catch (error) {\n if (isDependencySnapshotConflict(error)) {\n const cacheIdentity = pageDataCacheIdentity2(path);\n pageDataCache.delete(cacheIdentity);\n backgroundRefreshTimestamps.delete(cacheIdentity);\n prefetchedPaths.delete(path);\n throw error;\n }\n logBackgroundFetchFailure("Module prefetch", path, error);\n }\n }\n function removeQueuedPrefetch(path) {\n queuedPrefetchPaths.delete(path);\n for (let i = pageDataPrefetchQueue.length - 1; i >= 0; i--) {\n if (pageDataPrefetchQueue[i] === path) pageDataPrefetchQueue.splice(i, 1);\n }\n }\n function abortActiveSpeculativePrefetches() {\n for (const controller of activePageDataPrefetchControllers.values()) {\n controller.abort();\n }\n }\n function processPageDataPrefetchQueue() {\n if (isNavigating) return;\n while (activePageDataPrefetchControllers.size < PAGE_DATA_PREFETCH_CONCURRENCY && pageDataPrefetchQueue.length > 0) {\n const href = pageDataPrefetchQueue.shift();\n queuedPrefetchPaths.delete(href);\n if (prefetchedPaths.has(href) || inFlightPrefetches.has(href) || getCachedPageData(href)) {\n continue;\n }\n if (prefetchedPaths.size >= MAX_PREFETCH_PATHS) {\n const oldest = prefetchedPaths.values().next().value;\n if (oldest) prefetchedPaths.delete(oldest);\n }\n const controller = new AbortController();\n prefetchedPaths.add(href);\n inFlightPrefetches.add(href);\n activePageDataPrefetchControllers.set(href, controller);\n fetchPageDataForPrefetch(href, controller.signal).catch((error) => {\n prefetchedPaths.delete(href);\n if (isDependencySnapshotConflict(error)) {\n logBackgroundFetchFailure("Module prefetch", href, error);\n }\n }).finally(() => {\n inFlightPrefetches.delete(href);\n activePageDataPrefetchControllers.delete(href);\n processPageDataPrefetchQueue();\n });\n }\n }\n function prefetchPage(href) {\n if (isNavigating) return;\n if (prefetchedPaths.has(href) || inFlightPrefetches.has(href) || queuedPrefetchPaths.has(href)) return;\n const cachedPageData = getCachedPageData(href);\n if (cachedPageData) {\n preloadModulesForPageData(cachedPageData, href).catch((error) => {\n logBackgroundFetchFailure("Module prefetch", href, error);\n });\n return;\n }\n queuedPrefetchPaths.add(href);\n pageDataPrefetchQueue.push(href);\n processPageDataPrefetchQueue();\n }\n function prefetchEligibleRouteLinks(limit) {\n for (const { href } of getEligiblePrefetchLinks(limit)) {\n prefetchPage(href);\n }\n }\n function ensureViewportPrefetchObserver() {\n if (viewportPrefetchObserver || typeof IntersectionObserver !== "function") {\n return viewportPrefetchObserver;\n }\n viewportPrefetchObserver = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n viewportPrefetchObserver?.unobserve(entry.target);\n const href = getInternalRouteHrefFromLink(\n entry.target\n );\n if (href) prefetchPage(href);\n }\n }, { rootMargin: VIEWPORT_PREFETCH_ROOT_MARGIN });\n return viewportPrefetchObserver;\n }\n function observeViewportPrefetchLinks() {\n const observer = ensureViewportPrefetchObserver();\n if (!observer) return;\n for (const { link } of getEligiblePrefetchLinks(VIEWPORT_PREFETCH_MAX_LINKS)) {\n if (observedPrefetchLinks.has(link)) continue;\n observedPrefetchLinks.add(link);\n observer.observe(link);\n }\n }\n function runRoutePrefetchRefresh() {\n routePrefetchRefreshPending = false;\n prefetchEligibleRouteLinks(IDLE_PREFETCH_MAX_LINKS);\n observeViewportPrefetchLinks();\n }\n function scheduleRoutePrefetchRefresh() {\n if (routePrefetchRefreshPending) return;\n routePrefetchRefreshPending = true;\n setTimeout2(() => {\n if (typeof requestIdleCallback === "function") {\n requestIdleCallback(runRoutePrefetchRefresh, { timeout: IDLE_PREFETCH_DELAY_MS });\n return;\n }\n runRoutePrefetchRefresh();\n }, IDLE_PREFETCH_DELAY_MS);\n }\n const router = {\n domain: window.location.origin,\n path: window.location.pathname,\n push: (path) => {\n void navigateSPA(path, "push");\n },\n replace: (path) => {\n void navigateSPA(path, "replace");\n },\n back: () => {\n window.history.back();\n },\n forward: () => {\n window.history.forward();\n },\n prefetch: (path) => {\n prefetchPage(path);\n },\n pathname: window.location.pathname,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n // Seed route params from the hydration data (issue #2741). Catch-all\n // segments arrive as arrays and are joined so no path info is lost.\n params: flattenRouteParams(deps.initialHydrationData.params || {}),\n isPreview: false,\n isMounted: true,\n navigate: (path) => navigateSPA(path, "push"),\n reload: () => window.location.reload()\n };\n window.__veryfrontRouter = router;\n if (deps.navigationStoreUsesRegistryFallback) {\n log("Router runtime does not export getNavigationStore; using shared v1 registry fallback");\n }\n if (typeof deps.getNavigationStore === "function") {\n deps.getNavigationStore().setNavigator((href, options) => {\n const mode = options && options.history;\n const historyMode = mode === "replace" ? "replace" : mode === "none" ? "none" : "push";\n return navigateSPA(href, historyMode);\n });\n }\n window.addEventListener("popstate", async (e) => {\n const path = window.location.pathname;\n log("Popstate:", path);\n saveScrollPosition(currentPath);\n if (!e.state?.pageData) {\n await navigateSPA(path, "none", true);\n return;\n }\n showNavigationProgress();\n try {\n currentPath = path;\n router.pathname = path;\n router.query = Object.fromEntries(new URLSearchParams(window.location.search));\n router.params = flattenRouteParams(e.state.pageData.params);\n await renderPageFromData(e.state.pageData, path);\n restoreScrollPosition(path);\n hideNavigationProgress();\n } catch (error) {\n hideNavigationProgress();\n logError("Popstate render failed:", error.message);\n window.location.reload();\n }\n });\n document2.addEventListener("click", (e) => {\n const link = e.target?.closest("a[href]");\n if (!link) return;\n const href = link.getAttribute("href");\n if (!href) return;\n if (href.startsWith("#")) {\n const target = document2.getElementById(href.slice(1));\n if (!target) return;\n e.preventDefault();\n target.scrollIntoView({ behavior: "smooth" });\n window.history.pushState(null, "", href);\n return;\n }\n if (link.target === "_blank" || link.hasAttribute("download") || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !href.startsWith("/") || href.startsWith("//")) {\n return;\n }\n e.preventDefault();\n cancelScheduledPrefetch();\n void navigateSPA(href, "push");\n });\n document2.addEventListener(\n "mouseenter",\n (e) => {\n if (!e.target || typeof e.target.closest !== "function") return;\n const link = e.target.closest("a[href]");\n if (!link) return;\n const href = getInternalRouteHrefFromLink(link);\n if (!href) return;\n if (currentHoverLink === link) return;\n if (prefetchTimeout) {\n clearTimeout2(prefetchTimeout);\n prefetchTimeout = null;\n }\n currentHoverLink = link;\n prefetchTimeout = setTimeout2(() => {\n prefetchPage(href);\n prefetchTimeout = null;\n }, PREFETCH_DELAY_MS);\n },\n true\n );\n document2.addEventListener(\n "mouseleave",\n (e) => {\n if (!e.target || typeof e.target.closest !== "function") return;\n const relatedTarget = e.relatedTarget;\n if (currentHoverLink && relatedTarget && currentHoverLink.contains(relatedTarget)) return;\n cancelScheduledPrefetch();\n },\n true\n );\n if (document2.readyState === "loading") {\n document2.addEventListener("DOMContentLoaded", scheduleRoutePrefetchRefresh, { once: true });\n } else {\n scheduleRoutePrefetchRefresh();\n }\n window.useRouter = () => {\n try {\n return env2.useRouterFromModule();\n } catch (_) {\n return window.__veryfrontRouter;\n }\n };\n return {\n router,\n navigateSPA,\n renderPageFromData,\n prefetchPage,\n signalHydrationComplete,\n signalHydrationFailed\n };\n}\n\n// src/html/hydration-script-builder/runtime/renderer.ts\nfunction isModuleNotFoundError(error) {\n if (!error) return false;\n if (error instanceof SyntaxError) return false;\n const message = String(error.message || error);\n return /(?:dynamically imported module|Importing a module script failed|Failed to load module script)/i.test(message);\n}\nfunction preferReachedModuleError(earlier, later) {\n if (!earlier) return later;\n if (!later) return earlier;\n if (isModuleNotFoundError(earlier) && !isModuleNotFoundError(later)) return later;\n return earlier;\n}\nasync function loadPageModuleWithIndexFallback(basePath, pageSlug, pageModuleError, importModule) {\n try {\n return await importModule(basePath + ".js");\n } catch (error) {\n const routeError = preferReachedModuleError(pageModuleError, error);\n if (pageSlug === "index" || pageSlug.endsWith("/index")) throw routeError;\n try {\n return await importModule(basePath + "/index.js");\n } catch (indexError) {\n throw preferReachedModuleError(routeError, indexError);\n }\n }\n}\nfunction isAppRouterPath(path, appRouterRoot) {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n return normalizedPath === appRouterRoot || normalizedPath.startsWith(appRouterRoot + "/");\n}\nfunction isRootAppLayoutPath(path, appRouterRoot) {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n const pathWithoutExtension = normalizedPath.replace(/\\.(?:tsx|jsx|ts|js)$/, "");\n return pathWithoutExtension === appRouterRoot + "/layout";\n}\nfunction unwrapAppRouterDocumentLayout(LayoutComponent, React2) {\n return function AppRouterDocumentLayout(props) {\n const element = LayoutComponent(props);\n const asElement = element;\n if (!React2.isValidElement(element) || asElement.type !== "html") {\n return element;\n }\n const body = React2.Children.toArray(asElement.props?.children).find(\n (child) => React2.isValidElement(child) && child.type === "body"\n );\n return body?.props?.children ?? props.children;\n };\n}\nfunction createHydrationRenderer(deps) {\n const { env: env2, logging: logging2, componentLoader: componentLoader2, snapshotModules: snapshotModules2, moduleServerUrl: moduleServerUrl2 } = deps;\n const { window, document: document2, React: React2, RouterProvider: RouterProvider2, PageContextProvider: PageContextProvider2 } = env2;\n const { DEBUG, log, logError } = logging2;\n const { loadComponent, pathToModuleUrl } = componentLoader2;\n const { importSnapshotBoundModule } = snapshotModules2;\n async function renderPage(pathname) {\n const resolvedPathname = (() => {\n const input = typeof pathname === "string" ? pathname : window.location.pathname;\n try {\n return new URL(input, window.location.origin).pathname || "/";\n } catch (_) {\n const [pathOnly] = String(input || "/").split(/[?#]/);\n return pathOnly || "/";\n }\n })();\n const dataScript = findServerHydrationDataElement(document2);\n if (!dataScript) {\n logError("Hydration data not found");\n return;\n }\n let data = {};\n try {\n data = JSON.parse(dataScript.textContent || "{}");\n } catch (parseError) {\n logError("Failed to parse hydration data:", parseError);\n return;\n }\n log("Hydration data:", data);\n if (data.studioEmbed && window.__veryfrontSetStudioEmbed) {\n window.__veryfrontSetStudioEmbed(true);\n }\n if (window.__veryfrontSetReleaseId) {\n window.__veryfrontSetReleaseId(data.releaseId || null);\n }\n if (data.releaseAssetModules && window.__veryfrontSetReleaseAssetModules) {\n window.__veryfrontSetReleaseAssetModules(data.releaseAssetModules);\n }\n try {\n let pageModule;\n const pagePath = typeof data.pagePath === "string" ? data.pagePath : "";\n const normalizedPagePath = pagePath.replace(/^\\/+/, "");\n const normalizedAppRouterRoot = typeof data.appRouterRoot === "string" && data.appRouterRoot.replace(/^\\/+|\\/+$/g, "") ? data.appRouterRoot.replace(/^\\/+|\\/+$/g, "") : "app";\n const hasReleaseAssetModules = data.releaseAssetModules && Object.keys(data.releaseAssetModules).length > 0;\n const shouldRenderRscClientPage = data.clientModuleStrategy === "rsc-module" && !hasReleaseAssetModules && isAppRouterPath(normalizedPagePath, normalizedAppRouterRoot);\n const isolatedClientPage = data.isolatedClientPage === true;\n const loadHydrationComponent = async (path, preferRscModule) => {\n const normalizedPath = typeof path === "string" ? path.replace(/^\\/+/, "") : "";\n if (preferRscModule && isAppRouterPath(normalizedPath, normalizedAppRouterRoot)) {\n const moduleUrl = buildPinnedRscModuleUrl(path, data);\n log("Loading App Router component from RSC module:", moduleUrl);\n const module = await importSnapshotBoundModule(moduleUrl);\n return module.default || module;\n }\n return loadComponent(path, data);\n };\n let pageModuleError = null;\n if (data.pagePath) {\n const moduleUrl = shouldRenderRscClientPage ? buildPinnedRscModuleUrl(data.pagePath, data) : pathToModuleUrl(data.pagePath, data.studioEmbed, data);\n log("Loading page from hydration data:", moduleUrl);\n try {\n pageModule = await importSnapshotBoundModule(moduleUrl);\n } catch (error) {\n pageModuleError = error;\n logError("Failed to load page from hydration data:", error);\n }\n }\n if (!pageModule) {\n const pageSlug = resolvedPathname === "/" ? "index" : resolvedPathname.slice(1);\n log("Falling back to Pages Router pattern:", pageSlug);\n const prefix = pageSlug.startsWith("@/") ? "" : "/pages";\n const basePath = moduleServerUrl2 + prefix + "/" + pageSlug;\n pageModule = await loadPageModuleWithIndexFallback(\n basePath,\n pageSlug,\n pageModuleError,\n (moduleUrl) => importSnapshotBoundModule(appendDependencyPinningVersion(moduleUrl, data))\n );\n }\n if (!pageModule) {\n logError("Page module failed to load");\n return;\n }\n const PageComponent = pageModule.default || pageModule;\n if (!PageComponent) {\n logError("Page component not found");\n return;\n }\n const normalizedParams = flattenRouteParams(data.params);\n const pageProps = { ...data.props || {}, params: normalizedParams };\n let tree = React2.createElement(PageComponent, pageProps);\n const layouts = data.layouts;\n if (layouts?.length) {\n for (let i = layouts.length - 1; i >= 0; i--) {\n const layout = layouts[i];\n if (!layout) continue;\n const LayoutComponent = await loadHydrationComponent(\n layout.path,\n shouldRenderRscClientPage\n );\n if (LayoutComponent) {\n const WrappedLayoutComponent = shouldRenderRscClientPage && isRootAppLayoutPath(layout.path, normalizedAppRouterRoot) ? unwrapAppRouterDocumentLayout(LayoutComponent, React2) : LayoutComponent;\n const layoutProps = data.layoutProps?.[layout.path] || {};\n tree = React2.createElement(\n WrappedLayoutComponent,\n { ...layoutProps, children: tree }\n );\n }\n }\n }\n if (data.appPath && !isolatedClientPage) {\n const AppComponent = await loadHydrationComponent(data.appPath, shouldRenderRscClientPage);\n if (AppComponent) {\n tree = React2.createElement(AppComponent, { children: tree });\n }\n }\n if (data.errorPath) {\n const ErrorComponent = await loadHydrationComponent(\n data.errorPath,\n shouldRenderRscClientPage\n );\n if (ErrorComponent) {\n class AppRouterErrorBoundary extends React2.Component {\n constructor(props) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n static getDerivedStateFromError(error) {\n return { hasError: true, error };\n }\n render() {\n if (this.state.hasError) {\n return React2.createElement(ErrorComponent, {\n error: this.state.error,\n reset: () => this.setState({ hasError: false, error: null })\n });\n }\n return this.props.children;\n }\n }\n tree = React2.createElement(AppRouterErrorBoundary, null, tree);\n }\n }\n const headings = data.headings || [];\n const pageContext = {\n slug: data.slug || "",\n path: data.pagePath || resolvedPathname,\n params: normalizedParams,\n query: Object.fromEntries(new URLSearchParams(window.location.search)),\n frontmatter: data.frontmatter || {},\n data: data.props || {},\n headings,\n mdxHeadings: headings\n // Alias for backwards compatibility\n };\n tree = React2.createElement(PageContextProvider2, { pageContext, children: tree });\n tree = React2.createElement(RouterProvider2, { router: deps.router, children: tree });\n const container = isolatedClientPage ? document2.getElementById("veryfront-page-island") : document2.getElementById("root");\n if (!container) {\n if (isolatedClientPage) {\n throw new Error("Isolated client page root not found");\n }\n return;\n }\n if (container.__reactRoot) {\n container.__reactRoot.render(tree);\n log("Page re-rendered");\n return;\n }\n if (shouldRenderRscClientPage) {\n container.__reactRoot = env2.createRoot(container);\n container.__reactRoot.render(tree);\n log("Client-side React app rendered successfully");\n } else {\n const { hydrateRoot } = await import("react-dom/client");\n const options = {\n identifierPrefix: "vf",\n onRecoverableError: (error) => {\n if (data.dev && DEBUG) {\n log("Hydration mismatch (suppressed):", error.message);\n }\n }\n };\n container.__reactRoot = hydrateRoot(container, tree, options);\n log("Client-side React app hydrated successfully");\n }\n if (window.__veryfrontHydrationComplete) {\n window.__veryfrontHydrationComplete();\n }\n } catch (error) {\n logError("Client initialization error:", error);\n if (window.__veryfrontHydrationFailed) {\n window.__veryfrontHydrationFailed(error);\n }\n }\n }\n function start() {\n window.__veryfrontRenderPage = renderPage;\n void renderPage(window.location.pathname);\n const initialDataScript = findServerHydrationDataElement(document2);\n if (initialDataScript) {\n try {\n const pageData = JSON.parse(initialDataScript.textContent || "{}");\n if (pageData.pagePath) {\n window.history.replaceState({ pageData, scrollY: 0 }, "", window.location.href);\n log("Stored initial page data in history state");\n }\n } catch (_) {\n }\n }\n }\n return { renderPage, start };\n}\n\n// src/html/hydration-script-builder/runtime/navigation-store.ts\nvar NAVIGATION_STORE_REGISTRY_KEY = "veryfront.navigation.store.v1";\nfunction resolveNavigationStore(RouterRuntime2) {\n const usesRegistryFallback2 = typeof RouterRuntime2.getNavigationStore !== "function";\n if (!usesRegistryFallback2) {\n return {\n usesRegistryFallback: usesRegistryFallback2,\n getNavigationStore: RouterRuntime2.getNavigationStore\n };\n }\n return {\n usesRegistryFallback: usesRegistryFallback2,\n getNavigationStore: () => {\n const storeKey = Symbol.for(NAVIGATION_STORE_REGISTRY_KEY);\n const registry = globalThis;\n const existing = registry[storeKey];\n if (existing) return existing;\n const listeners = /* @__PURE__ */ new Set();\n let navigator = null;\n const store = {\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n getHref() {\n const loc = globalThis.location;\n return loc ? loc.pathname + loc.search + loc.hash : "/";\n },\n notify() {\n for (const listener of [...listeners]) {\n try {\n listener();\n } catch {\n }\n }\n },\n navigate(href, options) {\n if (navigator) return navigator(href, options);\n globalThis.location?.assign(href);\n return Promise.resolve();\n },\n setNavigator(next) {\n navigator = next;\n }\n };\n registry[storeKey] = store;\n return store;\n }\n };\n}\n\n// src/html/hydration-script-builder/runtime/main.ts\nvar runtimeWindow = globalThis;\nvar runtimeDocument = globalThis.document;\nvar env = {\n window: runtimeWindow,\n document: runtimeDocument,\n fetch: (url, init) => fetch(url, init),\n React,\n RouterProvider,\n PageContextProvider,\n createRoot: (container) => createRoot(container),\n importModule: (moduleUrl) => import(moduleUrl),\n useRouterFromModule,\n setTimeout: (handler, timeout) => setTimeout(handler, timeout),\n clearTimeout: (id) => clearTimeout(id)\n};\nvar logging = createLogging(runtimeWindow);\nvar initialHydrationData = readInitialHydrationData(runtimeDocument);\nvar documentDependencyPinningCacheKey = readDocumentDependencyPinningCacheKey(\n initialHydrationData\n);\nvar routeTiming = createRouteTimingRecorder(runtimeWindow, logging);\nvar snapshotModules = createSnapshotModuleImporter({\n importModule: env.importModule,\n fetchModule: env.fetch,\n reloadDocument: () => runtimeWindow.location.reload(),\n recoveryState: runtimeWindow\n});\nvar componentLoader = createComponentLoader({\n window: runtimeWindow,\n logging,\n moduleServerUrl: moduleServerUrl(runtimeWindow),\n snapshotModules\n});\nruntimeWindow.__veryfrontClearComponentCache = componentLoader.clearComponentCache;\nruntimeWindow.__veryfrontSetStudioEmbed = componentLoader.setStudioEmbed;\nruntimeWindow.__veryfrontSetReleaseId = componentLoader.setReleaseId;\nruntimeWindow.__veryfrontSetReleaseAssetModules = componentLoader.setReleaseAssetModules;\nruntimeWindow.__veryfrontSetHMRRefreshTimestamp = componentLoader.setHMRRefreshTimestamp;\nvar { usesRegistryFallback, getNavigationStore } = resolveNavigationStore(RouterRuntime);\nvar routerRuntime = createRouterRuntime({\n env,\n logging,\n routeTiming,\n componentLoader,\n snapshotModules,\n initialHydrationData,\n documentDependencyPinningCacheKey,\n getNavigationStore,\n navigationStoreUsesRegistryFallback: usesRegistryFallback\n});\ncreateHydrationRenderer({\n env,\n logging,\n componentLoader,\n snapshotModules,\n moduleServerUrl: moduleServerUrl(runtimeWindow),\n router: routerRuntime.router\n}).start();\n';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"candidate-tokenizer.d.ts","sourceRoot":"","sources":["../../../../src/src/html/styles-builder/candidate-tokenizer.ts"],"names":[],"mappings":"AAAA,2DAA2D;AA+
|
|
1
|
+
{"version":3,"file":"candidate-tokenizer.d.ts","sourceRoot":"","sources":["../../../../src/src/html/styles-builder/candidate-tokenizer.ts"],"names":[],"mappings":"AAAA,2DAA2D;AA+C3D,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,UAAU,EAAE,MAAM,EAAE,CAAC;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED,kFAAkF;AAClF,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,MAAM,EACf,KAAK,SAAyB,GAC7B,sBAAsB,CAiDxB;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAE3D"}
|
|
@@ -4,6 +4,10 @@ import { assertCSSFileContent } from "../../utils/css-content-admission.js";
|
|
|
4
4
|
const candidateBodyCharacterClass = "[a-zA-Z0-9_\\-:\\/\\.\\[\\]%#,()!'=<>$@{}|*+?;^~]";
|
|
5
5
|
const candidatePattern = new RegExp(`!?-?@?(?:[a-zA-Z0-9]|\\[&?)${candidateBodyCharacterClass}{0,${MAX_CSS_SELECTOR_TOKEN_CHARACTERS - 1}}`, "g");
|
|
6
6
|
const candidateContinuationPattern = new RegExp(candidateBodyCharacterClass);
|
|
7
|
+
// Sticky, so the remainder of an overlong run is consumed by one native scan
|
|
8
|
+
// instead of a character-at-a-time JS loop. MAX_CSS_FILE_BYTES admits inputs
|
|
9
|
+
// where a single base64 blob would otherwise cost millions of iterations.
|
|
10
|
+
const candidateRunPattern = new RegExp(`${candidateBodyCharacterClass}+`, "y");
|
|
7
11
|
const apply = Reflect.apply;
|
|
8
12
|
const NativeTypeError = TypeError;
|
|
9
13
|
const arrayPush = Array.prototype.push;
|
|
@@ -18,6 +22,17 @@ function hasCandidateContinuation(content, index) {
|
|
|
18
22
|
const nextCharacter = apply(stringCharAt, content, [index]);
|
|
19
23
|
return apply(regExpExec, candidateContinuationPattern, [nextCharacter]) !== null;
|
|
20
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* Index just past the remainder of a run that broke the token ceiling.
|
|
27
|
+
*
|
|
28
|
+
* One sticky match consumes the tail, so skipping stays linear in the source
|
|
29
|
+
* rather than one JS iteration per character.
|
|
30
|
+
*/
|
|
31
|
+
function skipOverlongCandidateRun(content, index) {
|
|
32
|
+
candidateRunPattern.lastIndex = index;
|
|
33
|
+
const run = apply(regExpExec, candidateRunPattern, [content]);
|
|
34
|
+
return run === null ? index : index + run[0].length;
|
|
35
|
+
}
|
|
21
36
|
/** Extract a bounded, deduplicated candidate snapshot and admitted byte count. */
|
|
22
37
|
export function extractCandidatesWithByteLength(content, label = "CSS candidate source") {
|
|
23
38
|
const sourceBytes = assertCSSFileContent(content, label);
|
|
@@ -28,9 +43,25 @@ export function extractCandidatesWithByteLength(content, label = "CSS candidate
|
|
|
28
43
|
let match;
|
|
29
44
|
while ((match = apply(regExpExec, candidatePattern, [content])) !== null) {
|
|
30
45
|
const candidate = match[0];
|
|
46
|
+
// A run longer than the cap is data, not a class name: a base64 data URI
|
|
47
|
+
// for an inline image or font, or the inline sourcemap esbuild writes into
|
|
48
|
+
// the build cache, is one unbroken run of characters this class accepts.
|
|
49
|
+
//
|
|
50
|
+
// Skip the whole run rather than throwing. The throw propagated out of
|
|
51
|
+
// getProjectCSS through generateHTMLShellPartsImpl, so it did not degrade
|
|
52
|
+
// to an unstyled page -- it aborted shell generation and the request 500'd
|
|
53
|
+
// for a token that could never have matched a rule.
|
|
54
|
+
//
|
|
55
|
+
// Both arms of the condition are load-bearing. The continuation check
|
|
56
|
+
// catches a run that is still going when the match stops; the length check
|
|
57
|
+
// catches one that ends cleanly but is over the cap anyway, which the head
|
|
58
|
+
// `!?-?@?(?:[a-zA-Z0-9]|\[&?)` makes reachable because it admits up to five
|
|
59
|
+
// characters on top of the pattern's MAX - 1 body. Dropping it emitted a
|
|
60
|
+
// 1025-character candidate that then threw in normalizeCSSCandidates.
|
|
31
61
|
if (candidate.length > MAX_CSS_SELECTOR_TOKEN_CHARACTERS ||
|
|
32
62
|
hasCandidateContinuation(content, candidatePattern.lastIndex)) {
|
|
33
|
-
|
|
63
|
+
candidatePattern.lastIndex = skipOverlongCandidateRun(content, candidatePattern.lastIndex);
|
|
64
|
+
continue;
|
|
34
65
|
}
|
|
35
66
|
if (apply(setHas, seenCandidates, [candidate]))
|
|
36
67
|
continue;
|
|
@@ -20,7 +20,21 @@
|
|
|
20
20
|
*/
|
|
21
21
|
/** Module extensions whose sources can carry CSS imports. */
|
|
22
22
|
export declare const CSS_IMPORTING_SOURCE_EXTENSIONS: string[];
|
|
23
|
-
/**
|
|
23
|
+
/**
|
|
24
|
+
* Extract the raw specifiers of all CSS imports in a source file.
|
|
25
|
+
*
|
|
26
|
+
* Deliberately loose, per this module's contract: over-matching is harmless
|
|
27
|
+
* because unresolvable specifiers are skipped downstream. A commented-out or
|
|
28
|
+
* quoted `import "./x.css"` will be reported, and that is fine.
|
|
29
|
+
*
|
|
30
|
+
* An earlier revision blanked comments, template literals and fenced blocks
|
|
31
|
+
* before matching, because the release-asset build had made this function's
|
|
32
|
+
* output fatal. That was the wrong layer to fix it: telling code from prose
|
|
33
|
+
* with a regex kept finding new holes, and worse, an unpaired `/*` or backtick
|
|
34
|
+
* blanked across intervening real code and silently dropped a genuine import --
|
|
35
|
+
* trading a loud failure for a page shipped without its stylesheet. The build
|
|
36
|
+
* no longer gaps on what it cannot resolve, so the looseness costs nothing.
|
|
37
|
+
*/
|
|
24
38
|
export declare function extractCssImportSpecifiers(source: string): string[];
|
|
25
39
|
/**
|
|
26
40
|
* Resolve a CSS import specifier to an absolute project path.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"css-import-extraction.d.ts","sourceRoot":"","sources":["../../../../src/src/html/styles-builder/css-import-extraction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,6DAA6D;AAC7D,eAAO,MAAM,+BAA+B,UAAyC,CAAC;
|
|
1
|
+
{"version":3,"file":"css-import-extraction.d.ts","sourceRoot":"","sources":["../../../../src/src/html/styles-builder/css-import-extraction.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,6DAA6D;AAC7D,eAAO,MAAM,+BAA+B,UAAyC,CAAC;AAqBtF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAMnE;AAkBD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,GACjB,MAAM,GAAG,IAAI,CAmBf;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,QAAQ,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,EAClD,UAAU,EAAE,MAAM,GACjB,MAAM,EAAE,CAcV"}
|
|
@@ -22,13 +22,38 @@ import { isWithinDirectory, normalizePath } from "../../utils/path-utils.js";
|
|
|
22
22
|
/** Module extensions whose sources can carry CSS imports. */
|
|
23
23
|
export const CSS_IMPORTING_SOURCE_EXTENSIONS = [".tsx", ".jsx", ".mdx", ".ts", ".js"];
|
|
24
24
|
/**
|
|
25
|
-
*
|
|
25
|
+
* ESM imports whose specifier ends in `.css`:
|
|
26
26
|
* import "./styles.css";
|
|
27
27
|
* import styles from "./button.module.css";
|
|
28
|
-
*
|
|
28
|
+
* import("./theme.css")
|
|
29
|
+
*
|
|
30
|
+
* Dynamic imports are matched on purpose, despite this once being described as
|
|
31
|
+
* static-only. `import("./theme.css")` loads that stylesheet at runtime, so
|
|
32
|
+
* leaving it out means the compiled stylesheet is missing CSS the page actually
|
|
33
|
+
* uses. A dynamic specifier pointing at a file that does not exist is a broken
|
|
34
|
+
* reference, not a false positive -- exactly as a static one would be.
|
|
35
|
+
* `[^'";]*` keeps the match from crossing statement boundaries, and `\bimport\b`
|
|
36
|
+
* keeps identifiers that merely contain the word out of it -- without it,
|
|
37
|
+
* `const important = "./styles.css"` reads as an import. That matters more here
|
|
38
|
+
* than it looks: release-asset builds turn a bogus specifier into a fatal
|
|
39
|
+
* coverage gap, so a false positive fails the release.
|
|
40
|
+
*/
|
|
41
|
+
const CSS_IMPORT_RE = /\bimport\b(?!\s*\.)[^'";]*['"]([^'"]+\.css)['"]/g;
|
|
42
|
+
/**
|
|
43
|
+
* Extract the raw specifiers of all CSS imports in a source file.
|
|
44
|
+
*
|
|
45
|
+
* Deliberately loose, per this module's contract: over-matching is harmless
|
|
46
|
+
* because unresolvable specifiers are skipped downstream. A commented-out or
|
|
47
|
+
* quoted `import "./x.css"` will be reported, and that is fine.
|
|
48
|
+
*
|
|
49
|
+
* An earlier revision blanked comments, template literals and fenced blocks
|
|
50
|
+
* before matching, because the release-asset build had made this function's
|
|
51
|
+
* output fatal. That was the wrong layer to fix it: telling code from prose
|
|
52
|
+
* with a regex kept finding new holes, and worse, an unpaired `/*` or backtick
|
|
53
|
+
* blanked across intervening real code and silently dropped a genuine import --
|
|
54
|
+
* trading a loud failure for a page shipped without its stylesheet. The build
|
|
55
|
+
* no longer gaps on what it cannot resolve, so the looseness costs nothing.
|
|
29
56
|
*/
|
|
30
|
-
const CSS_IMPORT_RE = /import[^'";]*['"]([^'"]+\.css)['"]/g;
|
|
31
|
-
/** Extract the raw specifiers of all static CSS imports in a source file. */
|
|
32
57
|
export function extractCssImportSpecifiers(source) {
|
|
33
58
|
const specifiers = [];
|
|
34
59
|
for (const match of source.matchAll(CSS_IMPORT_RE)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tailwind-compiler.d.ts","sourceRoot":"","sources":["../../../../src/src/html/styles-builder/tailwind-compiler.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAEL,KAAK,qBAAqB,EAE3B,MAAM,+BAA+B,CAAC;AAiBvC,OAAO,EAGL,KAAK,qBAAqB,EAC3B,MAAM,8BAA8B,CAAC;AAiBtC,OAAO,EAAE,iBAAiB,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AACzF,OAAO,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAC5C,OAAO,EACL,qBAAqB,EACrB,8BAA8B,EAC9B,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACpG,OAAO,EACL,yBAAyB,EACzB,o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EAAE,oBAAoB,CAAC;CACnD;AAcD,qFAAqF;AACrF,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,OAAO,GAAG,oBAAoB,CA+BjF;AAqED,wBAAsB,aAAa,CACjC,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,UAAU,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,EAClC,OAAO,CAAC,EAAE,oBAAoB,EAC9B,YAAY,GAAE,yBAA8B,GAC3C,OAAO,CAAC;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC,CA4D5D;AAMD,wBAAsB,mBAAmB,CACvC,YAAY,EAAE,MAAM,EACpB,WAAW,EAAE,MAAM,GAAG,SAAS,GAC9B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAmD7B;AAMD,wBAAsB,mBAAmB,CACvC,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,UAAU,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,EAClC,OAAO,CAAC,EAAE,oBAAoB,EAC9B,YAAY,GAAE,yBAA8B,GAC3C,OAAO,CAAC,mBAAmB,CAAC,CAoC9B;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,YAAY,CAGlE"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* imports nor discovers Tailwind. An explicit CSSProcessor owns compilation;
|
|
6
6
|
* an explicit CSSOptimizationEngine owns minification.
|
|
7
7
|
*/
|
|
8
|
-
import {
|
|
8
|
+
import { tryResolve } from "../../extensions/contracts.js";
|
|
9
9
|
import { captureCSSOptimizationEngine, CSSOptimizationEngineName, } from "../../extensions/css/index.js";
|
|
10
10
|
import { freezeExtensionContract, getExtensionOwnPropertyDescriptor, isDataPropertyDescriptor, isExtensionArray, } from "../../extensions/property-inspection.js";
|
|
11
11
|
import { SpanNames } from "../../observability/index.js";
|
|
@@ -41,9 +41,24 @@ function getCSSPipelineCacheIdentity(compilationIdentity, optimizationIdentity)
|
|
|
41
41
|
/** Capture all output-affecting providers before the operation performs an await. */
|
|
42
42
|
export function acquireCSSGenerationSession(minify) {
|
|
43
43
|
const compilationSession = acquireCSSCompilationSession();
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
// Minification is an optional enhancement, not a precondition for serving
|
|
45
|
+
// CSS. No first-party package registers a CSSOptimizationEngine -- it ships
|
|
46
|
+
// only in @veryfront/ext-css-lightning, which `veryfront` does not depend on
|
|
47
|
+
// -- while the production shell always asks for minify:true. Resolving
|
|
48
|
+
// through `resolve()` therefore made the fail-closed path unreachable-by-
|
|
49
|
+
// design for a default project: it could only ever fire as an outage. Absent
|
|
50
|
+
// an engine the CSS is emitted unminified and the identity below records it
|
|
51
|
+
// as such, so no cache can serve a stale minified entry in its place.
|
|
52
|
+
const optimizationProvider = minify ? tryResolve(CSSOptimizationEngineName) : undefined;
|
|
53
|
+
if (minify && optimizationProvider === undefined) {
|
|
54
|
+
// Warn, not debug: this is a silent quality regression for a project that
|
|
55
|
+
// did select an optimizer and whose registration failed. It must not be
|
|
56
|
+
// indistinguishable from a project that never wanted one.
|
|
57
|
+
logger.warn("No CSSOptimizationEngine registered; emitting unminified CSS");
|
|
58
|
+
}
|
|
59
|
+
const optimizationEngine = optimizationProvider === undefined
|
|
60
|
+
? undefined
|
|
61
|
+
: captureCSSOptimizationEngine(optimizationProvider);
|
|
47
62
|
const session = {
|
|
48
63
|
minify,
|
|
49
64
|
compilationSession,
|
|
@@ -152,7 +167,12 @@ export async function getProjectCSS(projectSlug, stylesheet, candidates, options
|
|
|
152
167
|
export async function regenerateCSSByHash(expectedHash, projectSlug) {
|
|
153
168
|
if (!isCSSContentHash(expectedHash))
|
|
154
169
|
return undefined;
|
|
155
|
-
|
|
170
|
+
// The session tolerates an absent optimizer and records the result in its
|
|
171
|
+
// cache identity, so asking for minify here is safe whether or not an engine
|
|
172
|
+
// is registered. The request below must pass the same value, or
|
|
173
|
+
// resolveGenerationSession rejects the pair.
|
|
174
|
+
const minify = true;
|
|
175
|
+
const generationSession = acquireCSSGenerationSession(minify);
|
|
156
176
|
const inFlightKey = `${hashString(generationSession.cacheIdentity)}:${expectedHash}`;
|
|
157
177
|
const pending = inFlightRegeneration.get(inFlightKey);
|
|
158
178
|
if (pending)
|
|
@@ -161,7 +181,7 @@ export async function regenerateCSSByHash(expectedHash, projectSlug) {
|
|
|
161
181
|
const inputs = await resolveRegenerationInputs(expectedHash, generationSession.cacheIdentity);
|
|
162
182
|
if (!inputs || inputs.candidates.length === 0)
|
|
163
183
|
return undefined;
|
|
164
|
-
const result = await generateTailwindCSS(inputs.stylesheet, inputs.candidates, { minify
|
|
184
|
+
const result = await generateTailwindCSS(inputs.stylesheet, inputs.candidates, { minify, projectSlug }, { generationSession });
|
|
165
185
|
if (hashCSS(result.css) !== expectedHash)
|
|
166
186
|
return undefined;
|
|
167
187
|
const entry = {
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* Client identity for guarded egress, standing in for the runtime-supplied
|
|
8
8
|
* `user-agent` (`node`, `Deno/x.y.z`) that this transport cannot inherit.
|
|
9
9
|
*/
|
|
10
|
-
export declare const DEFAULT_OUTBOUND_USER_AGENT = "veryfront/0.1.
|
|
10
|
+
export declare const DEFAULT_OUTBOUND_USER_AGENT = "veryfront/0.1.1205";
|
|
11
11
|
/**
|
|
12
12
|
* Fill in the request headers a plain `fetch` attaches on its own, leaving any
|
|
13
13
|
* the caller set untouched. This transport talks to `node:http` directly, so
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-executor.d.ts","sourceRoot":"","sources":["../../../src/src/release-assets/build-executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,sBA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EAAE;IAC7D,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,OAAO,CAAC;IACV,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC5C,MAAM,EAAE,oBAAoB,EAAE,CAAC;IAC/B,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC,CAiDD;AAqeD,wBAAsB,8BAA8B,CAAC,OAAO,EAAE;IAC5D,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,cAAc,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,qBAAqB,CAAC;IACjC,cAAc,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACpC,yBAAyB,CAAC,EAAE,yBAAyB,CAAC;IACtD,uBAAuB,CAAC,EAAE,4BAA4B,CAAC;CACxD,GAAG,OAAO,CAAC;IACV,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC5C,MAAM,EAAE,oBAAoB,EAAE,CAAC;IAC/B,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,CAAC,CAyCD;AA6ID;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,sBAAsB,EAC7B,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,uBAAuB,CAAC,CAkDlC"}
|
|
@@ -32,7 +32,7 @@ import { PLATFORM_UTILITIES } from "../html/utils.js";
|
|
|
32
32
|
import { extractCandidatesFromFiles } from "../html/styles-builder/candidate-extractor.js";
|
|
33
33
|
import { FRAMEWORK_CANDIDATES } from "../server/handlers/dev/framework-candidates.generated.js";
|
|
34
34
|
import { validateLexicalPath } from "../security/path-validation.js";
|
|
35
|
-
import { CSS_IMPORTING_SOURCE_EXTENSIONS, resolveCssImportPath, } from "../html/styles-builder/css-import-extraction.js";
|
|
35
|
+
import { CSS_IMPORTING_SOURCE_EXTENSIONS, extractCssImportSpecifiers, resolveCssImportPath, } from "../html/styles-builder/css-import-extraction.js";
|
|
36
36
|
import { rewriteCssModuleContent } from "../transforms/css-modules/naming.js";
|
|
37
37
|
import { computeHashBytes } from "../utils/index.js";
|
|
38
38
|
import { RELEASE_ASSET_BASE_PATH, RELEASE_ASSET_CONTENT_TYPES, RELEASE_ASSET_MANIFEST_LIMITS, RELEASE_ASSET_MANIFEST_SCHEMA_VERSION, RELEASE_ASSET_MAX_PENDING_BYTES, RELEASE_ASSET_MAX_SIZE_BYTES, RELEASE_ASSET_UPLOAD_CONCURRENCY, releaseAssetUrl, } from "./constants.js";
|
|
@@ -1864,7 +1864,7 @@ async function runBuildInner(input, tempDir, client, transform, manifestVersion)
|
|
|
1864
1864
|
pushGap(gaps, `stylesheet-missing:${stylesheetPath}`);
|
|
1865
1865
|
assertCompleteReleaseAssetCoverage(gaps);
|
|
1866
1866
|
}
|
|
1867
|
-
const stylesheet = await mergeModuleCssImports(sourceByPath, resolvedStylesheet
|
|
1867
|
+
const stylesheet = await mergeModuleCssImports(sourceByPath, resolvedStylesheet);
|
|
1868
1868
|
assertCompleteReleaseAssetCoverage(gaps);
|
|
1869
1869
|
const cssRequested = candidates.size > 0 || stylesheet !== undefined;
|
|
1870
1870
|
if (cssRequested) {
|
|
@@ -2041,42 +2041,50 @@ function resolveProjectStylesheet(sourceByPath, stylesheetPath) {
|
|
|
2041
2041
|
* CSS Module selectors are rewritten with the same project-relative identity
|
|
2042
2042
|
* used by the transform and HTML aggregation paths.
|
|
2043
2043
|
*/
|
|
2044
|
-
async function mergeModuleCssImports(sourceByPath, stylesheet
|
|
2044
|
+
async function mergeModuleCssImports(sourceByPath, stylesheet) {
|
|
2045
2045
|
const importedPaths = new Set();
|
|
2046
2046
|
for (const [path, content] of sourceByPath) {
|
|
2047
2047
|
if (!CSS_IMPORTING_SOURCE_EXTENSIONS.some((ext) => path.endsWith(ext)))
|
|
2048
2048
|
continue;
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
}
|
|
2061
|
-
for (const imp of imports) {
|
|
2062
|
-
const specifier = imp.n;
|
|
2063
|
-
if (!specifier)
|
|
2064
|
-
continue;
|
|
2049
|
+
// Regex extraction, not the ESM lexer. This runs over project source --
|
|
2050
|
+
// .tsx/.jsx/.mdx/.ts by definition, see CSS_IMPORTING_SOURCE_EXTENSIONS --
|
|
2051
|
+
// and es-module-lexer parses none of those. Every file containing JSX threw
|
|
2052
|
+
// here, each throw recorded a gap, and gaps are fatal since #3244, so no
|
|
2053
|
+
// project with a JSX component could publish a release at all.
|
|
2054
|
+
//
|
|
2055
|
+
// This is the same extractor the dev CSS scanner has always used, so the
|
|
2056
|
+
// two paths now agree. It also removes the failure mode rather than
|
|
2057
|
+
// handling it: a scanner that cannot throw cannot fail a release for a
|
|
2058
|
+
// reason that has nothing to do with the release.
|
|
2059
|
+
for (const specifier of extractCssImportSpecifiers(content)) {
|
|
2065
2060
|
const cssPath = specifier.split(/[?#]/, 1)[0] ?? "";
|
|
2066
2061
|
if (!cssPath.endsWith(".css"))
|
|
2067
2062
|
continue;
|
|
2063
|
+
// Nothing this scan fails to resolve is fatal, because a regex match is
|
|
2064
|
+
// not knowledge that the build needs the file. extractCssImportSpecifiers
|
|
2065
|
+
// is text-based by design and says so ("over-matching is harmless"); this
|
|
2066
|
+
// path broke that contract by turning its output into a coverage gap, and
|
|
2067
|
+
// assertCompleteReleaseAssetCoverage throws on gaps. Three rounds of
|
|
2068
|
+
// review found three more ways ordinary source produces a phantom
|
|
2069
|
+
// specifier, each of which would have blocked a project's releases.
|
|
2070
|
+
//
|
|
2071
|
+
// Merging module CSS is an enhancement: when it cannot resolve something
|
|
2072
|
+
// the right outcome is unmerged CSS, not a refused release. Genuine
|
|
2073
|
+
// missing-CSS detection belongs on the resolved module graph
|
|
2074
|
+
// (collectProjectModuleImports, over transformed code where the lexer is
|
|
2075
|
+
// trustworthy), not on this text scan.
|
|
2068
2076
|
if (cssPath !== specifier) {
|
|
2069
|
-
|
|
2077
|
+
logger.debug("Skipping CSS import with an unsupported specifier", { path, specifier });
|
|
2070
2078
|
continue;
|
|
2071
2079
|
}
|
|
2072
2080
|
const importedPath = resolveCssImportPath(specifier, `/${path}`, "/");
|
|
2073
2081
|
if (!importedPath) {
|
|
2074
|
-
|
|
2082
|
+
logger.debug("Skipping CSS import that does not resolve", { path, specifier });
|
|
2075
2083
|
continue;
|
|
2076
2084
|
}
|
|
2077
2085
|
const relativePath = importedPath.replace(/^\/+/, "");
|
|
2078
2086
|
if (!sourceByPath.has(relativePath)) {
|
|
2079
|
-
|
|
2087
|
+
logger.debug("Skipping CSS import with no matching source file", { path, relativePath });
|
|
2080
2088
|
continue;
|
|
2081
2089
|
}
|
|
2082
2090
|
importedPaths.add(relativePath);
|
|
@@ -63,6 +63,18 @@ interface AdapterResolutionOptions {
|
|
|
63
63
|
*/
|
|
64
64
|
prepareHostedConfigContext?: (isLocalProject: boolean) => Promise<PreparedHostedConfigContext>;
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Whether an error carries an own `status` of 404.
|
|
68
|
+
*
|
|
69
|
+
* Read through an own-property descriptor rather than plain access: this runs on
|
|
70
|
+
* a rejection value that may be anything, and a getter on an attacker-shaped
|
|
71
|
+
* object should not execute during error handling.
|
|
72
|
+
*
|
|
73
|
+
* Callers must scope this to the single operation whose 404 means "absent",
|
|
74
|
+
* never to a block that also performs other requests -- see the config load
|
|
75
|
+
* below, where only the getHostedConfig call is treated this way.
|
|
76
|
+
*/
|
|
77
|
+
export declare function hasNotFoundStatus(error: unknown): boolean;
|
|
66
78
|
/**
|
|
67
79
|
* Resolve the effective adapter and config for a request.
|
|
68
80
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter-factory.d.ts","sourceRoot":"","sources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ACzB,YAAY,EAAE,YAAY,CAAC;IAC3B,qFAAqF;IACrF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,WAAW,EAAE,OAAO,CAAC;IACrB,sEAAsE;IACtE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,qEAAqE;IACrE,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B;;;OAGG;IACH,0BAA0B,CAAC,EAAE,CAC3B,cAAc,EAAE,OAAO,KACpB,OAAO,CAAC,2BAA2B,CAAC,CAAC;CAC3C;AAgCD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,IAAI,EAAE,wBAAwB,GAC7B,OAAO,CAAC,uBAAuB,CAAC,
|
|
1
|
+
{"version":3,"file":"adapter-factory.d.ts","sourceRoot":"","sources":["../../../../src/src/server/runtime-handler/adapter-factory.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEtE,OAAO,EAGL,KAAK,2BAA2B,EACjC,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAG7D,OAAO,EAGL,KAAK,qBAAqB,EAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAO9D,UAAU,uBAAuB;IAC/B,6CAA6C;IAC7C,UAAU,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,OAAO,EAAE,cAAc,CAAC;IACxB,kCAAkC;IAClC,MAAM,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,yDAAyD;IACzD,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,UAAU,wBAAwB;IAChC;;;OAGG;IACH,GAAG,EAAE,OAAO,CAAC;IACb,6BAA6B;IAC7B,UAAU,EAAE,MAAM,CAAC;IACnB,mBAAmB;IACnB,OAAO,EAAE,cAAc,CAAC;IACxB,6BAA6B;IAC7B,MAAM,EAAE,eAAe,GAAG,SAAS,CAAC;IACpC,mBAAmB;IACnB,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,iBAAiB;IACjB,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,kBAAkB;IAClB,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,iBAAiB;IACjB,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,uCAAuC;IACvC,QAAQ,EAAE,SAAS,GAAG,YAAY,GAAG,SAAS,CAAC;IAC/C,kBAAkB;IAClB,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAClC,yCAAyC;IACzC,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,yBAAyB;IACzB,YAAY,EAAE,YAAY,CAAC;IAC3B,qFAAqF;IACrF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,WAAW,EAAE,OAAO,CAAC;IACrB,sEAAsE;IACtE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,qEAAqE;IACrE,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B;;;OAGG;IACH,0BAA0B,CAAC,EAAE,CAC3B,cAAc,EAAE,OAAO,KACpB,OAAO,CAAC,2BAA2B,CAAC,CAAC;CAC3C;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAkBzD;AAgCD;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,IAAI,EAAE,wBAAwB,GAC7B,OAAO,CAAC,uBAAuB,CAAC,CAkLlC"}
|
|
@@ -17,6 +17,39 @@ import { defaultDiscoveryCache, findLocalProjectPath, } from "./local-project-di
|
|
|
17
17
|
import { isProxyTrusted } from "../utils/proxy-trust.js";
|
|
18
18
|
const baseLogger = getBaseLogger("SERVER");
|
|
19
19
|
const logger = baseLogger.component("adapter-factory");
|
|
20
|
+
/**
|
|
21
|
+
* Whether an error carries an own `status` of 404.
|
|
22
|
+
*
|
|
23
|
+
* Read through an own-property descriptor rather than plain access: this runs on
|
|
24
|
+
* a rejection value that may be anything, and a getter on an attacker-shaped
|
|
25
|
+
* object should not execute during error handling.
|
|
26
|
+
*
|
|
27
|
+
* Callers must scope this to the single operation whose 404 means "absent",
|
|
28
|
+
* never to a block that also performs other requests -- see the config load
|
|
29
|
+
* below, where only the getHostedConfig call is treated this way.
|
|
30
|
+
*/
|
|
31
|
+
export function hasNotFoundStatus(error) {
|
|
32
|
+
// Walks `cause`, because the 404 does not always arrive on the outermost
|
|
33
|
+
// error. readHostedConfigSource lets a VeryfrontError through untouched but
|
|
34
|
+
// wraps anything else in CONFIG_PARSE_ERROR, which buries the original status
|
|
35
|
+
// one level down. Reading only the top object made the fallback fire for one
|
|
36
|
+
// error shape and not the other, for the same underlying 404.
|
|
37
|
+
//
|
|
38
|
+
// Depth-bounded so a self-referential cause cannot spin.
|
|
39
|
+
let current = error;
|
|
40
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
41
|
+
if (typeof current !== "object" || current === null)
|
|
42
|
+
return false;
|
|
43
|
+
const status = Object.getOwnPropertyDescriptor(current, "status");
|
|
44
|
+
if (status !== undefined && status.value === 404)
|
|
45
|
+
return true;
|
|
46
|
+
const cause = Object.getOwnPropertyDescriptor(current, "cause");
|
|
47
|
+
if (cause === undefined)
|
|
48
|
+
return false;
|
|
49
|
+
current = cause.value;
|
|
50
|
+
}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
20
53
|
function usesExactSourceConfig(opts) {
|
|
21
54
|
return opts.isProxyMode &&
|
|
22
55
|
!!opts.projectSlug &&
|
|
@@ -127,6 +160,11 @@ export async function resolveAdapter(opts) {
|
|
|
127
160
|
// Load config via proxy mode with project context.
|
|
128
161
|
// Unlike local projects, proxy mode config loading failures are propagated
|
|
129
162
|
// because proceeding without config causes silent 404s for valid projects.
|
|
163
|
+
// Set only when getHostedConfig itself reports 404, never when some other
|
|
164
|
+
// request in this block does. The catch below spans prepareProxyConfigLoad,
|
|
165
|
+
// the snapshot refresh and runWithContext too, and a 404 from any of those
|
|
166
|
+
// is a real failure that must not be read as "no config published".
|
|
167
|
+
let hostedConfigAbsent = false;
|
|
130
168
|
try {
|
|
131
169
|
effectiveConfig = await timeAsync("config:load-proxy-project", async () => {
|
|
132
170
|
const hosted = await prepareProxyConfigLoad(opts, false);
|
|
@@ -137,6 +175,10 @@ export async function resolveAdapter(opts) {
|
|
|
137
175
|
return await getHostedConfig(effectiveProjectDir, effectiveAdapter, {
|
|
138
176
|
...hosted,
|
|
139
177
|
signal: opts.req.signal,
|
|
178
|
+
}).catch((error) => {
|
|
179
|
+
if (hasNotFoundStatus(error))
|
|
180
|
+
hostedConfigAbsent = true;
|
|
181
|
+
throw error;
|
|
140
182
|
});
|
|
141
183
|
};
|
|
142
184
|
if (isExtendedFSAdapter(effectiveAdapter.fs) && effectiveAdapter.fs.runWithContext) {
|
|
@@ -157,19 +199,36 @@ export async function resolveAdapter(opts) {
|
|
|
157
199
|
});
|
|
158
200
|
}
|
|
159
201
|
catch (error) {
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
//
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
202
|
+
// A release with no config file at all is an ordinary project shape, not
|
|
203
|
+
// a failure: the API answers 404 because there is nothing to serve. This
|
|
204
|
+
// used to be re-thrown with everything else, which turned every request
|
|
205
|
+
// for such a project into a 404. Fall through to defaults instead --
|
|
206
|
+
// the same outcome as a project whose config resolves to nothing.
|
|
207
|
+
if (hostedConfigAbsent) {
|
|
208
|
+
// Defaults, not whatever a caller happened to pass in: a project with no
|
|
209
|
+
// published config must not silently inherit another config's routes.
|
|
210
|
+
effectiveConfig = undefined;
|
|
211
|
+
logger.debug("No hosted config for this release; using defaults", {
|
|
212
|
+
projectSlug: opts.projectSlug,
|
|
213
|
+
projectId: opts.projectId,
|
|
214
|
+
releaseId: opts.releaseId,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
// Log at error level — this is a real failure that will affect rendering.
|
|
219
|
+
// Config loading failure in proxy mode means the project's routes, layouts,
|
|
220
|
+
// and settings won't be available, leading to 404s for valid pages.
|
|
221
|
+
logger.error("Failed to load project config in proxy mode", {
|
|
222
|
+
projectSlug: opts.projectSlug,
|
|
223
|
+
projectId: opts.projectId,
|
|
224
|
+
releaseId: opts.releaseId,
|
|
225
|
+
proxyEnv: opts.proxyEnv,
|
|
226
|
+
error: getErrorMessage(error),
|
|
227
|
+
});
|
|
228
|
+
// Re-throw so the caller (runtime-handler) can return a proper error response
|
|
229
|
+
// instead of silently proceeding with broken defaults.
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
173
232
|
}
|
|
174
233
|
}
|
|
175
234
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../../../src/src/server/shared/renderer/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;4BAQ4B;
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../../../src/src/server/shared/renderer/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;4BAQ4B;AAO5B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAE9D,OAAO,EAOL,KAAK,QAAQ,EACb,KAAK,eAAe,EACrB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EACV,gBAAgB,EAChB,aAAa,EACb,YAAY,EACb,MAAM,0CAA0C,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAczD,MAAM,WAAW,eAAe;IAC9B,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAA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sBAAsB,CACpC,WAAW,CAAC,EAAE,mBAAmB,GAChC,IAAI,CAgBN;AA0UD,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,CAAC,CAiCzF;AAED,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC,CAW5D"}
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
**************************/
|
|
10
10
|
import { rendererLogger } from "../../../utils/index.js";
|
|
11
11
|
import { getConfig } from "../../../config/index.js";
|
|
12
|
-
import { getHostedConfig } from "../../../config/loader.js";
|
|
12
|
+
import { evaluateHostedConfigSource, getHostedConfig } from "../../../config/loader.js";
|
|
13
|
+
import { hasNotFoundStatus } from "../../runtime-handler/adapter-factory.js";
|
|
13
14
|
import { getEnvBoolean, getEnvString } from "../../../platform/compat/process.js";
|
|
14
15
|
import { buildEnrichedContext } from "../../context/enriched-context.js";
|
|
15
16
|
import { createRenderContextFromEnriched, destroyRenderer as destroySharedRenderer, getRenderer, initializeRenderer, isRendererInitialized, } from "../../../rendering/renderer.js";
|
|
@@ -150,10 +151,48 @@ function resolveEnvironment(ctx) {
|
|
|
150
151
|
*/
|
|
151
152
|
async function loadConfigForHandler(ctx, cacheKey) {
|
|
152
153
|
if (shouldUseMultiProjectContext(ctx) && ctx.prepareHostedConfigContext && cacheKey) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
154
|
+
// Prepared outside the try: a 404 from context preparation means the
|
|
155
|
+
// project, release or token could not be resolved, which is a real failure
|
|
156
|
+
// and must not be read as "this release published no config".
|
|
157
|
+
const hosted = await ctx.prepareHostedConfigContext();
|
|
158
|
+
// Set only where a 404 genuinely means absence. hasNotFoundStatus is
|
|
159
|
+
// documented as scoped to a single operation, never to a block that also
|
|
160
|
+
// performs other requests -- adapter-factory.ts does the same thing for the
|
|
161
|
+
// first config load, and the two must not drift.
|
|
162
|
+
let hostedConfigAbsent = false;
|
|
163
|
+
try {
|
|
164
|
+
return await getHostedConfig(ctx.projectDir, ctx.adapter, { cacheKey, ...hosted })
|
|
165
|
+
.catch((error) => {
|
|
166
|
+
if (hasNotFoundStatus(error))
|
|
167
|
+
hostedConfigAbsent = true;
|
|
168
|
+
throw error;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
// A release that published no config answers 404. The adapter factory
|
|
173
|
+
// already treats that as an ordinary project shape and falls through to
|
|
174
|
+
// defaults; this second load has to agree, or a project without a config
|
|
175
|
+
// clears that guard and dies here instead.
|
|
176
|
+
if (!hostedConfigAbsent)
|
|
177
|
+
throw error;
|
|
178
|
+
rendererLogger.debug("No hosted config for this release; using defaults", {
|
|
179
|
+
projectSlug: ctx.projectSlug,
|
|
180
|
+
projectId: ctx.projectId,
|
|
181
|
+
});
|
|
182
|
+
// `source: null` returns merged defaults on the first statement, so
|
|
183
|
+
// nothing below it is read today. The values are still the correct ones
|
|
184
|
+
// rather than placeholders: `?? "release"` would mislabel preview, whose
|
|
185
|
+
// VirtualConfigSourceContext carries no environmentName at all, and this
|
|
186
|
+
// becomes a live bug the moment the short-circuit moves. `environment` is
|
|
187
|
+
// empty because there is no source to evaluate against it -- the real one
|
|
188
|
+
// lives inside `hosted.preparedContext`, not on the context itself.
|
|
189
|
+
return await evaluateHostedConfigSource({
|
|
190
|
+
cacheKey,
|
|
191
|
+
source: null,
|
|
192
|
+
environmentName: hosted.sourceContext.environmentName ?? resolveEnvironment(ctx),
|
|
193
|
+
environment: {},
|
|
194
|
+
});
|
|
195
|
+
}
|
|
157
196
|
}
|
|
158
197
|
return await getConfig(ctx.projectDir, ctx.adapter, { cacheKey });
|
|
159
198
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-cache.d.ts","sourceRoot":"","sources":["../../../../src/src/transforms/esm/http-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAgBH,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,oBAA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{ createBundleManifest, storeBundleManifest } from "./bundle-manifest.js";
|
|
18
18
|
import { HTTP_MODULE_DISTRIBUTED_TTL_SEC } from "../../utils/constants/cache.js";
|
|
19
|
-
import {
|
|
19
|
+
import { HTTP_MODULE_FETCH_TIMEOUT_MS } from "../../utils/constants/http.js";
|
|
20
20
|
import { httpBundleCache } from "./http-cache-wrapper.js";
|
|
21
21
|
import { unbrand } from "./http-cache-types.js";
|
|
22
22
|
import { asLocalModuleCode, VeryfrontError } from "./http-cache-invariants.js";
|
|
@@ -41,7 +41,7 @@ const SLOW_HTTP_FETCH_THRESHOLD_MS = 500;
|
|
|
41
41
|
const HTTP_MODULE_FETCH_MAX_ATTEMPTS = 3;
|
|
42
42
|
const HTTP_MODULE_FETCH_RETRY_DELAY_MS = 100;
|
|
43
43
|
const HTTP_MODULE_FETCH_WAIT_GRACE_MS = 5_000;
|
|
44
|
-
const HTTP_MODULE_FETCH_MAX_WAIT_MS =
|
|
44
|
+
const HTTP_MODULE_FETCH_MAX_WAIT_MS = HTTP_MODULE_FETCH_TIMEOUT_MS * HTTP_MODULE_FETCH_MAX_ATTEMPTS +
|
|
45
45
|
HTTP_MODULE_FETCH_RETRY_DELAY_MS *
|
|
46
46
|
((HTTP_MODULE_FETCH_MAX_ATTEMPTS - 1) * HTTP_MODULE_FETCH_MAX_ATTEMPTS / 2) +
|
|
47
47
|
HTTP_MODULE_FETCH_WAIT_GRACE_MS;
|
|
@@ -125,7 +125,7 @@ async function fetchHttpModule(url) {
|
|
|
125
125
|
"esm.package_fetch": true,
|
|
126
126
|
}), {
|
|
127
127
|
maxAttempts: HTTP_MODULE_FETCH_MAX_ATTEMPTS,
|
|
128
|
-
timeoutMs:
|
|
128
|
+
timeoutMs: HTTP_MODULE_FETCH_TIMEOUT_MS,
|
|
129
129
|
shouldRetry: (error) => error instanceof HttpModuleBodyError
|
|
130
130
|
? false
|
|
131
131
|
: error instanceof OutboundRequestBlockedError
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "veryfront",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1205",
|
|
4
4
|
"description": "The simplest way to build AI-powered apps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -421,13 +421,13 @@
|
|
|
421
421
|
"@deno/shim-crypto": "0.3.1",
|
|
422
422
|
"@types/react": "19.2.14",
|
|
423
423
|
"@types/react-dom": "19.2.3",
|
|
424
|
-
"@veryfront/ext-bundler-esbuild": "0.1.
|
|
425
|
-
"@veryfront/ext-content-mdx": "0.1.
|
|
426
|
-
"@veryfront/ext-css-tailwind": "0.1.
|
|
427
|
-
"@veryfront/ext-dev-ui-react": "0.1.
|
|
428
|
-
"@veryfront/ext-node-websocket-ws": "0.1.
|
|
429
|
-
"@veryfront/ext-parser-babel": "0.1.
|
|
430
|
-
"@veryfront/ext-yaml": "0.1.
|
|
424
|
+
"@veryfront/ext-bundler-esbuild": "0.1.1205",
|
|
425
|
+
"@veryfront/ext-content-mdx": "0.1.1205",
|
|
426
|
+
"@veryfront/ext-css-tailwind": "0.1.1205",
|
|
427
|
+
"@veryfront/ext-dev-ui-react": "0.1.1205",
|
|
428
|
+
"@veryfront/ext-node-websocket-ws": "0.1.1205",
|
|
429
|
+
"@veryfront/ext-parser-babel": "0.1.1205",
|
|
430
|
+
"@veryfront/ext-yaml": "0.1.1205"
|
|
431
431
|
},
|
|
432
432
|
"devDependencies": {
|
|
433
433
|
"@types/node": "20.9.0"
|