veryfront 0.0.6 → 0.0.9

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/dist/cli.js CHANGED
@@ -317,6 +317,7 @@ function getUnoCSSTailwindResetUrl() {
317
317
  var ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;
318
318
  var init_cdn = __esm({
319
319
  "src/core/utils/constants/cdn.ts"() {
320
+ "use strict";
320
321
  ESM_CDN_BASE = "https://esm.sh";
321
322
  JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";
322
323
  DENO_STD_BASE = "https://deno.land";
@@ -336,6 +337,7 @@ var init_cdn = __esm({
336
337
  var HASH_SEED_DJB2, HASH_SEED_FNV1A;
337
338
  var init_hash = __esm({
338
339
  "src/core/utils/constants/hash.ts"() {
340
+ "use strict";
339
341
  HASH_SEED_DJB2 = 5381;
340
342
  HASH_SEED_FNV1A = 2166136261;
341
343
  }
@@ -345,6 +347,7 @@ var init_hash = __esm({
345
347
  var KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;
346
348
  var init_http = __esm({
347
349
  "src/core/utils/constants/http.ts"() {
350
+ "use strict";
348
351
  init_cache();
349
352
  KB_IN_BYTES = 1024;
350
353
  HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;
@@ -529,7 +532,7 @@ var init_deno = __esm({
529
532
  "deno.json"() {
530
533
  deno_default = {
531
534
  name: "veryfront",
532
- version: "0.0.6",
535
+ version: "0.0.8",
533
536
  nodeModulesDir: "auto",
534
537
  workspace: [
535
538
  "./examples/async-worker-redis",
@@ -658,6 +661,7 @@ var init_deno = __esm({
658
661
  dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",
659
662
  build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",
660
663
  "build:npm": "deno run -A scripts/build-npm.ts",
664
+ release: "deno run -A scripts/release.ts",
661
665
  test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",
662
666
  "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",
663
667
  "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",
@@ -3553,13 +3557,18 @@ function mergeConfigs(userConfig) {
3553
3557
  }
3554
3558
  async function loadAndMergeConfig(configPath, projectDir) {
3555
3559
  try {
3556
- const configUrl = `file://${configPath}?t=${Date.now()}`;
3560
+ const configUrl = `file://${configPath}?t=${Date.now()}-${crypto.randomUUID()}`;
3557
3561
  const configModule = await import(configUrl);
3558
3562
  const userConfig = configModule.default || configModule;
3563
+ if (userConfig === null || typeof userConfig !== "object" || Array.isArray(userConfig)) {
3564
+ throw new ConfigValidationError(
3565
+ `Expected object, received ${userConfig === null ? "null" : typeof userConfig}`
3566
+ );
3567
+ }
3559
3568
  validateCorsConfig(userConfig);
3560
3569
  validateConfigShape(userConfig);
3561
3570
  const merged = mergeConfigs(userConfig);
3562
- configCacheByProject.set(projectDir, merged);
3571
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });
3563
3572
  return merged;
3564
3573
  } catch (error2) {
3565
3574
  if (error2 instanceof ConfigValidationError) {
@@ -3573,8 +3582,8 @@ async function loadAndMergeConfig(configPath, projectDir) {
3573
3582
  }
3574
3583
  async function getConfig(projectDir, adapter) {
3575
3584
  const cached = configCacheByProject.get(projectDir);
3576
- if (cached)
3577
- return cached;
3585
+ if (cached && cached.revision === cacheRevision)
3586
+ return cached.config;
3578
3587
  const configFiles = ["veryfront.config.js", "veryfront.config.ts", "veryfront.config.mjs"];
3579
3588
  for (const configFile of configFiles) {
3580
3589
  const configPath = join2(projectDir, configFile);
@@ -3600,13 +3609,14 @@ async function getConfig(projectDir, adapter) {
3600
3609
  }
3601
3610
  }
3602
3611
  const defaultConfig2 = DEFAULT_CONFIG;
3603
- configCacheByProject.set(projectDir, defaultConfig2);
3612
+ configCacheByProject.set(projectDir, { revision: cacheRevision, config: defaultConfig2 });
3604
3613
  return defaultConfig2;
3605
3614
  }
3606
3615
  function clearConfigCache() {
3607
3616
  configCacheByProject.clear();
3617
+ cacheRevision++;
3608
3618
  }
3609
- var DEFAULT_CONFIG, configCacheByProject, ConfigValidationError;
3619
+ var DEFAULT_CONFIG, configCacheByProject, cacheRevision, ConfigValidationError;
3610
3620
  var init_loader = __esm({
3611
3621
  "src/core/config/loader.ts"() {
3612
3622
  "use strict";
@@ -3656,6 +3666,7 @@ var init_loader = __esm({
3656
3666
  }
3657
3667
  };
3658
3668
  configCacheByProject = /* @__PURE__ */ new Map();
3669
+ cacheRevision = 0;
3659
3670
  ConfigValidationError = class extends Error {
3660
3671
  constructor(message) {
3661
3672
  super(message);
@@ -8137,7 +8148,7 @@ var init_ai = __esm({
8137
8148
  },
8138
8149
  {
8139
8150
  path: "ai/agent.ts",
8140
- content: `import { agent, tool } from "@veryfront/ai";
8151
+ content: `import { agent, tool } from "veryfront/ai";
8141
8152
  import { z } from "zod";
8142
8153
 
8143
8154
  // Define a tool
@@ -8191,18 +8202,31 @@ export const myAgent = agent({
8191
8202
  </html>
8192
8203
  );
8193
8204
  }`
8205
+ },
8206
+ {
8207
+ path: "app/api/chat/route.ts",
8208
+ content: `import { myAgent } from "../../../ai/agent";
8209
+
8210
+ export async function POST(request: Request) {
8211
+ const { messages } = await request.json();
8212
+
8213
+ // Use the agent to generate a response
8214
+ const response = await myAgent.stream({ messages });
8215
+
8216
+ return response.toDataStreamResponse();
8217
+ }
8218
+ `
8194
8219
  },
8195
8220
  {
8196
8221
  path: "app/page.tsx",
8197
8222
  content: `/** @jsxImportSource react */
8198
8223
  'use client';
8199
8224
 
8200
- import { useChat } from "@veryfront/ai/react";
8201
- import { myAgent } from "../ai/agent.ts";
8225
+ import { useChat } from "veryfront/ai/react";
8202
8226
 
8203
8227
  export default function ChatPage() {
8204
- const { messages, input, setInput, sendMessage, isLoading } = useChat({
8205
- agent: myAgent,
8228
+ const { messages, input, setInput, append, isLoading, handleInputChange, handleSubmit } = useChat({
8229
+ api: "/api/chat",
8206
8230
  });
8207
8231
 
8208
8232
  return (
@@ -8269,13 +8293,13 @@ export default function ChatPage() {
8269
8293
  type="text"
8270
8294
  value={input}
8271
8295
  onChange={(e) => setInput(e.target.value)}
8272
- onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && sendMessage()}
8296
+ onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && handleSubmit(e as unknown as React.FormEvent)}
8273
8297
  placeholder="Type a message..."
8274
8298
  className="flex-1 border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:border-blue-500"
8275
8299
  disabled={isLoading}
8276
8300
  />
8277
8301
  <button
8278
- onClick={() => sendMessage()}
8302
+ onClick={(e) => handleSubmit(e as unknown as React.FormEvent)}
8279
8303
  disabled={isLoading || !input.trim()}
8280
8304
  className="bg-blue-600 text-white px-6 py-2 rounded-lg font-medium hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
8281
8305
  >
@@ -10820,23 +10844,19 @@ function encodeBase64(value) {
10820
10844
  var AuthHandler;
10821
10845
  var init_auth = __esm({
10822
10846
  "src/security/http/auth.ts"() {
10823
- "use strict";
10824
10847
  init_base_handler();
10825
10848
  init_veryfront_error();
10826
10849
  AuthHandler = class extends BaseHandler {
10827
- constructor() {
10828
- super(...arguments);
10829
- this.metadata = {
10830
- name: "AuthHandler",
10831
- priority: 0,
10832
- // CRITICAL priority - runs first
10833
- patterns: []
10834
- // Checks all requests
10835
- };
10836
- this.basicUser = null;
10837
- this.basicPass = null;
10838
- this.bearerToken = null;
10839
- }
10850
+ metadata = {
10851
+ name: "AuthHandler",
10852
+ priority: 0,
10853
+ // CRITICAL priority - runs first
10854
+ patterns: []
10855
+ // Checks all requests
10856
+ };
10857
+ basicUser = null;
10858
+ basicPass = null;
10859
+ bearerToken = null;
10840
10860
  handle(req, ctx) {
10841
10861
  this.loadAuthConfig(ctx);
10842
10862
  if (req.method.toUpperCase() === "OPTIONS") {
@@ -10893,7 +10913,6 @@ var init_auth = __esm({
10893
10913
  var SecurityConfigLoader;
10894
10914
  var init_config7 = __esm({
10895
10915
  "src/security/http/config.ts"() {
10896
- "use strict";
10897
10916
  init_config();
10898
10917
  init_utils();
10899
10918
  init_security_handler();
@@ -10901,11 +10920,11 @@ var init_config7 = __esm({
10901
10920
  constructor(projectDir, adapter) {
10902
10921
  this.projectDir = projectDir;
10903
10922
  this.adapter = adapter;
10904
- this.securityConfig = null;
10905
- this.cspUserHeader = null;
10906
- this.isLoaded = false;
10907
- this.loadPromise = null;
10908
10923
  }
10924
+ securityConfig = null;
10925
+ cspUserHeader = null;
10926
+ isLoaded = false;
10927
+ loadPromise = null;
10909
10928
  /**
10910
10929
  * Ensure security config is loaded (singleton pattern)
10911
10930
  */
@@ -14084,8 +14103,8 @@ var init_templates2 = __esm({
14084
14103
  padding: 0;
14085
14104
  color: inherit;
14086
14105
  }`;
14087
- CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\nfunction hasBunRuntime(global) {\n return typeof global === "object" && global !== null && "Bun" in global && typeof global.Bun !== "undefined";\n}\nvar init_runtime_guards = __esm({\n "src/core/utils/runtime-guards.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\nfunction isTestEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "test";\n}\nfunction isProductionEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "production";\n}\nfunction isDevelopmentEnvironment() {\n const env = getEnvironmentVariable("NODE_ENV");\n return env === "development" || env === void 0;\n}\nvar init_env = __esm({\n "src/core/utils/logger/env.ts"() {\n "use strict";\n init_runtime_guards();\n }\n});\n\n// src/core/utils/logger/logger.ts\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nfunction __loggerResetForTests(options = {}) {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\nvar LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;\nvar init_logger = __esm({\n "src/core/utils/logger/logger.ts"() {\n "use strict";\n init_env();\n LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";\n LogLevel2[LogLevel2["INFO"] = 1] = "INFO";\n LogLevel2[LogLevel2["WARN"] = 2] = "WARN";\n LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";\n return LogLevel2;\n })(LogLevel || {});\n originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error\n };\n ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error2) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error2);\n throw error2;\n }\n }\n };\n getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n };\n trackedLoggers = /* @__PURE__ */ new Set();\n cliLogger = createLogger("CLI");\n serverLogger = createLogger("SERVER");\n rendererLogger = createLogger("RENDERER");\n bundlerLogger = createLogger("BUNDLER");\n agentLogger = createLogger("AGENT");\n logger = createLogger("VERYFRONT");\n }\n});\n\n// src/core/utils/logger/index.ts\nvar init_logger2 = __esm({\n "src/core/utils/logger/index.ts"() {\n "use strict";\n init_logger();\n init_env();\n }\n});\n\n// src/core/utils/constants/build.ts\nvar DEFAULT_BUILD_CONCURRENCY, IMAGE_OPTIMIZATION;\nvar init_build = __esm({\n "src/core/utils/constants/build.ts"() {\n "use strict";\n DEFAULT_BUILD_CONCURRENCY = 4;\n IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80\n };\n }\n});\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;\nvar init_cache = __esm({\n "src/core/utils/constants/cache.ts"() {\n "use strict";\n SECONDS_PER_MINUTE = 60;\n MINUTES_PER_HOUR = 60;\n HOURS_PER_DAY = 24;\n MS_PER_SECOND = 1e3;\n DEFAULT_LRU_MAX_ENTRIES = 100;\n COMPONENT_LOADER_MAX_ENTRIES = 100;\n COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_RENDERER_MAX_ENTRIES = 200;\n MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RENDERER_CORE_MAX_ENTRIES = 100;\n RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n TSX_LAYOUT_MAX_ENTRIES = 50;\n TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n DATA_FETCHING_MAX_ENTRIES = 200;\n DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RSC_MANIFEST_CACHE_TTL_MS = 5e3;\n SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64e3;\n HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\n HTTP_CACHE_LONG_MAX_AGE_SEC = 31536e3;\n ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n CACHE_CLEANUP_INTERVAL_MS = 6e4;\n LRU_DEFAULT_MAX_ENTRIES = 1e3;\n LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n CLEANUP_INTERVAL_MULTIPLIER = 2;\n }\n});\n\n// src/core/utils/constants/cdn.ts\nfunction getReactCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\nfunction getReactDOMCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\nfunction getReactDOMClientCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\nfunction getReactDOMServerCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\nfunction getReactJSXRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\nfunction getReactJSXDevRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\nfunction getReactImportMap(version = REACT_DEFAULT_VERSION) {\n return {\n react: getReactCDNUrl(version),\n "react-dom": getReactDOMCDNUrl(version),\n "react-dom/client": getReactDOMClientCDNUrl(version),\n "react-dom/server": getReactDOMServerCDNUrl(version),\n "react/jsx-runtime": getReactJSXRuntimeCDNUrl(version),\n "react/jsx-dev-runtime": getReactJSXDevRuntimeCDNUrl(version)\n };\n}\nfunction getDenoStdNodeBase() {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\nfunction getUnoCSSTailwindResetUrl() {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\nvar ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;\nvar init_cdn = __esm({\n "src/core/utils/constants/cdn.ts"() {\n "use strict";\n ESM_CDN_BASE = "https://esm.sh";\n JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";\n DENO_STD_BASE = "https://deno.land";\n REACT_VERSION_17 = "17.0.2";\n REACT_VERSION_18_2 = "18.2.0";\n REACT_VERSION_18_3 = "18.3.1";\n REACT_VERSION_19_RC = "19.0.0-rc.0";\n REACT_VERSION_19 = "19.1.1";\n REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n DENO_STD_VERSION = "0.220.0";\n UNOCSS_VERSION = "0.59.0";\n }\n});\n\n// src/core/utils/constants/hash.ts\nvar HASH_SEED_DJB2, HASH_SEED_FNV1A;\nvar init_hash = __esm({\n "src/core/utils/constants/hash.ts"() {\n "use strict";\n HASH_SEED_DJB2 = 5381;\n HASH_SEED_FNV1A = 2166136261;\n }\n});\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;\nvar init_http = __esm({\n "src/core/utils/constants/http.ts"() {\n "use strict";\n init_cache();\n KB_IN_BYTES = 1024;\n HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n HMR_RECONNECT_DELAY_MS = 1e3;\n HMR_RELOAD_DELAY_MS = 1e3;\n HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n HMR_KEEP_ALIVE_INTERVAL_MS = 3e4;\n DASHBOARD_RECONNECT_DELAY_MS = 3e3;\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 3e4;\n PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\n PREFETCH_DEFAULT_DELAY_MS = 200;\n HTTP_OK = 200;\n HTTP_NO_CONTENT = 204;\n HTTP_CREATED = 201;\n HTTP_REDIRECT_FOUND = 302;\n HTTP_NOT_MODIFIED = 304;\n HTTP_BAD_REQUEST = 400;\n HTTP_UNAUTHORIZED = 401;\n HTTP_FORBIDDEN = 403;\n HTTP_NOT_FOUND = 404;\n HTTP_METHOD_NOT_ALLOWED = 405;\n HTTP_GONE = 410;\n HTTP_PAYLOAD_TOO_LARGE = 413;\n HTTP_URI_TOO_LONG = 414;\n HTTP_TOO_MANY_REQUESTS = 429;\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n HTTP_SERVER_ERROR = 500;\n HTTP_INTERNAL_SERVER_ERROR = 500;\n HTTP_BAD_GATEWAY = 502;\n HTTP_NOT_IMPLEMENTED = 501;\n HTTP_UNAVAILABLE = 503;\n HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n HTTP_STATUS_SUCCESS_MIN = 200;\n HTTP_STATUS_REDIRECT_MIN = 300;\n HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n HTTP_STATUS_SERVER_ERROR_MIN = 500;\n HTTP_CONTENT_TYPES = {\n JS: "application/javascript; charset=utf-8",\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n TEXT: "text/plain; charset=utf-8"\n };\n MS_PER_MINUTE = 6e4;\n HTTP_CONTENT_TYPE_IMAGE_PNG = "image/png";\n HTTP_CONTENT_TYPE_IMAGE_JPEG = "image/jpeg";\n HTTP_CONTENT_TYPE_IMAGE_WEBP = "image/webp";\n HTTP_CONTENT_TYPE_IMAGE_AVIF = "image/avif";\n HTTP_CONTENT_TYPE_IMAGE_SVG = "image/svg+xml";\n HTTP_CONTENT_TYPE_IMAGE_GIF = "image/gif";\n HTTP_CONTENT_TYPE_IMAGE_ICO = "image/x-icon";\n }\n});\n\n// src/core/utils/constants/hmr.ts\nfunction isValidHMRMessageType(type) {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type\n );\n}\nvar HMR_MAX_MESSAGE_SIZE_BYTES, HMR_MAX_MESSAGES_PER_MINUTE, HMR_CLIENT_RELOAD_DELAY_MS, HMR_PORT_OFFSET, HMR_RATE_LIMIT_WINDOW_MS, HMR_CLOSE_NORMAL, HMR_CLOSE_RATE_LIMIT, HMR_CLOSE_MESSAGE_TOO_LARGE, HMR_MESSAGE_TYPES;\nvar init_hmr = __esm({\n "src/core/utils/constants/hmr.ts"() {\n "use strict";\n init_http();\n HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n HMR_MAX_MESSAGES_PER_MINUTE = 100;\n HMR_CLIENT_RELOAD_DELAY_MS = 3e3;\n HMR_PORT_OFFSET = 1;\n HMR_RATE_LIMIT_WINDOW_MS = 6e4;\n HMR_CLOSE_NORMAL = 1e3;\n HMR_CLOSE_RATE_LIMIT = 1008;\n HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n HMR_MESSAGE_TYPES = {\n CONNECTED: "connected",\n UPDATE: "update",\n RELOAD: "reload",\n PING: "ping",\n PONG: "pong"\n };\n }\n});\n\n// src/core/utils/constants/html.ts\nvar Z_INDEX_DEV_INDICATOR, Z_INDEX_ERROR_OVERLAY, BREAKPOINT_SM, BREAKPOINT_MD, BREAKPOINT_LG, BREAKPOINT_XL, PROSE_MAX_WIDTH;\nvar init_html = __esm({\n "src/core/utils/constants/html.ts"() {\n "use strict";\n Z_INDEX_DEV_INDICATOR = 9998;\n Z_INDEX_ERROR_OVERLAY = 9999;\n BREAKPOINT_SM = 640;\n BREAKPOINT_MD = 768;\n BREAKPOINT_LG = 1024;\n BREAKPOINT_XL = 1280;\n PROSE_MAX_WIDTH = "65ch";\n }\n});\n\n// src/core/utils/constants/network.ts\nvar DEFAULT_DEV_SERVER_PORT, DEFAULT_REDIS_PORT, DEFAULT_API_SERVER_PORT, DEFAULT_PREVIEW_SERVER_PORT, DEFAULT_METRICS_PORT, BYTES_PER_KB, BYTES_PER_MB, DEFAULT_IMAGE_THUMBNAIL_SIZE, DEFAULT_IMAGE_SMALL_SIZE, DEFAULT_IMAGE_LARGE_SIZE, RESPONSIVE_IMAGE_WIDTH_XS, RESPONSIVE_IMAGE_WIDTH_SM, RESPONSIVE_IMAGE_WIDTH_MD, RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS, MAX_CHUNK_SIZE_KB, MIN_PORT, MAX_PORT, DEFAULT_SERVER_PORT;\nvar init_network = __esm({\n "src/core/utils/constants/network.ts"() {\n "use strict";\n DEFAULT_DEV_SERVER_PORT = 3e3;\n DEFAULT_REDIS_PORT = 6379;\n DEFAULT_API_SERVER_PORT = 8080;\n DEFAULT_PREVIEW_SERVER_PORT = 5e3;\n DEFAULT_METRICS_PORT = 9e3;\n BYTES_PER_KB = 1024;\n BYTES_PER_MB = 1024 * 1024;\n DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\n DEFAULT_IMAGE_SMALL_SIZE = 512;\n DEFAULT_IMAGE_LARGE_SIZE = 2048;\n RESPONSIVE_IMAGE_WIDTH_XS = 320;\n RESPONSIVE_IMAGE_WIDTH_SM = 640;\n RESPONSIVE_IMAGE_WIDTH_MD = 1024;\n RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG\n ];\n MAX_CHUNK_SIZE_KB = 4096;\n MIN_PORT = 1;\n MAX_PORT = 65535;\n DEFAULT_SERVER_PORT = 8e3;\n }\n});\n\n// src/core/utils/constants/security.ts\nvar MAX_PATH_TRAVERSAL_DEPTH, FORBIDDEN_PATH_PATTERNS, DIRECTORY_TRAVERSAL_PATTERN, ABSOLUTE_PATH_PATTERN, MAX_PATH_LENGTH, DEFAULT_MAX_STRING_LENGTH;\nvar init_security = __esm({\n "src/core/utils/constants/security.ts"() {\n "use strict";\n MAX_PATH_TRAVERSAL_DEPTH = 10;\n FORBIDDEN_PATH_PATTERNS = [\n /\\0/\n // Null bytes\n ];\n DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n MAX_PATH_LENGTH = 4096;\n DEFAULT_MAX_STRING_LENGTH = 1e3;\n }\n});\n\n// src/core/utils/constants/server.ts\nvar DEFAULT_DASHBOARD_PORT, DEV_SERVER_ENDPOINTS;\nvar init_server = __esm({\n "src/core/utils/constants/server.ts"() {\n "use strict";\n DEFAULT_DASHBOARD_PORT = 3002;\n DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n }\n});\n\n// src/core/utils/constants/index.ts\nvar init_constants = __esm({\n "src/core/utils/constants/index.ts"() {\n "use strict";\n init_build();\n init_cache();\n init_cdn();\n init_hash();\n init_hmr();\n init_html();\n init_http();\n init_network();\n init_security();\n init_server();\n }\n});\n\n// deno.json\nvar deno_default;\nvar init_deno = __esm({\n "deno.json"() {\n deno_default = {\n name: "veryfront",\n version: "0.0.6",\n nodeModulesDir: "auto",\n workspace: [\n "./examples/async-worker-redis",\n "./examples/knowledge-base",\n "./examples/form-handling",\n "./examples/middleware-demo",\n "./examples/coding-agent",\n "./examples/durable-workflows"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n };\n }\n});\n\n// src/core/utils/version.ts\nvar VERSION;\nvar init_version = __esm({\n "src/core/utils/version.ts"() {\n "use strict";\n init_deno();\n VERSION = typeof deno_default.version === "string" ? deno_default.version : "0.0.0";\n }\n});\n\n// src/core/utils/paths.ts\nvar PATHS, VERYFRONT_PATHS, FILE_EXTENSIONS;\nvar init_paths = __esm({\n "src/core/utils/paths.ts"() {\n "use strict";\n PATHS = {\n PAGES_DIR: "pages",\n COMPONENTS_DIR: "components",\n PUBLIC_DIR: "public",\n STYLES_DIR: "styles",\n DIST_DIR: "dist",\n CONFIG_FILE: "veryfront.config.js"\n };\n VERYFRONT_PATHS = {\n INTERNAL_PREFIX: "/_veryfront",\n BUILD_DIR: "_veryfront",\n CHUNKS_DIR: "_veryfront/chunks",\n DATA_DIR: "_veryfront/data",\n ASSETS_DIR: "_veryfront/assets",\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n CLIENT_JS: "/_veryfront/client.js",\n ROUTER_JS: "/_veryfront/router.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n FILE_EXTENSIONS = {\n MDX: [".mdx", ".md"],\n SCRIPT: [".tsx", ".ts", ".jsx", ".js"],\n STYLE: [".css", ".scss", ".sass"],\n ALL: [".mdx", ".md", ".tsx", ".ts", ".jsx", ".js", ".css"]\n };\n }\n});\n\n// src/core/utils/hash-utils.ts\nasync function computeHash(content) {\n const encoder = new TextEncoder();\n const data = encoder.encode(content);\n const hashBuffer = await crypto.subtle.digest("SHA-256", data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");\n}\nfunction getContentHash(content) {\n return computeHash(content);\n}\nfunction computeContentHash(content) {\n return computeHash(content);\n}\nfunction computeCodeHash(code) {\n const combined = code.code + (code.css || "") + (code.sourceMap || "");\n return computeHash(combined);\n}\nfunction simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n}\nasync function shortHash(content) {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\nvar init_hash_utils = __esm({\n "src/core/utils/hash-utils.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/memoize.ts\nfunction memoizeAsync(fn, keyHasher) {\n const cache = new MemoCache();\n return async (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction memoize(fn, keyHasher) {\n const cache = new MemoCache();\n return (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction simpleHash2(...values) {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n let hash = FNV_OFFSET_BASIS;\n for (const value of values) {\n const str = typeof value === "string" ? value : String(value);\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n return (hash >>> 0).toString(36);\n}\nvar MemoCache;\nvar init_memoize = __esm({\n "src/core/utils/memoize.ts"() {\n "use strict";\n MemoCache = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n return this.cache.get(key);\n }\n set(key, value) {\n this.cache.set(key, value);\n }\n has(key) {\n return this.cache.has(key);\n }\n clear() {\n this.cache.clear();\n }\n size() {\n return this.cache.size;\n }\n };\n }\n});\n\n// src/core/utils/path-utils.ts\nfunction normalizePath(pathname) {\n pathname = pathname.replace(/\\\\+/g, "/").replace(/\\/\\.+\\//g, "/");\n if (pathname !== "/" && pathname.endsWith("/")) {\n pathname = pathname.slice(0, -1);\n }\n return pathname;\n}\nfunction joinPath(a, b) {\n return `${a.replace(/\\/$/, "")}/${b.replace(/^\\//, "")}`;\n}\nfunction isWithinDirectory(root, target) {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\nfunction getExtension(path) {\n const lastDot = path.lastIndexOf(".");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return "";\n }\n return path.slice(lastDot);\n}\nfunction getDirectory(path) {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf("/");\n return lastSlash <= 0 ? "/" : normalized.slice(0, lastSlash);\n}\nfunction hasHashedFilename(path) {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\nfunction isAbsolutePath(path) {\n return path.startsWith("/") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\nfunction toBase64Url(s) {\n const b64 = btoa(s);\n return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");\n}\nfunction fromBase64Url(encoded) {\n const b64 = encoded.replaceAll("-", "+").replaceAll("_", "/");\n const pad = b64.length % 4 === 2 ? "==" : b64.length % 4 === 3 ? "=" : "";\n try {\n return atob(b64 + pad);\n } catch (error2) {\n logger.debug(`Failed to decode base64url string "${encoded}":`, error2);\n return "";\n }\n}\nvar init_path_utils = __esm({\n "src/core/utils/path-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/format-utils.ts\nfunction formatBytes(bytes) {\n if (bytes === 0)\n return "0 Bytes";\n const absBytes = Math.abs(bytes);\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\n const k = 1024;\n const sizes = ["Bytes", "KB", "MB", "GB", "TB"];\n const i = Math.floor(Math.log(absBytes) / Math.log(k));\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\nfunction estimateSize(value) {\n if (value === null || value === void 0)\n return 8;\n switch (typeof value) {\n case "boolean":\n return 4;\n case "number":\n return 8;\n case "string":\n return value.length * 2;\n case "function":\n return 0;\n case "object":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\nfunction estimateSizeWithCircularHandling(value) {\n const seen = /* @__PURE__ */ new WeakSet();\n const encoder = new TextEncoder();\n const json3 = JSON.stringify(value, (_key, val) => {\n if (typeof val === "object" && val !== null) {\n if (seen.has(val))\n return void 0;\n seen.add(val);\n if (val instanceof Map) {\n return { __type: "Map", entries: Array.from(val.entries()) };\n }\n if (val instanceof Set) {\n return { __type: "Set", values: Array.from(val.values()) };\n }\n }\n if (typeof val === "function")\n return void 0;\n if (val instanceof Uint8Array) {\n return { __type: "Uint8Array", length: val.length };\n }\n return val;\n });\n return encoder.encode(json3 ?? "").length;\n}\nfunction estimateObjectSize(value) {\n if (value instanceof ArrayBuffer)\n return value.byteLength;\n if (value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array) {\n return value.byteLength;\n }\n try {\n return JSON.stringify(value).length * 2;\n } catch (error2) {\n logger.debug("Failed to estimate size of non-serializable object:", error2);\n return 1024;\n }\n}\nfunction formatDuration(ms) {\n if (ms < 1e3)\n return `${ms}ms`;\n if (ms < 6e4)\n return `${(ms / 1e3).toFixed(1)}s`;\n if (ms < 36e5)\n return `${Math.floor(ms / 6e4)}m ${Math.floor(ms % 6e4 / 1e3)}s`;\n return `${Math.floor(ms / 36e5)}h ${Math.floor(ms % 36e5 / 6e4)}m`;\n}\nfunction formatNumber(num) {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",");\n}\nfunction truncateString(str, maxLength) {\n if (str.length <= maxLength)\n return str;\n return str.slice(0, maxLength - 3) + "...";\n}\nvar init_format_utils = __esm({\n "src/core/utils/format-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/bundle-manifest.ts\nfunction setBundleManifestStore(store) {\n manifestStore = store;\n serverLogger.info("[bundle-manifest] Bundle manifest store configured", {\n type: store.constructor.name\n });\n}\nfunction getBundleManifestStore() {\n return manifestStore;\n}\nvar InMemoryBundleManifestStore, manifestStore;\nvar init_bundle_manifest = __esm({\n "src/core/utils/bundle-manifest.ts"() {\n "use strict";\n init_logger2();\n init_hash_utils();\n InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n };\n manifestStore = new InMemoryBundleManifestStore();\n }\n});\n\n// src/core/utils/bundle-manifest-init.ts\nasync function initializeBundleManifest(config, mode, adapter) {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === "production";\n if (!enabled) {\n serverLogger.info("[bundle-manifest] Bundle manifest disabled");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n const envType = adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_TYPE");\n const storeType = manifestConfig?.type || envType || "memory";\n serverLogger.info("[bundle-manifest] Initializing bundle manifest", {\n type: storeType,\n mode\n });\n try {\n let store;\n switch (storeType) {\n case "redis": {\n const { RedisBundleManifestStore } = await import("./bundle-manifest-redis.ts");\n const redisUrl = manifestConfig?.redisUrl || adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_REDIS_URL");\n store = new RedisBundleManifestStore(\n {\n url: redisUrl,\n keyPrefix: manifestConfig?.keyPrefix\n },\n adapter\n );\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] Redis not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] Redis store initialized");\n }\n break;\n }\n case "kv": {\n const { KVBundleManifestStore } = await import("./bundle-manifest-kv.ts");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix\n });\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] KV not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] KV store initialized");\n }\n break;\n }\n case "memory":\n default: {\n store = new InMemoryBundleManifestStore();\n serverLogger.info("[bundle-manifest] In-memory store initialized");\n break;\n }\n }\n setBundleManifestStore(store);\n try {\n const stats = await store.getStats();\n serverLogger.info("[bundle-manifest] Store statistics", stats);\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to get stats", { error: error2 });\n }\n } catch (error2) {\n serverLogger.error("[bundle-manifest] Failed to initialize store, using in-memory fallback", {\n error: error2\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\nfunction getBundleManifestTTL(config, mode) {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n if (mode === "production") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\nasync function warmupBundleManifest(store, keys) {\n serverLogger.info("[bundle-manifest] Warming up cache", { keys: keys.length });\n let loaded = 0;\n let failed = 0;\n for (const key of keys) {\n try {\n const metadata = await store.getBundleMetadata(key);\n if (metadata) {\n await store.getBundleCode(metadata.codeHash);\n loaded++;\n }\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to warm up key", { key, error: error2 });\n failed++;\n }\n }\n serverLogger.info("[bundle-manifest] Cache warmup complete", { loaded, failed });\n}\nvar init_bundle_manifest_init = __esm({\n "src/core/utils/bundle-manifest-init.ts"() {\n "use strict";\n init_logger2();\n init_bundle_manifest();\n init_cache();\n }\n});\n\n// src/core/utils/feature-flags.ts\nfunction isRSCEnabled(config) {\n if (config?.experimental?.rsc !== void 0) {\n return config.experimental.rsc;\n }\n if (typeof Deno !== "undefined" && Deno.env) {\n return Deno.env.get("VERYFRONT_EXPERIMENTAL_RSC") === "1";\n }\n if (typeof process !== "undefined" && process?.env) {\n return process.env.VERYFRONT_EXPERIMENTAL_RSC === "1";\n }\n return false;\n}\nvar init_feature_flags = __esm({\n "src/core/utils/feature-flags.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/platform.ts\nfunction isCompiledBinary() {\n const hasDeno = typeof Deno !== "undefined";\n const hasExecPath = hasDeno && typeof Deno.execPath === "function";\n if (!hasExecPath)\n return false;\n try {\n const execPath = Deno.execPath();\n return execPath.includes("veryfront");\n } catch {\n return false;\n }\n}\nvar init_platform = __esm({\n "src/core/utils/platform.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/index.ts\nvar utils_exports = {};\n__export(utils_exports, {\n ABSOLUTE_PATH_PATTERN: () => ABSOLUTE_PATH_PATTERN,\n BREAKPOINT_LG: () => BREAKPOINT_LG,\n BREAKPOINT_MD: () => BREAKPOINT_MD,\n BREAKPOINT_SM: () => BREAKPOINT_SM,\n BREAKPOINT_XL: () => BREAKPOINT_XL,\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS: () => BUNDLE_CACHE_TTL_DEVELOPMENT_MS,\n BUNDLE_CACHE_TTL_PRODUCTION_MS: () => BUNDLE_CACHE_TTL_PRODUCTION_MS,\n BUNDLE_MANIFEST_DEV_TTL_MS: () => BUNDLE_MANIFEST_DEV_TTL_MS,\n BUNDLE_MANIFEST_PROD_TTL_MS: () => BUNDLE_MANIFEST_PROD_TTL_MS,\n BYTES_PER_KB: () => BYTES_PER_KB,\n BYTES_PER_MB: () => BYTES_PER_MB,\n CACHE_CLEANUP_INTERVAL_MS: () => CACHE_CLEANUP_INTERVAL_MS,\n CLEANUP_INTERVAL_MULTIPLIER: () => CLEANUP_INTERVAL_MULTIPLIER,\n COMPONENT_LOADER_MAX_ENTRIES: () => COMPONENT_LOADER_MAX_ENTRIES,\n COMPONENT_LOADER_TTL_MS: () => COMPONENT_LOADER_TTL_MS,\n DASHBOARD_RECONNECT_DELAY_MS: () => DASHBOARD_RECONNECT_DELAY_MS,\n DATA_FETCHING_MAX_ENTRIES: () => DATA_FETCHING_MAX_ENTRIES,\n DATA_FETCHING_TTL_MS: () => DATA_FETCHING_TTL_MS,\n DEFAULT_ALLOWED_CDN_HOSTS: () => DEFAULT_ALLOWED_CDN_HOSTS,\n DEFAULT_API_SERVER_PORT: () => DEFAULT_API_SERVER_PORT,\n DEFAULT_BUILD_CONCURRENCY: () => DEFAULT_BUILD_CONCURRENCY,\n DEFAULT_DASHBOARD_PORT: () => DEFAULT_DASHBOARD_PORT,\n DEFAULT_DEV_SERVER_PORT: () => DEFAULT_DEV_SERVER_PORT,\n DEFAULT_IMAGE_LARGE_SIZE: () => DEFAULT_IMAGE_LARGE_SIZE,\n DEFAULT_IMAGE_SMALL_SIZE: () => DEFAULT_IMAGE_SMALL_SIZE,\n DEFAULT_IMAGE_THUMBNAIL_SIZE: () => DEFAULT_IMAGE_THUMBNAIL_SIZE,\n DEFAULT_LRU_MAX_ENTRIES: () => DEFAULT_LRU_MAX_ENTRIES,\n DEFAULT_MAX_STRING_LENGTH: () => DEFAULT_MAX_STRING_LENGTH,\n DEFAULT_METRICS_PORT: () => DEFAULT_METRICS_PORT,\n DEFAULT_PREVIEW_SERVER_PORT: () => DEFAULT_PREVIEW_SERVER_PORT,\n DEFAULT_REDIS_PORT: () => DEFAULT_REDIS_PORT,\n DEFAULT_SERVER_PORT: () => DEFAULT_SERVER_PORT,\n DENO_KV_SAFE_SIZE_LIMIT_BYTES: () => DENO_KV_SAFE_SIZE_LIMIT_BYTES,\n DENO_STD_BASE: () => DENO_STD_BASE,\n DENO_STD_VERSION: () => DENO_STD_VERSION,\n DEV_SERVER_ENDPOINTS: () => DEV_SERVER_ENDPOINTS,\n DIRECTORY_TRAVERSAL_PATTERN: () => DIRECTORY_TRAVERSAL_PATTERN,\n ESM_CDN_BASE: () => ESM_CDN_BASE,\n FILE_EXTENSIONS: () => FILE_EXTENSIONS,\n FORBIDDEN_PATH_PATTERNS: () => FORBIDDEN_PATH_PATTERNS,\n HASH_SEED_DJB2: () => HASH_SEED_DJB2,\n HASH_SEED_FNV1A: () => HASH_SEED_FNV1A,\n HMR_CLIENT_RELOAD_DELAY_MS: () => HMR_CLIENT_RELOAD_DELAY_MS,\n HMR_CLOSE_MESSAGE_TOO_LARGE: () => HMR_CLOSE_MESSAGE_TOO_LARGE,\n HMR_CLOSE_NORMAL: () => HMR_CLOSE_NORMAL,\n HMR_CLOSE_RATE_LIMIT: () => HMR_CLOSE_RATE_LIMIT,\n HMR_FILE_WATCHER_DEBOUNCE_MS: () => HMR_FILE_WATCHER_DEBOUNCE_MS,\n HMR_KEEP_ALIVE_INTERVAL_MS: () => HMR_KEEP_ALIVE_INTERVAL_MS,\n HMR_MAX_MESSAGES_PER_MINUTE: () => HMR_MAX_MESSAGES_PER_MINUTE,\n HMR_MAX_MESSAGE_SIZE_BYTES: () => HMR_MAX_MESSAGE_SIZE_BYTES,\n HMR_MESSAGE_TYPES: () => HMR_MESSAGE_TYPES,\n HMR_PORT_OFFSET: () => HMR_PORT_OFFSET,\n HMR_RATE_LIMIT_WINDOW_MS: () => HMR_RATE_LIMIT_WINDOW_MS,\n HMR_RECONNECT_DELAY_MS: () => HMR_RECONNECT_DELAY_MS,\n HMR_RELOAD_DELAY_MS: () => HMR_RELOAD_DELAY_MS,\n HOURS_PER_DAY: () => HOURS_PER_DAY,\n HTTP_BAD_GATEWAY: () => HTTP_BAD_GATEWAY,\n HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,\n HTTP_CACHE_LONG_MAX_AGE_SEC: () => HTTP_CACHE_LONG_MAX_AGE_SEC,\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC: () => HTTP_CACHE_MEDIUM_MAX_AGE_SEC,\n HTTP_CACHE_SHORT_MAX_AGE_SEC: () => HTTP_CACHE_SHORT_MAX_AGE_SEC,\n HTTP_CONTENT_TYPES: () => HTTP_CONTENT_TYPES,\n HTTP_CONTENT_TYPE_IMAGE_AVIF: () => HTTP_CONTENT_TYPE_IMAGE_AVIF,\n HTTP_CONTENT_TYPE_IMAGE_GIF: () => HTTP_CONTENT_TYPE_IMAGE_GIF,\n HTTP_CONTENT_TYPE_IMAGE_ICO: () => HTTP_CONTENT_TYPE_IMAGE_ICO,\n HTTP_CONTENT_TYPE_IMAGE_JPEG: () => HTTP_CONTENT_TYPE_IMAGE_JPEG,\n HTTP_CONTENT_TYPE_IMAGE_PNG: () => HTTP_CONTENT_TYPE_IMAGE_PNG,\n HTTP_CONTENT_TYPE_IMAGE_SVG: () => HTTP_CONTENT_TYPE_IMAGE_SVG,\n HTTP_CONTENT_TYPE_IMAGE_WEBP: () => HTTP_CONTENT_TYPE_IMAGE_WEBP,\n HTTP_CREATED: () => HTTP_CREATED,\n HTTP_FORBIDDEN: () => HTTP_FORBIDDEN,\n HTTP_GONE: () => HTTP_GONE,\n HTTP_INTERNAL_SERVER_ERROR: () => HTTP_INTERNAL_SERVER_ERROR,\n HTTP_METHOD_NOT_ALLOWED: () => HTTP_METHOD_NOT_ALLOWED,\n HTTP_MODULE_FETCH_TIMEOUT_MS: () => HTTP_MODULE_FETCH_TIMEOUT_MS,\n HTTP_NETWORK_CONNECT_TIMEOUT: () => HTTP_NETWORK_CONNECT_TIMEOUT,\n HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,\n HTTP_NOT_IMPLEMENTED: () => HTTP_NOT_IMPLEMENTED,\n HTTP_NOT_MODIFIED: () => HTTP_NOT_MODIFIED,\n HTTP_NO_CONTENT: () => HTTP_NO_CONTENT,\n HTTP_OK: () => HTTP_OK,\n HTTP_PAYLOAD_TOO_LARGE: () => HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REDIRECT_FOUND: () => HTTP_REDIRECT_FOUND,\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: () => HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,\n HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,\n HTTP_STATUS_CLIENT_ERROR_MIN: () => HTTP_STATUS_CLIENT_ERROR_MIN,\n HTTP_STATUS_REDIRECT_MIN: () => HTTP_STATUS_REDIRECT_MIN,\n HTTP_STATUS_SERVER_ERROR_MIN: () => HTTP_STATUS_SERVER_ERROR_MIN,\n HTTP_STATUS_SUCCESS_MIN: () => HTTP_STATUS_SUCCESS_MIN,\n HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,\n HTTP_UNAVAILABLE: () => HTTP_UNAVAILABLE,\n HTTP_URI_TOO_LONG: () => HTTP_URI_TOO_LONG,\n IMAGE_OPTIMIZATION: () => IMAGE_OPTIMIZATION,\n InMemoryBundleManifestStore: () => InMemoryBundleManifestStore,\n JSDELIVR_CDN_BASE: () => JSDELIVR_CDN_BASE,\n KB_IN_BYTES: () => KB_IN_BYTES,\n LRU_DEFAULT_MAX_ENTRIES: () => LRU_DEFAULT_MAX_ENTRIES,\n LRU_DEFAULT_MAX_SIZE_BYTES: () => LRU_DEFAULT_MAX_SIZE_BYTES,\n LogLevel: () => LogLevel,\n MAX_CHUNK_SIZE_KB: () => MAX_CHUNK_SIZE_KB,\n MAX_PATH_LENGTH: () => MAX_PATH_LENGTH,\n MAX_PATH_TRAVERSAL_DEPTH: () => MAX_PATH_TRAVERSAL_DEPTH,\n MAX_PORT: () => MAX_PORT,\n MDX_CACHE_TTL_DEVELOPMENT_MS: () => MDX_CACHE_TTL_DEVELOPMENT_MS,\n MDX_CACHE_TTL_PRODUCTION_MS: () => MDX_CACHE_TTL_PRODUCTION_MS,\n MDX_RENDERER_MAX_ENTRIES: () => MDX_RENDERER_MAX_ENTRIES,\n MDX_RENDERER_TTL_MS: () => MDX_RENDERER_TTL_MS,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MIN_PORT: () => MIN_PORT,\n MS_PER_MINUTE: () => MS_PER_MINUTE,\n MS_PER_SECOND: () => MS_PER_SECOND,\n MemoCache: () => MemoCache,\n ONE_DAY_MS: () => ONE_DAY_MS,\n PATHS: () => PATHS,\n PREFETCH_DEFAULT_DELAY_MS: () => PREFETCH_DEFAULT_DELAY_MS,\n PREFETCH_DEFAULT_TIMEOUT_MS: () => PREFETCH_DEFAULT_TIMEOUT_MS,\n PREFETCH_MAX_SIZE_BYTES: () => PREFETCH_MAX_SIZE_BYTES,\n PROSE_MAX_WIDTH: () => PROSE_MAX_WIDTH,\n REACT_DEFAULT_VERSION: () => REACT_DEFAULT_VERSION,\n REACT_VERSION_17: () => REACT_VERSION_17,\n REACT_VERSION_18_2: () => REACT_VERSION_18_2,\n REACT_VERSION_18_3: () => REACT_VERSION_18_3,\n REACT_VERSION_19: () => REACT_VERSION_19,\n REACT_VERSION_19_RC: () => REACT_VERSION_19_RC,\n RENDERER_CORE_MAX_ENTRIES: () => RENDERER_CORE_MAX_ENTRIES,\n RENDERER_CORE_TTL_MS: () => RENDERER_CORE_TTL_MS,\n RESPONSIVE_IMAGE_WIDTHS: () => RESPONSIVE_IMAGE_WIDTHS,\n RESPONSIVE_IMAGE_WIDTH_LG: () => RESPONSIVE_IMAGE_WIDTH_LG,\n RESPONSIVE_IMAGE_WIDTH_MD: () => RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_SM: () => RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_XS: () => RESPONSIVE_IMAGE_WIDTH_XS,\n RSC_MANIFEST_CACHE_TTL_MS: () => RSC_MANIFEST_CACHE_TTL_MS,\n SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,\n SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,\n TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,\n TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,\n UNOCSS_VERSION: () => UNOCSS_VERSION,\n VERSION: () => VERSION,\n VERYFRONT_PATHS: () => VERYFRONT_PATHS,\n Z_INDEX_DEV_INDICATOR: () => Z_INDEX_DEV_INDICATOR,\n Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,\n __loggerResetForTests: () => __loggerResetForTests,\n agentLogger: () => agentLogger,\n bundlerLogger: () => bundlerLogger,\n cliLogger: () => cliLogger,\n computeCodeHash: () => computeCodeHash,\n computeContentHash: () => computeContentHash,\n computeHash: () => computeHash,\n estimateSize: () => estimateSize,\n estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,\n formatBytes: () => formatBytes,\n formatDuration: () => formatDuration,\n formatNumber: () => formatNumber,\n fromBase64Url: () => fromBase64Url,\n getBundleManifestStore: () => getBundleManifestStore,\n getBundleManifestTTL: () => getBundleManifestTTL,\n getContentHash: () => getContentHash,\n getDenoStdNodeBase: () => getDenoStdNodeBase,\n getDirectory: () => getDirectory,\n getEnvironmentVariable: () => getEnvironmentVariable,\n getExtension: () => getExtension,\n getReactCDNUrl: () => getReactCDNUrl,\n getReactDOMCDNUrl: () => getReactDOMCDNUrl,\n getReactDOMClientCDNUrl: () => getReactDOMClientCDNUrl,\n getReactDOMServerCDNUrl: () => getReactDOMServerCDNUrl,\n getReactImportMap: () => getReactImportMap,\n getReactJSXDevRuntimeCDNUrl: () => getReactJSXDevRuntimeCDNUrl,\n getReactJSXRuntimeCDNUrl: () => getReactJSXRuntimeCDNUrl,\n getUnoCSSTailwindResetUrl: () => getUnoCSSTailwindResetUrl,\n hasBunRuntime: () => hasBunRuntime,\n hasDenoRuntime: () => hasDenoRuntime,\n hasHashedFilename: () => hasHashedFilename,\n hasNodeProcess: () => hasNodeProcess,\n initializeBundleManifest: () => initializeBundleManifest,\n isAbsolutePath: () => isAbsolutePath,\n isCompiledBinary: () => isCompiledBinary,\n isDevelopmentEnvironment: () => isDevelopmentEnvironment,\n isProductionEnvironment: () => isProductionEnvironment,\n isRSCEnabled: () => isRSCEnabled,\n isTestEnvironment: () => isTestEnvironment,\n isValidHMRMessageType: () => isValidHMRMessageType,\n isWithinDirectory: () => isWithinDirectory,\n joinPath: () => joinPath,\n logger: () => logger,\n memoize: () => memoize,\n memoizeAsync: () => memoizeAsync,\n memoizeHash: () => simpleHash2,\n normalizePath: () => normalizePath,\n numericHash: () => simpleHash,\n rendererLogger: () => rendererLogger,\n serverLogger: () => serverLogger,\n setBundleManifestStore: () => setBundleManifestStore,\n shortHash: () => shortHash,\n simpleHash: () => simpleHash,\n toBase64Url: () => toBase64Url,\n truncateString: () => truncateString,\n warmupBundleManifest: () => warmupBundleManifest\n});\nvar init_utils = __esm({\n "src/core/utils/index.ts"() {\n init_runtime_guards();\n init_logger2();\n init_constants();\n init_version();\n init_paths();\n init_hash_utils();\n init_memoize();\n init_path_utils();\n init_format_utils();\n init_bundle_manifest();\n init_bundle_manifest_init();\n init_feature_flags();\n init_platform();\n }\n});\n\n// src/core/errors/veryfront-error.ts\nfunction createError(error2) {\n return error2;\n}\nfunction toError(veryfrontError) {\n const error2 = new Error(veryfrontError.message);\n error2.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error2, "context", {\n value: veryfrontError,\n enumerable: false,\n configurable: true\n });\n return error2;\n}\nvar init_veryfront_error = __esm({\n "src/core/errors/veryfront-error.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/schema.ts\nimport { z } from "zod";\nvar corsSchema, veryfrontConfigSchema;\nvar init_schema = __esm({\n "src/core/config/schema.ts"() {\n "use strict";\n init_veryfront_error();\n corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n veryfrontConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n experimental: z.object({\n esmLayouts: z.boolean().optional(),\n precompileMDX: z.boolean().optional()\n }).partial().optional(),\n router: z.enum(["app", "pages"]).optional(),\n defaultLayout: z.string().optional(),\n theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),\n build: z.object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z.object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n cache: z.object({\n dir: z.string().optional(),\n bundleManifest: z.object({\n type: z.enum(["redis", "kv", "memory"]).optional(),\n redisUrl: z.string().optional(),\n keyPrefix: z.string().optional(),\n ttl: z.number().int().positive().optional(),\n enabled: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n dev: z.object({\n port: z.number().int().positive().optional(),\n host: z.string().optional(),\n open: z.boolean().optional(),\n hmr: z.boolean().optional(),\n components: z.array(z.string()).optional()\n }).partial().optional(),\n resolve: z.object({\n importMap: z.object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional()\n }).partial().optional()\n }).partial().optional(),\n security: z.object({\n csp: z.record(z.array(z.string())).optional(),\n remoteHosts: z.array(z.string().url()).optional(),\n cors: corsSchema.optional(),\n coop: z.enum(["same-origin", "same-origin-allow-popups", "unsafe-none"]).optional(),\n corp: z.enum(["same-origin", "same-site", "cross-origin"]).optional(),\n coep: z.enum(["require-corp", "unsafe-none"]).optional()\n }).partial().optional(),\n middleware: z.object({\n custom: z.array(z.function()).optional()\n }).partial().optional(),\n theming: z.object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional()\n }).partial().optional(),\n assetPipeline: z.object({\n images: z.object({\n enabled: z.boolean().optional(),\n formats: z.array(z.enum(["webp", "avif", "jpeg", "png"])).optional(),\n sizes: z.array(z.number().int().positive()).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n preserveOriginal: z.boolean().optional()\n }).partial().optional(),\n css: z.object({\n enabled: z.boolean().optional(),\n minify: z.boolean().optional(),\n autoprefixer: z.boolean().optional(),\n purge: z.boolean().optional(),\n criticalCSS: z.boolean().optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n browsers: z.array(z.string()).optional(),\n purgeContent: z.array(z.string()).optional(),\n sourceMap: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n observability: z.object({\n tracing: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["jaeger", "zipkin", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n serviceName: z.string().optional(),\n sampleRate: z.number().min(0).max(1).optional()\n }).partial().optional(),\n metrics: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["prometheus", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n prefix: z.string().optional(),\n collectInterval: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n fs: z.object({\n type: z.enum(["local", "veryfront-api", "memory"]).optional(),\n local: z.object({\n baseDir: z.string().optional()\n }).partial().optional(),\n veryfront: z.object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z.object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional()\n }).partial().optional(),\n retry: z.object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n memory: z.object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional()\n }).partial().optional()\n }).partial().optional()\n }).partial();\n }\n});\n\n// src/_shims/std-path.ts\nimport * as nodeUrl from "node:url";\nimport * as nodePath from "node:path";\nvar init_std_path = __esm({\n "src/_shims/std-path.ts"() {\n }\n});\n\n// src/core/config/loader.ts\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\nvar DEFAULT_CONFIG;\nvar init_loader = __esm({\n "src/core/config/loader.ts"() {\n "use strict";\n init_schema();\n init_std_path();\n init_logger();\n init_cdn();\n DEFAULT_CONFIG = {\n title: "Veryfront App",\n description: "Built with Veryfront",\n experimental: {\n esmLayouts: true\n },\n router: void 0,\n defaultLayout: void 0,\n theme: {\n colors: {\n primary: "#3B82F6"\n }\n },\n build: {\n outDir: "dist",\n trailingSlash: false,\n esbuild: {\n wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",\n worker: false\n }\n },\n cache: {\n dir: ".veryfront/cache",\n render: {\n type: "memory",\n ttl: void 0,\n maxEntries: 500,\n kvPath: void 0,\n redisUrl: void 0,\n redisKeyPrefix: void 0\n }\n },\n dev: {\n port: 3002,\n host: "localhost",\n open: false\n },\n resolve: {\n importMap: getDefaultImportMapForConfig()\n }\n };\n }\n});\n\n// src/core/config/define-config.ts\nvar init_define_config = __esm({\n "src/core/config/define-config.ts"() {\n "use strict";\n init_veryfront_error();\n }\n});\n\n// src/core/config/defaults.ts\nvar DEFAULT_DEV_PORT, DEFAULT_PREFETCH_DELAY_MS, DURATION_HISTOGRAM_BOUNDARIES_MS, SIZE_HISTOGRAM_BOUNDARIES_KB, PAGE_TRANSITION_DELAY_MS;\nvar init_defaults = __esm({\n "src/core/config/defaults.ts"() {\n "use strict";\n DEFAULT_DEV_PORT = 3e3;\n DEFAULT_PREFETCH_DELAY_MS = 100;\n DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1e3,\n 2500,\n 5e3,\n 7500,\n 1e4\n ];\n SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1e3,\n 2500,\n 5e3,\n 1e4\n ];\n PAGE_TRANSITION_DELAY_MS = 150;\n }\n});\n\n// src/core/config/network-defaults.ts\nvar init_network_defaults = __esm({\n "src/core/config/network-defaults.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/index.ts\nvar init_config = __esm({\n "src/core/config/index.ts"() {\n init_loader();\n init_define_config();\n init_schema();\n init_defaults();\n init_network_defaults();\n }\n});\n\n// src/core/errors/types.ts\nvar VeryfrontError;\nvar init_types = __esm({\n "src/core/errors/types.ts"() {\n "use strict";\n VeryfrontError = class extends Error {\n constructor(message, code, context) {\n super(message);\n this.name = "VeryfrontError";\n this.code = code;\n this.context = context;\n }\n };\n }\n});\n\n// src/core/errors/agent-errors.ts\nvar init_agent_errors = __esm({\n "src/core/errors/agent-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/build-errors.ts\nvar init_build_errors = __esm({\n "src/core/errors/build-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/runtime-errors.ts\nvar init_runtime_errors = __esm({\n "src/core/errors/runtime-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/system-errors.ts\nvar NetworkError;\nvar init_system_errors = __esm({\n "src/core/errors/system-errors.ts"() {\n "use strict";\n init_types();\n NetworkError = class extends VeryfrontError {\n constructor(message, context) {\n super(message, "NETWORK_ERROR" /* NETWORK_ERROR */, context);\n this.name = "NetworkError";\n }\n };\n }\n});\n\n// src/core/errors/error-handlers.ts\nvar init_error_handlers = __esm({\n "src/core/errors/error-handlers.ts"() {\n "use strict";\n init_logger();\n init_types();\n }\n});\n\n// src/core/errors/error-codes.ts\nfunction getErrorDocsUrl(code) {\n return `https://veryfront.com/docs/errors/${code}`;\n}\nvar ErrorCode2;\nvar init_error_codes = __esm({\n "src/core/errors/error-codes.ts"() {\n "use strict";\n ErrorCode2 = {\n CONFIG_NOT_FOUND: "VF001",\n CONFIG_INVALID: "VF002",\n CONFIG_PARSE_ERROR: "VF003",\n CONFIG_VALIDATION_ERROR: "VF004",\n CONFIG_TYPE_ERROR: "VF005",\n IMPORT_MAP_INVALID: "VF006",\n CORS_CONFIG_INVALID: "VF007",\n BUILD_FAILED: "VF100",\n BUNDLE_ERROR: "VF101",\n TYPESCRIPT_ERROR: "VF102",\n MDX_COMPILE_ERROR: "VF103",\n ASSET_OPTIMIZATION_ERROR: "VF104",\n SSG_GENERATION_ERROR: "VF105",\n SOURCEMAP_ERROR: "VF106",\n HYDRATION_MISMATCH: "VF200",\n RENDER_ERROR: "VF201",\n COMPONENT_ERROR: "VF202",\n LAYOUT_NOT_FOUND: "VF203",\n PAGE_NOT_FOUND: "VF204",\n API_ERROR: "VF205",\n MIDDLEWARE_ERROR: "VF206",\n ROUTE_CONFLICT: "VF300",\n INVALID_ROUTE_FILE: "VF301",\n ROUTE_HANDLER_INVALID: "VF302",\n DYNAMIC_ROUTE_ERROR: "VF303",\n ROUTE_PARAMS_ERROR: "VF304",\n API_ROUTE_ERROR: "VF305",\n MODULE_NOT_FOUND: "VF400",\n IMPORT_RESOLUTION_ERROR: "VF401",\n CIRCULAR_DEPENDENCY: "VF402",\n INVALID_IMPORT: "VF403",\n DEPENDENCY_MISSING: "VF404",\n VERSION_MISMATCH: "VF405",\n PORT_IN_USE: "VF500",\n SERVER_START_ERROR: "VF501",\n HMR_ERROR: "VF502",\n CACHE_ERROR: "VF503",\n FILE_WATCH_ERROR: "VF504",\n REQUEST_ERROR: "VF505",\n CLIENT_BOUNDARY_VIOLATION: "VF600",\n SERVER_ONLY_IN_CLIENT: "VF601",\n CLIENT_ONLY_IN_SERVER: "VF602",\n INVALID_USE_CLIENT: "VF603",\n INVALID_USE_SERVER: "VF604",\n RSC_PAYLOAD_ERROR: "VF605",\n DEV_SERVER_ERROR: "VF700",\n FAST_REFRESH_ERROR: "VF701",\n ERROR_OVERLAY_ERROR: "VF702",\n SOURCE_MAP_ERROR: "VF703",\n DEPLOYMENT_ERROR: "VF800",\n PLATFORM_ERROR: "VF801",\n ENV_VAR_MISSING: "VF802",\n PRODUCTION_BUILD_REQUIRED: "VF803",\n UNKNOWN_ERROR: "VF900",\n PERMISSION_DENIED: "VF901",\n FILE_NOT_FOUND: "VF902",\n INVALID_ARGUMENT: "VF903",\n TIMEOUT_ERROR: "VF904"\n };\n }\n});\n\n// src/core/errors/catalog/factory.ts\nfunction createErrorSolution(code, config) {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code)\n };\n}\nfunction createSimpleError(code, title, message, steps) {\n return createErrorSolution(code, { title, message, steps });\n}\nvar init_factory = __esm({\n "src/core/errors/catalog/factory.ts"() {\n "use strict";\n init_error_codes();\n }\n});\n\n// src/core/errors/catalog/config-errors.ts\nvar CONFIG_ERROR_CATALOG;\nvar init_config_errors = __esm({\n "src/core/errors/catalog/config-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n CONFIG_ERROR_CATALOG = {\n [ErrorCode2.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode2.CONFIG_NOT_FOUND, {\n title: "Configuration file not found",\n message: "Veryfront could not find veryfront.config.js in your project root.",\n steps: [\n "Create veryfront.config.js in your project root directory",\n "Run \'veryfront init\' to generate a default configuration",\n "Or copy from an example project"\n ],\n example: `// veryfront.config.js\nexport default {\n title: "My App",\n dev: { port: 3002 }\n}`,\n tips: ["You can use .ts or .mjs extensions too", "Config is optional for simple projects"]\n }),\n [ErrorCode2.CONFIG_INVALID]: createErrorSolution(ErrorCode2.CONFIG_INVALID, {\n title: "Invalid configuration",\n message: "Your configuration file has invalid values or structure.",\n steps: [\n "Check that the config exports a default object",\n "Ensure all values are valid JavaScript types",\n "Remove any trailing commas",\n "Verify property names match the schema"\n ],\n example: `// \\u2713 Valid config\nexport default {\n title: "My App",\n dev: {\n port: 3002,\n open: true\n }\n}`\n }),\n [ErrorCode2.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_PARSE_ERROR,\n "Configuration parse error",\n "Failed to parse your configuration file.",\n [\n "Check for syntax errors (missing brackets, quotes, etc.)",\n "Ensure the file has valid JavaScript/TypeScript syntax",\n "Look for the specific parse error in the output above"\n ]\n ),\n [ErrorCode2.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_VALIDATION_ERROR,\n "Configuration validation failed",\n "Configuration values do not pass validation.",\n [\n "Check that port numbers are between 1-65535",\n "Ensure boolean flags are true/false (not strings)",\n "Verify URLs are properly formatted",\n "Check array/object structures match expected format"\n ]\n ),\n [ErrorCode2.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_TYPE_ERROR,\n "Configuration type error",\n "A configuration value has the wrong type.",\n [\n "Check that numbers are not in quotes",\n \'Ensure booleans are true/false, not "true"/"false"\',\n "Verify arrays use [] brackets",\n "Check objects use {} braces"\n ]\n ),\n [ErrorCode2.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode2.IMPORT_MAP_INVALID, {\n title: "Invalid import map",\n message: "The import map in your configuration is invalid.",\n steps: [\n "Check import map structure: { imports: {}, scopes: {} }",\n "Ensure URLs are valid and accessible",\n "Verify package names are correct"\n ],\n example: `resolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "@/utils": "./src/utils/index.ts"\n }\n }\n}`\n }),\n [ErrorCode2.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode2.CORS_CONFIG_INVALID, {\n title: "Invalid CORS configuration",\n message: "The CORS configuration is invalid.",\n steps: [\n "Use true for default CORS settings",\n "Or provide an object with origin, methods, headers",\n "Ensure origin is a string, not an array"\n ],\n example: `security: {\n cors: true // or { origin: "https://example.com" }\n}`\n })\n };\n }\n});\n\n// src/core/errors/catalog/build-errors.ts\nvar BUILD_ERROR_CATALOG;\nvar init_build_errors2 = __esm({\n "src/core/errors/catalog/build-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n BUILD_ERROR_CATALOG = {\n [ErrorCode2.BUILD_FAILED]: createErrorSolution(ErrorCode2.BUILD_FAILED, {\n title: "Build failed",\n message: "The build process encountered errors.",\n steps: [\n "Check the error messages above for specific issues",\n "Fix any TypeScript or syntax errors",\n "Ensure all imports can be resolved",\n "Run \'veryfront doctor\' to check your environment"\n ],\n tips: ["Try running with --verbose for more details", "Check build logs for warnings"]\n }),\n [ErrorCode2.BUNDLE_ERROR]: createSimpleError(\n ErrorCode2.BUNDLE_ERROR,\n "Bundle generation failed",\n "Failed to generate JavaScript bundles.",\n [\n "Check for circular dependencies",\n "Ensure all imports are valid",\n "Try clearing cache: veryfront clean"\n ]\n ),\n [ErrorCode2.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode2.TYPESCRIPT_ERROR,\n "TypeScript compilation error",\n "TypeScript found errors in your code.",\n [\n "Fix the TypeScript errors shown above",\n "Check your tsconfig.json configuration",\n "Ensure all types are properly imported"\n ]\n ),\n [ErrorCode2.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode2.MDX_COMPILE_ERROR, {\n title: "MDX compilation failed",\n message: "Failed to compile MDX file.",\n steps: [\n "Check for syntax errors in your MDX file",\n "Ensure frontmatter YAML is valid",\n "Verify JSX components are properly imported",\n "Check for unclosed tags or brackets"\n ],\n example: `---\ntitle: My Post\n---\n\nimport Button from \'./components/Button.jsx\'\n\n# Hello World\n\n<Button>Click me</Button>`\n }),\n [ErrorCode2.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode2.ASSET_OPTIMIZATION_ERROR,\n "Asset optimization failed",\n "Failed to optimize assets (images, CSS, etc.).",\n [\n "Check that asset files are valid",\n "Ensure file paths are correct",\n "Try disabling optimization temporarily"\n ]\n ),\n [ErrorCode2.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode2.SSG_GENERATION_ERROR,\n "Static site generation failed",\n "Failed to generate static pages.",\n [\n "Check that all routes are valid",\n "Ensure getStaticData functions return correctly",\n "Verify no dynamic content requires runtime"\n ]\n ),\n [ErrorCode2.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCEMAP_ERROR,\n "Source map generation failed",\n "Failed to generate source maps.",\n [\n "Try disabling source maps temporarily",\n "Check for very large files that might cause issues"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/runtime-errors.ts\nvar RUNTIME_ERROR_CATALOG;\nvar init_runtime_errors2 = __esm({\n "src/core/errors/catalog/runtime-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RUNTIME_ERROR_CATALOG = {\n [ErrorCode2.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode2.HYDRATION_MISMATCH, {\n title: "Hydration mismatch",\n message: "Client-side HTML does not match server-rendered HTML.",\n steps: [\n "Check for random values or timestamps in render",\n "Ensure Date() calls are consistent",\n "Avoid using browser-only APIs during SSR",\n "Check for white space or formatting differences"\n ],\n example: `// \\u274C Wrong - random on each render\n<div>{Math.random()}</div>\n\nconst [random, setRandom] = useState(0)\nuseEffect(() => setRandom(Math.random()), [])\n<div>{random}</div>`,\n relatedErrors: [ErrorCode2.RENDER_ERROR]\n }),\n [ErrorCode2.RENDER_ERROR]: createSimpleError(\n ErrorCode2.RENDER_ERROR,\n "Render error",\n "Failed to render component.",\n [\n "Check the component for errors",\n "Ensure all props are valid",\n "Look for null/undefined access",\n "Check error boundaries"\n ]\n ),\n [ErrorCode2.COMPONENT_ERROR]: createSimpleError(\n ErrorCode2.COMPONENT_ERROR,\n "Component error",\n "Error in component lifecycle or render.",\n [\n "Check component code for errors",\n "Ensure hooks follow Rules of Hooks",\n "Verify props are passed correctly"\n ]\n ),\n [ErrorCode2.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode2.LAYOUT_NOT_FOUND, {\n title: "Layout file not found",\n message: "Required layout file is missing.",\n steps: [\n "Create app/layout.tsx in App Router",\n "Or create layouts/default.mdx for Pages Router",\n "Check file path and name are correct"\n ],\n example: `// app/layout.tsx\nexport default function RootLayout({ children }) {\n return (\n <html lang="en">\n <body>{children}</body>\n </html>\n )\n}`\n }),\n [ErrorCode2.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode2.PAGE_NOT_FOUND,\n "Page not found",\n "The requested page does not exist.",\n [\n "Check that the page file exists",\n "Verify file name matches route",\n "Ensure file extension is correct (.tsx, .jsx, .mdx)"\n ]\n ),\n [ErrorCode2.API_ERROR]: createSimpleError(\n ErrorCode2.API_ERROR,\n "API handler error",\n "Error in API route handler.",\n [\n "Check API handler code for errors",\n "Ensure proper error handling",\n "Verify request/response format"\n ]\n ),\n [ErrorCode2.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode2.MIDDLEWARE_ERROR,\n "Middleware error",\n "Error in middleware execution.",\n [\n "Check middleware code for errors",\n "Ensure middleware returns Response",\n "Verify middleware is properly exported"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/route-errors.ts\nvar ROUTE_ERROR_CATALOG;\nvar init_route_errors = __esm({\n "src/core/errors/catalog/route-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n ROUTE_ERROR_CATALOG = {\n [ErrorCode2.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode2.ROUTE_CONFLICT,\n "Route conflict",\n "Multiple files are trying to handle the same route.",\n [\n "Check for duplicate route files",\n "Remove conflicting routes",\n "Use dynamic routes [id] carefully"\n ]\n ),\n [ErrorCode2.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode2.INVALID_ROUTE_FILE, {\n title: "Invalid route file",\n message: "Route file has invalid structure or exports.",\n steps: [\n "API routes must export GET, POST, etc. functions",\n "Page routes must export default component",\n "Check for syntax errors"\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] })\n}`\n }),\n [ErrorCode2.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode2.ROUTE_HANDLER_INVALID,\n "Invalid route handler",\n "Route handler does not return Response.",\n [\n "Ensure handler returns Response object",\n "Use Response.json() for JSON responses",\n "Check for missing return statement"\n ]\n ),\n [ErrorCode2.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.DYNAMIC_ROUTE_ERROR,\n "Dynamic route error",\n "Error in dynamic route handling.",\n [\n "Check [param] syntax is correct",\n "Ensure params are accessed properly",\n "Verify dynamic segment names"\n ]\n ),\n [ErrorCode2.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode2.ROUTE_PARAMS_ERROR,\n "Route parameters error",\n "Error accessing route parameters.",\n [\n "Check params object structure",\n "Ensure parameter names match route",\n "Verify params are strings"\n ]\n ),\n [ErrorCode2.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.API_ROUTE_ERROR,\n "API route error",\n "Error in API route execution.",\n [\n "Check API handler code",\n "Ensure proper error handling",\n "Verify request parsing"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/module-errors.ts\nvar MODULE_ERROR_CATALOG;\nvar init_module_errors = __esm({\n "src/core/errors/catalog/module-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n MODULE_ERROR_CATALOG = {\n [ErrorCode2.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode2.MODULE_NOT_FOUND, {\n title: "Module not found",\n message: "Cannot find the imported module.",\n steps: [\n "Check that the file path is correct",\n "Ensure the module is installed or exists",\n "Add missing module to import map",\n "Check for typos in import statement"\n ],\n example: `// Add to veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n "missing-lib": "https://esm.sh/missing-lib@1.0.0"\n }\n }\n}`\n }),\n [ErrorCode2.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode2.IMPORT_RESOLUTION_ERROR,\n "Import resolution failed",\n "Failed to resolve import specifier.",\n [\n "Check import paths are correct",\n "Ensure modules are in import map",\n "Verify network connectivity for remote imports"\n ]\n ),\n [ErrorCode2.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode2.CIRCULAR_DEPENDENCY,\n "Circular dependency detected",\n "Files are importing each other in a circle.",\n [\n "Identify the circular import chain",\n "Extract shared code to separate file",\n "Use dependency injection or lazy imports"\n ]\n ),\n [ErrorCode2.INVALID_IMPORT]: createSimpleError(\n ErrorCode2.INVALID_IMPORT,\n "Invalid import statement",\n "Import statement has invalid syntax.",\n [\n \'Check import syntax: import X from "y"\',\n "Ensure quotes are properly closed",\n "Verify export exists in target module"\n ]\n ),\n [ErrorCode2.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode2.DEPENDENCY_MISSING, {\n title: "Required dependency not found",\n message: "A required dependency is missing.",\n steps: [\n "Add React to your import map",\n "Ensure all peer dependencies are included",\n "Run \'veryfront doctor\' to verify setup"\n ],\n example: `// Minimum required imports\nresolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "react-dom": "https://esm.sh/react-dom@19"\n }\n }\n}`\n }),\n [ErrorCode2.VERSION_MISMATCH]: createSimpleError(\n ErrorCode2.VERSION_MISMATCH,\n "Dependency version mismatch",\n "Incompatible versions of dependencies detected.",\n [\n "Ensure React and React-DOM versions match",\n "Check for multiple React instances",\n "Update dependencies to compatible versions"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/server-errors.ts\nvar SERVER_ERROR_CATALOG;\nvar init_server_errors = __esm({\n "src/core/errors/catalog/server-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n SERVER_ERROR_CATALOG = {\n [ErrorCode2.PORT_IN_USE]: createErrorSolution(ErrorCode2.PORT_IN_USE, {\n title: "Port already in use",\n message: "Another process is using the specified port.",\n steps: [\n "Stop the other process: lsof -i :PORT",\n "Use a different port: veryfront dev --port 3003",\n "Add port to config file"\n ],\n example: `// veryfront.config.js\ndev: {\n port: 3003\n}`\n }),\n [ErrorCode2.SERVER_START_ERROR]: createSimpleError(\n ErrorCode2.SERVER_START_ERROR,\n "Server failed to start",\n "Development server could not start.",\n [\n "Check for port conflicts",\n "Ensure file permissions are correct",\n "Verify configuration is valid"\n ]\n ),\n [ErrorCode2.HMR_ERROR]: createSimpleError(\n ErrorCode2.HMR_ERROR,\n "Hot Module Replacement error",\n "HMR failed to update module.",\n [\n "Try refreshing the page",\n "Check for syntax errors",\n "Restart dev server if persistent"\n ]\n ),\n [ErrorCode2.CACHE_ERROR]: createSimpleError(\n ErrorCode2.CACHE_ERROR,\n "Cache operation failed",\n "Error reading or writing cache.",\n [\n "Clear cache: veryfront clean --cache",\n "Check disk space",\n "Verify file permissions"\n ]\n ),\n [ErrorCode2.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode2.FILE_WATCH_ERROR,\n "File watching failed",\n "Could not watch files for changes.",\n [\n "Check system file watch limits",\n "Reduce number of watched files",\n "Try restarting dev server"\n ]\n ),\n [ErrorCode2.REQUEST_ERROR]: createSimpleError(\n ErrorCode2.REQUEST_ERROR,\n "Request handling error",\n "Error processing HTTP request.",\n [\n "Check request format and headers",\n "Verify route handler code",\n "Check for middleware errors"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/rsc-errors.ts\nvar RSC_ERROR_CATALOG;\nvar init_rsc_errors = __esm({\n "src/core/errors/catalog/rsc-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RSC_ERROR_CATALOG = {\n [ErrorCode2.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode2.CLIENT_BOUNDARY_VIOLATION,\n {\n title: "Client/Server boundary violation",\n message: "Server-only code used in Client Component.",\n steps: [\n "Move server-only imports to Server Components",\n "Use \'use server\' for server actions",\n "Split component into server and client parts"\n ],\n example: `// \\u2713 Correct pattern\nimport { db } from \'./database\'\nexport default async function ServerComponent() {\n const data = await db.query(\'...\')\n return <ClientComponent data={data} />\n}\n\n\'use client\'\nexport default function ClientComponent({ data }) {\n return <div>{data}</div>\n}`\n }\n ),\n [ErrorCode2.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode2.SERVER_ONLY_IN_CLIENT,\n "Server-only module in Client Component",\n "Cannot use server-only module in client code.",\n [\n "Move server logic to Server Component",\n "Use API routes for client data fetching",\n "Pass data as props from server"\n ]\n ),\n [ErrorCode2.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode2.CLIENT_ONLY_IN_SERVER,\n "Client-only code in Server Component",\n "Cannot use browser APIs in Server Component.",\n [\n "Add \'use client\' directive",\n "Move client-only code to Client Component",\n "Use useEffect for client-side logic"\n ]\n ),\n [ErrorCode2.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode2.INVALID_USE_CLIENT, {\n title: "Invalid \'use client\' directive",\n message: "\'use client\' directive is not properly placed.",\n steps: [\n "Place \'use client\' at the very top of file",\n "Must be before any imports",\n \'Use exact string: "use client"\'\n ],\n example: `\'use client\' // Must be first line\n\nimport React from \'react\'`\n }),\n [ErrorCode2.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode2.INVALID_USE_SERVER,\n "Invalid \'use server\' directive",\n "\'use server\' directive is not properly placed.",\n [\n "Place \'use server\' at top of function",\n "Or at top of file for all functions",\n \'Use exact string: "use server"\'\n ]\n ),\n [ErrorCode2.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode2.RSC_PAYLOAD_ERROR,\n "RSC payload error",\n "Error serializing Server Component payload.",\n [\n "Ensure props are JSON-serializable",\n "Avoid passing functions as props",\n "Check for circular references"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/dev-errors.ts\nvar DEV_ERROR_CATALOG;\nvar init_dev_errors = __esm({\n "src/core/errors/catalog/dev-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEV_ERROR_CATALOG = {\n [ErrorCode2.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode2.DEV_SERVER_ERROR,\n "Development server error",\n "Error in development server.",\n [\n "Check server logs for details",\n "Try restarting dev server",\n "Clear cache and restart"\n ]\n ),\n [ErrorCode2.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode2.FAST_REFRESH_ERROR,\n "Fast Refresh error",\n "React Fast Refresh failed.",\n [\n "Check for syntax errors",\n "Ensure components follow Fast Refresh rules",\n "Try full page refresh"\n ]\n ),\n [ErrorCode2.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode2.ERROR_OVERLAY_ERROR,\n "Error overlay failed",\n "Could not display error overlay.",\n [\n "Check browser console for details",\n "Try disabling browser extensions",\n "Refresh the page"\n ]\n ),\n [ErrorCode2.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCE_MAP_ERROR,\n "Source map error",\n "Error loading or parsing source map.",\n [\n "Check that source maps are enabled",\n "Try rebuilding the project",\n "Check for corrupted build files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/deployment-errors.ts\nvar DEPLOYMENT_ERROR_CATALOG;\nvar init_deployment_errors = __esm({\n "src/core/errors/catalog/deployment-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEPLOYMENT_ERROR_CATALOG = {\n [ErrorCode2.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode2.DEPLOYMENT_ERROR,\n "Deployment failed",\n "Failed to deploy application.",\n [\n "Check deployment logs for details",\n "Verify platform credentials",\n "Ensure build succeeded first"\n ]\n ),\n [ErrorCode2.PLATFORM_ERROR]: createSimpleError(\n ErrorCode2.PLATFORM_ERROR,\n "Platform error",\n "Deployment platform returned an error.",\n [\n "Check platform status page",\n "Verify API keys and credentials",\n "Try deploying again"\n ]\n ),\n [ErrorCode2.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode2.ENV_VAR_MISSING,\n "Environment variable missing",\n "Required environment variable is not set.",\n [\n "Add variable to .env file",\n "Set variable in deployment platform",\n "Check variable name is correct"\n ]\n ),\n [ErrorCode2.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode2.PRODUCTION_BUILD_REQUIRED,\n "Production build required",\n "Must build project before deploying.",\n [\n "Run \'veryfront build\' first",\n "Check that dist/ directory exists",\n "Verify build completed successfully"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/general-errors.ts\nvar GENERAL_ERROR_CATALOG;\nvar init_general_errors = __esm({\n "src/core/errors/catalog/general-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n GENERAL_ERROR_CATALOG = {\n [ErrorCode2.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode2.UNKNOWN_ERROR,\n "Unknown error",\n "An unexpected error occurred.",\n [\n "Check error details above",\n "Run \'veryfront doctor\' to diagnose",\n "Try restarting the operation",\n "Check GitHub issues for similar problems"\n ]\n ),\n [ErrorCode2.PERMISSION_DENIED]: createSimpleError(\n ErrorCode2.PERMISSION_DENIED,\n "Permission denied",\n "Insufficient permissions to perform operation.",\n [\n "Check file/directory permissions",\n "Run with appropriate permissions",\n "Verify user has write access"\n ]\n ),\n [ErrorCode2.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode2.FILE_NOT_FOUND,\n "File not found",\n "Required file does not exist.",\n [\n "Check that file path is correct",\n "Verify file exists in project",\n "Check for typos in file name"\n ]\n ),\n [ErrorCode2.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode2.INVALID_ARGUMENT,\n "Invalid argument",\n "Command received invalid argument.",\n [\n "Check command syntax",\n "Verify argument values",\n "Run \'veryfront help <command>\' for usage"\n ]\n ),\n [ErrorCode2.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode2.TIMEOUT_ERROR,\n "Operation timed out",\n "Operation took too long to complete.",\n [\n "Check network connectivity",\n "Try increasing timeout if available",\n "Check for very large files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/index.ts\nvar ERROR_CATALOG;\nvar init_catalog = __esm({\n "src/core/errors/catalog/index.ts"() {\n "use strict";\n init_config_errors();\n init_build_errors2();\n init_runtime_errors2();\n init_route_errors();\n init_module_errors();\n init_server_errors();\n init_rsc_errors();\n init_dev_errors();\n init_deployment_errors();\n init_general_errors();\n init_factory();\n ERROR_CATALOG = {\n ...CONFIG_ERROR_CATALOG,\n ...BUILD_ERROR_CATALOG,\n ...RUNTIME_ERROR_CATALOG,\n ...ROUTE_ERROR_CATALOG,\n ...MODULE_ERROR_CATALOG,\n ...SERVER_ERROR_CATALOG,\n ...RSC_ERROR_CATALOG,\n ...DEV_ERROR_CATALOG,\n ...DEPLOYMENT_ERROR_CATALOG,\n ...GENERAL_ERROR_CATALOG\n };\n }\n});\n\n// src/core/errors/user-friendly/error-catalog.ts\nvar init_error_catalog = __esm({\n "src/core/errors/user-friendly/error-catalog.ts"() {\n "use strict";\n }\n});\n\n// src/platform/compat/runtime.ts\nvar isDeno, isNode, isBun, isCloudflare;\nvar init_runtime = __esm({\n "src/platform/compat/runtime.ts"() {\n "use strict";\n isDeno = typeof Deno !== "undefined";\n isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\n isBun = typeof globalThis.Bun !== "undefined";\n isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n }\n});\n\n// src/platform/compat/console/ansi.ts\nvar ansi, red, green, yellow, blue, magenta, cyan, white, gray, bold, dim, italic, underline, strikethrough, reset;\nvar init_ansi = __esm({\n "src/platform/compat/console/ansi.ts"() {\n ansi = (open, close) => (text2) => `\\x1B[${open}m${text2}\\x1B[${close}m`;\n red = ansi(31, 39);\n green = ansi(32, 39);\n yellow = ansi(33, 39);\n blue = ansi(34, 39);\n magenta = ansi(35, 39);\n cyan = ansi(36, 39);\n white = ansi(37, 39);\n gray = ansi(90, 39);\n bold = ansi(1, 22);\n dim = ansi(2, 22);\n italic = ansi(3, 23);\n underline = ansi(4, 24);\n strikethrough = ansi(9, 29);\n reset = (text2) => `\\x1B[0m${text2}`;\n }\n});\n\n// src/platform/compat/console/deno.ts\nvar deno_exports = {};\n__export(deno_exports, {\n blue: () => blue,\n bold: () => bold,\n colors: () => colors,\n cyan: () => cyan,\n dim: () => dim,\n gray: () => gray,\n green: () => green,\n italic: () => italic,\n magenta: () => magenta,\n red: () => red,\n reset: () => reset,\n strikethrough: () => strikethrough,\n underline: () => underline,\n white: () => white,\n yellow: () => yellow\n});\nvar colors;\nvar init_deno2 = __esm({\n "src/platform/compat/console/deno.ts"() {\n "use strict";\n init_ansi();\n colors = {\n red,\n green,\n yellow,\n blue,\n cyan,\n magenta,\n white,\n gray,\n bold,\n dim,\n italic,\n underline,\n strikethrough,\n reset\n };\n }\n});\n\n// src/platform/compat/console/node.ts\nvar node_exports = {};\n__export(node_exports, {\n blue: () => blue2,\n bold: () => bold2,\n colors: () => colors2,\n cyan: () => cyan2,\n dim: () => dim2,\n gray: () => gray2,\n green: () => green2,\n italic: () => italic2,\n magenta: () => magenta2,\n red: () => red2,\n reset: () => reset2,\n strikethrough: () => strikethrough2,\n underline: () => underline2,\n white: () => white2,\n yellow: () => yellow2\n});\nimport pc from "npm:picocolors";\nvar colors2, red2, green2, yellow2, blue2, cyan2, magenta2, white2, gray2, bold2, dim2, italic2, underline2, strikethrough2, reset2;\nvar init_node = __esm({\n "src/platform/compat/console/node.ts"() {\n "use strict";\n colors2 = {\n red: pc.red,\n green: pc.green,\n yellow: pc.yellow,\n blue: pc.blue,\n cyan: pc.cyan,\n magenta: pc.magenta,\n white: pc.white,\n gray: pc.gray,\n bold: pc.bold,\n dim: pc.dim,\n italic: pc.italic,\n underline: pc.underline,\n strikethrough: pc.strikethrough,\n reset: (text2) => pc.reset(text2)\n };\n red2 = pc.red;\n green2 = pc.green;\n yellow2 = pc.yellow;\n blue2 = pc.blue;\n cyan2 = pc.cyan;\n magenta2 = pc.magenta;\n white2 = pc.white;\n gray2 = pc.gray;\n bold2 = pc.bold;\n dim2 = pc.dim;\n italic2 = pc.italic;\n underline2 = pc.underline;\n strikethrough2 = pc.strikethrough;\n reset2 = (text2) => pc.reset(text2);\n }\n});\n\n// src/platform/compat/console/index.ts\nasync function loadColors() {\n if (_colors)\n return _colors;\n try {\n if (isDeno) {\n const mod = await Promise.resolve().then(() => (init_deno2(), deno_exports));\n _colors = mod.colors;\n } else {\n const mod = await Promise.resolve().then(() => (init_node(), node_exports));\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n return _colors;\n}\nvar noOp, fallbackColors, _colors, colorsPromise;\nvar init_console = __esm({\n "src/platform/compat/console/index.ts"() {\n init_runtime();\n noOp = (text2) => text2;\n fallbackColors = {\n red: noOp,\n green: noOp,\n yellow: noOp,\n blue: noOp,\n cyan: noOp,\n magenta: noOp,\n white: noOp,\n gray: noOp,\n bold: noOp,\n dim: noOp,\n italic: noOp,\n underline: noOp,\n strikethrough: noOp,\n reset: noOp\n };\n _colors = null;\n colorsPromise = loadColors();\n }\n});\n\n// src/core/errors/user-friendly/error-identifier.ts\nvar init_error_identifier = __esm({\n "src/core/errors/user-friendly/error-identifier.ts"() {\n "use strict";\n }\n});\n\n// src/core/errors/user-friendly/error-formatter.ts\nvar init_error_formatter = __esm({\n "src/core/errors/user-friendly/error-formatter.ts"() {\n "use strict";\n init_console();\n init_error_catalog();\n init_error_identifier();\n }\n});\n\n// src/platform/compat/process.ts\nimport process2 from "node:process";\nvar init_process = __esm({\n "src/platform/compat/process.ts"() {\n init_runtime();\n }\n});\n\n// src/core/errors/user-friendly/error-wrapper.ts\nvar init_error_wrapper = __esm({\n "src/core/errors/user-friendly/error-wrapper.ts"() {\n "use strict";\n init_console();\n init_process();\n init_logger();\n init_error_formatter();\n }\n});\n\n// src/core/errors/user-friendly/index.ts\nvar init_user_friendly = __esm({\n "src/core/errors/user-friendly/index.ts"() {\n "use strict";\n init_error_catalog();\n init_error_formatter();\n init_error_identifier();\n init_error_wrapper();\n }\n});\n\n// src/core/errors/index.ts\nvar init_errors = __esm({\n "src/core/errors/index.ts"() {\n init_types();\n init_agent_errors();\n init_build_errors();\n init_runtime_errors();\n init_system_errors();\n init_error_handlers();\n init_catalog();\n init_user_friendly();\n }\n});\n\n// src/platform/adapters/deno.ts\nvar DenoFileSystemAdapter, DenoEnvironmentAdapter, DenoServerAdapter, DenoShellAdapter, DenoServer, DenoAdapter, denoAdapter;\nvar init_deno3 = __esm({\n "src/platform/adapters/deno.ts"() {\n "use strict";\n init_veryfront_error();\n init_config();\n init_utils();\n DenoFileSystemAdapter = class {\n async readFile(path) {\n return await Deno.readTextFile(path);\n }\n async writeFile(path, content) {\n await Deno.writeTextFile(path, content);\n }\n async exists(path) {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n async *readDir(path) {\n for await (const entry of Deno.readDir(path)) {\n yield {\n name: entry.name,\n isFile: entry.isFile,\n isDirectory: entry.isDirectory,\n isSymlink: entry.isSymlink\n };\n }\n }\n async stat(path) {\n const stat = await Deno.stat(path);\n return {\n size: stat.size,\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n isSymlink: stat.isSymlink,\n mtime: stat.mtime\n };\n }\n async mkdir(path, options) {\n await Deno.mkdir(path, options);\n }\n async remove(path, options) {\n await Deno.remove(path, options);\n }\n async makeTempDir(prefix) {\n return await Deno.makeTempDir({ prefix });\n }\n watch(paths, options) {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n const denoIterator = watcher[Symbol.asyncIterator]();\n const mapEventKind = (kind) => {\n switch (kind) {\n case "create":\n return "create";\n case "modify":\n return "modify";\n case "remove":\n return "delete";\n default:\n return "any";\n }\n };\n const iterator = {\n async next() {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths\n }\n };\n } catch (error2) {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n throw error2;\n }\n },\n async return() {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: void 0 };\n }\n };\n const cleanup = () => {\n if (closed)\n return;\n closed = true;\n try {\n if ("close" in watcher && typeof watcher.close === "function") {\n watcher.close();\n }\n } catch (error2) {\n serverLogger.debug("[Deno] Filesystem watcher cleanup failed", { error: error2 });\n }\n };\n if (signal) {\n signal.addEventListener("abort", cleanup);\n }\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup\n };\n }\n };\n DenoEnvironmentAdapter = class {\n get(key) {\n return Deno.env.get(key);\n }\n set(key, value) {\n Deno.env.set(key, value);\n }\n toObject() {\n return Deno.env.toObject();\n }\n };\n DenoServerAdapter = class {\n upgradeWebSocket(request) {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n };\n DenoShellAdapter = class {\n statSync(path) {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory\n };\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to stat file: ${error2}`\n }));\n }\n }\n readFileSync(path) {\n try {\n return Deno.readTextFileSync(path);\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to read file: ${error2}`\n }));\n }\n }\n };\n DenoServer = class {\n constructor(server, hostname, port, abortController) {\n this.server = server;\n this.hostname = hostname;\n this.port = port;\n this.abortController = abortController;\n }\n async stop() {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n await this.server.shutdown();\n } catch (error2) {\n serverLogger.debug("[Deno] Server shutdown failed", { error: error2 });\n }\n }\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n };\n DenoAdapter = class {\n constructor() {\n this.id = "deno";\n this.name = "deno";\n /** @deprecated Use `id` instead */\n this.platform = "deno";\n this.fs = new DenoFileSystemAdapter();\n this.env = new DenoEnvironmentAdapter();\n this.server = new DenoServerAdapter();\n this.shell = new DenoShellAdapter();\n this.capabilities = {\n typescript: true,\n jsx: true,\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: true,\n // Deno KV available\n writableFs: true\n };\n /** @deprecated Use `capabilities` instead */\n this.features = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true\n };\n }\n serve(handler, options = {}) {\n const { port = DEFAULT_DEV_PORT, hostname = "localhost", onListen } = options;\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n const server = Deno.serve({\n port,\n hostname,\n signal,\n handler: async (request, _info) => {\n try {\n return await handler(request);\n } catch (error2) {\n const { serverLogger: serverLogger2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));\n serverLogger2.error("Request handler error:", error2);\n return new Response("Internal Server Error", { status: 500 });\n }\n },\n onListen: (params) => {\n onListen?.({ hostname: params.hostname, port: params.port });\n }\n });\n const controllerToPass = options.signal ? void 0 : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n };\n denoAdapter = new DenoAdapter();\n }\n});\n\n// src/rendering/client/router.ts\ninit_utils();\nimport ReactDOM from "react-dom/client";\n\n// src/routing/matchers/pattern-route-matcher.ts\ninit_path_utils();\n\n// src/routing/matchers/index.ts\ninit_utils();\n\n// src/routing/slug-mapper/path-candidate-generator.ts\nimport { join } from "https://deno.land/std@0.220.0/path/mod.ts";\n\n// src/routing/client/dom-utils.ts\ninit_utils();\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href)\n return false;\n if (href.startsWith("http") || href.startsWith("mailto:"))\n return false;\n if (href.startsWith("#"))\n return false;\n if (target.getAttribute("target") === "_blank" || target.getAttribute("download")) {\n return false;\n }\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n if (!current || !(current instanceof HTMLAnchorElement)) {\n return null;\n }\n return current;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n const scripts = container.querySelectorAll("script");\n scripts.forEach((oldScript) => {\n const newScript = document.createElement("script");\n Array.from(oldScript.attributes).forEach((attribute) => {\n newScript.setAttribute(attribute.name, attribute.value);\n });\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n });\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (nodes.length > 0) {\n cleanManagedHeadTags();\n }\n nodes.forEach((wrapper) => {\n processHeadWrapper(wrapper);\n wrapper.parentElement?.removeChild(wrapper);\n });\n}\nfunction cleanManagedHeadTags() {\n document.head.querySelectorAll(\'[data-veryfront-managed="1"]\').forEach((element) => element.parentElement?.removeChild(element));\n}\nfunction processHeadWrapper(wrapper) {\n wrapper.childNodes.forEach((node) => {\n if (!(node instanceof Element))\n return;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n return;\n }\n const clone = document.createElement(tagName);\n for (const attribute of Array.from(node.attributes)) {\n clone.setAttribute(attribute.name, attribute.value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n });\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n if (focusElement && focusElement instanceof HTMLElement && "focus" in focusElement) {\n focusElement.focus({ preventScroll: true });\n }\n } catch (error2) {\n rendererLogger.warn("[router] focus management failed", error2);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript)\n return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n rendererLogger.warn("[dom-utils] Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data:", error2);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html3) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html3, "text/html");\n const root = doc.getElementById("root");\n let content = "";\n if (root) {\n content = root.innerHTML || "";\n } else {\n rendererLogger.warn("[dom-utils] No root element found in HTML");\n }\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const content2 = pageDataScript.textContent;\n if (!content2) {\n rendererLogger.warn("[dom-utils] Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(content2);\n }\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data from HTML:", error2);\n }\n }\n return { content, pageData };\n}\n\n// src/routing/client/navigation-handlers.ts\ninit_utils();\ninit_config();\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n this.prefetchQueue = /* @__PURE__ */ new Set();\n this.scrollPositions = /* @__PURE__ */ new Map();\n this.isPopStateNav = false;\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor))\n return;\n const href = anchor.getAttribute("href");\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n const path = globalThis.location.pathname;\n this.isPopStateNav = true;\n callbacks.onNavigate(path);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n const target = event.target;\n if (target.tagName !== "A")\n return;\n const href = target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#"))\n return;\n if (!this.shouldPrefetchOnHover(target))\n return;\n if (!this.prefetchQueue.has(href)) {\n this.prefetchQueue.add(href);\n setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n }, this.prefetchDelay);\n }\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n const isHoverEnabled = Boolean(this.prefetchOptions.hover);\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "true" || isHoverEnabled;\n }\n saveScrollPosition(path) {\n try {\n const scrollY = globalThis.scrollY;\n if (typeof scrollY === "number") {\n this.scrollPositions.set(path, scrollY);\n } else {\n rendererLogger.debug("[router] No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n }\n } catch (error2) {\n rendererLogger.warn("[router] failed to record scroll position", error2);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n rendererLogger.debug(`[router] No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/routing/client/page-loader.ts\ninit_utils();\ninit_errors();\nvar PageLoader = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n }\n async fetchPageData(path) {\n const jsonData = await this.tryFetchJSON(path);\n if (jsonData)\n return jsonData;\n return this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (response.ok) {\n return await response.json();\n }\n } catch (error2) {\n rendererLogger.debug(`[PageLoader] RSC fetch failed for ${path}, falling back to HTML:`, error2);\n }\n return null;\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw new NetworkError(`Failed to fetch ${path}`, {\n status: response.status,\n path\n });\n }\n const html3 = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html3);\n return {\n html: content,\n ...pageData\n };\n }\n async loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n rendererLogger.debug(`Loading ${path} from cache`);\n return cachedData;\n }\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n }\n async prefetch(path) {\n if (this.isCached(path))\n return;\n rendererLogger.debug(`Prefetching ${path}`);\n try {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n } catch (error2) {\n rendererLogger.warn(`Failed to prefetch ${path}`, error2);\n }\n }\n};\n\n// src/routing/client/page-transition.ts\ninit_utils();\ninit_config();\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERNS = [\n { pattern: /<script[^>]*>[\\s\\S]*?<\\/script>/gi, name: "inline script" },\n { pattern: /javascript:/gi, name: "javascript: URL" },\n { pattern: /\\bon\\w+\\s*=/gi, name: "event handler attribute" },\n { pattern: /data:\\s*text\\/html/gi, name: "data: HTML URL" }\n];\nfunction isDevMode() {\n if (typeof globalThis !== "undefined") {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n }\n return false;\n}\nfunction validateTrustedHtml(html3, options = {}) {\n const { strict = false, warn = true } = options;\n for (const { pattern, name } of SUSPICIOUS_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(html3)) {\n const message = `[Security] Suspicious ${name} detected in server HTML`;\n if (warn) {\n console.warn(message);\n }\n if (strict || !isDevMode()) {\n throw new Error(`Potentially unsafe HTML: ${name} detected`);\n }\n }\n }\n return html3;\n}\n\n// src/routing/client/page-transition.ts\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n this.setupViewportPrefetch = setupViewportPrefetch;\n }\n destroy() {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n }\n updatePage(data, isPopState, scrollY) {\n if (data.frontmatter?.title) {\n document.title = data.frontmatter.title;\n }\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (rootElement && (data.html ?? "") !== "") {\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html ?? ""));\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error2) {\n rendererLogger.warn("[router] scroll handling failed", error2);\n }\n }\n showError(error2) {\n const rootElement = document.getElementById("root");\n if (!rootElement)\n return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error2.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.appendChild(heading);\n errorDiv.appendChild(message);\n errorDiv.appendChild(button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) {\n indicator.style.display = loading ? "block" : "none";\n }\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\ninit_utils();\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n this.observer = null;\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis))\n return;\n if (this.observer)\n this.observer.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error2) {\n rendererLogger.debug("[router] setupViewportPrefetch failed", error2);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? entry.target instanceof HTMLAnchorElement : entry.target.tagName === "A";\n if (isAnchor) {\n const href = entry.target.getAttribute("href");\n if (href) {\n this.prefetchCallback(href);\n }\n this.observer?.unobserve(entry.target);\n }\n }\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll?.(\'a[href]:not([target="_blank"])\') ?? document.createDocumentFragment().querySelectorAll("a");\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n anchors.forEach((anchor) => {\n if (this.shouldObserveAnchor(anchor, isViewportEnabled)) {\n this.observer?.observe(anchor);\n }\n });\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href") || "";\n if (!href || href.startsWith("http") || href.startsWith("#") || anchor.getAttribute("download")) {\n return false;\n }\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (this.observer) {\n try {\n this.observer.disconnect();\n } catch (error2) {\n rendererLogger.warn("[router] prefetchObserver.disconnect failed", error2);\n }\n this.observer = null;\n }\n }\n};\n\n// src/routing/api/handler.ts\ninit_utils();\ninit_std_path();\ninit_config();\n\n// src/core/utils/lru-wrapper.ts\ninit_utils();\n\n// src/routing/api/handler.ts\ninit_veryfront_error();\n\n// src/security/http/response/constants.ts\nvar CONTENT_TYPES = {\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n TEXT: "text/plain; charset=utf-8",\n JAVASCRIPT: "application/javascript; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n XML: "application/xml; charset=utf-8"\n};\nvar CACHE_DURATIONS = {\n SHORT: 60,\n MEDIUM: 3600,\n LONG: 31536e3\n};\n\n// src/security/http/cors/validators.ts\ninit_logger();\n\n// src/observability/tracing/manager.ts\ninit_utils();\n\n// src/observability/tracing/config.ts\nvar DEFAULT_CONFIG2 = {\n enabled: false,\n exporter: "console",\n serviceName: "veryfront",\n sampleRate: 1,\n debug: false\n};\nfunction loadConfig(config = {}, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG2, ...config };\n if (adapter?.env) {\n applyEnvFromAdapter(finalConfig, adapter.env);\n } else {\n applyEnvFromDeno(finalConfig);\n }\n return finalConfig;\n}\nfunction applyEnvFromAdapter(config, envAdapter) {\n if (!envAdapter)\n return;\n const otelEnabled = envAdapter.get("OTEL_TRACES_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n const serviceName = envAdapter.get("OTEL_SERVICE_NAME");\n config.enabled = otelEnabled === "true" || veryfrontOtel === "1" || config.enabled;\n if (serviceName)\n config.serviceName = serviceName;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const tracesEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT");\n config.endpoint = otlpEndpoint || tracesEndpoint || config.endpoint;\n const exporterType = envAdapter.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n}\nfunction applyEnvFromDeno(config) {\n try {\n const denoEnv = globalThis.Deno?.env;\n if (!denoEnv)\n return;\n config.enabled = denoEnv.get("OTEL_TRACES_ENABLED") === "true" || denoEnv.get("VERYFRONT_OTEL") === "1" || config.enabled;\n config.serviceName = denoEnv.get("OTEL_SERVICE_NAME") || config.serviceName;\n config.endpoint = denoEnv.get("OTEL_EXPORTER_OTLP_ENDPOINT") || denoEnv.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;\n const exporterType = denoEnv.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n } catch {\n }\n}\nfunction isValidExporter(value) {\n return value === "jaeger" || value === "zipkin" || value === "otlp" || value === "console";\n}\n\n// src/observability/tracing/span-operations.ts\ninit_utils();\nvar SpanOperations = class {\n constructor(api, tracer2) {\n this.api = api;\n this.tracer = tracer2;\n }\n startSpan(name, options = {}) {\n try {\n const spanKind = this.mapSpanKind(options.kind);\n const span = this.tracer.startSpan(name, {\n kind: spanKind,\n attributes: options.attributes || {}\n }, options.parent);\n return span;\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to start span", { name, error: error2 });\n return null;\n }\n }\n endSpan(span, error2) {\n if (!span)\n return;\n try {\n if (error2) {\n span.recordException(error2);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: error2.message\n });\n } else {\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n }\n span.end();\n } catch (err) {\n serverLogger.debug("[tracing] Failed to end span", err);\n }\n }\n setAttributes(span, attributes) {\n if (!span)\n return;\n try {\n span.setAttributes(attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to set span attributes", error2);\n }\n }\n addEvent(span, name, attributes) {\n if (!span)\n return;\n try {\n span.addEvent(name, attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to add span event", error2);\n }\n }\n createChildSpan(parentSpan, name, options = {}) {\n if (!parentSpan)\n return this.startSpan(name, options);\n try {\n const parentContext = this.api.trace.setSpan(this.api.context.active(), parentSpan);\n return this.startSpan(name, { ...options, parent: parentContext });\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to create child span", error2);\n return null;\n }\n }\n mapSpanKind(kind) {\n if (!kind)\n return this.api.SpanKind.INTERNAL;\n const kindMap = {\n "internal": this.api.SpanKind.INTERNAL,\n "server": this.api.SpanKind.SERVER,\n "client": this.api.SpanKind.CLIENT,\n "producer": this.api.SpanKind.PRODUCER,\n "consumer": this.api.SpanKind.CONSUMER\n };\n return kindMap[kind.toLowerCase()] || this.api.SpanKind.INTERNAL;\n }\n};\n\n// src/observability/tracing/context-propagation.ts\ninit_utils();\nvar ContextPropagation = class {\n constructor(api, propagator) {\n this.api = api;\n this.propagator = propagator;\n }\n extractContext(headers) {\n try {\n const carrier = {};\n headers.forEach((value, key) => {\n carrier[key] = value;\n });\n return this.api.propagation.extract(this.api.context.active(), carrier);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to extract context from headers", error2);\n return void 0;\n }\n }\n injectContext(context, headers) {\n try {\n const carrier = {};\n this.api.propagation.inject(context, carrier);\n for (const [key, value] of Object.entries(carrier)) {\n headers.set(key, value);\n }\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to inject context into headers", error2);\n }\n }\n getActiveContext() {\n try {\n return this.api.context.active();\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to get active context", error2);\n return void 0;\n }\n }\n async withActiveSpan(span, fn) {\n if (!span)\n return await fn();\n return await this.api.context.with(\n this.api.trace.setSpan(this.api.context.active(), span),\n fn\n );\n }\n withSpan(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n async withSpanAsync(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = await fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n};\n\n// src/observability/tracing/manager.ts\nvar TracingManager = class {\n constructor() {\n this.state = {\n initialized: false,\n tracer: null,\n api: null,\n propagator: null\n };\n this.spanOps = null;\n this.contextProp = null;\n }\n async initialize(config = {}, adapter) {\n if (this.state.initialized) {\n serverLogger.debug("[tracing] Already initialized");\n return;\n }\n const finalConfig = loadConfig(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[tracing] Tracing disabled");\n this.state.initialized = true;\n return;\n }\n try {\n await this.initializeTracer(finalConfig);\n this.state.initialized = true;\n serverLogger.info("[tracing] OpenTelemetry tracing initialized", {\n exporter: finalConfig.exporter,\n serviceName: finalConfig.serviceName,\n endpoint: finalConfig.endpoint\n });\n } catch (error2) {\n serverLogger.warn("[tracing] Failed to initialize OpenTelemetry tracing", error2);\n this.state.initialized = true;\n }\n }\n async initializeTracer(config) {\n const api = await import("npm:@opentelemetry/api@1");\n this.state.api = api;\n this.state.tracer = api.trace.getTracer(config.serviceName || "veryfront", "0.1.0");\n const { W3CTraceContextPropagator } = await import("npm:@opentelemetry/core@1");\n this.state.propagator = new W3CTraceContextPropagator();\n api.propagation.setGlobalPropagator(this.state.propagator);\n if (this.state.api && this.state.tracer) {\n this.spanOps = new SpanOperations(this.state.api, this.state.tracer);\n }\n if (this.state.api && this.state.propagator) {\n this.contextProp = new ContextPropagation(this.state.api, this.state.propagator);\n }\n }\n isEnabled() {\n return this.state.initialized && this.state.tracer !== null;\n }\n getSpanOperations() {\n return this.spanOps;\n }\n getContextPropagation() {\n return this.contextProp;\n }\n getState() {\n return this.state;\n }\n shutdown() {\n if (!this.state.initialized)\n return;\n try {\n serverLogger.info("[tracing] Tracing shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[tracing] Error during tracing shutdown", error2);\n }\n }\n};\nvar tracingManager = new TracingManager();\n\n// src/observability/metrics/manager.ts\ninit_utils();\n\n// src/observability/metrics/config.ts\nvar DEFAULT_METRICS_COLLECT_INTERVAL_MS2 = 6e4;\nvar DEFAULT_CONFIG3 = {\n enabled: false,\n exporter: "console",\n prefix: "veryfront",\n collectInterval: DEFAULT_METRICS_COLLECT_INTERVAL_MS2,\n debug: false\n};\nfunction loadConfig2(config, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG3, ...config };\n if (adapter?.env) {\n const envAdapter = adapter.env;\n const otelEnabled = envAdapter.get("OTEL_METRICS_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n finalConfig.enabled = otelEnabled === "true" || veryfrontOtel === "1" || finalConfig.enabled;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const metricsEndpoint = envAdapter.get(\n "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"\n );\n finalConfig.endpoint = otlpEndpoint || metricsEndpoint || finalConfig.endpoint;\n const exporterType = envAdapter.get("OTEL_METRICS_EXPORTER");\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n } else {\n try {\n const env = process.env;\n if (env) {\n finalConfig.enabled = env.OTEL_METRICS_ENABLED === "true" || env.VERYFRONT_OTEL === "1" || finalConfig.enabled;\n finalConfig.endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT || env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || finalConfig.endpoint;\n const exporterType = env.OTEL_METRICS_EXPORTER;\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n }\n } catch {\n }\n }\n return finalConfig;\n}\nfunction getMemoryUsage() {\n try {\n if (process?.memoryUsage) {\n return process.memoryUsage();\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// src/observability/instruments/instruments-factory.ts\ninit_utils();\n\n// src/observability/instruments/build-instruments.ts\ninit_config();\nfunction createBuildInstruments(meter, config) {\n const buildDuration = meter.createHistogram(\n `${config.prefix}.build.duration`,\n {\n description: "Build operation duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const bundleSizeHistogram = meter.createHistogram(\n `${config.prefix}.build.bundle.size`,\n {\n description: "Bundle size distribution",\n unit: "kb",\n advice: { explicitBucketBoundaries: SIZE_HISTOGRAM_BOUNDARIES_KB }\n }\n );\n const bundleCounter = meter.createCounter(\n `${config.prefix}.build.bundles`,\n {\n description: "Total number of bundles created",\n unit: "bundles"\n }\n );\n return {\n buildDuration,\n bundleSizeHistogram,\n bundleCounter\n };\n}\n\n// src/observability/instruments/cache-instruments.ts\nfunction createCacheInstruments(meter, config, runtimeState) {\n const cacheGetCounter = meter.createCounter(\n `${config.prefix}.cache.gets`,\n {\n description: "Total number of cache get operations",\n unit: "operations"\n }\n );\n const cacheHitCounter = meter.createCounter(\n `${config.prefix}.cache.hits`,\n {\n description: "Total number of cache hits",\n unit: "hits"\n }\n );\n const cacheMissCounter = meter.createCounter(\n `${config.prefix}.cache.misses`,\n {\n description: "Total number of cache misses",\n unit: "misses"\n }\n );\n const cacheSetCounter = meter.createCounter(\n `${config.prefix}.cache.sets`,\n {\n description: "Total number of cache set operations",\n unit: "operations"\n }\n );\n const cacheInvalidateCounter = meter.createCounter(\n `${config.prefix}.cache.invalidations`,\n {\n description: "Total number of cache invalidations",\n unit: "operations"\n }\n );\n const cacheSizeGauge = meter.createObservableGauge(\n `${config.prefix}.cache.size`,\n {\n description: "Current cache size",\n unit: "entries"\n }\n );\n cacheSizeGauge.addCallback((result) => {\n result.observe(runtimeState.cacheSize);\n });\n return {\n cacheGetCounter,\n cacheHitCounter,\n cacheMissCounter,\n cacheSetCounter,\n cacheInvalidateCounter,\n cacheSizeGauge\n };\n}\n\n// src/observability/instruments/data-instruments.ts\ninit_config();\nfunction createDataInstruments(meter, config) {\n const dataFetchDuration = meter.createHistogram(\n `${config.prefix}.data.fetch.duration`,\n {\n description: "Data fetch duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const dataFetchCounter = meter.createCounter(\n `${config.prefix}.data.fetch.count`,\n {\n description: "Total number of data fetches",\n unit: "fetches"\n }\n );\n const dataFetchErrorCounter = meter.createCounter(\n `${config.prefix}.data.fetch.errors`,\n {\n description: "Data fetch errors",\n unit: "errors"\n }\n );\n return {\n dataFetchDuration,\n dataFetchCounter,\n dataFetchErrorCounter\n };\n}\n\n// src/observability/instruments/http-instruments.ts\ninit_config();\nfunction createHttpInstruments(meter, config) {\n const httpRequestCounter = meter.createCounter(\n `${config.prefix}.http.requests`,\n {\n description: "Total number of HTTP requests",\n unit: "requests"\n }\n );\n const httpRequestDuration = meter.createHistogram(\n `${config.prefix}.http.request.duration`,\n {\n description: "HTTP request duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const httpActiveRequests = meter.createUpDownCounter(\n `${config.prefix}.http.requests.active`,\n {\n description: "Number of active HTTP requests",\n unit: "requests"\n }\n );\n return {\n httpRequestCounter,\n httpRequestDuration,\n httpActiveRequests\n };\n}\n\n// src/observability/instruments/memory-instruments.ts\nfunction createMemoryInstruments(meter, config) {\n const memoryUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.usage`,\n {\n description: "Memory usage",\n unit: "bytes"\n }\n );\n memoryUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.rss);\n }\n });\n const heapUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.heap`,\n {\n description: "Heap memory usage",\n unit: "bytes"\n }\n );\n heapUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.heapUsed);\n }\n });\n return {\n memoryUsageGauge,\n heapUsageGauge\n };\n}\n\n// src/observability/instruments/render-instruments.ts\ninit_config();\nfunction createRenderInstruments(meter, config) {\n const renderDuration = meter.createHistogram(\n `${config.prefix}.render.duration`,\n {\n description: "Page render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const renderCounter = meter.createCounter(\n `${config.prefix}.render.count`,\n {\n description: "Total number of page renders",\n unit: "renders"\n }\n );\n const renderErrorCounter = meter.createCounter(\n `${config.prefix}.render.errors`,\n {\n description: "Total number of render errors",\n unit: "errors"\n }\n );\n return {\n renderDuration,\n renderCounter,\n renderErrorCounter\n };\n}\n\n// src/observability/instruments/rsc-instruments.ts\ninit_config();\nfunction createRscInstruments(meter, config) {\n const rscRenderDuration = meter.createHistogram(\n `${config.prefix}.rsc.render.duration`,\n {\n description: "RSC render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscStreamDuration = meter.createHistogram(\n `${config.prefix}.rsc.stream.duration`,\n {\n description: "RSC stream duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscManifestCounter = meter.createCounter(\n `${config.prefix}.rsc.manifest`,\n {\n description: "RSC manifest requests",\n unit: "requests"\n }\n );\n const rscPageCounter = meter.createCounter(\n `${config.prefix}.rsc.page`,\n {\n description: "RSC page requests",\n unit: "requests"\n }\n );\n const rscStreamCounter = meter.createCounter(\n `${config.prefix}.rsc.stream`,\n {\n description: "RSC stream requests",\n unit: "requests"\n }\n );\n const rscActionCounter = meter.createCounter(\n `${config.prefix}.rsc.action`,\n {\n description: "RSC action requests",\n unit: "requests"\n }\n );\n const rscErrorCounter = meter.createCounter(\n `${config.prefix}.rsc.errors`,\n {\n description: "RSC errors",\n unit: "errors"\n }\n );\n return {\n rscRenderDuration,\n rscStreamDuration,\n rscManifestCounter,\n rscPageCounter,\n rscStreamCounter,\n rscActionCounter,\n rscErrorCounter\n };\n}\n\n// src/observability/instruments/instruments-factory.ts\nasync function initializeInstruments(meter, config, runtimeState) {\n const instruments = {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n try {\n const httpInstruments = createHttpInstruments(meter, config);\n Object.assign(instruments, httpInstruments);\n const cacheInstruments = createCacheInstruments(meter, config, runtimeState);\n Object.assign(instruments, cacheInstruments);\n const renderInstruments = createRenderInstruments(meter, config);\n Object.assign(instruments, renderInstruments);\n const rscInstruments = createRscInstruments(meter, config);\n Object.assign(instruments, rscInstruments);\n const buildInstruments = createBuildInstruments(meter, config);\n Object.assign(instruments, buildInstruments);\n const dataInstruments = createDataInstruments(meter, config);\n Object.assign(instruments, dataInstruments);\n const memoryInstruments = createMemoryInstruments(meter, config);\n Object.assign(instruments, memoryInstruments);\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize metric instruments", error2);\n }\n return instruments;\n}\n\n// src/observability/metrics/recorder.ts\nvar MetricsRecorder = class {\n constructor(instruments, runtimeState) {\n this.instruments = instruments;\n this.runtimeState = runtimeState;\n }\n recordHttpRequest(attributes) {\n this.instruments.httpRequestCounter?.add(1, attributes);\n this.instruments.httpActiveRequests?.add(1, attributes);\n this.runtimeState.activeRequests++;\n }\n recordHttpRequestComplete(durationMs, attributes) {\n this.instruments.httpRequestDuration?.record(durationMs, attributes);\n this.instruments.httpActiveRequests?.add(-1, attributes);\n this.runtimeState.activeRequests--;\n }\n recordCacheGet(hit, attributes) {\n this.instruments.cacheGetCounter?.add(1, attributes);\n if (hit) {\n this.instruments.cacheHitCounter?.add(1, attributes);\n } else {\n this.instruments.cacheMissCounter?.add(1, attributes);\n }\n }\n recordCacheSet(attributes) {\n this.instruments.cacheSetCounter?.add(1, attributes);\n this.runtimeState.cacheSize++;\n }\n recordCacheInvalidate(count, attributes) {\n this.instruments.cacheInvalidateCounter?.add(count, attributes);\n this.runtimeState.cacheSize = Math.max(\n 0,\n this.runtimeState.cacheSize - count\n );\n }\n setCacheSize(size) {\n this.runtimeState.cacheSize = size;\n }\n // Render Metrics\n recordRender(durationMs, attributes) {\n this.instruments.renderDuration?.record(durationMs, attributes);\n this.instruments.renderCounter?.add(1, attributes);\n }\n recordRenderError(attributes) {\n this.instruments.renderErrorCounter?.add(1, attributes);\n }\n // RSC Metrics\n recordRSCRender(durationMs, attributes) {\n this.instruments.rscRenderDuration?.record(durationMs, attributes);\n }\n recordRSCStream(durationMs, attributes) {\n this.instruments.rscStreamDuration?.record(durationMs, attributes);\n }\n recordRSCRequest(type, attributes) {\n switch (type) {\n case "manifest":\n this.instruments.rscManifestCounter?.add(1, attributes);\n break;\n case "page":\n this.instruments.rscPageCounter?.add(1, attributes);\n break;\n case "stream":\n this.instruments.rscStreamCounter?.add(1, attributes);\n break;\n case "action":\n this.instruments.rscActionCounter?.add(1, attributes);\n break;\n }\n }\n recordRSCError(attributes) {\n this.instruments.rscErrorCounter?.add(1, attributes);\n }\n // Build Metrics\n recordBuild(durationMs, attributes) {\n this.instruments.buildDuration?.record(durationMs, attributes);\n }\n recordBundle(sizeKb, attributes) {\n this.instruments.bundleSizeHistogram?.record(sizeKb, attributes);\n this.instruments.bundleCounter?.add(1, attributes);\n }\n // Data Fetching Metrics\n recordDataFetch(durationMs, attributes) {\n this.instruments.dataFetchDuration?.record(durationMs, attributes);\n this.instruments.dataFetchCounter?.add(1, attributes);\n }\n recordDataFetchError(attributes) {\n this.instruments.dataFetchErrorCounter?.add(1, attributes);\n }\n // Security Metrics\n recordCorsRejection(attributes) {\n this.instruments.corsRejectionCounter?.add(1, attributes);\n }\n recordSecurityHeaders(attributes) {\n this.instruments.securityHeadersCounter?.add(1, attributes);\n }\n};\n\n// src/observability/metrics/manager.ts\nvar MetricsManager = class {\n constructor() {\n this.initialized = false;\n this.meter = null;\n this.api = null;\n this.recorder = null;\n this.instruments = this.createEmptyInstruments();\n this.runtimeState = {\n cacheSize: 0,\n activeRequests: 0\n };\n this.recorder = new MetricsRecorder(this.instruments, this.runtimeState);\n }\n createEmptyInstruments() {\n return {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n }\n async initialize(config = {}, adapter) {\n if (this.initialized) {\n serverLogger.debug("[metrics] Already initialized");\n return;\n }\n const finalConfig = loadConfig2(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[metrics] Metrics collection disabled");\n this.initialized = true;\n return;\n }\n try {\n this.api = await import("npm:@opentelemetry/api@1");\n this.meter = this.api.metrics.getMeter(finalConfig.prefix, "0.1.0");\n this.instruments = await initializeInstruments(\n this.meter,\n finalConfig,\n this.runtimeState\n );\n if (this.recorder) {\n this.recorder.instruments = this.instruments;\n }\n this.initialized = true;\n serverLogger.info("[metrics] OpenTelemetry metrics initialized", {\n exporter: finalConfig.exporter,\n endpoint: finalConfig.endpoint,\n prefix: finalConfig.prefix\n });\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize OpenTelemetry metrics", error2);\n this.initialized = true;\n }\n }\n isEnabled() {\n return this.initialized && this.meter !== null;\n }\n getRecorder() {\n return this.recorder;\n }\n getState() {\n return {\n initialized: this.initialized,\n cacheSize: this.runtimeState.cacheSize,\n activeRequests: this.runtimeState.activeRequests\n };\n }\n shutdown() {\n if (!this.initialized)\n return;\n try {\n serverLogger.info("[metrics] Metrics shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[metrics] Error during metrics shutdown", error2);\n }\n }\n};\nvar metricsManager = new MetricsManager();\n\n// src/observability/metrics/index.ts\nvar getRecorder = () => metricsManager.getRecorder();\nfunction recordCorsRejection(attributes) {\n getRecorder()?.recordCorsRejection?.(attributes);\n}\nfunction recordSecurityHeaders(attributes) {\n getRecorder()?.recordSecurityHeaders?.(attributes);\n}\n\n// src/observability/auto-instrument/orchestrator.ts\ninit_utils();\n\n// src/observability/auto-instrument/http-instrumentation.ts\ninit_utils();\nimport {\n context as otContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace\n} from "npm:@opentelemetry/api@1";\nvar tracer = trace.getTracer("veryfront-http");\n\n// src/security/http/cors/validators.ts\nasync function validateOrigin(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = await corsConfig.origin(requestOrigin);\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\nfunction validateOriginSync(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = corsConfig.origin(requestOrigin);\n if (result instanceof Promise) {\n serverLogger.warn(\n "[CORS] Async origin validators are not supported in synchronous contexts"\n );\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Async origin validators not supported"\n };\n }\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist (sync)", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match (sync)", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\n\n// src/security/http/cors/headers.ts\nasync function applyCORSHeaders(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = await validateOrigin(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\nfunction applyCORSHeadersSync(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = validateOriginSync(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\n\n// src/security/http/cors/constants.ts\ninit_config();\n\n// src/security/http/cors/preflight.ts\ninit_logger();\n\n// src/security/http/cors/middleware.ts\ninit_veryfront_error();\n\n// src/security/http/response/security-handler.ts\nfunction generateNonce() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return btoa(String.fromCharCode(...array));\n}\nfunction buildCSP(isDev, nonce, cspUserHeader, config, adapter) {\n const envCsp = adapter?.env?.get?.("VERYFRONT_CSP");\n if (envCsp?.trim())\n return envCsp.replace(/{NONCE}/g, nonce);\n const defaultCsp = isDev ? [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\' \'unsafe-inline\' https://esm.sh https://cdnjs.cloudflare.com https://cdn.veryfront.com https://cdn.jsdelivr.net`,\n "img-src \'self\' data: https://cdn.veryfront.com https://cdnjs.cloudflare.com",\n `script-src \'self\' \'nonce-${nonce}\' \'unsafe-eval\' https://esm.sh https://cdn.tailwindcss.com`,\n "connect-src \'self\' https://esm.sh ws://localhost:* wss://localhost:*",\n "font-src \'self\' data: https://cdnjs.cloudflare.com"\n ].join("; ") : [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\'`,\n "img-src \'self\' data:",\n `script-src \'self\' \'nonce-${nonce}\'`,\n "connect-src \'self\'"\n ].join("; ");\n if (cspUserHeader?.trim()) {\n return `${cspUserHeader.replace(/{NONCE}/g, nonce)}; ${defaultCsp}`;\n }\n const cfgCsp = config?.csp;\n if (cfgCsp && typeof cfgCsp === "object") {\n const pieces = [];\n for (const [k, v] of Object.entries(cfgCsp)) {\n if (v === void 0)\n continue;\n const key = String(k).replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n const val = Array.isArray(v) ? v.join(" ") : String(v);\n pieces.push(`${key} ${val}`.replace(/{NONCE}/g, nonce));\n }\n if (pieces.length > 0) {\n return `${pieces.join("; ")}; ${defaultCsp}`;\n }\n }\n return defaultCsp;\n}\nfunction getSecurityHeader(headerName, defaultValue, config, adapter) {\n const configKey = headerName.toLowerCase();\n const configValue = config?.[configKey];\n const envValue = adapter?.env?.get?.(`VERYFRONT_${headerName}`);\n return (typeof configValue === "string" ? configValue : void 0) || envValue || defaultValue;\n}\nfunction applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter) {\n const getHeaderOverride = (name) => {\n const overrides = config?.headers;\n if (!overrides)\n return void 0;\n const lower = name.toLowerCase();\n for (const [key, value] of Object.entries(overrides)) {\n if (key.toLowerCase() === lower) {\n return value;\n }\n }\n return void 0;\n };\n const contentTypeOptions = getHeaderOverride("x-content-type-options") ?? "nosniff";\n headers.set("X-Content-Type-Options", contentTypeOptions);\n const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";\n headers.set("X-Frame-Options", frameOptions);\n const xssProtection = getHeaderOverride("x-xss-protection") ?? "1; mode=block";\n headers.set("X-XSS-Protection", xssProtection);\n const csp = buildCSP(isDev, nonce, cspUserHeader, config, adapter);\n if (csp) {\n headers.set("Content-Security-Policy", csp);\n }\n if (!isDev) {\n const hstsMaxAge = config?.hsts?.maxAge ?? 31536e3;\n const hstsIncludeSubDomains = config?.hsts?.includeSubDomains ?? true;\n const hstsPreload = config?.hsts?.preload ?? false;\n let hstsValue = `max-age=${hstsMaxAge}`;\n if (hstsIncludeSubDomains) {\n hstsValue += "; includeSubDomains";\n }\n if (hstsPreload) {\n hstsValue += "; preload";\n }\n const hstsOverride = getHeaderOverride("strict-transport-security");\n headers.set("Strict-Transport-Security", hstsOverride ?? hstsValue);\n }\n const coop = getSecurityHeader("COOP", "same-origin", config, adapter);\n const corp = getSecurityHeader("CORP", "same-origin", config, adapter);\n const coep = getSecurityHeader("COEP", "", config, adapter);\n headers.set("Cross-Origin-Opener-Policy", coop);\n headers.set("Cross-Origin-Resource-Policy", corp);\n if (coep) {\n headers.set("Cross-Origin-Embedder-Policy", coep);\n }\n if (config?.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n if (value === void 0)\n continue;\n headers.set(key, value);\n }\n }\n recordSecurityHeaders();\n}\n\n// src/security/http/response/cache-handler.ts\nfunction buildCacheControl(strategy) {\n let cacheControl;\n if (typeof strategy === "string") {\n switch (strategy) {\n case "no-cache":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n case "no-store":\n cacheControl = "no-store";\n break;\n case "short":\n cacheControl = `public, max-age=${CACHE_DURATIONS.SHORT}`;\n break;\n case "medium":\n cacheControl = `public, max-age=${CACHE_DURATIONS.MEDIUM}`;\n break;\n case "long":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}`;\n break;\n case "immutable":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}, immutable`;\n break;\n case "none":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n default:\n cacheControl = "public, max-age=0";\n }\n } else {\n const parts = [];\n parts.push(strategy.public !== false ? "public" : "private");\n parts.push(`max-age=${strategy.maxAge}`);\n if (strategy.immutable)\n parts.push("immutable");\n if (strategy.mustRevalidate)\n parts.push("must-revalidate");\n cacheControl = parts.join(", ");\n }\n return cacheControl;\n}\n\n// src/security/http/response/fluent-methods.ts\nfunction withCORS(req, corsConfig) {\n const config = corsConfig ?? this.securityConfig?.cors;\n applyCORSHeadersSync({\n request: req,\n headers: this.headers,\n config\n });\n return this;\n}\nfunction withCORSAsync(req) {\n return applyCORSHeaders({\n request: req,\n headers: this.headers,\n config: this.securityConfig?.cors\n }).then(() => this);\n}\nfunction withSecurity(config) {\n const cfg = config ?? this.securityConfig;\n applySecurityHeaders(\n this.headers,\n this.isDev,\n this.nonce,\n this.cspUserHeader,\n cfg,\n this.adapter\n );\n return this;\n}\nfunction withCache(strategy) {\n const cacheControl = buildCacheControl(strategy);\n this.headers.set("cache-control", cacheControl);\n return this;\n}\nfunction withETag(etag) {\n this.headers.set("ETag", etag);\n return this;\n}\nfunction withHeaders(headers) {\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n this.headers.set(key, value);\n });\n } else if (Array.isArray(headers)) {\n headers.forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n } else {\n Object.entries(headers).forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n }\n return this;\n}\nfunction withStatus(status) {\n this.status = status;\n return this;\n}\nfunction withAllow(methods) {\n const methodStr = Array.isArray(methods) ? methods.join(", ") : methods;\n this.headers.set("Allow", methodStr);\n this.headers.set("Access-Control-Allow-Methods", methodStr);\n return this;\n}\n\n// src/security/http/response/response-methods.ts\nfunction json(data, status) {\n this.headers.set("content-type", CONTENT_TYPES.JSON);\n return new Response(JSON.stringify(data), {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction text(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.TEXT);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction html(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.HTML);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction javascript(code, status) {\n this.headers.set("content-type", CONTENT_TYPES.JAVASCRIPT);\n return new Response(code, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction withContentType(contentType, body, status) {\n this.headers.set("content-type", contentType);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction build(body = null, status) {\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction notModified(etag) {\n if (etag) {\n this.headers.set("ETag", etag);\n }\n return new Response(null, {\n status: 304,\n headers: this.headers\n });\n}\n\n// src/security/http/response/static-helpers.ts\ninit_veryfront_error();\nvar ResponseBuilderClass = null;\nfunction setResponseBuilderClass(builderClass) {\n ResponseBuilderClass = builderClass;\n}\nfunction error(status, message, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const contentType = config?.contentType ?? CONTENT_TYPES.TEXT;\n if (contentType === CONTENT_TYPES.JSON) {\n return builder.json({ error: message }, status);\n } else if (contentType === CONTENT_TYPES.HTML) {\n return builder.html(message, status);\n }\n return builder.text(message, status);\n}\nfunction json2(data, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.json(data, config?.status);\n}\nfunction html2(body, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.html(body, config?.status);\n}\nfunction preflight(req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const methods = config?.allowMethods ?? "GET,POST,PUT,PATCH,DELETE,OPTIONS";\n builder.withAllow(methods);\n const headers = config?.allowHeaders ?? req.headers.get("access-control-request-headers") ?? "Content-Type,Authorization";\n builder.headers.set(\n "Access-Control-Allow-Headers",\n Array.isArray(headers) ? headers.join(", ") : headers\n );\n return builder.build(null, 204);\n}\nfunction stream(streamData, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n const contentType = config?.contentType ?? "application/octet-stream";\n return builder.withContentType(contentType, streamData);\n}\n\n// src/security/http/response/builder.ts\nvar ResponseBuilder = class {\n constructor(config) {\n this.withCORS = withCORS;\n this.withCORSAsync = withCORSAsync;\n this.withSecurity = withSecurity;\n this.withCache = withCache;\n this.withETag = withETag;\n this.withHeaders = withHeaders;\n this.withStatus = withStatus;\n this.withAllow = withAllow;\n this.json = json;\n this.text = text;\n this.html = html;\n this.javascript = javascript;\n this.withContentType = withContentType;\n this.build = build;\n this.notModified = notModified;\n this.headers = new Headers();\n this.status = 200;\n this.securityConfig = config?.securityConfig ?? null;\n this.isDev = config?.isDev ?? false;\n this.nonce = config?.nonce ?? generateNonce();\n this.cspUserHeader = config?.cspUserHeader ?? null;\n this.adapter = config?.adapter;\n }\n};\nResponseBuilder.error = error;\nResponseBuilder.json = json2;\nResponseBuilder.html = html2;\nResponseBuilder.preflight = preflight;\nResponseBuilder.stream = stream;\nsetResponseBuilderClass(ResponseBuilder);\n\n// src/security/http/base-handler.ts\ninit_utils();\n\n// src/core/constants/index.ts\ninit_constants();\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/core/constants/limits.ts\nvar MAX_URL_LENGTH_FOR_VALIDATION = 2048;\n\n// src/security/input-validation/parsers.ts\nimport { z as z2 } from "zod";\n\n// src/security/input-validation/schemas.ts\nimport { z as z3 } from "zod";\nvar CommonSchemas = {\n /**\n * Valid email address (RFC-compliant, max 255 chars)\n */\n email: z3.string().email().max(255),\n /**\n * Valid UUID v4 identifier\n */\n uuid: z3.string().uuid(),\n /**\n * URL-safe slug (lowercase alphanumeric with hyphens)\n */\n slug: z3.string().regex(/^[a-z0-9-]+$/).min(1).max(100),\n /**\n * Valid HTTP/HTTPS URL (max 2048 chars)\n */\n url: z3.string().url().max(MAX_URL_LENGTH_FOR_VALIDATION),\n /**\n * International phone number (E.164 format)\n */\n phoneNumber: z3.string().regex(/^\\+?[1-9]\\d{1,14}$/),\n /**\n * Pagination parameters with defaults\n */\n pagination: z3.object({\n page: z3.coerce.number().int().positive().default(1),\n limit: z3.coerce.number().int().positive().max(100).default(10),\n sort: z3.string().optional(),\n order: z3.enum(["asc", "desc"]).optional()\n }),\n /**\n * Date range with validation\n */\n dateRange: z3.object({\n from: z3.string().datetime(),\n to: z3.string().datetime()\n }).refine((data) => new Date(data.from) <= new Date(data.to), {\n message: "From date must be before or equal to To date"\n }),\n /**\n * Strong password requirements\n * - Minimum 8 characters\n * - At least one uppercase letter\n * - At least one lowercase letter\n * - At least one number\n * - At least one special character\n */\n strongPassword: z3.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character")\n};\n\n// src/security/http/auth.ts\ninit_veryfront_error();\n\n// src/security/http/config.ts\ninit_config();\ninit_utils();\n\n// src/security/http/middleware/config-loader.ts\ninit_utils();\n\n// src/security/http/middleware/etag.ts\ninit_hash();\n\n// src/security/http/middleware/content-types.ts\ninit_http();\n\n// src/security/path-validation.ts\ninit_utils();\n\n// src/security/secure-fs.ts\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_utils();\ninit_std_path();\n\n// src/routing/api/module-loader/esbuild-plugin.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/http-validator.ts\ninit_veryfront_error();\n\n// src/routing/api/module-loader/security-config.ts\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_veryfront_error();\n\n// src/routing/api/route-discovery.ts\ninit_std_path();\n\n// src/core/utils/file-discovery.ts\ninit_std_path();\ninit_deno3();\n\n// src/routing/api/route-executor.ts\ninit_veryfront_error();\n\n// src/routing/api/method-validator.ts\ninit_utils();\n\n// src/routing/api/error-handler.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/rendering/client/router.ts\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n this.root = null;\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n onNavigate: (url) => this.navigate(url, false),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n rendererLogger.debug("[router] No global options configured");\n return {};\n }\n return options;\n } catch (error2) {\n rendererLogger.error("[router] Failed to read global options:", error2);\n return {};\n }\n }\n init() {\n rendererLogger.info("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n rendererLogger.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM || ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) {\n this.pageLoader.setCache(this.currentPath, pageData);\n }\n }\n async navigate(url, pushState = true) {\n rendererLogger.info(`Navigating to ${url}`);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (pushState) {\n globalThis.history.pushState({}, "", url);\n }\n await this.loadPage(url);\n this.options.onNavigate?.(url);\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n rendererLogger.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (!data) {\n rendererLogger.warn(`[router] Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n } else {\n if (updateUI) {\n this.updatePage(data);\n }\n return;\n }\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) {\n this.updatePage(data);\n }\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error2) {\n rendererLogger.error(`Failed to load ${path}`, error2);\n this.options.onError?.(error2);\n this.pageTransition.showError(error2);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root)\n return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nif (typeof window !== "undefined" && globalThis.document) {\n const router = new VeryfrontRouter();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init());\n } else {\n router.init();\n }\n globalThis.veryFrontRouter = router;\n}\nexport {\n VeryfrontRouter\n};\n';
14088
- CLIENT_PREFETCH_BUNDLE = '// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n this.prefix = prefix;\n this.level = level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug?.(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log?.(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn?.(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error?.(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") {\n return 2 /* WARN */;\n }\n const windowObject = window;\n const isDevelopment = windowObject.__VERYFRONT_DEV__ || windowObject.__RSC_DEV__;\n if (!isDevelopment) {\n return 2 /* WARN */;\n }\n const isDebugEnabled = windowObject.__VERYFRONT_DEBUG__ || windowObject.__RSC_DEBUG__;\n return isDebugEnabled ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/rendering/client/prefetch/link-observer.ts\nvar LinkObserver = class {\n constructor(options, prefetchedUrls) {\n this.intersectionObserver = null;\n this.mutationObserver = null;\n this.pendingTimeouts = /* @__PURE__ */ new Map();\n this.elementTimeoutMap = /* @__PURE__ */ new WeakMap();\n this.timeoutCounter = 0;\n this.options = options;\n this.prefetchedUrls = prefetchedUrls;\n }\n init() {\n this.createIntersectionObserver();\n this.observeLinks();\n this.setupMutationObserver();\n }\n createIntersectionObserver() {\n this.intersectionObserver = new IntersectionObserver(\n (entries) => this.handleIntersection(entries),\n { rootMargin: this.options.rootMargin }\n );\n }\n handleIntersection(entries) {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const target = entry.target;\n let isAnchor = false;\n if (typeof HTMLAnchorElement !== "undefined") {\n isAnchor = target instanceof HTMLAnchorElement;\n } else {\n isAnchor = target.tagName === "A";\n }\n if (!isAnchor) {\n continue;\n }\n const link = target;\n const timeoutKey = this.timeoutCounter++;\n const timeoutId = setTimeout(() => {\n this.pendingTimeouts.delete(timeoutKey);\n this.elementTimeoutMap.delete(link);\n this.options.onLinkVisible(link);\n }, this.options.delay);\n this.pendingTimeouts.set(timeoutKey, timeoutId);\n this.elementTimeoutMap.set(link, timeoutKey);\n }\n }\n }\n observeLinks() {\n const links = document.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n if (this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n setupMutationObserver() {\n this.mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === "childList") {\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.observeElement(node);\n }\n });\n mutation.removedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.clearElementTimeouts(node);\n }\n });\n }\n }\n });\n this.mutationObserver.observe(document.body, {\n childList: true,\n subtree: true\n });\n }\n clearElementTimeouts(element) {\n if (element.tagName === "A") {\n const timeoutKey = this.elementTimeoutMap.get(element);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(element);\n }\n }\n const links = element.querySelectorAll("a");\n links.forEach((link) => {\n const timeoutKey = this.elementTimeoutMap.get(link);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(link);\n }\n });\n }\n observeElement(element) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? element instanceof HTMLAnchorElement : element.tagName === "A";\n if (isAnchor && this.isValidLink(element)) {\n this.intersectionObserver?.observe(element);\n }\n const links = element.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n const isLinkAnchor = typeof HTMLAnchorElement !== "undefined" ? link instanceof HTMLAnchorElement : link.tagName === "A";\n if (isLinkAnchor && this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n isValidLink(link) {\n if (link.hostname !== globalThis.location.hostname)\n return false;\n if (link.hasAttribute("download"))\n return false;\n if (link.target === "_blank")\n return false;\n const url = link.href;\n if (this.prefetchedUrls.has(url))\n return false;\n if (url === globalThis.location.href)\n return false;\n if (link.hash && link.pathname === globalThis.location.pathname) {\n return false;\n }\n if (link.dataset.noPrefetch)\n return false;\n return true;\n }\n destroy() {\n for (const [_, timeoutId] of this.pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n this.pendingTimeouts.clear();\n if (this.intersectionObserver) {\n this.intersectionObserver.disconnect();\n this.intersectionObserver = null;\n }\n if (this.mutationObserver) {\n this.mutationObserver.disconnect();\n this.mutationObserver = null;\n }\n }\n};\n\n// src/rendering/client/prefetch/network-utils.ts\nvar NetworkUtils = class {\n constructor(allowedNetworks = ["4g", "wifi", "ethernet"]) {\n this.allowedNetworks = allowedNetworks;\n this.networkInfo = this.getNetworkConnection();\n }\n getNavigatorWithConnection() {\n if (typeof globalThis.navigator === "undefined") {\n return null;\n }\n return globalThis.navigator;\n }\n getNetworkConnection() {\n const nav = this.getNavigatorWithConnection();\n return nav?.connection || nav?.mozConnection || nav?.webkitConnection || null;\n }\n shouldPrefetch() {\n const nav = this.getNavigatorWithConnection();\n if (nav?.connection?.saveData) {\n return false;\n }\n if (this.networkInfo) {\n const effectiveType = this.networkInfo.effectiveType;\n if (effectiveType !== void 0 && !this.allowedNetworks.includes(effectiveType)) {\n return false;\n }\n }\n return true;\n }\n onNetworkChange(callback) {\n if (this.networkInfo?.addEventListener) {\n this.networkInfo.addEventListener("change", callback);\n }\n }\n getNetworkInfo() {\n return this.networkInfo;\n }\n};\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE = 60;\nvar MINUTES_PER_HOUR = 60;\nvar HOURS_PER_DAY = 24;\nvar MS_PER_SECOND = 1e3;\nvar COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\nvar ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES = 1024;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\nvar PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\nvar PREFETCH_DEFAULT_DELAY_MS = 200;\n\n// src/core/utils/constants/hmr.ts\nvar HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\n// src/core/utils/constants/network.ts\nvar BYTES_PER_MB = 1024 * 1024;\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/rendering/client/prefetch/prefetch-queue.ts\nvar DEFAULT_OPTIONS = {\n maxConcurrent: 4,\n maxSize: PREFETCH_QUEUE_MAX_SIZE_BYTES,\n timeout: 5e3\n};\nfunction isAbortError(error) {\n return Boolean(\n error && typeof error === "object" && "name" in error && error.name === "AbortError"\n );\n}\nvar PrefetchQueue = class {\n constructor(options = {}, prefetchedUrls) {\n this.controllers = /* @__PURE__ */ new Map();\n this.concurrent = 0;\n this.stopped = false;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.prefetchedUrls = prefetchedUrls ?? /* @__PURE__ */ new Set();\n }\n setResourceCallback(callback) {\n this.onResourcesFetched = callback;\n }\n enqueue(url) {\n void this.prefetch(url);\n }\n has(url) {\n return this.prefetchedUrls.has(url) || this.controllers.has(url);\n }\n get size() {\n return this.getQueueSize();\n }\n clear() {\n this.stopAll();\n this.prefetchedUrls.clear();\n }\n start() {\n this.stopped = false;\n }\n stop() {\n this.stopped = true;\n this.stopAll();\n }\n getQueueSize() {\n return this.controllers.size;\n }\n getConcurrentCount() {\n return this.concurrent;\n }\n async prefetchLink(link) {\n if (this.stopped) {\n return;\n }\n const url = link.href;\n if (!url || this.controllers.has(url) || this.prefetchedUrls.has(url)) {\n return;\n }\n if (this.concurrent >= this.options.maxConcurrent) {\n prefetchLogger.debug?.(`Prefetch queue full, skipping ${url}`);\n return;\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (_error) {\n prefetchLogger.debug?.(`Invalid prefetch URL ${url}`);\n return;\n }\n const controller = new AbortController();\n this.controllers.set(url, controller);\n this.concurrent += 1;\n const timeoutId = this.options.timeout > 0 ? setTimeout(() => controller.abort(), this.options.timeout) : void 0;\n try {\n const response = await fetch(parsedUrl.toString(), {\n method: "GET",\n signal: controller.signal,\n headers: { "X-Veryfront-Prefetch": "1" }\n });\n if (!response.ok) {\n return;\n }\n if (this.isResponseTooLarge(response)) {\n prefetchLogger.debug?.(`Prefetch too large, skipping ${url}`);\n return;\n }\n this.prefetchedUrls.add(url);\n if (this.onResourcesFetched) {\n try {\n await this.onResourcesFetched(response, url);\n } catch (callbackError) {\n prefetchLogger.error?.(`Prefetch callback failed for ${url}`, callbackError);\n }\n }\n } catch (error) {\n if (!isAbortError(error)) {\n prefetchLogger.error?.(`Failed to prefetch ${url}`, error);\n }\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n this.controllers.delete(url);\n this.concurrent = Math.max(0, this.concurrent - 1);\n }\n }\n async prefetch(url) {\n const link = typeof document !== "undefined" ? document.createElement("a") : { href: url };\n link.href = url;\n await this.prefetchLink(link);\n }\n stopAll() {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n this.concurrent = 0;\n }\n isResponseTooLarge(response) {\n const rawLength = response.headers.get("content-length");\n if (rawLength === null) {\n return false;\n }\n const size = Number.parseInt(rawLength, 10);\n if (!Number.isFinite(size)) {\n return false;\n }\n return size > this.options.maxSize;\n }\n};\nvar prefetchQueue = new PrefetchQueue();\n\n// src/rendering/client/prefetch/resource-hints.ts\nvar ResourceHintsManager = class {\n constructor() {\n this.appliedHints = /* @__PURE__ */ new Set();\n }\n applyResourceHints(hints) {\n for (const hint of hints) {\n const key = `${hint.type}:${hint.href}`;\n if (this.appliedHints.has(key))\n continue;\n const existing = document.querySelector(`link[rel="${hint.type}"][href="${hint.href}"]`);\n if (existing) {\n this.appliedHints.add(key);\n continue;\n }\n this.createAndAppendHint(hint);\n this.appliedHints.add(key);\n prefetchLogger.debug(`Added resource hint: ${hint.type} ${hint.href}`);\n }\n }\n createAndAppendHint(hint) {\n if (!document.head) {\n prefetchLogger.warn("document.head is not available, skipping resource hint");\n return;\n }\n const link = document.createElement("link");\n link.rel = hint.type;\n link.href = hint.href;\n if (hint.as)\n link.setAttribute("as", hint.as);\n if (hint.crossOrigin)\n link.setAttribute("crossorigin", hint.crossOrigin);\n if (hint.media)\n link.setAttribute("media", hint.media);\n document.head.appendChild(link);\n }\n extractResourceHints(html, prefetchedUrls) {\n try {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, "text/html");\n const hints = [];\n this.extractPreloadLinks(doc, prefetchedUrls, hints);\n this.extractScripts(doc, prefetchedUrls, hints);\n this.extractStylesheets(doc, prefetchedUrls, hints);\n return hints;\n } catch (error) {\n prefetchLogger.error("Failed to parse prefetched page", error);\n return [];\n }\n }\n isValidResourceHintType(rel) {\n return rel === "prefetch" || rel === "preload" || rel === "preconnect" || rel === "dns-prefetch";\n }\n extractPreloadLinks(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="preload"], link[rel="prefetch"]\').forEach((link) => {\n const htmlLink = link;\n const href = htmlLink.href;\n if (href && !prefetchedUrls.has(href) && this.isValidResourceHintType(htmlLink.rel)) {\n hints.push({\n type: htmlLink.rel,\n href,\n as: htmlLink.getAttribute("as") || void 0\n });\n }\n });\n }\n extractScripts(doc, prefetchedUrls, hints) {\n doc.querySelectorAll("script[src]").forEach((script) => {\n const src = script.src;\n if (src && !prefetchedUrls.has(src)) {\n hints.push({ type: "prefetch", href: src, as: "script" });\n }\n });\n }\n extractStylesheets(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="stylesheet"]\').forEach((link) => {\n const href = link.href;\n if (href && !prefetchedUrls.has(href)) {\n hints.push({ type: "prefetch", href, as: "style" });\n }\n });\n }\n static generateResourceHints(_route, assets) {\n const hints = [\n \'<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">\',\n \'<link rel="dns-prefetch" href="https://esm.sh">\',\n \'<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>\'\n ];\n for (const asset of assets) {\n if (asset.endsWith(".js")) {\n hints.push(`<link rel="modulepreload" href="${asset}">`);\n } else if (asset.endsWith(".css")) {\n hints.push(`<link rel="preload" as="style" href="${asset}">`);\n } else if (asset.match(/\\.(woff2?|ttf|otf)$/)) {\n hints.push(`<link rel="preload" as="font" href="${asset}" crossorigin>`);\n }\n }\n return hints.join("\\n");\n }\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\n\n// src/core/utils/logger/logger.ts\nvar cachedLogLevel;\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nvar ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n};\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nvar getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n};\nvar trackedLoggers = /* @__PURE__ */ new Set();\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nvar cliLogger = createLogger("CLI");\nvar serverLogger = createLogger("SERVER");\nvar rendererLogger = createLogger("RENDERER");\nvar bundlerLogger = createLogger("BUNDLER");\nvar agentLogger = createLogger("AGENT");\nvar logger = createLogger("VERYFRONT");\n\n// deno.json\nvar deno_default = {\n name: "veryfront",\n version: "0.0.6",\n nodeModulesDir: "auto",\n workspace: [\n "./examples/async-worker-redis",\n "./examples/knowledge-base",\n "./examples/form-handling",\n "./examples/middleware-demo",\n "./examples/coding-agent",\n "./examples/durable-workflows"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n};\n\n// src/core/utils/version.ts\nvar VERSION = typeof deno_default.version === "string" ? deno_default.version : "0.0.0";\n\n// src/core/utils/bundle-manifest.ts\nvar InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n};\nvar manifestStore = new InMemoryBundleManifestStore();\n\n// src/rendering/client/prefetch.ts\nvar PrefetchManager = class {\n constructor(options = {}) {\n this.prefetchedUrls = /* @__PURE__ */ new Set();\n this.linkObserver = null;\n this.options = {\n rootMargin: options.rootMargin || "50px",\n delay: options.delay || PREFETCH_DEFAULT_DELAY_MS,\n maxConcurrent: options.maxConcurrent || 2,\n allowedNetworks: options.allowedNetworks || ["4g", "wifi", "ethernet"],\n maxSize: options.maxSize || PREFETCH_MAX_SIZE_BYTES,\n timeout: options.timeout || PREFETCH_DEFAULT_TIMEOUT_MS\n };\n this.networkUtils = new NetworkUtils(this.options.allowedNetworks);\n this.resourceHintsManager = new ResourceHintsManager();\n this.prefetchQueue = new PrefetchQueue(\n {\n maxConcurrent: this.options.maxConcurrent,\n maxSize: this.options.maxSize,\n timeout: this.options.timeout\n },\n this.prefetchedUrls\n );\n this.prefetchQueue.setResourceCallback(\n (response, url) => this.prefetchPageResources(response, url)\n );\n }\n init() {\n prefetchLogger.info("Initializing prefetch manager");\n if (!this.networkUtils.shouldPrefetch()) {\n prefetchLogger.info("Prefetching disabled due to network conditions");\n return;\n }\n this.linkObserver = new LinkObserver(\n {\n rootMargin: this.options.rootMargin,\n delay: this.options.delay,\n onLinkVisible: (link) => this.prefetchQueue.prefetchLink(link)\n },\n this.prefetchedUrls\n );\n this.linkObserver.init();\n this.networkUtils.onNetworkChange(() => {\n if (!this.networkUtils.shouldPrefetch()) {\n this.prefetchQueue.stopAll();\n }\n });\n }\n async prefetchPageResources(response, _pageUrl) {\n const html = await response.text();\n const hints = this.resourceHintsManager.extractResourceHints(html, this.prefetchedUrls);\n this.resourceHintsManager.applyResourceHints(hints);\n }\n applyResourceHints(hints) {\n this.resourceHintsManager.applyResourceHints(hints);\n }\n async prefetch(url) {\n await this.prefetchQueue.prefetch(url);\n }\n static generateResourceHints(route, assets) {\n return ResourceHintsManager.generateResourceHints(route, assets);\n }\n destroy() {\n this.linkObserver?.destroy();\n this.prefetchQueue.stopAll();\n this.prefetchedUrls.clear();\n }\n};\nif (typeof window !== "undefined") {\n const prefetchManager = new PrefetchManager();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => prefetchManager.init());\n } else {\n prefetchManager.init();\n }\n globalThis.veryFrontPrefetch = prefetchManager;\n}\nexport {\n PrefetchManager\n};\n';
14106
+ CLIENT_ROUTER_BUNDLE = 'var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\nfunction hasBunRuntime(global) {\n return typeof global === "object" && global !== null && "Bun" in global && typeof global.Bun !== "undefined";\n}\nvar init_runtime_guards = __esm({\n "src/core/utils/runtime-guards.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\nfunction isTestEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "test";\n}\nfunction isProductionEnvironment() {\n return getEnvironmentVariable("NODE_ENV") === "production";\n}\nfunction isDevelopmentEnvironment() {\n const env = getEnvironmentVariable("NODE_ENV");\n return env === "development" || env === void 0;\n}\nvar init_env = __esm({\n "src/core/utils/logger/env.ts"() {\n "use strict";\n init_runtime_guards();\n }\n});\n\n// src/core/utils/logger/logger.ts\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nfunction __loggerResetForTests(options = {}) {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\n if (options.restoreConsole) {\n console.debug = originalConsole.debug;\n console.log = originalConsole.log;\n console.warn = originalConsole.warn;\n console.error = originalConsole.error;\n }\n}\nvar LogLevel, originalConsole, cachedLogLevel, ConsoleLogger, getDefaultLevel, trackedLoggers, cliLogger, serverLogger, rendererLogger, bundlerLogger, agentLogger, logger;\nvar init_logger = __esm({\n "src/core/utils/logger/logger.ts"() {\n "use strict";\n init_env();\n LogLevel = /* @__PURE__ */ ((LogLevel2) => {\n LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";\n LogLevel2[LogLevel2["INFO"] = 1] = "INFO";\n LogLevel2[LogLevel2["WARN"] = 2] = "WARN";\n LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";\n return LogLevel2;\n })(LogLevel || {});\n originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error\n };\n ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error2) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error2);\n throw error2;\n }\n }\n };\n getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n };\n trackedLoggers = /* @__PURE__ */ new Set();\n cliLogger = createLogger("CLI");\n serverLogger = createLogger("SERVER");\n rendererLogger = createLogger("RENDERER");\n bundlerLogger = createLogger("BUNDLER");\n agentLogger = createLogger("AGENT");\n logger = createLogger("VERYFRONT");\n }\n});\n\n// src/core/utils/logger/index.ts\nvar init_logger2 = __esm({\n "src/core/utils/logger/index.ts"() {\n "use strict";\n init_logger();\n init_env();\n }\n});\n\n// src/core/utils/constants/build.ts\nvar DEFAULT_BUILD_CONCURRENCY, IMAGE_OPTIMIZATION;\nvar init_build = __esm({\n "src/core/utils/constants/build.ts"() {\n "use strict";\n DEFAULT_BUILD_CONCURRENCY = 4;\n IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80\n };\n }\n});\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, MS_PER_SECOND, DEFAULT_LRU_MAX_ENTRIES, COMPONENT_LOADER_MAX_ENTRIES, COMPONENT_LOADER_TTL_MS, MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS, RENDERER_CORE_MAX_ENTRIES, RENDERER_CORE_TTL_MS, TSX_LAYOUT_MAX_ENTRIES, TSX_LAYOUT_TTL_MS, DATA_FETCHING_MAX_ENTRIES, DATA_FETCHING_TTL_MS, MDX_CACHE_TTL_PRODUCTION_MS, MDX_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_CACHE_TTL_PRODUCTION_MS, BUNDLE_CACHE_TTL_DEVELOPMENT_MS, BUNDLE_MANIFEST_PROD_TTL_MS, BUNDLE_MANIFEST_DEV_TTL_MS, RSC_MANIFEST_CACHE_TTL_MS, SERVER_ACTION_DEFAULT_TTL_SEC, DENO_KV_SAFE_SIZE_LIMIT_BYTES, HTTP_CACHE_SHORT_MAX_AGE_SEC, HTTP_CACHE_MEDIUM_MAX_AGE_SEC, HTTP_CACHE_LONG_MAX_AGE_SEC, ONE_DAY_MS, CACHE_CLEANUP_INTERVAL_MS, LRU_DEFAULT_MAX_ENTRIES, LRU_DEFAULT_MAX_SIZE_BYTES, CLEANUP_INTERVAL_MULTIPLIER;\nvar init_cache = __esm({\n "src/core/utils/constants/cache.ts"() {\n "use strict";\n SECONDS_PER_MINUTE = 60;\n MINUTES_PER_HOUR = 60;\n HOURS_PER_DAY = 24;\n MS_PER_SECOND = 1e3;\n DEFAULT_LRU_MAX_ENTRIES = 100;\n COMPONENT_LOADER_MAX_ENTRIES = 100;\n COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_RENDERER_MAX_ENTRIES = 200;\n MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RENDERER_CORE_MAX_ENTRIES = 100;\n RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n TSX_LAYOUT_MAX_ENTRIES = 50;\n TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n DATA_FETCHING_MAX_ENTRIES = 200;\n DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n RSC_MANIFEST_CACHE_TTL_MS = 5e3;\n SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64e3;\n HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\n HTTP_CACHE_LONG_MAX_AGE_SEC = 31536e3;\n ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n CACHE_CLEANUP_INTERVAL_MS = 6e4;\n LRU_DEFAULT_MAX_ENTRIES = 1e3;\n LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n CLEANUP_INTERVAL_MULTIPLIER = 2;\n }\n});\n\n// src/core/utils/constants/cdn.ts\nfunction getReactCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\nfunction getReactDOMCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\nfunction getReactDOMClientCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\nfunction getReactDOMServerCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\nfunction getReactJSXRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\nfunction getReactJSXDevRuntimeCDNUrl(version = REACT_DEFAULT_VERSION) {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\nfunction getReactImportMap(version = REACT_DEFAULT_VERSION) {\n return {\n react: getReactCDNUrl(version),\n "react-dom": getReactDOMCDNUrl(version),\n "react-dom/client": getReactDOMClientCDNUrl(version),\n "react-dom/server": getReactDOMServerCDNUrl(version),\n "react/jsx-runtime": getReactJSXRuntimeCDNUrl(version),\n "react/jsx-dev-runtime": getReactJSXDevRuntimeCDNUrl(version)\n };\n}\nfunction getDenoStdNodeBase() {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\nfunction getUnoCSSTailwindResetUrl() {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\nvar ESM_CDN_BASE, JSDELIVR_CDN_BASE, DENO_STD_BASE, REACT_VERSION_17, REACT_VERSION_18_2, REACT_VERSION_18_3, REACT_VERSION_19_RC, REACT_VERSION_19, REACT_DEFAULT_VERSION, DEFAULT_ALLOWED_CDN_HOSTS, DENO_STD_VERSION, UNOCSS_VERSION;\nvar init_cdn = __esm({\n "src/core/utils/constants/cdn.ts"() {\n "use strict";\n ESM_CDN_BASE = "https://esm.sh";\n JSDELIVR_CDN_BASE = "https://cdn.jsdelivr.net";\n DENO_STD_BASE = "https://deno.land";\n REACT_VERSION_17 = "17.0.2";\n REACT_VERSION_18_2 = "18.2.0";\n REACT_VERSION_18_3 = "18.3.1";\n REACT_VERSION_19_RC = "19.0.0-rc.0";\n REACT_VERSION_19 = "19.1.1";\n REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n DENO_STD_VERSION = "0.220.0";\n UNOCSS_VERSION = "0.59.0";\n }\n});\n\n// src/core/utils/constants/hash.ts\nvar HASH_SEED_DJB2, HASH_SEED_FNV1A;\nvar init_hash = __esm({\n "src/core/utils/constants/hash.ts"() {\n "use strict";\n HASH_SEED_DJB2 = 5381;\n HASH_SEED_FNV1A = 2166136261;\n }\n});\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES, HTTP_MODULE_FETCH_TIMEOUT_MS, HMR_RECONNECT_DELAY_MS, HMR_RELOAD_DELAY_MS, HMR_FILE_WATCHER_DEBOUNCE_MS, HMR_KEEP_ALIVE_INTERVAL_MS, DASHBOARD_RECONNECT_DELAY_MS, SERVER_FUNCTION_DEFAULT_TIMEOUT_MS, PREFETCH_MAX_SIZE_BYTES, PREFETCH_DEFAULT_TIMEOUT_MS, PREFETCH_DEFAULT_DELAY_MS, HTTP_OK, HTTP_NO_CONTENT, HTTP_CREATED, HTTP_REDIRECT_FOUND, HTTP_NOT_MODIFIED, HTTP_BAD_REQUEST, HTTP_UNAUTHORIZED, HTTP_FORBIDDEN, HTTP_NOT_FOUND, HTTP_METHOD_NOT_ALLOWED, HTTP_GONE, HTTP_PAYLOAD_TOO_LARGE, HTTP_URI_TOO_LONG, HTTP_TOO_MANY_REQUESTS, HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_SERVER_ERROR, HTTP_INTERNAL_SERVER_ERROR, HTTP_BAD_GATEWAY, HTTP_NOT_IMPLEMENTED, HTTP_UNAVAILABLE, HTTP_NETWORK_CONNECT_TIMEOUT, HTTP_STATUS_SUCCESS_MIN, HTTP_STATUS_REDIRECT_MIN, HTTP_STATUS_CLIENT_ERROR_MIN, HTTP_STATUS_SERVER_ERROR_MIN, HTTP_CONTENT_TYPES, MS_PER_MINUTE, HTTP_CONTENT_TYPE_IMAGE_PNG, HTTP_CONTENT_TYPE_IMAGE_JPEG, HTTP_CONTENT_TYPE_IMAGE_WEBP, HTTP_CONTENT_TYPE_IMAGE_AVIF, HTTP_CONTENT_TYPE_IMAGE_SVG, HTTP_CONTENT_TYPE_IMAGE_GIF, HTTP_CONTENT_TYPE_IMAGE_ICO;\nvar init_http = __esm({\n "src/core/utils/constants/http.ts"() {\n "use strict";\n init_cache();\n KB_IN_BYTES = 1024;\n HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n HMR_RECONNECT_DELAY_MS = 1e3;\n HMR_RELOAD_DELAY_MS = 1e3;\n HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n HMR_KEEP_ALIVE_INTERVAL_MS = 3e4;\n DASHBOARD_RECONNECT_DELAY_MS = 3e3;\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 3e4;\n PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\n PREFETCH_DEFAULT_DELAY_MS = 200;\n HTTP_OK = 200;\n HTTP_NO_CONTENT = 204;\n HTTP_CREATED = 201;\n HTTP_REDIRECT_FOUND = 302;\n HTTP_NOT_MODIFIED = 304;\n HTTP_BAD_REQUEST = 400;\n HTTP_UNAUTHORIZED = 401;\n HTTP_FORBIDDEN = 403;\n HTTP_NOT_FOUND = 404;\n HTTP_METHOD_NOT_ALLOWED = 405;\n HTTP_GONE = 410;\n HTTP_PAYLOAD_TOO_LARGE = 413;\n HTTP_URI_TOO_LONG = 414;\n HTTP_TOO_MANY_REQUESTS = 429;\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n HTTP_SERVER_ERROR = 500;\n HTTP_INTERNAL_SERVER_ERROR = 500;\n HTTP_BAD_GATEWAY = 502;\n HTTP_NOT_IMPLEMENTED = 501;\n HTTP_UNAVAILABLE = 503;\n HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n HTTP_STATUS_SUCCESS_MIN = 200;\n HTTP_STATUS_REDIRECT_MIN = 300;\n HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n HTTP_STATUS_SERVER_ERROR_MIN = 500;\n HTTP_CONTENT_TYPES = {\n JS: "application/javascript; charset=utf-8",\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n TEXT: "text/plain; charset=utf-8"\n };\n MS_PER_MINUTE = 6e4;\n HTTP_CONTENT_TYPE_IMAGE_PNG = "image/png";\n HTTP_CONTENT_TYPE_IMAGE_JPEG = "image/jpeg";\n HTTP_CONTENT_TYPE_IMAGE_WEBP = "image/webp";\n HTTP_CONTENT_TYPE_IMAGE_AVIF = "image/avif";\n HTTP_CONTENT_TYPE_IMAGE_SVG = "image/svg+xml";\n HTTP_CONTENT_TYPE_IMAGE_GIF = "image/gif";\n HTTP_CONTENT_TYPE_IMAGE_ICO = "image/x-icon";\n }\n});\n\n// src/core/utils/constants/hmr.ts\nfunction isValidHMRMessageType(type) {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type\n );\n}\nvar HMR_MAX_MESSAGE_SIZE_BYTES, HMR_MAX_MESSAGES_PER_MINUTE, HMR_CLIENT_RELOAD_DELAY_MS, HMR_PORT_OFFSET, HMR_RATE_LIMIT_WINDOW_MS, HMR_CLOSE_NORMAL, HMR_CLOSE_RATE_LIMIT, HMR_CLOSE_MESSAGE_TOO_LARGE, HMR_MESSAGE_TYPES;\nvar init_hmr = __esm({\n "src/core/utils/constants/hmr.ts"() {\n "use strict";\n init_http();\n HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n HMR_MAX_MESSAGES_PER_MINUTE = 100;\n HMR_CLIENT_RELOAD_DELAY_MS = 3e3;\n HMR_PORT_OFFSET = 1;\n HMR_RATE_LIMIT_WINDOW_MS = 6e4;\n HMR_CLOSE_NORMAL = 1e3;\n HMR_CLOSE_RATE_LIMIT = 1008;\n HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n HMR_MESSAGE_TYPES = {\n CONNECTED: "connected",\n UPDATE: "update",\n RELOAD: "reload",\n PING: "ping",\n PONG: "pong"\n };\n }\n});\n\n// src/core/utils/constants/html.ts\nvar Z_INDEX_DEV_INDICATOR, Z_INDEX_ERROR_OVERLAY, BREAKPOINT_SM, BREAKPOINT_MD, BREAKPOINT_LG, BREAKPOINT_XL, PROSE_MAX_WIDTH;\nvar init_html = __esm({\n "src/core/utils/constants/html.ts"() {\n "use strict";\n Z_INDEX_DEV_INDICATOR = 9998;\n Z_INDEX_ERROR_OVERLAY = 9999;\n BREAKPOINT_SM = 640;\n BREAKPOINT_MD = 768;\n BREAKPOINT_LG = 1024;\n BREAKPOINT_XL = 1280;\n PROSE_MAX_WIDTH = "65ch";\n }\n});\n\n// src/core/utils/constants/network.ts\nvar DEFAULT_DEV_SERVER_PORT, DEFAULT_REDIS_PORT, DEFAULT_API_SERVER_PORT, DEFAULT_PREVIEW_SERVER_PORT, DEFAULT_METRICS_PORT, BYTES_PER_KB, BYTES_PER_MB, DEFAULT_IMAGE_THUMBNAIL_SIZE, DEFAULT_IMAGE_SMALL_SIZE, DEFAULT_IMAGE_LARGE_SIZE, RESPONSIVE_IMAGE_WIDTH_XS, RESPONSIVE_IMAGE_WIDTH_SM, RESPONSIVE_IMAGE_WIDTH_MD, RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS, MAX_CHUNK_SIZE_KB, MIN_PORT, MAX_PORT, DEFAULT_SERVER_PORT;\nvar init_network = __esm({\n "src/core/utils/constants/network.ts"() {\n "use strict";\n DEFAULT_DEV_SERVER_PORT = 3e3;\n DEFAULT_REDIS_PORT = 6379;\n DEFAULT_API_SERVER_PORT = 8080;\n DEFAULT_PREVIEW_SERVER_PORT = 5e3;\n DEFAULT_METRICS_PORT = 9e3;\n BYTES_PER_KB = 1024;\n BYTES_PER_MB = 1024 * 1024;\n DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\n DEFAULT_IMAGE_SMALL_SIZE = 512;\n DEFAULT_IMAGE_LARGE_SIZE = 2048;\n RESPONSIVE_IMAGE_WIDTH_XS = 320;\n RESPONSIVE_IMAGE_WIDTH_SM = 640;\n RESPONSIVE_IMAGE_WIDTH_MD = 1024;\n RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG\n ];\n MAX_CHUNK_SIZE_KB = 4096;\n MIN_PORT = 1;\n MAX_PORT = 65535;\n DEFAULT_SERVER_PORT = 8e3;\n }\n});\n\n// src/core/utils/constants/security.ts\nvar MAX_PATH_TRAVERSAL_DEPTH, FORBIDDEN_PATH_PATTERNS, DIRECTORY_TRAVERSAL_PATTERN, ABSOLUTE_PATH_PATTERN, MAX_PATH_LENGTH, DEFAULT_MAX_STRING_LENGTH;\nvar init_security = __esm({\n "src/core/utils/constants/security.ts"() {\n "use strict";\n MAX_PATH_TRAVERSAL_DEPTH = 10;\n FORBIDDEN_PATH_PATTERNS = [\n /\\0/\n // Null bytes\n ];\n DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n MAX_PATH_LENGTH = 4096;\n DEFAULT_MAX_STRING_LENGTH = 1e3;\n }\n});\n\n// src/core/utils/constants/server.ts\nvar DEFAULT_DASHBOARD_PORT, DEV_SERVER_ENDPOINTS;\nvar init_server = __esm({\n "src/core/utils/constants/server.ts"() {\n "use strict";\n DEFAULT_DASHBOARD_PORT = 3002;\n DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n }\n});\n\n// src/core/utils/constants/index.ts\nvar init_constants = __esm({\n "src/core/utils/constants/index.ts"() {\n "use strict";\n init_build();\n init_cache();\n init_cdn();\n init_hash();\n init_hmr();\n init_html();\n init_http();\n init_network();\n init_security();\n init_server();\n }\n});\n\n// deno.json\nvar deno_default;\nvar init_deno = __esm({\n "deno.json"() {\n deno_default = {\n name: "veryfront",\n version: "0.0.8",\n nodeModulesDir: "auto",\n workspace: [\n "./examples/async-worker-redis",\n "./examples/knowledge-base",\n "./examples/form-handling",\n "./examples/middleware-demo",\n "./examples/coding-agent",\n "./examples/durable-workflows"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n };\n }\n});\n\n// src/core/utils/version.ts\nvar VERSION;\nvar init_version = __esm({\n "src/core/utils/version.ts"() {\n "use strict";\n init_deno();\n VERSION = typeof deno_default.version === "string" ? deno_default.version : "0.0.0";\n }\n});\n\n// src/core/utils/paths.ts\nvar PATHS, VERYFRONT_PATHS, FILE_EXTENSIONS;\nvar init_paths = __esm({\n "src/core/utils/paths.ts"() {\n "use strict";\n PATHS = {\n PAGES_DIR: "pages",\n COMPONENTS_DIR: "components",\n PUBLIC_DIR: "public",\n STYLES_DIR: "styles",\n DIST_DIR: "dist",\n CONFIG_FILE: "veryfront.config.js"\n };\n VERYFRONT_PATHS = {\n INTERNAL_PREFIX: "/_veryfront",\n BUILD_DIR: "_veryfront",\n CHUNKS_DIR: "_veryfront/chunks",\n DATA_DIR: "_veryfront/data",\n ASSETS_DIR: "_veryfront/assets",\n HMR_RUNTIME: "/_veryfront/hmr-runtime.js",\n CLIENT_JS: "/_veryfront/client.js",\n ROUTER_JS: "/_veryfront/router.js",\n ERROR_OVERLAY: "/_veryfront/error-overlay.js"\n };\n FILE_EXTENSIONS = {\n MDX: [".mdx", ".md"],\n SCRIPT: [".tsx", ".ts", ".jsx", ".js"],\n STYLE: [".css", ".scss", ".sass"],\n ALL: [".mdx", ".md", ".tsx", ".ts", ".jsx", ".js", ".css"]\n };\n }\n});\n\n// src/core/utils/hash-utils.ts\nasync function computeHash(content) {\n const encoder = new TextEncoder();\n const data = encoder.encode(content);\n const hashBuffer = await crypto.subtle.digest("SHA-256", data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");\n}\nfunction getContentHash(content) {\n return computeHash(content);\n}\nfunction computeContentHash(content) {\n return computeHash(content);\n}\nfunction computeCodeHash(code) {\n const combined = code.code + (code.css || "") + (code.sourceMap || "");\n return computeHash(combined);\n}\nfunction simpleHash(str) {\n let hash = 0;\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n return Math.abs(hash);\n}\nasync function shortHash(content) {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\nvar init_hash_utils = __esm({\n "src/core/utils/hash-utils.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/memoize.ts\nfunction memoizeAsync(fn, keyHasher) {\n const cache = new MemoCache();\n return async (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction memoize(fn, keyHasher) {\n const cache = new MemoCache();\n return (...args) => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\nfunction simpleHash2(...values) {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n let hash = FNV_OFFSET_BASIS;\n for (const value of values) {\n const str = typeof value === "string" ? value : String(value);\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n return (hash >>> 0).toString(36);\n}\nvar MemoCache;\nvar init_memoize = __esm({\n "src/core/utils/memoize.ts"() {\n "use strict";\n MemoCache = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n get(key) {\n return this.cache.get(key);\n }\n set(key, value) {\n this.cache.set(key, value);\n }\n has(key) {\n return this.cache.has(key);\n }\n clear() {\n this.cache.clear();\n }\n size() {\n return this.cache.size;\n }\n };\n }\n});\n\n// src/core/utils/path-utils.ts\nfunction normalizePath(pathname) {\n pathname = pathname.replace(/\\\\+/g, "/").replace(/\\/\\.+\\//g, "/");\n if (pathname !== "/" && pathname.endsWith("/")) {\n pathname = pathname.slice(0, -1);\n }\n return pathname;\n}\nfunction joinPath(a, b) {\n return `${a.replace(/\\/$/, "")}/${b.replace(/^\\//, "")}`;\n}\nfunction isWithinDirectory(root, target) {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\nfunction getExtension(path) {\n const lastDot = path.lastIndexOf(".");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return "";\n }\n return path.slice(lastDot);\n}\nfunction getDirectory(path) {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf("/");\n return lastSlash <= 0 ? "/" : normalized.slice(0, lastSlash);\n}\nfunction hasHashedFilename(path) {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\nfunction isAbsolutePath(path) {\n return path.startsWith("/") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\nfunction toBase64Url(s) {\n const b64 = btoa(s);\n return b64.replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");\n}\nfunction fromBase64Url(encoded) {\n const b64 = encoded.replaceAll("-", "+").replaceAll("_", "/");\n const pad = b64.length % 4 === 2 ? "==" : b64.length % 4 === 3 ? "=" : "";\n try {\n return atob(b64 + pad);\n } catch (error2) {\n logger.debug(`Failed to decode base64url string "${encoded}":`, error2);\n return "";\n }\n}\nvar init_path_utils = __esm({\n "src/core/utils/path-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/format-utils.ts\nfunction formatBytes(bytes) {\n if (bytes === 0)\n return "0 Bytes";\n const absBytes = Math.abs(bytes);\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\n const k = 1024;\n const sizes = ["Bytes", "KB", "MB", "GB", "TB"];\n const i = Math.floor(Math.log(absBytes) / Math.log(k));\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\nfunction estimateSize(value) {\n if (value === null || value === void 0)\n return 8;\n switch (typeof value) {\n case "boolean":\n return 4;\n case "number":\n return 8;\n case "string":\n return value.length * 2;\n case "function":\n return 0;\n case "object":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\nfunction estimateSizeWithCircularHandling(value) {\n const seen = /* @__PURE__ */ new WeakSet();\n const encoder = new TextEncoder();\n const json3 = JSON.stringify(value, (_key, val) => {\n if (typeof val === "object" && val !== null) {\n if (seen.has(val))\n return void 0;\n seen.add(val);\n if (val instanceof Map) {\n return { __type: "Map", entries: Array.from(val.entries()) };\n }\n if (val instanceof Set) {\n return { __type: "Set", values: Array.from(val.values()) };\n }\n }\n if (typeof val === "function")\n return void 0;\n if (val instanceof Uint8Array) {\n return { __type: "Uint8Array", length: val.length };\n }\n return val;\n });\n return encoder.encode(json3 ?? "").length;\n}\nfunction estimateObjectSize(value) {\n if (value instanceof ArrayBuffer)\n return value.byteLength;\n if (value instanceof Uint8Array || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array) {\n return value.byteLength;\n }\n try {\n return JSON.stringify(value).length * 2;\n } catch (error2) {\n logger.debug("Failed to estimate size of non-serializable object:", error2);\n return 1024;\n }\n}\nfunction formatDuration(ms) {\n if (ms < 1e3)\n return `${ms}ms`;\n if (ms < 6e4)\n return `${(ms / 1e3).toFixed(1)}s`;\n if (ms < 36e5)\n return `${Math.floor(ms / 6e4)}m ${Math.floor(ms % 6e4 / 1e3)}s`;\n return `${Math.floor(ms / 36e5)}h ${Math.floor(ms % 36e5 / 6e4)}m`;\n}\nfunction formatNumber(num) {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",");\n}\nfunction truncateString(str, maxLength) {\n if (str.length <= maxLength)\n return str;\n return str.slice(0, maxLength - 3) + "...";\n}\nvar init_format_utils = __esm({\n "src/core/utils/format-utils.ts"() {\n "use strict";\n init_logger();\n }\n});\n\n// src/core/utils/bundle-manifest.ts\nfunction setBundleManifestStore(store) {\n manifestStore = store;\n serverLogger.info("[bundle-manifest] Bundle manifest store configured", {\n type: store.constructor.name\n });\n}\nfunction getBundleManifestStore() {\n return manifestStore;\n}\nvar InMemoryBundleManifestStore, manifestStore;\nvar init_bundle_manifest = __esm({\n "src/core/utils/bundle-manifest.ts"() {\n "use strict";\n init_logger2();\n init_hash_utils();\n InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n };\n manifestStore = new InMemoryBundleManifestStore();\n }\n});\n\n// src/core/utils/bundle-manifest-init.ts\nasync function initializeBundleManifest(config, mode, adapter) {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === "production";\n if (!enabled) {\n serverLogger.info("[bundle-manifest] Bundle manifest disabled");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n const envType = adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_TYPE");\n const storeType = manifestConfig?.type || envType || "memory";\n serverLogger.info("[bundle-manifest] Initializing bundle manifest", {\n type: storeType,\n mode\n });\n try {\n let store;\n switch (storeType) {\n case "redis": {\n const { RedisBundleManifestStore } = await import("./bundle-manifest-redis.ts");\n const redisUrl = manifestConfig?.redisUrl || adapter?.env.get("VERYFRONT_BUNDLE_MANIFEST_REDIS_URL");\n store = new RedisBundleManifestStore(\n {\n url: redisUrl,\n keyPrefix: manifestConfig?.keyPrefix\n },\n adapter\n );\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] Redis not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] Redis store initialized");\n }\n break;\n }\n case "kv": {\n const { KVBundleManifestStore } = await import("./bundle-manifest-kv.ts");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix\n });\n const available = await store.isAvailable();\n if (!available) {\n serverLogger.warn("[bundle-manifest] KV not available, falling back to in-memory");\n store = new InMemoryBundleManifestStore();\n } else {\n serverLogger.info("[bundle-manifest] KV store initialized");\n }\n break;\n }\n case "memory":\n default: {\n store = new InMemoryBundleManifestStore();\n serverLogger.info("[bundle-manifest] In-memory store initialized");\n break;\n }\n }\n setBundleManifestStore(store);\n try {\n const stats = await store.getStats();\n serverLogger.info("[bundle-manifest] Store statistics", stats);\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to get stats", { error: error2 });\n }\n } catch (error2) {\n serverLogger.error("[bundle-manifest] Failed to initialize store, using in-memory fallback", {\n error: error2\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\nfunction getBundleManifestTTL(config, mode) {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n if (mode === "production") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\nasync function warmupBundleManifest(store, keys) {\n serverLogger.info("[bundle-manifest] Warming up cache", { keys: keys.length });\n let loaded = 0;\n let failed = 0;\n for (const key of keys) {\n try {\n const metadata = await store.getBundleMetadata(key);\n if (metadata) {\n await store.getBundleCode(metadata.codeHash);\n loaded++;\n }\n } catch (error2) {\n serverLogger.debug("[bundle-manifest] Failed to warm up key", { key, error: error2 });\n failed++;\n }\n }\n serverLogger.info("[bundle-manifest] Cache warmup complete", { loaded, failed });\n}\nvar init_bundle_manifest_init = __esm({\n "src/core/utils/bundle-manifest-init.ts"() {\n "use strict";\n init_logger2();\n init_bundle_manifest();\n init_cache();\n }\n});\n\n// src/core/utils/feature-flags.ts\nfunction isRSCEnabled(config) {\n if (config?.experimental?.rsc !== void 0) {\n return config.experimental.rsc;\n }\n if (typeof Deno !== "undefined" && Deno.env) {\n return Deno.env.get("VERYFRONT_EXPERIMENTAL_RSC") === "1";\n }\n if (typeof process !== "undefined" && process?.env) {\n return process.env.VERYFRONT_EXPERIMENTAL_RSC === "1";\n }\n return false;\n}\nvar init_feature_flags = __esm({\n "src/core/utils/feature-flags.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/platform.ts\nfunction isCompiledBinary() {\n const hasDeno = typeof Deno !== "undefined";\n const hasExecPath = hasDeno && typeof Deno.execPath === "function";\n if (!hasExecPath)\n return false;\n try {\n const execPath = Deno.execPath();\n return execPath.includes("veryfront");\n } catch {\n return false;\n }\n}\nvar init_platform = __esm({\n "src/core/utils/platform.ts"() {\n "use strict";\n }\n});\n\n// src/core/utils/index.ts\nvar utils_exports = {};\n__export(utils_exports, {\n ABSOLUTE_PATH_PATTERN: () => ABSOLUTE_PATH_PATTERN,\n BREAKPOINT_LG: () => BREAKPOINT_LG,\n BREAKPOINT_MD: () => BREAKPOINT_MD,\n BREAKPOINT_SM: () => BREAKPOINT_SM,\n BREAKPOINT_XL: () => BREAKPOINT_XL,\n BUNDLE_CACHE_TTL_DEVELOPMENT_MS: () => BUNDLE_CACHE_TTL_DEVELOPMENT_MS,\n BUNDLE_CACHE_TTL_PRODUCTION_MS: () => BUNDLE_CACHE_TTL_PRODUCTION_MS,\n BUNDLE_MANIFEST_DEV_TTL_MS: () => BUNDLE_MANIFEST_DEV_TTL_MS,\n BUNDLE_MANIFEST_PROD_TTL_MS: () => BUNDLE_MANIFEST_PROD_TTL_MS,\n BYTES_PER_KB: () => BYTES_PER_KB,\n BYTES_PER_MB: () => BYTES_PER_MB,\n CACHE_CLEANUP_INTERVAL_MS: () => CACHE_CLEANUP_INTERVAL_MS,\n CLEANUP_INTERVAL_MULTIPLIER: () => CLEANUP_INTERVAL_MULTIPLIER,\n COMPONENT_LOADER_MAX_ENTRIES: () => COMPONENT_LOADER_MAX_ENTRIES,\n COMPONENT_LOADER_TTL_MS: () => COMPONENT_LOADER_TTL_MS,\n DASHBOARD_RECONNECT_DELAY_MS: () => DASHBOARD_RECONNECT_DELAY_MS,\n DATA_FETCHING_MAX_ENTRIES: () => DATA_FETCHING_MAX_ENTRIES,\n DATA_FETCHING_TTL_MS: () => DATA_FETCHING_TTL_MS,\n DEFAULT_ALLOWED_CDN_HOSTS: () => DEFAULT_ALLOWED_CDN_HOSTS,\n DEFAULT_API_SERVER_PORT: () => DEFAULT_API_SERVER_PORT,\n DEFAULT_BUILD_CONCURRENCY: () => DEFAULT_BUILD_CONCURRENCY,\n DEFAULT_DASHBOARD_PORT: () => DEFAULT_DASHBOARD_PORT,\n DEFAULT_DEV_SERVER_PORT: () => DEFAULT_DEV_SERVER_PORT,\n DEFAULT_IMAGE_LARGE_SIZE: () => DEFAULT_IMAGE_LARGE_SIZE,\n DEFAULT_IMAGE_SMALL_SIZE: () => DEFAULT_IMAGE_SMALL_SIZE,\n DEFAULT_IMAGE_THUMBNAIL_SIZE: () => DEFAULT_IMAGE_THUMBNAIL_SIZE,\n DEFAULT_LRU_MAX_ENTRIES: () => DEFAULT_LRU_MAX_ENTRIES,\n DEFAULT_MAX_STRING_LENGTH: () => DEFAULT_MAX_STRING_LENGTH,\n DEFAULT_METRICS_PORT: () => DEFAULT_METRICS_PORT,\n DEFAULT_PREVIEW_SERVER_PORT: () => DEFAULT_PREVIEW_SERVER_PORT,\n DEFAULT_REDIS_PORT: () => DEFAULT_REDIS_PORT,\n DEFAULT_SERVER_PORT: () => DEFAULT_SERVER_PORT,\n DENO_KV_SAFE_SIZE_LIMIT_BYTES: () => DENO_KV_SAFE_SIZE_LIMIT_BYTES,\n DENO_STD_BASE: () => DENO_STD_BASE,\n DENO_STD_VERSION: () => DENO_STD_VERSION,\n DEV_SERVER_ENDPOINTS: () => DEV_SERVER_ENDPOINTS,\n DIRECTORY_TRAVERSAL_PATTERN: () => DIRECTORY_TRAVERSAL_PATTERN,\n ESM_CDN_BASE: () => ESM_CDN_BASE,\n FILE_EXTENSIONS: () => FILE_EXTENSIONS,\n FORBIDDEN_PATH_PATTERNS: () => FORBIDDEN_PATH_PATTERNS,\n HASH_SEED_DJB2: () => HASH_SEED_DJB2,\n HASH_SEED_FNV1A: () => HASH_SEED_FNV1A,\n HMR_CLIENT_RELOAD_DELAY_MS: () => HMR_CLIENT_RELOAD_DELAY_MS,\n HMR_CLOSE_MESSAGE_TOO_LARGE: () => HMR_CLOSE_MESSAGE_TOO_LARGE,\n HMR_CLOSE_NORMAL: () => HMR_CLOSE_NORMAL,\n HMR_CLOSE_RATE_LIMIT: () => HMR_CLOSE_RATE_LIMIT,\n HMR_FILE_WATCHER_DEBOUNCE_MS: () => HMR_FILE_WATCHER_DEBOUNCE_MS,\n HMR_KEEP_ALIVE_INTERVAL_MS: () => HMR_KEEP_ALIVE_INTERVAL_MS,\n HMR_MAX_MESSAGES_PER_MINUTE: () => HMR_MAX_MESSAGES_PER_MINUTE,\n HMR_MAX_MESSAGE_SIZE_BYTES: () => HMR_MAX_MESSAGE_SIZE_BYTES,\n HMR_MESSAGE_TYPES: () => HMR_MESSAGE_TYPES,\n HMR_PORT_OFFSET: () => HMR_PORT_OFFSET,\n HMR_RATE_LIMIT_WINDOW_MS: () => HMR_RATE_LIMIT_WINDOW_MS,\n HMR_RECONNECT_DELAY_MS: () => HMR_RECONNECT_DELAY_MS,\n HMR_RELOAD_DELAY_MS: () => HMR_RELOAD_DELAY_MS,\n HOURS_PER_DAY: () => HOURS_PER_DAY,\n HTTP_BAD_GATEWAY: () => HTTP_BAD_GATEWAY,\n HTTP_BAD_REQUEST: () => HTTP_BAD_REQUEST,\n HTTP_CACHE_LONG_MAX_AGE_SEC: () => HTTP_CACHE_LONG_MAX_AGE_SEC,\n HTTP_CACHE_MEDIUM_MAX_AGE_SEC: () => HTTP_CACHE_MEDIUM_MAX_AGE_SEC,\n HTTP_CACHE_SHORT_MAX_AGE_SEC: () => HTTP_CACHE_SHORT_MAX_AGE_SEC,\n HTTP_CONTENT_TYPES: () => HTTP_CONTENT_TYPES,\n HTTP_CONTENT_TYPE_IMAGE_AVIF: () => HTTP_CONTENT_TYPE_IMAGE_AVIF,\n HTTP_CONTENT_TYPE_IMAGE_GIF: () => HTTP_CONTENT_TYPE_IMAGE_GIF,\n HTTP_CONTENT_TYPE_IMAGE_ICO: () => HTTP_CONTENT_TYPE_IMAGE_ICO,\n HTTP_CONTENT_TYPE_IMAGE_JPEG: () => HTTP_CONTENT_TYPE_IMAGE_JPEG,\n HTTP_CONTENT_TYPE_IMAGE_PNG: () => HTTP_CONTENT_TYPE_IMAGE_PNG,\n HTTP_CONTENT_TYPE_IMAGE_SVG: () => HTTP_CONTENT_TYPE_IMAGE_SVG,\n HTTP_CONTENT_TYPE_IMAGE_WEBP: () => HTTP_CONTENT_TYPE_IMAGE_WEBP,\n HTTP_CREATED: () => HTTP_CREATED,\n HTTP_FORBIDDEN: () => HTTP_FORBIDDEN,\n HTTP_GONE: () => HTTP_GONE,\n HTTP_INTERNAL_SERVER_ERROR: () => HTTP_INTERNAL_SERVER_ERROR,\n HTTP_METHOD_NOT_ALLOWED: () => HTTP_METHOD_NOT_ALLOWED,\n HTTP_MODULE_FETCH_TIMEOUT_MS: () => HTTP_MODULE_FETCH_TIMEOUT_MS,\n HTTP_NETWORK_CONNECT_TIMEOUT: () => HTTP_NETWORK_CONNECT_TIMEOUT,\n HTTP_NOT_FOUND: () => HTTP_NOT_FOUND,\n HTTP_NOT_IMPLEMENTED: () => HTTP_NOT_IMPLEMENTED,\n HTTP_NOT_MODIFIED: () => HTTP_NOT_MODIFIED,\n HTTP_NO_CONTENT: () => HTTP_NO_CONTENT,\n HTTP_OK: () => HTTP_OK,\n HTTP_PAYLOAD_TOO_LARGE: () => HTTP_PAYLOAD_TOO_LARGE,\n HTTP_REDIRECT_FOUND: () => HTTP_REDIRECT_FOUND,\n HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE: () => HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE,\n HTTP_SERVER_ERROR: () => HTTP_SERVER_ERROR,\n HTTP_STATUS_CLIENT_ERROR_MIN: () => HTTP_STATUS_CLIENT_ERROR_MIN,\n HTTP_STATUS_REDIRECT_MIN: () => HTTP_STATUS_REDIRECT_MIN,\n HTTP_STATUS_SERVER_ERROR_MIN: () => HTTP_STATUS_SERVER_ERROR_MIN,\n HTTP_STATUS_SUCCESS_MIN: () => HTTP_STATUS_SUCCESS_MIN,\n HTTP_TOO_MANY_REQUESTS: () => HTTP_TOO_MANY_REQUESTS,\n HTTP_UNAUTHORIZED: () => HTTP_UNAUTHORIZED,\n HTTP_UNAVAILABLE: () => HTTP_UNAVAILABLE,\n HTTP_URI_TOO_LONG: () => HTTP_URI_TOO_LONG,\n IMAGE_OPTIMIZATION: () => IMAGE_OPTIMIZATION,\n InMemoryBundleManifestStore: () => InMemoryBundleManifestStore,\n JSDELIVR_CDN_BASE: () => JSDELIVR_CDN_BASE,\n KB_IN_BYTES: () => KB_IN_BYTES,\n LRU_DEFAULT_MAX_ENTRIES: () => LRU_DEFAULT_MAX_ENTRIES,\n LRU_DEFAULT_MAX_SIZE_BYTES: () => LRU_DEFAULT_MAX_SIZE_BYTES,\n LogLevel: () => LogLevel,\n MAX_CHUNK_SIZE_KB: () => MAX_CHUNK_SIZE_KB,\n MAX_PATH_LENGTH: () => MAX_PATH_LENGTH,\n MAX_PATH_TRAVERSAL_DEPTH: () => MAX_PATH_TRAVERSAL_DEPTH,\n MAX_PORT: () => MAX_PORT,\n MDX_CACHE_TTL_DEVELOPMENT_MS: () => MDX_CACHE_TTL_DEVELOPMENT_MS,\n MDX_CACHE_TTL_PRODUCTION_MS: () => MDX_CACHE_TTL_PRODUCTION_MS,\n MDX_RENDERER_MAX_ENTRIES: () => MDX_RENDERER_MAX_ENTRIES,\n MDX_RENDERER_TTL_MS: () => MDX_RENDERER_TTL_MS,\n MINUTES_PER_HOUR: () => MINUTES_PER_HOUR,\n MIN_PORT: () => MIN_PORT,\n MS_PER_MINUTE: () => MS_PER_MINUTE,\n MS_PER_SECOND: () => MS_PER_SECOND,\n MemoCache: () => MemoCache,\n ONE_DAY_MS: () => ONE_DAY_MS,\n PATHS: () => PATHS,\n PREFETCH_DEFAULT_DELAY_MS: () => PREFETCH_DEFAULT_DELAY_MS,\n PREFETCH_DEFAULT_TIMEOUT_MS: () => PREFETCH_DEFAULT_TIMEOUT_MS,\n PREFETCH_MAX_SIZE_BYTES: () => PREFETCH_MAX_SIZE_BYTES,\n PROSE_MAX_WIDTH: () => PROSE_MAX_WIDTH,\n REACT_DEFAULT_VERSION: () => REACT_DEFAULT_VERSION,\n REACT_VERSION_17: () => REACT_VERSION_17,\n REACT_VERSION_18_2: () => REACT_VERSION_18_2,\n REACT_VERSION_18_3: () => REACT_VERSION_18_3,\n REACT_VERSION_19: () => REACT_VERSION_19,\n REACT_VERSION_19_RC: () => REACT_VERSION_19_RC,\n RENDERER_CORE_MAX_ENTRIES: () => RENDERER_CORE_MAX_ENTRIES,\n RENDERER_CORE_TTL_MS: () => RENDERER_CORE_TTL_MS,\n RESPONSIVE_IMAGE_WIDTHS: () => RESPONSIVE_IMAGE_WIDTHS,\n RESPONSIVE_IMAGE_WIDTH_LG: () => RESPONSIVE_IMAGE_WIDTH_LG,\n RESPONSIVE_IMAGE_WIDTH_MD: () => RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_SM: () => RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_XS: () => RESPONSIVE_IMAGE_WIDTH_XS,\n RSC_MANIFEST_CACHE_TTL_MS: () => RSC_MANIFEST_CACHE_TTL_MS,\n SECONDS_PER_MINUTE: () => SECONDS_PER_MINUTE,\n SERVER_ACTION_DEFAULT_TTL_SEC: () => SERVER_ACTION_DEFAULT_TTL_SEC,\n SERVER_FUNCTION_DEFAULT_TIMEOUT_MS: () => SERVER_FUNCTION_DEFAULT_TIMEOUT_MS,\n TSX_LAYOUT_MAX_ENTRIES: () => TSX_LAYOUT_MAX_ENTRIES,\n TSX_LAYOUT_TTL_MS: () => TSX_LAYOUT_TTL_MS,\n UNOCSS_VERSION: () => UNOCSS_VERSION,\n VERSION: () => VERSION,\n VERYFRONT_PATHS: () => VERYFRONT_PATHS,\n Z_INDEX_DEV_INDICATOR: () => Z_INDEX_DEV_INDICATOR,\n Z_INDEX_ERROR_OVERLAY: () => Z_INDEX_ERROR_OVERLAY,\n __loggerResetForTests: () => __loggerResetForTests,\n agentLogger: () => agentLogger,\n bundlerLogger: () => bundlerLogger,\n cliLogger: () => cliLogger,\n computeCodeHash: () => computeCodeHash,\n computeContentHash: () => computeContentHash,\n computeHash: () => computeHash,\n estimateSize: () => estimateSize,\n estimateSizeWithCircularHandling: () => estimateSizeWithCircularHandling,\n formatBytes: () => formatBytes,\n formatDuration: () => formatDuration,\n formatNumber: () => formatNumber,\n fromBase64Url: () => fromBase64Url,\n getBundleManifestStore: () => getBundleManifestStore,\n getBundleManifestTTL: () => getBundleManifestTTL,\n getContentHash: () => getContentHash,\n getDenoStdNodeBase: () => getDenoStdNodeBase,\n getDirectory: () => getDirectory,\n getEnvironmentVariable: () => getEnvironmentVariable,\n getExtension: () => getExtension,\n getReactCDNUrl: () => getReactCDNUrl,\n getReactDOMCDNUrl: () => getReactDOMCDNUrl,\n getReactDOMClientCDNUrl: () => getReactDOMClientCDNUrl,\n getReactDOMServerCDNUrl: () => getReactDOMServerCDNUrl,\n getReactImportMap: () => getReactImportMap,\n getReactJSXDevRuntimeCDNUrl: () => getReactJSXDevRuntimeCDNUrl,\n getReactJSXRuntimeCDNUrl: () => getReactJSXRuntimeCDNUrl,\n getUnoCSSTailwindResetUrl: () => getUnoCSSTailwindResetUrl,\n hasBunRuntime: () => hasBunRuntime,\n hasDenoRuntime: () => hasDenoRuntime,\n hasHashedFilename: () => hasHashedFilename,\n hasNodeProcess: () => hasNodeProcess,\n initializeBundleManifest: () => initializeBundleManifest,\n isAbsolutePath: () => isAbsolutePath,\n isCompiledBinary: () => isCompiledBinary,\n isDevelopmentEnvironment: () => isDevelopmentEnvironment,\n isProductionEnvironment: () => isProductionEnvironment,\n isRSCEnabled: () => isRSCEnabled,\n isTestEnvironment: () => isTestEnvironment,\n isValidHMRMessageType: () => isValidHMRMessageType,\n isWithinDirectory: () => isWithinDirectory,\n joinPath: () => joinPath,\n logger: () => logger,\n memoize: () => memoize,\n memoizeAsync: () => memoizeAsync,\n memoizeHash: () => simpleHash2,\n normalizePath: () => normalizePath,\n numericHash: () => simpleHash,\n rendererLogger: () => rendererLogger,\n serverLogger: () => serverLogger,\n setBundleManifestStore: () => setBundleManifestStore,\n shortHash: () => shortHash,\n simpleHash: () => simpleHash,\n toBase64Url: () => toBase64Url,\n truncateString: () => truncateString,\n warmupBundleManifest: () => warmupBundleManifest\n});\nvar init_utils = __esm({\n "src/core/utils/index.ts"() {\n init_runtime_guards();\n init_logger2();\n init_constants();\n init_version();\n init_paths();\n init_hash_utils();\n init_memoize();\n init_path_utils();\n init_format_utils();\n init_bundle_manifest();\n init_bundle_manifest_init();\n init_feature_flags();\n init_platform();\n }\n});\n\n// src/core/errors/veryfront-error.ts\nfunction createError(error2) {\n return error2;\n}\nfunction toError(veryfrontError) {\n const error2 = new Error(veryfrontError.message);\n error2.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error2, "context", {\n value: veryfrontError,\n enumerable: false,\n configurable: true\n });\n return error2;\n}\nvar init_veryfront_error = __esm({\n "src/core/errors/veryfront-error.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/schema.ts\nimport { z } from "zod";\nvar corsSchema, veryfrontConfigSchema;\nvar init_schema = __esm({\n "src/core/config/schema.ts"() {\n "use strict";\n init_veryfront_error();\n corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n veryfrontConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n experimental: z.object({\n esmLayouts: z.boolean().optional(),\n precompileMDX: z.boolean().optional()\n }).partial().optional(),\n router: z.enum(["app", "pages"]).optional(),\n defaultLayout: z.string().optional(),\n theme: z.object({ colors: z.record(z.string()).optional() }).partial().optional(),\n build: z.object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z.object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n cache: z.object({\n dir: z.string().optional(),\n bundleManifest: z.object({\n type: z.enum(["redis", "kv", "memory"]).optional(),\n redisUrl: z.string().optional(),\n keyPrefix: z.string().optional(),\n ttl: z.number().int().positive().optional(),\n enabled: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n dev: z.object({\n port: z.number().int().positive().optional(),\n host: z.string().optional(),\n open: z.boolean().optional(),\n hmr: z.boolean().optional(),\n components: z.array(z.string()).optional()\n }).partial().optional(),\n resolve: z.object({\n importMap: z.object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional()\n }).partial().optional()\n }).partial().optional(),\n security: z.object({\n csp: z.record(z.array(z.string())).optional(),\n remoteHosts: z.array(z.string().url()).optional(),\n cors: corsSchema.optional(),\n coop: z.enum(["same-origin", "same-origin-allow-popups", "unsafe-none"]).optional(),\n corp: z.enum(["same-origin", "same-site", "cross-origin"]).optional(),\n coep: z.enum(["require-corp", "unsafe-none"]).optional()\n }).partial().optional(),\n middleware: z.object({\n custom: z.array(z.function()).optional()\n }).partial().optional(),\n theming: z.object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional()\n }).partial().optional(),\n assetPipeline: z.object({\n images: z.object({\n enabled: z.boolean().optional(),\n formats: z.array(z.enum(["webp", "avif", "jpeg", "png"])).optional(),\n sizes: z.array(z.number().int().positive()).optional(),\n quality: z.number().int().min(1).max(100).optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n preserveOriginal: z.boolean().optional()\n }).partial().optional(),\n css: z.object({\n enabled: z.boolean().optional(),\n minify: z.boolean().optional(),\n autoprefixer: z.boolean().optional(),\n purge: z.boolean().optional(),\n criticalCSS: z.boolean().optional(),\n inputDir: z.string().optional(),\n outputDir: z.string().optional(),\n browsers: z.array(z.string()).optional(),\n purgeContent: z.array(z.string()).optional(),\n sourceMap: z.boolean().optional()\n }).partial().optional()\n }).partial().optional(),\n observability: z.object({\n tracing: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["jaeger", "zipkin", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n serviceName: z.string().optional(),\n sampleRate: z.number().min(0).max(1).optional()\n }).partial().optional(),\n metrics: z.object({\n enabled: z.boolean().optional(),\n exporter: z.enum(["prometheus", "otlp", "console"]).optional(),\n endpoint: z.string().optional(),\n prefix: z.string().optional(),\n collectInterval: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n fs: z.object({\n type: z.enum(["local", "veryfront-api", "memory"]).optional(),\n local: z.object({\n baseDir: z.string().optional()\n }).partial().optional(),\n veryfront: z.object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z.object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional()\n }).partial().optional(),\n retry: z.object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional()\n }).partial().optional()\n }).partial().optional(),\n memory: z.object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional()\n }).partial().optional()\n }).partial().optional()\n }).partial();\n }\n});\n\n// src/_shims/std-path.ts\nimport * as nodeUrl from "node:url";\nimport * as nodePath from "node:path";\nvar init_std_path = __esm({\n "src/_shims/std-path.ts"() {\n }\n});\n\n// src/core/config/loader.ts\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\nvar DEFAULT_CONFIG;\nvar init_loader = __esm({\n "src/core/config/loader.ts"() {\n "use strict";\n init_schema();\n init_std_path();\n init_logger();\n init_cdn();\n DEFAULT_CONFIG = {\n title: "Veryfront App",\n description: "Built with Veryfront",\n experimental: {\n esmLayouts: true\n },\n router: void 0,\n defaultLayout: void 0,\n theme: {\n colors: {\n primary: "#3B82F6"\n }\n },\n build: {\n outDir: "dist",\n trailingSlash: false,\n esbuild: {\n wasmURL: "https://deno.land/x/esbuild@v0.20.1/esbuild.wasm",\n worker: false\n }\n },\n cache: {\n dir: ".veryfront/cache",\n render: {\n type: "memory",\n ttl: void 0,\n maxEntries: 500,\n kvPath: void 0,\n redisUrl: void 0,\n redisKeyPrefix: void 0\n }\n },\n dev: {\n port: 3002,\n host: "localhost",\n open: false\n },\n resolve: {\n importMap: getDefaultImportMapForConfig()\n }\n };\n }\n});\n\n// src/core/config/define-config.ts\nvar init_define_config = __esm({\n "src/core/config/define-config.ts"() {\n "use strict";\n init_veryfront_error();\n }\n});\n\n// src/core/config/defaults.ts\nvar DEFAULT_DEV_PORT, DEFAULT_PREFETCH_DELAY_MS, DURATION_HISTOGRAM_BOUNDARIES_MS, SIZE_HISTOGRAM_BOUNDARIES_KB, PAGE_TRANSITION_DELAY_MS;\nvar init_defaults = __esm({\n "src/core/config/defaults.ts"() {\n "use strict";\n DEFAULT_DEV_PORT = 3e3;\n DEFAULT_PREFETCH_DELAY_MS = 100;\n DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1e3,\n 2500,\n 5e3,\n 7500,\n 1e4\n ];\n SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1e3,\n 2500,\n 5e3,\n 1e4\n ];\n PAGE_TRANSITION_DELAY_MS = 150;\n }\n});\n\n// src/core/config/network-defaults.ts\nvar init_network_defaults = __esm({\n "src/core/config/network-defaults.ts"() {\n "use strict";\n }\n});\n\n// src/core/config/index.ts\nvar init_config = __esm({\n "src/core/config/index.ts"() {\n init_loader();\n init_define_config();\n init_schema();\n init_defaults();\n init_network_defaults();\n }\n});\n\n// src/core/errors/types.ts\nvar VeryfrontError;\nvar init_types = __esm({\n "src/core/errors/types.ts"() {\n "use strict";\n VeryfrontError = class extends Error {\n constructor(message, code, context) {\n super(message);\n this.name = "VeryfrontError";\n this.code = code;\n this.context = context;\n }\n };\n }\n});\n\n// src/core/errors/agent-errors.ts\nvar init_agent_errors = __esm({\n "src/core/errors/agent-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/build-errors.ts\nvar init_build_errors = __esm({\n "src/core/errors/build-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/runtime-errors.ts\nvar init_runtime_errors = __esm({\n "src/core/errors/runtime-errors.ts"() {\n "use strict";\n init_types();\n }\n});\n\n// src/core/errors/system-errors.ts\nvar NetworkError;\nvar init_system_errors = __esm({\n "src/core/errors/system-errors.ts"() {\n "use strict";\n init_types();\n NetworkError = class extends VeryfrontError {\n constructor(message, context) {\n super(message, "NETWORK_ERROR" /* NETWORK_ERROR */, context);\n this.name = "NetworkError";\n }\n };\n }\n});\n\n// src/core/errors/error-handlers.ts\nvar init_error_handlers = __esm({\n "src/core/errors/error-handlers.ts"() {\n "use strict";\n init_logger();\n init_types();\n }\n});\n\n// src/core/errors/error-codes.ts\nfunction getErrorDocsUrl(code) {\n return `https://veryfront.com/docs/errors/${code}`;\n}\nvar ErrorCode2;\nvar init_error_codes = __esm({\n "src/core/errors/error-codes.ts"() {\n "use strict";\n ErrorCode2 = {\n CONFIG_NOT_FOUND: "VF001",\n CONFIG_INVALID: "VF002",\n CONFIG_PARSE_ERROR: "VF003",\n CONFIG_VALIDATION_ERROR: "VF004",\n CONFIG_TYPE_ERROR: "VF005",\n IMPORT_MAP_INVALID: "VF006",\n CORS_CONFIG_INVALID: "VF007",\n BUILD_FAILED: "VF100",\n BUNDLE_ERROR: "VF101",\n TYPESCRIPT_ERROR: "VF102",\n MDX_COMPILE_ERROR: "VF103",\n ASSET_OPTIMIZATION_ERROR: "VF104",\n SSG_GENERATION_ERROR: "VF105",\n SOURCEMAP_ERROR: "VF106",\n HYDRATION_MISMATCH: "VF200",\n RENDER_ERROR: "VF201",\n COMPONENT_ERROR: "VF202",\n LAYOUT_NOT_FOUND: "VF203",\n PAGE_NOT_FOUND: "VF204",\n API_ERROR: "VF205",\n MIDDLEWARE_ERROR: "VF206",\n ROUTE_CONFLICT: "VF300",\n INVALID_ROUTE_FILE: "VF301",\n ROUTE_HANDLER_INVALID: "VF302",\n DYNAMIC_ROUTE_ERROR: "VF303",\n ROUTE_PARAMS_ERROR: "VF304",\n API_ROUTE_ERROR: "VF305",\n MODULE_NOT_FOUND: "VF400",\n IMPORT_RESOLUTION_ERROR: "VF401",\n CIRCULAR_DEPENDENCY: "VF402",\n INVALID_IMPORT: "VF403",\n DEPENDENCY_MISSING: "VF404",\n VERSION_MISMATCH: "VF405",\n PORT_IN_USE: "VF500",\n SERVER_START_ERROR: "VF501",\n HMR_ERROR: "VF502",\n CACHE_ERROR: "VF503",\n FILE_WATCH_ERROR: "VF504",\n REQUEST_ERROR: "VF505",\n CLIENT_BOUNDARY_VIOLATION: "VF600",\n SERVER_ONLY_IN_CLIENT: "VF601",\n CLIENT_ONLY_IN_SERVER: "VF602",\n INVALID_USE_CLIENT: "VF603",\n INVALID_USE_SERVER: "VF604",\n RSC_PAYLOAD_ERROR: "VF605",\n DEV_SERVER_ERROR: "VF700",\n FAST_REFRESH_ERROR: "VF701",\n ERROR_OVERLAY_ERROR: "VF702",\n SOURCE_MAP_ERROR: "VF703",\n DEPLOYMENT_ERROR: "VF800",\n PLATFORM_ERROR: "VF801",\n ENV_VAR_MISSING: "VF802",\n PRODUCTION_BUILD_REQUIRED: "VF803",\n UNKNOWN_ERROR: "VF900",\n PERMISSION_DENIED: "VF901",\n FILE_NOT_FOUND: "VF902",\n INVALID_ARGUMENT: "VF903",\n TIMEOUT_ERROR: "VF904"\n };\n }\n});\n\n// src/core/errors/catalog/factory.ts\nfunction createErrorSolution(code, config) {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code)\n };\n}\nfunction createSimpleError(code, title, message, steps) {\n return createErrorSolution(code, { title, message, steps });\n}\nvar init_factory = __esm({\n "src/core/errors/catalog/factory.ts"() {\n "use strict";\n init_error_codes();\n }\n});\n\n// src/core/errors/catalog/config-errors.ts\nvar CONFIG_ERROR_CATALOG;\nvar init_config_errors = __esm({\n "src/core/errors/catalog/config-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n CONFIG_ERROR_CATALOG = {\n [ErrorCode2.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode2.CONFIG_NOT_FOUND, {\n title: "Configuration file not found",\n message: "Veryfront could not find veryfront.config.js in your project root.",\n steps: [\n "Create veryfront.config.js in your project root directory",\n "Run \'veryfront init\' to generate a default configuration",\n "Or copy from an example project"\n ],\n example: `// veryfront.config.js\nexport default {\n title: "My App",\n dev: { port: 3002 }\n}`,\n tips: ["You can use .ts or .mjs extensions too", "Config is optional for simple projects"]\n }),\n [ErrorCode2.CONFIG_INVALID]: createErrorSolution(ErrorCode2.CONFIG_INVALID, {\n title: "Invalid configuration",\n message: "Your configuration file has invalid values or structure.",\n steps: [\n "Check that the config exports a default object",\n "Ensure all values are valid JavaScript types",\n "Remove any trailing commas",\n "Verify property names match the schema"\n ],\n example: `// \\u2713 Valid config\nexport default {\n title: "My App",\n dev: {\n port: 3002,\n open: true\n }\n}`\n }),\n [ErrorCode2.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_PARSE_ERROR,\n "Configuration parse error",\n "Failed to parse your configuration file.",\n [\n "Check for syntax errors (missing brackets, quotes, etc.)",\n "Ensure the file has valid JavaScript/TypeScript syntax",\n "Look for the specific parse error in the output above"\n ]\n ),\n [ErrorCode2.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_VALIDATION_ERROR,\n "Configuration validation failed",\n "Configuration values do not pass validation.",\n [\n "Check that port numbers are between 1-65535",\n "Ensure boolean flags are true/false (not strings)",\n "Verify URLs are properly formatted",\n "Check array/object structures match expected format"\n ]\n ),\n [ErrorCode2.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode2.CONFIG_TYPE_ERROR,\n "Configuration type error",\n "A configuration value has the wrong type.",\n [\n "Check that numbers are not in quotes",\n \'Ensure booleans are true/false, not "true"/"false"\',\n "Verify arrays use [] brackets",\n "Check objects use {} braces"\n ]\n ),\n [ErrorCode2.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode2.IMPORT_MAP_INVALID, {\n title: "Invalid import map",\n message: "The import map in your configuration is invalid.",\n steps: [\n "Check import map structure: { imports: {}, scopes: {} }",\n "Ensure URLs are valid and accessible",\n "Verify package names are correct"\n ],\n example: `resolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "@/utils": "./src/utils/index.ts"\n }\n }\n}`\n }),\n [ErrorCode2.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode2.CORS_CONFIG_INVALID, {\n title: "Invalid CORS configuration",\n message: "The CORS configuration is invalid.",\n steps: [\n "Use true for default CORS settings",\n "Or provide an object with origin, methods, headers",\n "Ensure origin is a string, not an array"\n ],\n example: `security: {\n cors: true // or { origin: "https://example.com" }\n}`\n })\n };\n }\n});\n\n// src/core/errors/catalog/build-errors.ts\nvar BUILD_ERROR_CATALOG;\nvar init_build_errors2 = __esm({\n "src/core/errors/catalog/build-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n BUILD_ERROR_CATALOG = {\n [ErrorCode2.BUILD_FAILED]: createErrorSolution(ErrorCode2.BUILD_FAILED, {\n title: "Build failed",\n message: "The build process encountered errors.",\n steps: [\n "Check the error messages above for specific issues",\n "Fix any TypeScript or syntax errors",\n "Ensure all imports can be resolved",\n "Run \'veryfront doctor\' to check your environment"\n ],\n tips: ["Try running with --verbose for more details", "Check build logs for warnings"]\n }),\n [ErrorCode2.BUNDLE_ERROR]: createSimpleError(\n ErrorCode2.BUNDLE_ERROR,\n "Bundle generation failed",\n "Failed to generate JavaScript bundles.",\n [\n "Check for circular dependencies",\n "Ensure all imports are valid",\n "Try clearing cache: veryfront clean"\n ]\n ),\n [ErrorCode2.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode2.TYPESCRIPT_ERROR,\n "TypeScript compilation error",\n "TypeScript found errors in your code.",\n [\n "Fix the TypeScript errors shown above",\n "Check your tsconfig.json configuration",\n "Ensure all types are properly imported"\n ]\n ),\n [ErrorCode2.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode2.MDX_COMPILE_ERROR, {\n title: "MDX compilation failed",\n message: "Failed to compile MDX file.",\n steps: [\n "Check for syntax errors in your MDX file",\n "Ensure frontmatter YAML is valid",\n "Verify JSX components are properly imported",\n "Check for unclosed tags or brackets"\n ],\n example: `---\ntitle: My Post\n---\n\nimport Button from \'./components/Button.jsx\'\n\n# Hello World\n\n<Button>Click me</Button>`\n }),\n [ErrorCode2.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode2.ASSET_OPTIMIZATION_ERROR,\n "Asset optimization failed",\n "Failed to optimize assets (images, CSS, etc.).",\n [\n "Check that asset files are valid",\n "Ensure file paths are correct",\n "Try disabling optimization temporarily"\n ]\n ),\n [ErrorCode2.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode2.SSG_GENERATION_ERROR,\n "Static site generation failed",\n "Failed to generate static pages.",\n [\n "Check that all routes are valid",\n "Ensure getStaticData functions return correctly",\n "Verify no dynamic content requires runtime"\n ]\n ),\n [ErrorCode2.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCEMAP_ERROR,\n "Source map generation failed",\n "Failed to generate source maps.",\n [\n "Try disabling source maps temporarily",\n "Check for very large files that might cause issues"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/runtime-errors.ts\nvar RUNTIME_ERROR_CATALOG;\nvar init_runtime_errors2 = __esm({\n "src/core/errors/catalog/runtime-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RUNTIME_ERROR_CATALOG = {\n [ErrorCode2.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode2.HYDRATION_MISMATCH, {\n title: "Hydration mismatch",\n message: "Client-side HTML does not match server-rendered HTML.",\n steps: [\n "Check for random values or timestamps in render",\n "Ensure Date() calls are consistent",\n "Avoid using browser-only APIs during SSR",\n "Check for white space or formatting differences"\n ],\n example: `// \\u274C Wrong - random on each render\n<div>{Math.random()}</div>\n\nconst [random, setRandom] = useState(0)\nuseEffect(() => setRandom(Math.random()), [])\n<div>{random}</div>`,\n relatedErrors: [ErrorCode2.RENDER_ERROR]\n }),\n [ErrorCode2.RENDER_ERROR]: createSimpleError(\n ErrorCode2.RENDER_ERROR,\n "Render error",\n "Failed to render component.",\n [\n "Check the component for errors",\n "Ensure all props are valid",\n "Look for null/undefined access",\n "Check error boundaries"\n ]\n ),\n [ErrorCode2.COMPONENT_ERROR]: createSimpleError(\n ErrorCode2.COMPONENT_ERROR,\n "Component error",\n "Error in component lifecycle or render.",\n [\n "Check component code for errors",\n "Ensure hooks follow Rules of Hooks",\n "Verify props are passed correctly"\n ]\n ),\n [ErrorCode2.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode2.LAYOUT_NOT_FOUND, {\n title: "Layout file not found",\n message: "Required layout file is missing.",\n steps: [\n "Create app/layout.tsx in App Router",\n "Or create layouts/default.mdx for Pages Router",\n "Check file path and name are correct"\n ],\n example: `// app/layout.tsx\nexport default function RootLayout({ children }) {\n return (\n <html lang="en">\n <body>{children}</body>\n </html>\n )\n}`\n }),\n [ErrorCode2.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode2.PAGE_NOT_FOUND,\n "Page not found",\n "The requested page does not exist.",\n [\n "Check that the page file exists",\n "Verify file name matches route",\n "Ensure file extension is correct (.tsx, .jsx, .mdx)"\n ]\n ),\n [ErrorCode2.API_ERROR]: createSimpleError(\n ErrorCode2.API_ERROR,\n "API handler error",\n "Error in API route handler.",\n [\n "Check API handler code for errors",\n "Ensure proper error handling",\n "Verify request/response format"\n ]\n ),\n [ErrorCode2.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode2.MIDDLEWARE_ERROR,\n "Middleware error",\n "Error in middleware execution.",\n [\n "Check middleware code for errors",\n "Ensure middleware returns Response",\n "Verify middleware is properly exported"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/route-errors.ts\nvar ROUTE_ERROR_CATALOG;\nvar init_route_errors = __esm({\n "src/core/errors/catalog/route-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n ROUTE_ERROR_CATALOG = {\n [ErrorCode2.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode2.ROUTE_CONFLICT,\n "Route conflict",\n "Multiple files are trying to handle the same route.",\n [\n "Check for duplicate route files",\n "Remove conflicting routes",\n "Use dynamic routes [id] carefully"\n ]\n ),\n [ErrorCode2.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode2.INVALID_ROUTE_FILE, {\n title: "Invalid route file",\n message: "Route file has invalid structure or exports.",\n steps: [\n "API routes must export GET, POST, etc. functions",\n "Page routes must export default component",\n "Check for syntax errors"\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] })\n}`\n }),\n [ErrorCode2.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode2.ROUTE_HANDLER_INVALID,\n "Invalid route handler",\n "Route handler does not return Response.",\n [\n "Ensure handler returns Response object",\n "Use Response.json() for JSON responses",\n "Check for missing return statement"\n ]\n ),\n [ErrorCode2.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.DYNAMIC_ROUTE_ERROR,\n "Dynamic route error",\n "Error in dynamic route handling.",\n [\n "Check [param] syntax is correct",\n "Ensure params are accessed properly",\n "Verify dynamic segment names"\n ]\n ),\n [ErrorCode2.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode2.ROUTE_PARAMS_ERROR,\n "Route parameters error",\n "Error accessing route parameters.",\n [\n "Check params object structure",\n "Ensure parameter names match route",\n "Verify params are strings"\n ]\n ),\n [ErrorCode2.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode2.API_ROUTE_ERROR,\n "API route error",\n "Error in API route execution.",\n [\n "Check API handler code",\n "Ensure proper error handling",\n "Verify request parsing"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/module-errors.ts\nvar MODULE_ERROR_CATALOG;\nvar init_module_errors = __esm({\n "src/core/errors/catalog/module-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n MODULE_ERROR_CATALOG = {\n [ErrorCode2.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode2.MODULE_NOT_FOUND, {\n title: "Module not found",\n message: "Cannot find the imported module.",\n steps: [\n "Check that the file path is correct",\n "Ensure the module is installed or exists",\n "Add missing module to import map",\n "Check for typos in import statement"\n ],\n example: `// Add to veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n "missing-lib": "https://esm.sh/missing-lib@1.0.0"\n }\n }\n}`\n }),\n [ErrorCode2.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode2.IMPORT_RESOLUTION_ERROR,\n "Import resolution failed",\n "Failed to resolve import specifier.",\n [\n "Check import paths are correct",\n "Ensure modules are in import map",\n "Verify network connectivity for remote imports"\n ]\n ),\n [ErrorCode2.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode2.CIRCULAR_DEPENDENCY,\n "Circular dependency detected",\n "Files are importing each other in a circle.",\n [\n "Identify the circular import chain",\n "Extract shared code to separate file",\n "Use dependency injection or lazy imports"\n ]\n ),\n [ErrorCode2.INVALID_IMPORT]: createSimpleError(\n ErrorCode2.INVALID_IMPORT,\n "Invalid import statement",\n "Import statement has invalid syntax.",\n [\n \'Check import syntax: import X from "y"\',\n "Ensure quotes are properly closed",\n "Verify export exists in target module"\n ]\n ),\n [ErrorCode2.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode2.DEPENDENCY_MISSING, {\n title: "Required dependency not found",\n message: "A required dependency is missing.",\n steps: [\n "Add React to your import map",\n "Ensure all peer dependencies are included",\n "Run \'veryfront doctor\' to verify setup"\n ],\n example: `// Minimum required imports\nresolve: {\n importMap: {\n imports: {\n "react": "https://esm.sh/react@19",\n "react-dom": "https://esm.sh/react-dom@19"\n }\n }\n}`\n }),\n [ErrorCode2.VERSION_MISMATCH]: createSimpleError(\n ErrorCode2.VERSION_MISMATCH,\n "Dependency version mismatch",\n "Incompatible versions of dependencies detected.",\n [\n "Ensure React and React-DOM versions match",\n "Check for multiple React instances",\n "Update dependencies to compatible versions"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/server-errors.ts\nvar SERVER_ERROR_CATALOG;\nvar init_server_errors = __esm({\n "src/core/errors/catalog/server-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n SERVER_ERROR_CATALOG = {\n [ErrorCode2.PORT_IN_USE]: createErrorSolution(ErrorCode2.PORT_IN_USE, {\n title: "Port already in use",\n message: "Another process is using the specified port.",\n steps: [\n "Stop the other process: lsof -i :PORT",\n "Use a different port: veryfront dev --port 3003",\n "Add port to config file"\n ],\n example: `// veryfront.config.js\ndev: {\n port: 3003\n}`\n }),\n [ErrorCode2.SERVER_START_ERROR]: createSimpleError(\n ErrorCode2.SERVER_START_ERROR,\n "Server failed to start",\n "Development server could not start.",\n [\n "Check for port conflicts",\n "Ensure file permissions are correct",\n "Verify configuration is valid"\n ]\n ),\n [ErrorCode2.HMR_ERROR]: createSimpleError(\n ErrorCode2.HMR_ERROR,\n "Hot Module Replacement error",\n "HMR failed to update module.",\n [\n "Try refreshing the page",\n "Check for syntax errors",\n "Restart dev server if persistent"\n ]\n ),\n [ErrorCode2.CACHE_ERROR]: createSimpleError(\n ErrorCode2.CACHE_ERROR,\n "Cache operation failed",\n "Error reading or writing cache.",\n [\n "Clear cache: veryfront clean --cache",\n "Check disk space",\n "Verify file permissions"\n ]\n ),\n [ErrorCode2.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode2.FILE_WATCH_ERROR,\n "File watching failed",\n "Could not watch files for changes.",\n [\n "Check system file watch limits",\n "Reduce number of watched files",\n "Try restarting dev server"\n ]\n ),\n [ErrorCode2.REQUEST_ERROR]: createSimpleError(\n ErrorCode2.REQUEST_ERROR,\n "Request handling error",\n "Error processing HTTP request.",\n [\n "Check request format and headers",\n "Verify route handler code",\n "Check for middleware errors"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/rsc-errors.ts\nvar RSC_ERROR_CATALOG;\nvar init_rsc_errors = __esm({\n "src/core/errors/catalog/rsc-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n RSC_ERROR_CATALOG = {\n [ErrorCode2.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode2.CLIENT_BOUNDARY_VIOLATION,\n {\n title: "Client/Server boundary violation",\n message: "Server-only code used in Client Component.",\n steps: [\n "Move server-only imports to Server Components",\n "Use \'use server\' for server actions",\n "Split component into server and client parts"\n ],\n example: `// \\u2713 Correct pattern\nimport { db } from \'./database\'\nexport default async function ServerComponent() {\n const data = await db.query(\'...\')\n return <ClientComponent data={data} />\n}\n\n\'use client\'\nexport default function ClientComponent({ data }) {\n return <div>{data}</div>\n}`\n }\n ),\n [ErrorCode2.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode2.SERVER_ONLY_IN_CLIENT,\n "Server-only module in Client Component",\n "Cannot use server-only module in client code.",\n [\n "Move server logic to Server Component",\n "Use API routes for client data fetching",\n "Pass data as props from server"\n ]\n ),\n [ErrorCode2.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode2.CLIENT_ONLY_IN_SERVER,\n "Client-only code in Server Component",\n "Cannot use browser APIs in Server Component.",\n [\n "Add \'use client\' directive",\n "Move client-only code to Client Component",\n "Use useEffect for client-side logic"\n ]\n ),\n [ErrorCode2.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode2.INVALID_USE_CLIENT, {\n title: "Invalid \'use client\' directive",\n message: "\'use client\' directive is not properly placed.",\n steps: [\n "Place \'use client\' at the very top of file",\n "Must be before any imports",\n \'Use exact string: "use client"\'\n ],\n example: `\'use client\' // Must be first line\n\nimport React from \'react\'`\n }),\n [ErrorCode2.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode2.INVALID_USE_SERVER,\n "Invalid \'use server\' directive",\n "\'use server\' directive is not properly placed.",\n [\n "Place \'use server\' at top of function",\n "Or at top of file for all functions",\n \'Use exact string: "use server"\'\n ]\n ),\n [ErrorCode2.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode2.RSC_PAYLOAD_ERROR,\n "RSC payload error",\n "Error serializing Server Component payload.",\n [\n "Ensure props are JSON-serializable",\n "Avoid passing functions as props",\n "Check for circular references"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/dev-errors.ts\nvar DEV_ERROR_CATALOG;\nvar init_dev_errors = __esm({\n "src/core/errors/catalog/dev-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEV_ERROR_CATALOG = {\n [ErrorCode2.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode2.DEV_SERVER_ERROR,\n "Development server error",\n "Error in development server.",\n [\n "Check server logs for details",\n "Try restarting dev server",\n "Clear cache and restart"\n ]\n ),\n [ErrorCode2.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode2.FAST_REFRESH_ERROR,\n "Fast Refresh error",\n "React Fast Refresh failed.",\n [\n "Check for syntax errors",\n "Ensure components follow Fast Refresh rules",\n "Try full page refresh"\n ]\n ),\n [ErrorCode2.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode2.ERROR_OVERLAY_ERROR,\n "Error overlay failed",\n "Could not display error overlay.",\n [\n "Check browser console for details",\n "Try disabling browser extensions",\n "Refresh the page"\n ]\n ),\n [ErrorCode2.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode2.SOURCE_MAP_ERROR,\n "Source map error",\n "Error loading or parsing source map.",\n [\n "Check that source maps are enabled",\n "Try rebuilding the project",\n "Check for corrupted build files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/deployment-errors.ts\nvar DEPLOYMENT_ERROR_CATALOG;\nvar init_deployment_errors = __esm({\n "src/core/errors/catalog/deployment-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n DEPLOYMENT_ERROR_CATALOG = {\n [ErrorCode2.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode2.DEPLOYMENT_ERROR,\n "Deployment failed",\n "Failed to deploy application.",\n [\n "Check deployment logs for details",\n "Verify platform credentials",\n "Ensure build succeeded first"\n ]\n ),\n [ErrorCode2.PLATFORM_ERROR]: createSimpleError(\n ErrorCode2.PLATFORM_ERROR,\n "Platform error",\n "Deployment platform returned an error.",\n [\n "Check platform status page",\n "Verify API keys and credentials",\n "Try deploying again"\n ]\n ),\n [ErrorCode2.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode2.ENV_VAR_MISSING,\n "Environment variable missing",\n "Required environment variable is not set.",\n [\n "Add variable to .env file",\n "Set variable in deployment platform",\n "Check variable name is correct"\n ]\n ),\n [ErrorCode2.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode2.PRODUCTION_BUILD_REQUIRED,\n "Production build required",\n "Must build project before deploying.",\n [\n "Run \'veryfront build\' first",\n "Check that dist/ directory exists",\n "Verify build completed successfully"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/general-errors.ts\nvar GENERAL_ERROR_CATALOG;\nvar init_general_errors = __esm({\n "src/core/errors/catalog/general-errors.ts"() {\n "use strict";\n init_error_codes();\n init_factory();\n GENERAL_ERROR_CATALOG = {\n [ErrorCode2.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode2.UNKNOWN_ERROR,\n "Unknown error",\n "An unexpected error occurred.",\n [\n "Check error details above",\n "Run \'veryfront doctor\' to diagnose",\n "Try restarting the operation",\n "Check GitHub issues for similar problems"\n ]\n ),\n [ErrorCode2.PERMISSION_DENIED]: createSimpleError(\n ErrorCode2.PERMISSION_DENIED,\n "Permission denied",\n "Insufficient permissions to perform operation.",\n [\n "Check file/directory permissions",\n "Run with appropriate permissions",\n "Verify user has write access"\n ]\n ),\n [ErrorCode2.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode2.FILE_NOT_FOUND,\n "File not found",\n "Required file does not exist.",\n [\n "Check that file path is correct",\n "Verify file exists in project",\n "Check for typos in file name"\n ]\n ),\n [ErrorCode2.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode2.INVALID_ARGUMENT,\n "Invalid argument",\n "Command received invalid argument.",\n [\n "Check command syntax",\n "Verify argument values",\n "Run \'veryfront help <command>\' for usage"\n ]\n ),\n [ErrorCode2.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode2.TIMEOUT_ERROR,\n "Operation timed out",\n "Operation took too long to complete.",\n [\n "Check network connectivity",\n "Try increasing timeout if available",\n "Check for very large files"\n ]\n )\n };\n }\n});\n\n// src/core/errors/catalog/index.ts\nvar ERROR_CATALOG;\nvar init_catalog = __esm({\n "src/core/errors/catalog/index.ts"() {\n "use strict";\n init_config_errors();\n init_build_errors2();\n init_runtime_errors2();\n init_route_errors();\n init_module_errors();\n init_server_errors();\n init_rsc_errors();\n init_dev_errors();\n init_deployment_errors();\n init_general_errors();\n init_factory();\n ERROR_CATALOG = {\n ...CONFIG_ERROR_CATALOG,\n ...BUILD_ERROR_CATALOG,\n ...RUNTIME_ERROR_CATALOG,\n ...ROUTE_ERROR_CATALOG,\n ...MODULE_ERROR_CATALOG,\n ...SERVER_ERROR_CATALOG,\n ...RSC_ERROR_CATALOG,\n ...DEV_ERROR_CATALOG,\n ...DEPLOYMENT_ERROR_CATALOG,\n ...GENERAL_ERROR_CATALOG\n };\n }\n});\n\n// src/core/errors/user-friendly/error-catalog.ts\nvar init_error_catalog = __esm({\n "src/core/errors/user-friendly/error-catalog.ts"() {\n "use strict";\n }\n});\n\n// src/platform/compat/runtime.ts\nvar isDeno, isNode, isBun, isCloudflare;\nvar init_runtime = __esm({\n "src/platform/compat/runtime.ts"() {\n "use strict";\n isDeno = typeof Deno !== "undefined";\n isNode = typeof globalThis.process !== "undefined" && globalThis.process?.versions?.node !== void 0;\n isBun = typeof globalThis.Bun !== "undefined";\n isCloudflare = typeof globalThis !== "undefined" && "caches" in globalThis && "WebSocketPair" in globalThis;\n }\n});\n\n// src/platform/compat/console/ansi.ts\nvar ansi, red, green, yellow, blue, magenta, cyan, white, gray, bold, dim, italic, underline, strikethrough, reset;\nvar init_ansi = __esm({\n "src/platform/compat/console/ansi.ts"() {\n ansi = (open, close) => (text2) => `\\x1B[${open}m${text2}\\x1B[${close}m`;\n red = ansi(31, 39);\n green = ansi(32, 39);\n yellow = ansi(33, 39);\n blue = ansi(34, 39);\n magenta = ansi(35, 39);\n cyan = ansi(36, 39);\n white = ansi(37, 39);\n gray = ansi(90, 39);\n bold = ansi(1, 22);\n dim = ansi(2, 22);\n italic = ansi(3, 23);\n underline = ansi(4, 24);\n strikethrough = ansi(9, 29);\n reset = (text2) => `\\x1B[0m${text2}`;\n }\n});\n\n// src/platform/compat/console/deno.ts\nvar deno_exports = {};\n__export(deno_exports, {\n blue: () => blue,\n bold: () => bold,\n colors: () => colors,\n cyan: () => cyan,\n dim: () => dim,\n gray: () => gray,\n green: () => green,\n italic: () => italic,\n magenta: () => magenta,\n red: () => red,\n reset: () => reset,\n strikethrough: () => strikethrough,\n underline: () => underline,\n white: () => white,\n yellow: () => yellow\n});\nvar colors;\nvar init_deno2 = __esm({\n "src/platform/compat/console/deno.ts"() {\n "use strict";\n init_ansi();\n colors = {\n red,\n green,\n yellow,\n blue,\n cyan,\n magenta,\n white,\n gray,\n bold,\n dim,\n italic,\n underline,\n strikethrough,\n reset\n };\n }\n});\n\n// src/platform/compat/console/node.ts\nvar node_exports = {};\n__export(node_exports, {\n blue: () => blue2,\n bold: () => bold2,\n colors: () => colors2,\n cyan: () => cyan2,\n dim: () => dim2,\n gray: () => gray2,\n green: () => green2,\n italic: () => italic2,\n magenta: () => magenta2,\n red: () => red2,\n reset: () => reset2,\n strikethrough: () => strikethrough2,\n underline: () => underline2,\n white: () => white2,\n yellow: () => yellow2\n});\nimport pc from "npm:picocolors";\nvar colors2, red2, green2, yellow2, blue2, cyan2, magenta2, white2, gray2, bold2, dim2, italic2, underline2, strikethrough2, reset2;\nvar init_node = __esm({\n "src/platform/compat/console/node.ts"() {\n "use strict";\n colors2 = {\n red: pc.red,\n green: pc.green,\n yellow: pc.yellow,\n blue: pc.blue,\n cyan: pc.cyan,\n magenta: pc.magenta,\n white: pc.white,\n gray: pc.gray,\n bold: pc.bold,\n dim: pc.dim,\n italic: pc.italic,\n underline: pc.underline,\n strikethrough: pc.strikethrough,\n reset: (text2) => pc.reset(text2)\n };\n red2 = pc.red;\n green2 = pc.green;\n yellow2 = pc.yellow;\n blue2 = pc.blue;\n cyan2 = pc.cyan;\n magenta2 = pc.magenta;\n white2 = pc.white;\n gray2 = pc.gray;\n bold2 = pc.bold;\n dim2 = pc.dim;\n italic2 = pc.italic;\n underline2 = pc.underline;\n strikethrough2 = pc.strikethrough;\n reset2 = (text2) => pc.reset(text2);\n }\n});\n\n// src/platform/compat/console/index.ts\nasync function loadColors() {\n if (_colors)\n return _colors;\n try {\n if (isDeno) {\n const mod = await Promise.resolve().then(() => (init_deno2(), deno_exports));\n _colors = mod.colors;\n } else {\n const mod = await Promise.resolve().then(() => (init_node(), node_exports));\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n return _colors;\n}\nvar noOp, fallbackColors, _colors, colorsPromise;\nvar init_console = __esm({\n "src/platform/compat/console/index.ts"() {\n init_runtime();\n noOp = (text2) => text2;\n fallbackColors = {\n red: noOp,\n green: noOp,\n yellow: noOp,\n blue: noOp,\n cyan: noOp,\n magenta: noOp,\n white: noOp,\n gray: noOp,\n bold: noOp,\n dim: noOp,\n italic: noOp,\n underline: noOp,\n strikethrough: noOp,\n reset: noOp\n };\n _colors = null;\n colorsPromise = loadColors();\n }\n});\n\n// src/core/errors/user-friendly/error-identifier.ts\nvar init_error_identifier = __esm({\n "src/core/errors/user-friendly/error-identifier.ts"() {\n "use strict";\n }\n});\n\n// src/core/errors/user-friendly/error-formatter.ts\nvar init_error_formatter = __esm({\n "src/core/errors/user-friendly/error-formatter.ts"() {\n "use strict";\n init_console();\n init_error_catalog();\n init_error_identifier();\n }\n});\n\n// src/platform/compat/process.ts\nimport process2 from "node:process";\nvar init_process = __esm({\n "src/platform/compat/process.ts"() {\n init_runtime();\n }\n});\n\n// src/core/errors/user-friendly/error-wrapper.ts\nvar init_error_wrapper = __esm({\n "src/core/errors/user-friendly/error-wrapper.ts"() {\n "use strict";\n init_console();\n init_process();\n init_logger();\n init_error_formatter();\n }\n});\n\n// src/core/errors/user-friendly/index.ts\nvar init_user_friendly = __esm({\n "src/core/errors/user-friendly/index.ts"() {\n "use strict";\n init_error_catalog();\n init_error_formatter();\n init_error_identifier();\n init_error_wrapper();\n }\n});\n\n// src/core/errors/index.ts\nvar init_errors = __esm({\n "src/core/errors/index.ts"() {\n init_types();\n init_agent_errors();\n init_build_errors();\n init_runtime_errors();\n init_system_errors();\n init_error_handlers();\n init_catalog();\n init_user_friendly();\n }\n});\n\n// src/platform/adapters/deno.ts\nvar DenoFileSystemAdapter, DenoEnvironmentAdapter, DenoServerAdapter, DenoShellAdapter, DenoServer, DenoAdapter, denoAdapter;\nvar init_deno3 = __esm({\n "src/platform/adapters/deno.ts"() {\n "use strict";\n init_veryfront_error();\n init_config();\n init_utils();\n DenoFileSystemAdapter = class {\n async readFile(path) {\n return await Deno.readTextFile(path);\n }\n async writeFile(path, content) {\n await Deno.writeTextFile(path, content);\n }\n async exists(path) {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n async *readDir(path) {\n for await (const entry of Deno.readDir(path)) {\n yield {\n name: entry.name,\n isFile: entry.isFile,\n isDirectory: entry.isDirectory,\n isSymlink: entry.isSymlink\n };\n }\n }\n async stat(path) {\n const stat = await Deno.stat(path);\n return {\n size: stat.size,\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n isSymlink: stat.isSymlink,\n mtime: stat.mtime\n };\n }\n async mkdir(path, options) {\n await Deno.mkdir(path, options);\n }\n async remove(path, options) {\n await Deno.remove(path, options);\n }\n async makeTempDir(prefix) {\n return await Deno.makeTempDir({ prefix });\n }\n watch(paths, options) {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n const denoIterator = watcher[Symbol.asyncIterator]();\n const mapEventKind = (kind) => {\n switch (kind) {\n case "create":\n return "create";\n case "modify":\n return "modify";\n case "remove":\n return "delete";\n default:\n return "any";\n }\n };\n const iterator = {\n async next() {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: void 0 };\n }\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths\n }\n };\n } catch (error2) {\n if (closed || signal?.aborted) {\n return { done: true, value: void 0 };\n }\n throw error2;\n }\n },\n async return() {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: void 0 };\n }\n };\n const cleanup = () => {\n if (closed)\n return;\n closed = true;\n try {\n if ("close" in watcher && typeof watcher.close === "function") {\n watcher.close();\n }\n } catch (error2) {\n serverLogger.debug("[Deno] Filesystem watcher cleanup failed", { error: error2 });\n }\n };\n if (signal) {\n signal.addEventListener("abort", cleanup);\n }\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup\n };\n }\n };\n DenoEnvironmentAdapter = class {\n get(key) {\n return Deno.env.get(key);\n }\n set(key, value) {\n Deno.env.set(key, value);\n }\n toObject() {\n return Deno.env.toObject();\n }\n };\n DenoServerAdapter = class {\n upgradeWebSocket(request) {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n };\n DenoShellAdapter = class {\n statSync(path) {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory\n };\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to stat file: ${error2}`\n }));\n }\n }\n readFileSync(path) {\n try {\n return Deno.readTextFileSync(path);\n } catch (error2) {\n throw toError(createError({\n type: "file",\n message: `Failed to read file: ${error2}`\n }));\n }\n }\n };\n DenoServer = class {\n constructor(server, hostname, port, abortController) {\n this.server = server;\n this.hostname = hostname;\n this.port = port;\n this.abortController = abortController;\n }\n async stop() {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n await this.server.shutdown();\n } catch (error2) {\n serverLogger.debug("[Deno] Server shutdown failed", { error: error2 });\n }\n }\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n };\n DenoAdapter = class {\n constructor() {\n this.id = "deno";\n this.name = "deno";\n /** @deprecated Use `id` instead */\n this.platform = "deno";\n this.fs = new DenoFileSystemAdapter();\n this.env = new DenoEnvironmentAdapter();\n this.server = new DenoServerAdapter();\n this.shell = new DenoShellAdapter();\n this.capabilities = {\n typescript: true,\n jsx: true,\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: true,\n // Deno KV available\n writableFs: true\n };\n /** @deprecated Use `capabilities` instead */\n this.features = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true\n };\n }\n serve(handler, options = {}) {\n const { port = DEFAULT_DEV_PORT, hostname = "localhost", onListen } = options;\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n const server = Deno.serve({\n port,\n hostname,\n signal,\n handler: async (request, _info) => {\n try {\n return await handler(request);\n } catch (error2) {\n const { serverLogger: serverLogger2 } = await Promise.resolve().then(() => (init_utils(), utils_exports));\n serverLogger2.error("Request handler error:", error2);\n return new Response("Internal Server Error", { status: 500 });\n }\n },\n onListen: (params) => {\n onListen?.({ hostname: params.hostname, port: params.port });\n }\n });\n const controllerToPass = options.signal ? void 0 : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n };\n denoAdapter = new DenoAdapter();\n }\n});\n\n// src/rendering/client/router.ts\ninit_utils();\nimport ReactDOM from "react-dom/client";\n\n// src/routing/matchers/pattern-route-matcher.ts\ninit_path_utils();\n\n// src/routing/matchers/index.ts\ninit_utils();\n\n// src/routing/slug-mapper/path-candidate-generator.ts\nimport { join } from "https://deno.land/std@0.220.0/path/mod.ts";\n\n// src/routing/client/dom-utils.ts\ninit_utils();\nfunction isInternalLink(target) {\n const href = target.getAttribute("href");\n if (!href)\n return false;\n if (href.startsWith("http") || href.startsWith("mailto:"))\n return false;\n if (href.startsWith("#"))\n return false;\n if (target.getAttribute("target") === "_blank" || target.getAttribute("download")) {\n return false;\n }\n return true;\n}\nfunction findAnchorElement(element) {\n let current = element;\n while (current && current.tagName !== "A") {\n current = current.parentElement;\n }\n if (!current || !(current instanceof HTMLAnchorElement)) {\n return null;\n }\n return current;\n}\nfunction updateMetaTags(frontmatter) {\n if (frontmatter.description) {\n updateMetaTag(\'meta[name="description"]\', "name", "description", frontmatter.description);\n }\n if (frontmatter.ogTitle) {\n updateMetaTag(\'meta[property="og:title"]\', "property", "og:title", frontmatter.ogTitle);\n }\n}\nfunction updateMetaTag(selector, attributeName, attributeValue, content) {\n let metaTag = document.querySelector(selector);\n if (!metaTag) {\n metaTag = document.createElement("meta");\n metaTag.setAttribute(attributeName, attributeValue);\n document.head.appendChild(metaTag);\n }\n metaTag.setAttribute("content", content);\n}\nfunction executeScripts(container) {\n const scripts = container.querySelectorAll("script");\n scripts.forEach((oldScript) => {\n const newScript = document.createElement("script");\n Array.from(oldScript.attributes).forEach((attribute) => {\n newScript.setAttribute(attribute.name, attribute.value);\n });\n newScript.textContent = oldScript.textContent;\n oldScript.parentNode?.replaceChild(newScript, oldScript);\n });\n}\nfunction applyHeadDirectives(container) {\n const nodes = container.querySelectorAll(\'[data-veryfront-head="1"], vf-head\');\n if (nodes.length > 0) {\n cleanManagedHeadTags();\n }\n nodes.forEach((wrapper) => {\n processHeadWrapper(wrapper);\n wrapper.parentElement?.removeChild(wrapper);\n });\n}\nfunction cleanManagedHeadTags() {\n document.head.querySelectorAll(\'[data-veryfront-managed="1"]\').forEach((element) => element.parentElement?.removeChild(element));\n}\nfunction processHeadWrapper(wrapper) {\n wrapper.childNodes.forEach((node) => {\n if (!(node instanceof Element))\n return;\n const tagName = node.tagName.toLowerCase();\n if (tagName === "title") {\n document.title = node.textContent || document.title;\n return;\n }\n const clone = document.createElement(tagName);\n for (const attribute of Array.from(node.attributes)) {\n clone.setAttribute(attribute.name, attribute.value);\n }\n if (node.textContent && !clone.hasAttribute("src")) {\n clone.textContent = node.textContent;\n }\n clone.setAttribute("data-veryfront-managed", "1");\n document.head.appendChild(clone);\n });\n}\nfunction manageFocus(container) {\n try {\n const focusElement = container.querySelector("[data-router-focus]") || container.querySelector("main") || container.querySelector("h1");\n if (focusElement && focusElement instanceof HTMLElement && "focus" in focusElement) {\n focusElement.focus({ preventScroll: true });\n }\n } catch (error2) {\n rendererLogger.warn("[router] focus management failed", error2);\n }\n}\nfunction extractPageDataFromScript() {\n const pageDataScript = document.querySelector("script[data-veryfront-page]");\n if (!pageDataScript)\n return null;\n try {\n const content = pageDataScript.textContent;\n if (!content) {\n rendererLogger.warn("[dom-utils] Page data script has no content");\n return {};\n }\n return JSON.parse(content);\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data:", error2);\n return null;\n }\n}\nfunction parsePageDataFromHTML(html3) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html3, "text/html");\n const root = doc.getElementById("root");\n let content = "";\n if (root) {\n content = root.innerHTML || "";\n } else {\n rendererLogger.warn("[dom-utils] No root element found in HTML");\n }\n const pageDataScript = doc.querySelector("script[data-veryfront-page]");\n let pageData = {};\n if (pageDataScript) {\n try {\n const content2 = pageDataScript.textContent;\n if (!content2) {\n rendererLogger.warn("[dom-utils] Page data script in HTML has no content");\n } else {\n pageData = JSON.parse(content2);\n }\n } catch (error2) {\n rendererLogger.error("[dom-utils] Failed to parse page data from HTML:", error2);\n }\n }\n return { content, pageData };\n}\n\n// src/routing/client/navigation-handlers.ts\ninit_utils();\ninit_config();\nvar NavigationHandlers = class {\n constructor(prefetchDelay = DEFAULT_PREFETCH_DELAY_MS, prefetchOptions = {}) {\n this.prefetchQueue = /* @__PURE__ */ new Set();\n this.scrollPositions = /* @__PURE__ */ new Map();\n this.isPopStateNav = false;\n this.prefetchDelay = prefetchDelay;\n this.prefetchOptions = prefetchOptions;\n }\n createClickHandler(callbacks) {\n return (event) => {\n const anchor = findAnchorElement(event.target);\n if (!anchor || !isInternalLink(anchor))\n return;\n const href = anchor.getAttribute("href");\n event.preventDefault();\n callbacks.onNavigate(href);\n };\n }\n createPopStateHandler(callbacks) {\n return (_event) => {\n const path = globalThis.location.pathname;\n this.isPopStateNav = true;\n callbacks.onNavigate(path);\n };\n }\n createMouseOverHandler(callbacks) {\n return (event) => {\n const target = event.target;\n if (target.tagName !== "A")\n return;\n const href = target.getAttribute("href");\n if (!href || href.startsWith("http") || href.startsWith("#"))\n return;\n if (!this.shouldPrefetchOnHover(target))\n return;\n if (!this.prefetchQueue.has(href)) {\n this.prefetchQueue.add(href);\n setTimeout(() => {\n callbacks.onPrefetch(href);\n this.prefetchQueue.delete(href);\n }, this.prefetchDelay);\n }\n };\n }\n shouldPrefetchOnHover(target) {\n const prefetchAttribute = target.getAttribute("data-prefetch");\n const isHoverEnabled = Boolean(this.prefetchOptions.hover);\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "true" || isHoverEnabled;\n }\n saveScrollPosition(path) {\n try {\n const scrollY = globalThis.scrollY;\n if (typeof scrollY === "number") {\n this.scrollPositions.set(path, scrollY);\n } else {\n rendererLogger.debug("[router] No valid scrollY value available");\n this.scrollPositions.set(path, 0);\n }\n } catch (error2) {\n rendererLogger.warn("[router] failed to record scroll position", error2);\n }\n }\n getScrollPosition(path) {\n const position = this.scrollPositions.get(path);\n if (position === void 0) {\n rendererLogger.debug(`[router] No scroll position stored for ${path}`);\n return 0;\n }\n return position;\n }\n isPopState() {\n return this.isPopStateNav;\n }\n clearPopStateFlag() {\n this.isPopStateNav = false;\n }\n clear() {\n this.prefetchQueue.clear();\n this.scrollPositions.clear();\n this.isPopStateNav = false;\n }\n};\n\n// src/routing/client/page-loader.ts\ninit_utils();\ninit_errors();\nvar PageLoader = class {\n constructor() {\n this.cache = /* @__PURE__ */ new Map();\n }\n getCached(path) {\n return this.cache.get(path);\n }\n isCached(path) {\n return this.cache.has(path);\n }\n setCache(path, data) {\n this.cache.set(path, data);\n }\n clearCache() {\n this.cache.clear();\n }\n async fetchPageData(path) {\n const jsonData = await this.tryFetchJSON(path);\n if (jsonData)\n return jsonData;\n return this.fetchAndParseHTML(path);\n }\n async tryFetchJSON(path) {\n try {\n const response = await fetch(`/_veryfront/data${path}.json`, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (response.ok) {\n return await response.json();\n }\n } catch (error2) {\n rendererLogger.debug(`[PageLoader] RSC fetch failed for ${path}, falling back to HTML:`, error2);\n }\n return null;\n }\n async fetchAndParseHTML(path) {\n const response = await fetch(path, {\n headers: { "X-Veryfront-Navigation": "client" }\n });\n if (!response.ok) {\n throw new NetworkError(`Failed to fetch ${path}`, {\n status: response.status,\n path\n });\n }\n const html3 = await response.text();\n const { content, pageData } = parsePageDataFromHTML(html3);\n return {\n html: content,\n ...pageData\n };\n }\n async loadPage(path) {\n const cachedData = this.getCached(path);\n if (cachedData) {\n rendererLogger.debug(`Loading ${path} from cache`);\n return cachedData;\n }\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n return data;\n }\n async prefetch(path) {\n if (this.isCached(path))\n return;\n rendererLogger.debug(`Prefetching ${path}`);\n try {\n const data = await this.fetchPageData(path);\n this.setCache(path, data);\n } catch (error2) {\n rendererLogger.warn(`Failed to prefetch ${path}`, error2);\n }\n }\n};\n\n// src/routing/client/page-transition.ts\ninit_utils();\ninit_config();\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERNS = [\n { pattern: /<script[^>]*>[\\s\\S]*?<\\/script>/gi, name: "inline script" },\n { pattern: /javascript:/gi, name: "javascript: URL" },\n { pattern: /\\bon\\w+\\s*=/gi, name: "event handler attribute" },\n { pattern: /data:\\s*text\\/html/gi, name: "data: HTML URL" }\n];\nfunction isDevMode() {\n if (typeof globalThis !== "undefined") {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n }\n return false;\n}\nfunction validateTrustedHtml(html3, options = {}) {\n const { strict = false, warn = true } = options;\n for (const { pattern, name } of SUSPICIOUS_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(html3)) {\n const message = `[Security] Suspicious ${name} detected in server HTML`;\n if (warn) {\n console.warn(message);\n }\n if (strict || !isDevMode()) {\n throw new Error(`Potentially unsafe HTML: ${name} detected`);\n }\n }\n }\n return html3;\n}\n\n// src/routing/client/page-transition.ts\nvar PageTransition = class {\n constructor(setupViewportPrefetch) {\n this.setupViewportPrefetch = setupViewportPrefetch;\n }\n destroy() {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n this.pendingTransitionTimeout = void 0;\n }\n }\n updatePage(data, isPopState, scrollY) {\n if (data.frontmatter?.title) {\n document.title = data.frontmatter.title;\n }\n updateMetaTags(data.frontmatter ?? {});\n const rootElement = document.getElementById("root");\n if (rootElement && (data.html ?? "") !== "") {\n this.performTransition(rootElement, data, isPopState, scrollY);\n }\n }\n performTransition(rootElement, data, isPopState, scrollY) {\n if (this.pendingTransitionTimeout !== void 0) {\n clearTimeout(this.pendingTransitionTimeout);\n }\n rootElement.style.opacity = "0";\n this.pendingTransitionTimeout = setTimeout(() => {\n this.pendingTransitionTimeout = void 0;\n rootElement.innerHTML = validateTrustedHtml(String(data.html ?? ""));\n rootElement.style.opacity = "1";\n executeScripts(rootElement);\n applyHeadDirectives(rootElement);\n this.setupViewportPrefetch(rootElement);\n manageFocus(rootElement);\n this.handleScroll(isPopState, scrollY);\n }, PAGE_TRANSITION_DELAY_MS);\n }\n handleScroll(isPopState, scrollY) {\n try {\n globalThis.scrollTo(0, isPopState ? scrollY : 0);\n } catch (error2) {\n rendererLogger.warn("[router] scroll handling failed", error2);\n }\n }\n showError(error2) {\n const rootElement = document.getElementById("root");\n if (!rootElement)\n return;\n const errorDiv = document.createElement("div");\n errorDiv.className = "veryfront-error-page";\n const heading = document.createElement("h1");\n heading.textContent = "Oops! Something went wrong";\n const message = document.createElement("p");\n message.textContent = error2.message;\n const button = document.createElement("button");\n button.type = "button";\n button.textContent = "Reload Page";\n button.onclick = () => globalThis.location.reload();\n errorDiv.appendChild(heading);\n errorDiv.appendChild(message);\n errorDiv.appendChild(button);\n rootElement.innerHTML = "";\n rootElement.appendChild(errorDiv);\n }\n setLoadingState(loading) {\n const indicator = document.getElementById("veryfront-loading");\n if (indicator) {\n indicator.style.display = loading ? "block" : "none";\n }\n document.body.classList.toggle("veryfront-loading", loading);\n }\n};\n\n// src/routing/client/viewport-prefetch.ts\ninit_utils();\nvar ViewportPrefetch = class {\n constructor(prefetchCallback, prefetchOptions = {}) {\n this.observer = null;\n this.prefetchCallback = prefetchCallback;\n this.prefetchOptions = prefetchOptions;\n }\n setup(root) {\n try {\n if (!("IntersectionObserver" in globalThis))\n return;\n if (this.observer)\n this.observer.disconnect();\n this.createObserver();\n this.observeLinks(root);\n } catch (error2) {\n rendererLogger.debug("[router] setupViewportPrefetch failed", error2);\n }\n }\n createObserver() {\n this.observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? entry.target instanceof HTMLAnchorElement : entry.target.tagName === "A";\n if (isAnchor) {\n const href = entry.target.getAttribute("href");\n if (href) {\n this.prefetchCallback(href);\n }\n this.observer?.unobserve(entry.target);\n }\n }\n }\n },\n { rootMargin: "200px" }\n );\n }\n observeLinks(root) {\n const anchors = root.querySelectorAll?.(\'a[href]:not([target="_blank"])\') ?? document.createDocumentFragment().querySelectorAll("a");\n const isViewportEnabled = Boolean(this.prefetchOptions.viewport);\n anchors.forEach((anchor) => {\n if (this.shouldObserveAnchor(anchor, isViewportEnabled)) {\n this.observer?.observe(anchor);\n }\n });\n }\n shouldObserveAnchor(anchor, isViewportEnabled) {\n const href = anchor.getAttribute("href") || "";\n if (!href || href.startsWith("http") || href.startsWith("#") || anchor.getAttribute("download")) {\n return false;\n }\n const prefetchAttribute = anchor.getAttribute("data-prefetch");\n if (prefetchAttribute === "false")\n return false;\n return prefetchAttribute === "viewport" || isViewportEnabled;\n }\n disconnect() {\n if (this.observer) {\n try {\n this.observer.disconnect();\n } catch (error2) {\n rendererLogger.warn("[router] prefetchObserver.disconnect failed", error2);\n }\n this.observer = null;\n }\n }\n};\n\n// src/routing/api/handler.ts\ninit_utils();\ninit_std_path();\ninit_config();\n\n// src/core/utils/lru-wrapper.ts\ninit_utils();\n\n// src/routing/api/handler.ts\ninit_veryfront_error();\n\n// src/security/http/response/constants.ts\nvar CONTENT_TYPES = {\n JSON: "application/json; charset=utf-8",\n HTML: "text/html; charset=utf-8",\n TEXT: "text/plain; charset=utf-8",\n JAVASCRIPT: "application/javascript; charset=utf-8",\n CSS: "text/css; charset=utf-8",\n XML: "application/xml; charset=utf-8"\n};\nvar CACHE_DURATIONS = {\n SHORT: 60,\n MEDIUM: 3600,\n LONG: 31536e3\n};\n\n// src/security/http/cors/validators.ts\ninit_logger();\n\n// src/observability/tracing/manager.ts\ninit_utils();\n\n// src/observability/tracing/config.ts\nvar DEFAULT_CONFIG2 = {\n enabled: false,\n exporter: "console",\n serviceName: "veryfront",\n sampleRate: 1,\n debug: false\n};\nfunction loadConfig(config = {}, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG2, ...config };\n if (adapter?.env) {\n applyEnvFromAdapter(finalConfig, adapter.env);\n } else {\n applyEnvFromDeno(finalConfig);\n }\n return finalConfig;\n}\nfunction applyEnvFromAdapter(config, envAdapter) {\n if (!envAdapter)\n return;\n const otelEnabled = envAdapter.get("OTEL_TRACES_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n const serviceName = envAdapter.get("OTEL_SERVICE_NAME");\n config.enabled = otelEnabled === "true" || veryfrontOtel === "1" || config.enabled;\n if (serviceName)\n config.serviceName = serviceName;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const tracesEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT");\n config.endpoint = otlpEndpoint || tracesEndpoint || config.endpoint;\n const exporterType = envAdapter.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n}\nfunction applyEnvFromDeno(config) {\n try {\n const denoEnv = globalThis.Deno?.env;\n if (!denoEnv)\n return;\n config.enabled = denoEnv.get("OTEL_TRACES_ENABLED") === "true" || denoEnv.get("VERYFRONT_OTEL") === "1" || config.enabled;\n config.serviceName = denoEnv.get("OTEL_SERVICE_NAME") || config.serviceName;\n config.endpoint = denoEnv.get("OTEL_EXPORTER_OTLP_ENDPOINT") || denoEnv.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT") || config.endpoint;\n const exporterType = denoEnv.get("OTEL_TRACES_EXPORTER");\n if (isValidExporter(exporterType)) {\n config.exporter = exporterType;\n }\n } catch {\n }\n}\nfunction isValidExporter(value) {\n return value === "jaeger" || value === "zipkin" || value === "otlp" || value === "console";\n}\n\n// src/observability/tracing/span-operations.ts\ninit_utils();\nvar SpanOperations = class {\n constructor(api, tracer2) {\n this.api = api;\n this.tracer = tracer2;\n }\n startSpan(name, options = {}) {\n try {\n const spanKind = this.mapSpanKind(options.kind);\n const span = this.tracer.startSpan(name, {\n kind: spanKind,\n attributes: options.attributes || {}\n }, options.parent);\n return span;\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to start span", { name, error: error2 });\n return null;\n }\n }\n endSpan(span, error2) {\n if (!span)\n return;\n try {\n if (error2) {\n span.recordException(error2);\n span.setStatus({\n code: this.api.SpanStatusCode.ERROR,\n message: error2.message\n });\n } else {\n span.setStatus({ code: this.api.SpanStatusCode.OK });\n }\n span.end();\n } catch (err) {\n serverLogger.debug("[tracing] Failed to end span", err);\n }\n }\n setAttributes(span, attributes) {\n if (!span)\n return;\n try {\n span.setAttributes(attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to set span attributes", error2);\n }\n }\n addEvent(span, name, attributes) {\n if (!span)\n return;\n try {\n span.addEvent(name, attributes);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to add span event", error2);\n }\n }\n createChildSpan(parentSpan, name, options = {}) {\n if (!parentSpan)\n return this.startSpan(name, options);\n try {\n const parentContext = this.api.trace.setSpan(this.api.context.active(), parentSpan);\n return this.startSpan(name, { ...options, parent: parentContext });\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to create child span", error2);\n return null;\n }\n }\n mapSpanKind(kind) {\n if (!kind)\n return this.api.SpanKind.INTERNAL;\n const kindMap = {\n "internal": this.api.SpanKind.INTERNAL,\n "server": this.api.SpanKind.SERVER,\n "client": this.api.SpanKind.CLIENT,\n "producer": this.api.SpanKind.PRODUCER,\n "consumer": this.api.SpanKind.CONSUMER\n };\n return kindMap[kind.toLowerCase()] || this.api.SpanKind.INTERNAL;\n }\n};\n\n// src/observability/tracing/context-propagation.ts\ninit_utils();\nvar ContextPropagation = class {\n constructor(api, propagator) {\n this.api = api;\n this.propagator = propagator;\n }\n extractContext(headers) {\n try {\n const carrier = {};\n headers.forEach((value, key) => {\n carrier[key] = value;\n });\n return this.api.propagation.extract(this.api.context.active(), carrier);\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to extract context from headers", error2);\n return void 0;\n }\n }\n injectContext(context, headers) {\n try {\n const carrier = {};\n this.api.propagation.inject(context, carrier);\n for (const [key, value] of Object.entries(carrier)) {\n headers.set(key, value);\n }\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to inject context into headers", error2);\n }\n }\n getActiveContext() {\n try {\n return this.api.context.active();\n } catch (error2) {\n serverLogger.debug("[tracing] Failed to get active context", error2);\n return void 0;\n }\n }\n async withActiveSpan(span, fn) {\n if (!span)\n return await fn();\n return await this.api.context.with(\n this.api.trace.setSpan(this.api.context.active(), span),\n fn\n );\n }\n withSpan(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n async withSpanAsync(name, fn, startSpan2, endSpan2) {\n const span = startSpan2(name);\n try {\n const result = await fn(span);\n endSpan2(span);\n return result;\n } catch (error2) {\n endSpan2(span, error2);\n throw error2;\n }\n }\n};\n\n// src/observability/tracing/manager.ts\nvar TracingManager = class {\n constructor() {\n this.state = {\n initialized: false,\n tracer: null,\n api: null,\n propagator: null\n };\n this.spanOps = null;\n this.contextProp = null;\n }\n async initialize(config = {}, adapter) {\n if (this.state.initialized) {\n serverLogger.debug("[tracing] Already initialized");\n return;\n }\n const finalConfig = loadConfig(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[tracing] Tracing disabled");\n this.state.initialized = true;\n return;\n }\n try {\n await this.initializeTracer(finalConfig);\n this.state.initialized = true;\n serverLogger.info("[tracing] OpenTelemetry tracing initialized", {\n exporter: finalConfig.exporter,\n serviceName: finalConfig.serviceName,\n endpoint: finalConfig.endpoint\n });\n } catch (error2) {\n serverLogger.warn("[tracing] Failed to initialize OpenTelemetry tracing", error2);\n this.state.initialized = true;\n }\n }\n async initializeTracer(config) {\n const api = await import("npm:@opentelemetry/api@1");\n this.state.api = api;\n this.state.tracer = api.trace.getTracer(config.serviceName || "veryfront", "0.1.0");\n const { W3CTraceContextPropagator } = await import("npm:@opentelemetry/core@1");\n this.state.propagator = new W3CTraceContextPropagator();\n api.propagation.setGlobalPropagator(this.state.propagator);\n if (this.state.api && this.state.tracer) {\n this.spanOps = new SpanOperations(this.state.api, this.state.tracer);\n }\n if (this.state.api && this.state.propagator) {\n this.contextProp = new ContextPropagation(this.state.api, this.state.propagator);\n }\n }\n isEnabled() {\n return this.state.initialized && this.state.tracer !== null;\n }\n getSpanOperations() {\n return this.spanOps;\n }\n getContextPropagation() {\n return this.contextProp;\n }\n getState() {\n return this.state;\n }\n shutdown() {\n if (!this.state.initialized)\n return;\n try {\n serverLogger.info("[tracing] Tracing shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[tracing] Error during tracing shutdown", error2);\n }\n }\n};\nvar tracingManager = new TracingManager();\n\n// src/observability/metrics/manager.ts\ninit_utils();\n\n// src/observability/metrics/config.ts\nvar DEFAULT_METRICS_COLLECT_INTERVAL_MS2 = 6e4;\nvar DEFAULT_CONFIG3 = {\n enabled: false,\n exporter: "console",\n prefix: "veryfront",\n collectInterval: DEFAULT_METRICS_COLLECT_INTERVAL_MS2,\n debug: false\n};\nfunction loadConfig2(config, adapter) {\n const finalConfig = { ...DEFAULT_CONFIG3, ...config };\n if (adapter?.env) {\n const envAdapter = adapter.env;\n const otelEnabled = envAdapter.get("OTEL_METRICS_ENABLED");\n const veryfrontOtel = envAdapter.get("VERYFRONT_OTEL");\n finalConfig.enabled = otelEnabled === "true" || veryfrontOtel === "1" || finalConfig.enabled;\n const otlpEndpoint = envAdapter.get("OTEL_EXPORTER_OTLP_ENDPOINT");\n const metricsEndpoint = envAdapter.get(\n "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"\n );\n finalConfig.endpoint = otlpEndpoint || metricsEndpoint || finalConfig.endpoint;\n const exporterType = envAdapter.get("OTEL_METRICS_EXPORTER");\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n } else {\n try {\n const env = process.env;\n if (env) {\n finalConfig.enabled = env.OTEL_METRICS_ENABLED === "true" || env.VERYFRONT_OTEL === "1" || finalConfig.enabled;\n finalConfig.endpoint = env.OTEL_EXPORTER_OTLP_ENDPOINT || env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT || finalConfig.endpoint;\n const exporterType = env.OTEL_METRICS_EXPORTER;\n if (exporterType === "prometheus" || exporterType === "otlp" || exporterType === "console") {\n finalConfig.exporter = exporterType;\n }\n }\n } catch {\n }\n }\n return finalConfig;\n}\nfunction getMemoryUsage() {\n try {\n if (process?.memoryUsage) {\n return process.memoryUsage();\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// src/observability/instruments/instruments-factory.ts\ninit_utils();\n\n// src/observability/instruments/build-instruments.ts\ninit_config();\nfunction createBuildInstruments(meter, config) {\n const buildDuration = meter.createHistogram(\n `${config.prefix}.build.duration`,\n {\n description: "Build operation duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const bundleSizeHistogram = meter.createHistogram(\n `${config.prefix}.build.bundle.size`,\n {\n description: "Bundle size distribution",\n unit: "kb",\n advice: { explicitBucketBoundaries: SIZE_HISTOGRAM_BOUNDARIES_KB }\n }\n );\n const bundleCounter = meter.createCounter(\n `${config.prefix}.build.bundles`,\n {\n description: "Total number of bundles created",\n unit: "bundles"\n }\n );\n return {\n buildDuration,\n bundleSizeHistogram,\n bundleCounter\n };\n}\n\n// src/observability/instruments/cache-instruments.ts\nfunction createCacheInstruments(meter, config, runtimeState) {\n const cacheGetCounter = meter.createCounter(\n `${config.prefix}.cache.gets`,\n {\n description: "Total number of cache get operations",\n unit: "operations"\n }\n );\n const cacheHitCounter = meter.createCounter(\n `${config.prefix}.cache.hits`,\n {\n description: "Total number of cache hits",\n unit: "hits"\n }\n );\n const cacheMissCounter = meter.createCounter(\n `${config.prefix}.cache.misses`,\n {\n description: "Total number of cache misses",\n unit: "misses"\n }\n );\n const cacheSetCounter = meter.createCounter(\n `${config.prefix}.cache.sets`,\n {\n description: "Total number of cache set operations",\n unit: "operations"\n }\n );\n const cacheInvalidateCounter = meter.createCounter(\n `${config.prefix}.cache.invalidations`,\n {\n description: "Total number of cache invalidations",\n unit: "operations"\n }\n );\n const cacheSizeGauge = meter.createObservableGauge(\n `${config.prefix}.cache.size`,\n {\n description: "Current cache size",\n unit: "entries"\n }\n );\n cacheSizeGauge.addCallback((result) => {\n result.observe(runtimeState.cacheSize);\n });\n return {\n cacheGetCounter,\n cacheHitCounter,\n cacheMissCounter,\n cacheSetCounter,\n cacheInvalidateCounter,\n cacheSizeGauge\n };\n}\n\n// src/observability/instruments/data-instruments.ts\ninit_config();\nfunction createDataInstruments(meter, config) {\n const dataFetchDuration = meter.createHistogram(\n `${config.prefix}.data.fetch.duration`,\n {\n description: "Data fetch duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const dataFetchCounter = meter.createCounter(\n `${config.prefix}.data.fetch.count`,\n {\n description: "Total number of data fetches",\n unit: "fetches"\n }\n );\n const dataFetchErrorCounter = meter.createCounter(\n `${config.prefix}.data.fetch.errors`,\n {\n description: "Data fetch errors",\n unit: "errors"\n }\n );\n return {\n dataFetchDuration,\n dataFetchCounter,\n dataFetchErrorCounter\n };\n}\n\n// src/observability/instruments/http-instruments.ts\ninit_config();\nfunction createHttpInstruments(meter, config) {\n const httpRequestCounter = meter.createCounter(\n `${config.prefix}.http.requests`,\n {\n description: "Total number of HTTP requests",\n unit: "requests"\n }\n );\n const httpRequestDuration = meter.createHistogram(\n `${config.prefix}.http.request.duration`,\n {\n description: "HTTP request duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const httpActiveRequests = meter.createUpDownCounter(\n `${config.prefix}.http.requests.active`,\n {\n description: "Number of active HTTP requests",\n unit: "requests"\n }\n );\n return {\n httpRequestCounter,\n httpRequestDuration,\n httpActiveRequests\n };\n}\n\n// src/observability/instruments/memory-instruments.ts\nfunction createMemoryInstruments(meter, config) {\n const memoryUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.usage`,\n {\n description: "Memory usage",\n unit: "bytes"\n }\n );\n memoryUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.rss);\n }\n });\n const heapUsageGauge = meter.createObservableGauge(\n `${config.prefix}.memory.heap`,\n {\n description: "Heap memory usage",\n unit: "bytes"\n }\n );\n heapUsageGauge.addCallback((result) => {\n const memoryUsage = getMemoryUsage();\n if (memoryUsage) {\n result.observe(memoryUsage.heapUsed);\n }\n });\n return {\n memoryUsageGauge,\n heapUsageGauge\n };\n}\n\n// src/observability/instruments/render-instruments.ts\ninit_config();\nfunction createRenderInstruments(meter, config) {\n const renderDuration = meter.createHistogram(\n `${config.prefix}.render.duration`,\n {\n description: "Page render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const renderCounter = meter.createCounter(\n `${config.prefix}.render.count`,\n {\n description: "Total number of page renders",\n unit: "renders"\n }\n );\n const renderErrorCounter = meter.createCounter(\n `${config.prefix}.render.errors`,\n {\n description: "Total number of render errors",\n unit: "errors"\n }\n );\n return {\n renderDuration,\n renderCounter,\n renderErrorCounter\n };\n}\n\n// src/observability/instruments/rsc-instruments.ts\ninit_config();\nfunction createRscInstruments(meter, config) {\n const rscRenderDuration = meter.createHistogram(\n `${config.prefix}.rsc.render.duration`,\n {\n description: "RSC render duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscStreamDuration = meter.createHistogram(\n `${config.prefix}.rsc.stream.duration`,\n {\n description: "RSC stream duration",\n unit: "ms",\n advice: { explicitBucketBoundaries: DURATION_HISTOGRAM_BOUNDARIES_MS }\n }\n );\n const rscManifestCounter = meter.createCounter(\n `${config.prefix}.rsc.manifest`,\n {\n description: "RSC manifest requests",\n unit: "requests"\n }\n );\n const rscPageCounter = meter.createCounter(\n `${config.prefix}.rsc.page`,\n {\n description: "RSC page requests",\n unit: "requests"\n }\n );\n const rscStreamCounter = meter.createCounter(\n `${config.prefix}.rsc.stream`,\n {\n description: "RSC stream requests",\n unit: "requests"\n }\n );\n const rscActionCounter = meter.createCounter(\n `${config.prefix}.rsc.action`,\n {\n description: "RSC action requests",\n unit: "requests"\n }\n );\n const rscErrorCounter = meter.createCounter(\n `${config.prefix}.rsc.errors`,\n {\n description: "RSC errors",\n unit: "errors"\n }\n );\n return {\n rscRenderDuration,\n rscStreamDuration,\n rscManifestCounter,\n rscPageCounter,\n rscStreamCounter,\n rscActionCounter,\n rscErrorCounter\n };\n}\n\n// src/observability/instruments/instruments-factory.ts\nasync function initializeInstruments(meter, config, runtimeState) {\n const instruments = {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n try {\n const httpInstruments = createHttpInstruments(meter, config);\n Object.assign(instruments, httpInstruments);\n const cacheInstruments = createCacheInstruments(meter, config, runtimeState);\n Object.assign(instruments, cacheInstruments);\n const renderInstruments = createRenderInstruments(meter, config);\n Object.assign(instruments, renderInstruments);\n const rscInstruments = createRscInstruments(meter, config);\n Object.assign(instruments, rscInstruments);\n const buildInstruments = createBuildInstruments(meter, config);\n Object.assign(instruments, buildInstruments);\n const dataInstruments = createDataInstruments(meter, config);\n Object.assign(instruments, dataInstruments);\n const memoryInstruments = createMemoryInstruments(meter, config);\n Object.assign(instruments, memoryInstruments);\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize metric instruments", error2);\n }\n return instruments;\n}\n\n// src/observability/metrics/recorder.ts\nvar MetricsRecorder = class {\n constructor(instruments, runtimeState) {\n this.instruments = instruments;\n this.runtimeState = runtimeState;\n }\n recordHttpRequest(attributes) {\n this.instruments.httpRequestCounter?.add(1, attributes);\n this.instruments.httpActiveRequests?.add(1, attributes);\n this.runtimeState.activeRequests++;\n }\n recordHttpRequestComplete(durationMs, attributes) {\n this.instruments.httpRequestDuration?.record(durationMs, attributes);\n this.instruments.httpActiveRequests?.add(-1, attributes);\n this.runtimeState.activeRequests--;\n }\n recordCacheGet(hit, attributes) {\n this.instruments.cacheGetCounter?.add(1, attributes);\n if (hit) {\n this.instruments.cacheHitCounter?.add(1, attributes);\n } else {\n this.instruments.cacheMissCounter?.add(1, attributes);\n }\n }\n recordCacheSet(attributes) {\n this.instruments.cacheSetCounter?.add(1, attributes);\n this.runtimeState.cacheSize++;\n }\n recordCacheInvalidate(count, attributes) {\n this.instruments.cacheInvalidateCounter?.add(count, attributes);\n this.runtimeState.cacheSize = Math.max(\n 0,\n this.runtimeState.cacheSize - count\n );\n }\n setCacheSize(size) {\n this.runtimeState.cacheSize = size;\n }\n // Render Metrics\n recordRender(durationMs, attributes) {\n this.instruments.renderDuration?.record(durationMs, attributes);\n this.instruments.renderCounter?.add(1, attributes);\n }\n recordRenderError(attributes) {\n this.instruments.renderErrorCounter?.add(1, attributes);\n }\n // RSC Metrics\n recordRSCRender(durationMs, attributes) {\n this.instruments.rscRenderDuration?.record(durationMs, attributes);\n }\n recordRSCStream(durationMs, attributes) {\n this.instruments.rscStreamDuration?.record(durationMs, attributes);\n }\n recordRSCRequest(type, attributes) {\n switch (type) {\n case "manifest":\n this.instruments.rscManifestCounter?.add(1, attributes);\n break;\n case "page":\n this.instruments.rscPageCounter?.add(1, attributes);\n break;\n case "stream":\n this.instruments.rscStreamCounter?.add(1, attributes);\n break;\n case "action":\n this.instruments.rscActionCounter?.add(1, attributes);\n break;\n }\n }\n recordRSCError(attributes) {\n this.instruments.rscErrorCounter?.add(1, attributes);\n }\n // Build Metrics\n recordBuild(durationMs, attributes) {\n this.instruments.buildDuration?.record(durationMs, attributes);\n }\n recordBundle(sizeKb, attributes) {\n this.instruments.bundleSizeHistogram?.record(sizeKb, attributes);\n this.instruments.bundleCounter?.add(1, attributes);\n }\n // Data Fetching Metrics\n recordDataFetch(durationMs, attributes) {\n this.instruments.dataFetchDuration?.record(durationMs, attributes);\n this.instruments.dataFetchCounter?.add(1, attributes);\n }\n recordDataFetchError(attributes) {\n this.instruments.dataFetchErrorCounter?.add(1, attributes);\n }\n // Security Metrics\n recordCorsRejection(attributes) {\n this.instruments.corsRejectionCounter?.add(1, attributes);\n }\n recordSecurityHeaders(attributes) {\n this.instruments.securityHeadersCounter?.add(1, attributes);\n }\n};\n\n// src/observability/metrics/manager.ts\nvar MetricsManager = class {\n constructor() {\n this.initialized = false;\n this.meter = null;\n this.api = null;\n this.recorder = null;\n this.instruments = this.createEmptyInstruments();\n this.runtimeState = {\n cacheSize: 0,\n activeRequests: 0\n };\n this.recorder = new MetricsRecorder(this.instruments, this.runtimeState);\n }\n createEmptyInstruments() {\n return {\n httpRequestCounter: null,\n httpRequestDuration: null,\n httpActiveRequests: null,\n cacheGetCounter: null,\n cacheHitCounter: null,\n cacheMissCounter: null,\n cacheSetCounter: null,\n cacheInvalidateCounter: null,\n cacheSizeGauge: null,\n renderDuration: null,\n renderCounter: null,\n renderErrorCounter: null,\n rscRenderDuration: null,\n rscStreamDuration: null,\n rscManifestCounter: null,\n rscPageCounter: null,\n rscStreamCounter: null,\n rscActionCounter: null,\n rscErrorCounter: null,\n buildDuration: null,\n bundleSizeHistogram: null,\n bundleCounter: null,\n dataFetchDuration: null,\n dataFetchCounter: null,\n dataFetchErrorCounter: null,\n corsRejectionCounter: null,\n securityHeadersCounter: null,\n memoryUsageGauge: null,\n heapUsageGauge: null\n };\n }\n async initialize(config = {}, adapter) {\n if (this.initialized) {\n serverLogger.debug("[metrics] Already initialized");\n return;\n }\n const finalConfig = loadConfig2(config, adapter);\n if (!finalConfig.enabled) {\n serverLogger.debug("[metrics] Metrics collection disabled");\n this.initialized = true;\n return;\n }\n try {\n this.api = await import("npm:@opentelemetry/api@1");\n this.meter = this.api.metrics.getMeter(finalConfig.prefix, "0.1.0");\n this.instruments = await initializeInstruments(\n this.meter,\n finalConfig,\n this.runtimeState\n );\n if (this.recorder) {\n this.recorder.instruments = this.instruments;\n }\n this.initialized = true;\n serverLogger.info("[metrics] OpenTelemetry metrics initialized", {\n exporter: finalConfig.exporter,\n endpoint: finalConfig.endpoint,\n prefix: finalConfig.prefix\n });\n } catch (error2) {\n serverLogger.warn("[metrics] Failed to initialize OpenTelemetry metrics", error2);\n this.initialized = true;\n }\n }\n isEnabled() {\n return this.initialized && this.meter !== null;\n }\n getRecorder() {\n return this.recorder;\n }\n getState() {\n return {\n initialized: this.initialized,\n cacheSize: this.runtimeState.cacheSize,\n activeRequests: this.runtimeState.activeRequests\n };\n }\n shutdown() {\n if (!this.initialized)\n return;\n try {\n serverLogger.info("[metrics] Metrics shutdown initiated");\n } catch (error2) {\n serverLogger.warn("[metrics] Error during metrics shutdown", error2);\n }\n }\n};\nvar metricsManager = new MetricsManager();\n\n// src/observability/metrics/index.ts\nvar getRecorder = () => metricsManager.getRecorder();\nfunction recordCorsRejection(attributes) {\n getRecorder()?.recordCorsRejection?.(attributes);\n}\nfunction recordSecurityHeaders(attributes) {\n getRecorder()?.recordSecurityHeaders?.(attributes);\n}\n\n// src/observability/auto-instrument/orchestrator.ts\ninit_utils();\n\n// src/observability/auto-instrument/http-instrumentation.ts\ninit_utils();\nimport {\n context as otContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n trace\n} from "npm:@opentelemetry/api@1";\nvar tracer = trace.getTracer("veryfront-http");\n\n// src/security/http/cors/validators.ts\nasync function validateOrigin(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = await corsConfig.origin(requestOrigin);\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\nfunction validateOriginSync(requestOrigin, config) {\n if (!config) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (config === true) {\n const origin = requestOrigin || "*";\n return { allowedOrigin: origin, allowCredentials: false };\n }\n const corsConfig = config;\n if (!corsConfig.origin) {\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (!requestOrigin) {\n if (corsConfig.origin === "*") {\n return { allowedOrigin: "*", allowCredentials: false };\n }\n return { allowedOrigin: null, allowCredentials: false };\n }\n if (corsConfig.origin === "*") {\n if (corsConfig.credentials) {\n serverLogger.warn("[CORS] Cannot use credentials with wildcard origin - denying");\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Cannot use credentials with wildcard origin"\n };\n }\n return { allowedOrigin: "*", allowCredentials: false };\n }\n if (typeof corsConfig.origin === "function") {\n try {\n const result = corsConfig.origin(requestOrigin);\n if (result instanceof Promise) {\n serverLogger.warn(\n "[CORS] Async origin validators are not supported in synchronous contexts"\n );\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Async origin validators not supported"\n };\n }\n if (typeof result === "string") {\n return {\n allowedOrigin: result,\n allowCredentials: corsConfig.credentials ?? false\n };\n }\n const allowed = result === true;\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin rejected by validation function"\n };\n } catch (error2) {\n serverLogger.error("[CORS] Origin validation function error", error2);\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Origin validation error"\n };\n }\n }\n if (Array.isArray(corsConfig.origin)) {\n const allowed = corsConfig.origin.includes(requestOrigin);\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin not in allowlist (sync)", {\n requestOrigin,\n allowedOrigins: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin not in allowlist"\n };\n }\n if (typeof corsConfig.origin === "string") {\n const allowed = corsConfig.origin === requestOrigin;\n if (!allowed) {\n recordCorsRejection();\n serverLogger.warn("[CORS] Origin does not match (sync)", {\n requestOrigin,\n expectedOrigin: corsConfig.origin\n });\n }\n return {\n allowedOrigin: allowed ? requestOrigin : null,\n allowCredentials: allowed && (corsConfig.credentials ?? false),\n error: allowed ? void 0 : "Origin does not match"\n };\n }\n return {\n allowedOrigin: null,\n allowCredentials: false,\n error: "Invalid origin configuration"\n };\n}\n\n// src/security/http/cors/headers.ts\nasync function applyCORSHeaders(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = await validateOrigin(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\nfunction applyCORSHeadersSync(options) {\n const { request, response, headers: headersObj, config } = options;\n const validation = validateOriginSync(request.headers.get("origin"), config);\n if (!validation.allowedOrigin) {\n return response;\n }\n const headers = headersObj || (response ? new Headers(response.headers) : new Headers());\n headers.set("Access-Control-Allow-Origin", validation.allowedOrigin);\n if (validation.allowedOrigin !== "*") {\n const existingVary = headers.get("Vary");\n const varyValues = existingVary ? existingVary.split(",").map((v) => v.trim()) : [];\n if (!varyValues.includes("Origin")) {\n varyValues.push("Origin");\n headers.set("Vary", varyValues.join(", "));\n }\n }\n if (validation.allowCredentials && validation.allowedOrigin !== "*") {\n headers.set("Access-Control-Allow-Credentials", "true");\n }\n const corsConfig = typeof config === "object" ? config : null;\n if (corsConfig?.exposedHeaders && corsConfig.exposedHeaders.length > 0) {\n headers.set("Access-Control-Expose-Headers", corsConfig.exposedHeaders.join(", "));\n }\n if (response) {\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers\n });\n }\n return;\n}\n\n// src/security/http/cors/constants.ts\ninit_config();\n\n// src/security/http/cors/preflight.ts\ninit_logger();\n\n// src/security/http/cors/middleware.ts\ninit_veryfront_error();\n\n// src/security/http/response/security-handler.ts\nfunction generateNonce() {\n const array = new Uint8Array(16);\n crypto.getRandomValues(array);\n return btoa(String.fromCharCode(...array));\n}\nfunction buildCSP(isDev, nonce, cspUserHeader, config, adapter) {\n const envCsp = adapter?.env?.get?.("VERYFRONT_CSP");\n if (envCsp?.trim())\n return envCsp.replace(/{NONCE}/g, nonce);\n const defaultCsp = isDev ? [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\' \'unsafe-inline\' https://esm.sh https://cdnjs.cloudflare.com https://cdn.veryfront.com https://cdn.jsdelivr.net`,\n "img-src \'self\' data: https://cdn.veryfront.com https://cdnjs.cloudflare.com",\n `script-src \'self\' \'nonce-${nonce}\' \'unsafe-eval\' https://esm.sh https://cdn.tailwindcss.com`,\n "connect-src \'self\' https://esm.sh ws://localhost:* wss://localhost:*",\n "font-src \'self\' data: https://cdnjs.cloudflare.com"\n ].join("; ") : [\n "default-src \'self\'",\n `style-src \'self\' \'nonce-${nonce}\'`,\n "img-src \'self\' data:",\n `script-src \'self\' \'nonce-${nonce}\'`,\n "connect-src \'self\'"\n ].join("; ");\n if (cspUserHeader?.trim()) {\n return `${cspUserHeader.replace(/{NONCE}/g, nonce)}; ${defaultCsp}`;\n }\n const cfgCsp = config?.csp;\n if (cfgCsp && typeof cfgCsp === "object") {\n const pieces = [];\n for (const [k, v] of Object.entries(cfgCsp)) {\n if (v === void 0)\n continue;\n const key = String(k).replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);\n const val = Array.isArray(v) ? v.join(" ") : String(v);\n pieces.push(`${key} ${val}`.replace(/{NONCE}/g, nonce));\n }\n if (pieces.length > 0) {\n return `${pieces.join("; ")}; ${defaultCsp}`;\n }\n }\n return defaultCsp;\n}\nfunction getSecurityHeader(headerName, defaultValue, config, adapter) {\n const configKey = headerName.toLowerCase();\n const configValue = config?.[configKey];\n const envValue = adapter?.env?.get?.(`VERYFRONT_${headerName}`);\n return (typeof configValue === "string" ? configValue : void 0) || envValue || defaultValue;\n}\nfunction applySecurityHeaders(headers, isDev, nonce, cspUserHeader, config, adapter) {\n const getHeaderOverride = (name) => {\n const overrides = config?.headers;\n if (!overrides)\n return void 0;\n const lower = name.toLowerCase();\n for (const [key, value] of Object.entries(overrides)) {\n if (key.toLowerCase() === lower) {\n return value;\n }\n }\n return void 0;\n };\n const contentTypeOptions = getHeaderOverride("x-content-type-options") ?? "nosniff";\n headers.set("X-Content-Type-Options", contentTypeOptions);\n const frameOptions = getHeaderOverride("x-frame-options") ?? "DENY";\n headers.set("X-Frame-Options", frameOptions);\n const xssProtection = getHeaderOverride("x-xss-protection") ?? "1; mode=block";\n headers.set("X-XSS-Protection", xssProtection);\n const csp = buildCSP(isDev, nonce, cspUserHeader, config, adapter);\n if (csp) {\n headers.set("Content-Security-Policy", csp);\n }\n if (!isDev) {\n const hstsMaxAge = config?.hsts?.maxAge ?? 31536e3;\n const hstsIncludeSubDomains = config?.hsts?.includeSubDomains ?? true;\n const hstsPreload = config?.hsts?.preload ?? false;\n let hstsValue = `max-age=${hstsMaxAge}`;\n if (hstsIncludeSubDomains) {\n hstsValue += "; includeSubDomains";\n }\n if (hstsPreload) {\n hstsValue += "; preload";\n }\n const hstsOverride = getHeaderOverride("strict-transport-security");\n headers.set("Strict-Transport-Security", hstsOverride ?? hstsValue);\n }\n const coop = getSecurityHeader("COOP", "same-origin", config, adapter);\n const corp = getSecurityHeader("CORP", "same-origin", config, adapter);\n const coep = getSecurityHeader("COEP", "", config, adapter);\n headers.set("Cross-Origin-Opener-Policy", coop);\n headers.set("Cross-Origin-Resource-Policy", corp);\n if (coep) {\n headers.set("Cross-Origin-Embedder-Policy", coep);\n }\n if (config?.headers) {\n for (const [key, value] of Object.entries(config.headers)) {\n if (value === void 0)\n continue;\n headers.set(key, value);\n }\n }\n recordSecurityHeaders();\n}\n\n// src/security/http/response/cache-handler.ts\nfunction buildCacheControl(strategy) {\n let cacheControl;\n if (typeof strategy === "string") {\n switch (strategy) {\n case "no-cache":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n case "no-store":\n cacheControl = "no-store";\n break;\n case "short":\n cacheControl = `public, max-age=${CACHE_DURATIONS.SHORT}`;\n break;\n case "medium":\n cacheControl = `public, max-age=${CACHE_DURATIONS.MEDIUM}`;\n break;\n case "long":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}`;\n break;\n case "immutable":\n cacheControl = `public, max-age=${CACHE_DURATIONS.LONG}, immutable`;\n break;\n case "none":\n cacheControl = "no-cache, no-store, must-revalidate";\n break;\n default:\n cacheControl = "public, max-age=0";\n }\n } else {\n const parts = [];\n parts.push(strategy.public !== false ? "public" : "private");\n parts.push(`max-age=${strategy.maxAge}`);\n if (strategy.immutable)\n parts.push("immutable");\n if (strategy.mustRevalidate)\n parts.push("must-revalidate");\n cacheControl = parts.join(", ");\n }\n return cacheControl;\n}\n\n// src/security/http/response/fluent-methods.ts\nfunction withCORS(req, corsConfig) {\n const config = corsConfig ?? this.securityConfig?.cors;\n applyCORSHeadersSync({\n request: req,\n headers: this.headers,\n config\n });\n return this;\n}\nfunction withCORSAsync(req) {\n return applyCORSHeaders({\n request: req,\n headers: this.headers,\n config: this.securityConfig?.cors\n }).then(() => this);\n}\nfunction withSecurity(config) {\n const cfg = config ?? this.securityConfig;\n applySecurityHeaders(\n this.headers,\n this.isDev,\n this.nonce,\n this.cspUserHeader,\n cfg,\n this.adapter\n );\n return this;\n}\nfunction withCache(strategy) {\n const cacheControl = buildCacheControl(strategy);\n this.headers.set("cache-control", cacheControl);\n return this;\n}\nfunction withETag(etag) {\n this.headers.set("ETag", etag);\n return this;\n}\nfunction withHeaders(headers) {\n if (headers instanceof Headers) {\n headers.forEach((value, key) => {\n this.headers.set(key, value);\n });\n } else if (Array.isArray(headers)) {\n headers.forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n } else {\n Object.entries(headers).forEach(([key, value]) => {\n this.headers.set(key, value);\n });\n }\n return this;\n}\nfunction withStatus(status) {\n this.status = status;\n return this;\n}\nfunction withAllow(methods) {\n const methodStr = Array.isArray(methods) ? methods.join(", ") : methods;\n this.headers.set("Allow", methodStr);\n this.headers.set("Access-Control-Allow-Methods", methodStr);\n return this;\n}\n\n// src/security/http/response/response-methods.ts\nfunction json(data, status) {\n this.headers.set("content-type", CONTENT_TYPES.JSON);\n return new Response(JSON.stringify(data), {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction text(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.TEXT);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction html(body, status) {\n this.headers.set("content-type", CONTENT_TYPES.HTML);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction javascript(code, status) {\n this.headers.set("content-type", CONTENT_TYPES.JAVASCRIPT);\n return new Response(code, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction withContentType(contentType, body, status) {\n this.headers.set("content-type", contentType);\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction build(body = null, status) {\n return new Response(body, {\n status: status ?? this.status,\n headers: this.headers\n });\n}\nfunction notModified(etag) {\n if (etag) {\n this.headers.set("ETag", etag);\n }\n return new Response(null, {\n status: 304,\n headers: this.headers\n });\n}\n\n// src/security/http/response/static-helpers.ts\ninit_veryfront_error();\nvar ResponseBuilderClass = null;\nfunction setResponseBuilderClass(builderClass) {\n ResponseBuilderClass = builderClass;\n}\nfunction error(status, message, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const contentType = config?.contentType ?? CONTENT_TYPES.TEXT;\n if (contentType === CONTENT_TYPES.JSON) {\n return builder.json({ error: message }, status);\n } else if (contentType === CONTENT_TYPES.HTML) {\n return builder.html(message, status);\n }\n return builder.text(message, status);\n}\nfunction json2(data, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.json(data, config?.status);\n}\nfunction html2(body, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n if (config?.etag) {\n builder.withETag(config.etag);\n }\n return builder.html(body, config?.status);\n}\nfunction preflight(req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n const methods = config?.allowMethods ?? "GET,POST,PUT,PATCH,DELETE,OPTIONS";\n builder.withAllow(methods);\n const headers = config?.allowHeaders ?? req.headers.get("access-control-request-headers") ?? "Content-Type,Authorization";\n builder.headers.set(\n "Access-Control-Allow-Headers",\n Array.isArray(headers) ? headers.join(", ") : headers\n );\n return builder.build(null, 204);\n}\nfunction stream(streamData, req, config) {\n if (!ResponseBuilderClass) {\n throw toError(createError({\n type: "config",\n message: "ResponseBuilder class not initialized"\n }));\n }\n const builder = new ResponseBuilderClass(config);\n builder.withCORS(req, config?.corsConfig);\n if (config?.securityConfig !== void 0) {\n builder.withSecurity(config.securityConfig ?? void 0);\n }\n if (config?.cache) {\n builder.withCache(config.cache);\n }\n const contentType = config?.contentType ?? "application/octet-stream";\n return builder.withContentType(contentType, streamData);\n}\n\n// src/security/http/response/builder.ts\nvar ResponseBuilder = class {\n constructor(config) {\n this.withCORS = withCORS;\n this.withCORSAsync = withCORSAsync;\n this.withSecurity = withSecurity;\n this.withCache = withCache;\n this.withETag = withETag;\n this.withHeaders = withHeaders;\n this.withStatus = withStatus;\n this.withAllow = withAllow;\n this.json = json;\n this.text = text;\n this.html = html;\n this.javascript = javascript;\n this.withContentType = withContentType;\n this.build = build;\n this.notModified = notModified;\n this.headers = new Headers();\n this.status = 200;\n this.securityConfig = config?.securityConfig ?? null;\n this.isDev = config?.isDev ?? false;\n this.nonce = config?.nonce ?? generateNonce();\n this.cspUserHeader = config?.cspUserHeader ?? null;\n this.adapter = config?.adapter;\n }\n};\nResponseBuilder.error = error;\nResponseBuilder.json = json2;\nResponseBuilder.html = html2;\nResponseBuilder.preflight = preflight;\nResponseBuilder.stream = stream;\nsetResponseBuilderClass(ResponseBuilder);\n\n// src/security/http/base-handler.ts\ninit_utils();\n\n// src/core/constants/index.ts\ninit_constants();\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/core/constants/limits.ts\nvar MAX_URL_LENGTH_FOR_VALIDATION = 2048;\n\n// src/security/input-validation/parsers.ts\nimport { z as z2 } from "zod";\n\n// src/security/input-validation/schemas.ts\nimport { z as z3 } from "zod";\nvar CommonSchemas = {\n /**\n * Valid email address (RFC-compliant, max 255 chars)\n */\n email: z3.string().email().max(255),\n /**\n * Valid UUID v4 identifier\n */\n uuid: z3.string().uuid(),\n /**\n * URL-safe slug (lowercase alphanumeric with hyphens)\n */\n slug: z3.string().regex(/^[a-z0-9-]+$/).min(1).max(100),\n /**\n * Valid HTTP/HTTPS URL (max 2048 chars)\n */\n url: z3.string().url().max(MAX_URL_LENGTH_FOR_VALIDATION),\n /**\n * International phone number (E.164 format)\n */\n phoneNumber: z3.string().regex(/^\\+?[1-9]\\d{1,14}$/),\n /**\n * Pagination parameters with defaults\n */\n pagination: z3.object({\n page: z3.coerce.number().int().positive().default(1),\n limit: z3.coerce.number().int().positive().max(100).default(10),\n sort: z3.string().optional(),\n order: z3.enum(["asc", "desc"]).optional()\n }),\n /**\n * Date range with validation\n */\n dateRange: z3.object({\n from: z3.string().datetime(),\n to: z3.string().datetime()\n }).refine((data) => new Date(data.from) <= new Date(data.to), {\n message: "From date must be before or equal to To date"\n }),\n /**\n * Strong password requirements\n * - Minimum 8 characters\n * - At least one uppercase letter\n * - At least one lowercase letter\n * - At least one number\n * - At least one special character\n */\n strongPassword: z3.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character")\n};\n\n// src/security/http/auth.ts\ninit_veryfront_error();\n\n// src/security/http/config.ts\ninit_config();\ninit_utils();\n\n// src/security/http/middleware/config-loader.ts\ninit_utils();\n\n// src/security/http/middleware/etag.ts\ninit_hash();\n\n// src/security/http/middleware/content-types.ts\ninit_http();\n\n// src/security/path-validation.ts\ninit_utils();\n\n// src/security/secure-fs.ts\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_utils();\ninit_std_path();\n\n// src/routing/api/module-loader/esbuild-plugin.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/http-validator.ts\ninit_veryfront_error();\n\n// src/routing/api/module-loader/security-config.ts\ninit_utils();\ninit_utils();\n\n// src/routing/api/module-loader/loader.ts\ninit_veryfront_error();\n\n// src/routing/api/route-discovery.ts\ninit_std_path();\n\n// src/core/utils/file-discovery.ts\ninit_std_path();\ninit_deno3();\n\n// src/routing/api/route-executor.ts\ninit_veryfront_error();\n\n// src/routing/api/method-validator.ts\ninit_utils();\n\n// src/routing/api/error-handler.ts\ninit_utils();\ninit_utils();\ninit_utils();\n\n// src/rendering/client/router.ts\nvar VeryfrontRouter = class {\n constructor(options = {}) {\n this.root = null;\n const globalOptions = this.loadGlobalOptions();\n this.options = { ...globalOptions, ...options };\n this.baseUrl = options.baseUrl || globalThis.location.origin;\n this.currentPath = globalThis.location.pathname;\n this.pageLoader = new PageLoader();\n this.navigationHandlers = new NavigationHandlers(\n this.options.prefetchDelay,\n this.options.prefetch\n );\n this.pageTransition = new PageTransition((root) => this.viewportPrefetch.setup(root));\n this.viewportPrefetch = new ViewportPrefetch(\n (path) => this.prefetch(path),\n this.options.prefetch\n );\n this.handleClick = this.navigationHandlers.createClickHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handlePopState = this.navigationHandlers.createPopStateHandler({\n onNavigate: (url) => this.navigate(url, false),\n onPrefetch: (url) => this.prefetch(url)\n });\n this.handleMouseOver = this.navigationHandlers.createMouseOverHandler({\n onNavigate: (url) => this.navigate(url),\n onPrefetch: (url) => this.prefetch(url)\n });\n }\n loadGlobalOptions() {\n try {\n const options = globalThis.__VERYFRONT_ROUTER_OPTS__;\n if (!options) {\n rendererLogger.debug("[router] No global options configured");\n return {};\n }\n return options;\n } catch (error2) {\n rendererLogger.error("[router] Failed to read global options:", error2);\n return {};\n }\n }\n init() {\n rendererLogger.info("Initializing client-side router");\n const rootElement = document.getElementById("root");\n if (!rootElement) {\n rendererLogger.error("Root element not found");\n return;\n }\n const ReactDOMToUse = globalThis.ReactDOM || ReactDOM;\n this.root = ReactDOMToUse.createRoot(rootElement);\n document.addEventListener("click", this.handleClick);\n globalThis.addEventListener("popstate", this.handlePopState);\n document.addEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.setup(document);\n this.cacheCurrentPage();\n }\n cacheCurrentPage() {\n const pageData = extractPageDataFromScript();\n if (pageData) {\n this.pageLoader.setCache(this.currentPath, pageData);\n }\n }\n async navigate(url, pushState = true) {\n rendererLogger.info(`Navigating to ${url}`);\n this.navigationHandlers.saveScrollPosition(this.currentPath);\n this.options.onStart?.(url);\n if (pushState) {\n globalThis.history.pushState({}, "", url);\n }\n await this.loadPage(url);\n this.options.onNavigate?.(url);\n }\n async loadPage(path, updateUI = true) {\n if (this.pageLoader.isCached(path)) {\n rendererLogger.debug(`Loading ${path} from cache`);\n const data = this.pageLoader.getCached(path);\n if (!data) {\n rendererLogger.warn(`[router] Cache entry for ${path} was unexpectedly null, fetching fresh data`);\n } else {\n if (updateUI) {\n this.updatePage(data);\n }\n return;\n }\n }\n this.pageTransition.setLoadingState(true);\n try {\n const data = await this.pageLoader.loadPage(path);\n if (updateUI) {\n this.updatePage(data);\n }\n this.currentPath = path;\n this.options.onComplete?.(path);\n } catch (error2) {\n rendererLogger.error(`Failed to load ${path}`, error2);\n this.options.onError?.(error2);\n this.pageTransition.showError(error2);\n } finally {\n this.pageTransition.setLoadingState(false);\n }\n }\n async prefetch(path) {\n await this.pageLoader.prefetch(path);\n }\n updatePage(data) {\n if (!this.root)\n return;\n const isPopState = this.navigationHandlers.isPopState();\n const scrollY = this.navigationHandlers.getScrollPosition(this.currentPath);\n this.pageTransition.updatePage(data, isPopState, scrollY);\n this.navigationHandlers.clearPopStateFlag();\n }\n destroy() {\n document.removeEventListener("click", this.handleClick);\n globalThis.removeEventListener("popstate", this.handlePopState);\n document.removeEventListener("mouseover", this.handleMouseOver);\n this.viewportPrefetch.disconnect();\n this.pageLoader.clearCache();\n this.navigationHandlers.clear();\n this.pageTransition.destroy();\n }\n};\nif (typeof window !== "undefined" && globalThis.document) {\n const router = new VeryfrontRouter();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => router.init());\n } else {\n router.init();\n }\n globalThis.veryFrontRouter = router;\n}\nexport {\n VeryfrontRouter\n};\n';
14107
+ CLIENT_PREFETCH_BUNDLE = '// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n this.prefix = prefix;\n this.level = level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug?.(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log?.(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn?.(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error?.(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") {\n return 2 /* WARN */;\n }\n const windowObject = window;\n const isDevelopment = windowObject.__VERYFRONT_DEV__ || windowObject.__RSC_DEV__;\n if (!isDevelopment) {\n return 2 /* WARN */;\n }\n const isDebugEnabled = windowObject.__VERYFRONT_DEBUG__ || windowObject.__RSC_DEBUG__;\n return isDebugEnabled ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/rendering/client/prefetch/link-observer.ts\nvar LinkObserver = class {\n constructor(options, prefetchedUrls) {\n this.intersectionObserver = null;\n this.mutationObserver = null;\n this.pendingTimeouts = /* @__PURE__ */ new Map();\n this.elementTimeoutMap = /* @__PURE__ */ new WeakMap();\n this.timeoutCounter = 0;\n this.options = options;\n this.prefetchedUrls = prefetchedUrls;\n }\n init() {\n this.createIntersectionObserver();\n this.observeLinks();\n this.setupMutationObserver();\n }\n createIntersectionObserver() {\n this.intersectionObserver = new IntersectionObserver(\n (entries) => this.handleIntersection(entries),\n { rootMargin: this.options.rootMargin }\n );\n }\n handleIntersection(entries) {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n const target = entry.target;\n let isAnchor = false;\n if (typeof HTMLAnchorElement !== "undefined") {\n isAnchor = target instanceof HTMLAnchorElement;\n } else {\n isAnchor = target.tagName === "A";\n }\n if (!isAnchor) {\n continue;\n }\n const link = target;\n const timeoutKey = this.timeoutCounter++;\n const timeoutId = setTimeout(() => {\n this.pendingTimeouts.delete(timeoutKey);\n this.elementTimeoutMap.delete(link);\n this.options.onLinkVisible(link);\n }, this.options.delay);\n this.pendingTimeouts.set(timeoutKey, timeoutId);\n this.elementTimeoutMap.set(link, timeoutKey);\n }\n }\n }\n observeLinks() {\n const links = document.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n if (this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n setupMutationObserver() {\n this.mutationObserver = new MutationObserver((mutations) => {\n for (const mutation of mutations) {\n if (mutation.type === "childList") {\n mutation.addedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.observeElement(node);\n }\n });\n mutation.removedNodes.forEach((node) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n this.clearElementTimeouts(node);\n }\n });\n }\n }\n });\n this.mutationObserver.observe(document.body, {\n childList: true,\n subtree: true\n });\n }\n clearElementTimeouts(element) {\n if (element.tagName === "A") {\n const timeoutKey = this.elementTimeoutMap.get(element);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(element);\n }\n }\n const links = element.querySelectorAll("a");\n links.forEach((link) => {\n const timeoutKey = this.elementTimeoutMap.get(link);\n if (timeoutKey !== void 0) {\n const timeoutId = this.pendingTimeouts.get(timeoutKey);\n if (timeoutId) {\n clearTimeout(timeoutId);\n this.pendingTimeouts.delete(timeoutKey);\n }\n this.elementTimeoutMap.delete(link);\n }\n });\n }\n observeElement(element) {\n const isAnchor = typeof HTMLAnchorElement !== "undefined" ? element instanceof HTMLAnchorElement : element.tagName === "A";\n if (isAnchor && this.isValidLink(element)) {\n this.intersectionObserver?.observe(element);\n }\n const links = element.querySelectorAll(\'a[href^="/"], a[href^="./"]\');\n links.forEach((link) => {\n const isLinkAnchor = typeof HTMLAnchorElement !== "undefined" ? link instanceof HTMLAnchorElement : link.tagName === "A";\n if (isLinkAnchor && this.isValidLink(link)) {\n this.intersectionObserver?.observe(link);\n }\n });\n }\n isValidLink(link) {\n if (link.hostname !== globalThis.location.hostname)\n return false;\n if (link.hasAttribute("download"))\n return false;\n if (link.target === "_blank")\n return false;\n const url = link.href;\n if (this.prefetchedUrls.has(url))\n return false;\n if (url === globalThis.location.href)\n return false;\n if (link.hash && link.pathname === globalThis.location.pathname) {\n return false;\n }\n if (link.dataset.noPrefetch)\n return false;\n return true;\n }\n destroy() {\n for (const [_, timeoutId] of this.pendingTimeouts) {\n clearTimeout(timeoutId);\n }\n this.pendingTimeouts.clear();\n if (this.intersectionObserver) {\n this.intersectionObserver.disconnect();\n this.intersectionObserver = null;\n }\n if (this.mutationObserver) {\n this.mutationObserver.disconnect();\n this.mutationObserver = null;\n }\n }\n};\n\n// src/rendering/client/prefetch/network-utils.ts\nvar NetworkUtils = class {\n constructor(allowedNetworks = ["4g", "wifi", "ethernet"]) {\n this.allowedNetworks = allowedNetworks;\n this.networkInfo = this.getNetworkConnection();\n }\n getNavigatorWithConnection() {\n if (typeof globalThis.navigator === "undefined") {\n return null;\n }\n return globalThis.navigator;\n }\n getNetworkConnection() {\n const nav = this.getNavigatorWithConnection();\n return nav?.connection || nav?.mozConnection || nav?.webkitConnection || null;\n }\n shouldPrefetch() {\n const nav = this.getNavigatorWithConnection();\n if (nav?.connection?.saveData) {\n return false;\n }\n if (this.networkInfo) {\n const effectiveType = this.networkInfo.effectiveType;\n if (effectiveType !== void 0 && !this.allowedNetworks.includes(effectiveType)) {\n return false;\n }\n }\n return true;\n }\n onNetworkChange(callback) {\n if (this.networkInfo?.addEventListener) {\n this.networkInfo.addEventListener("change", callback);\n }\n }\n getNetworkInfo() {\n return this.networkInfo;\n }\n};\n\n// src/core/utils/constants/cache.ts\nvar SECONDS_PER_MINUTE = 60;\nvar MINUTES_PER_HOUR = 60;\nvar HOURS_PER_DAY = 24;\nvar MS_PER_SECOND = 1e3;\nvar COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\nvar ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\nvar LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\n// src/core/utils/constants/http.ts\nvar KB_IN_BYTES = 1024;\nvar PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\nvar PREFETCH_DEFAULT_TIMEOUT_MS = 1e4;\nvar PREFETCH_DEFAULT_DELAY_MS = 200;\n\n// src/core/utils/constants/hmr.ts\nvar HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\n// src/core/utils/constants/network.ts\nvar BYTES_PER_MB = 1024 * 1024;\n\n// src/core/constants/buffers.ts\nvar DEFAULT_MAX_BODY_SIZE_BYTES = 1024 * 1024;\nvar DEFAULT_MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;\nvar PREFETCH_QUEUE_MAX_SIZE_BYTES = 1024 * 1024;\nvar MAX_BUNDLE_CHUNK_SIZE_BYTES = 4096 * 1024;\n\n// src/rendering/client/prefetch/prefetch-queue.ts\nvar DEFAULT_OPTIONS = {\n maxConcurrent: 4,\n maxSize: PREFETCH_QUEUE_MAX_SIZE_BYTES,\n timeout: 5e3\n};\nfunction isAbortError(error) {\n return Boolean(\n error && typeof error === "object" && "name" in error && error.name === "AbortError"\n );\n}\nvar PrefetchQueue = class {\n constructor(options = {}, prefetchedUrls) {\n this.controllers = /* @__PURE__ */ new Map();\n this.concurrent = 0;\n this.stopped = false;\n this.options = { ...DEFAULT_OPTIONS, ...options };\n this.prefetchedUrls = prefetchedUrls ?? /* @__PURE__ */ new Set();\n }\n setResourceCallback(callback) {\n this.onResourcesFetched = callback;\n }\n enqueue(url) {\n void this.prefetch(url);\n }\n has(url) {\n return this.prefetchedUrls.has(url) || this.controllers.has(url);\n }\n get size() {\n return this.getQueueSize();\n }\n clear() {\n this.stopAll();\n this.prefetchedUrls.clear();\n }\n start() {\n this.stopped = false;\n }\n stop() {\n this.stopped = true;\n this.stopAll();\n }\n getQueueSize() {\n return this.controllers.size;\n }\n getConcurrentCount() {\n return this.concurrent;\n }\n async prefetchLink(link) {\n if (this.stopped) {\n return;\n }\n const url = link.href;\n if (!url || this.controllers.has(url) || this.prefetchedUrls.has(url)) {\n return;\n }\n if (this.concurrent >= this.options.maxConcurrent) {\n prefetchLogger.debug?.(`Prefetch queue full, skipping ${url}`);\n return;\n }\n let parsedUrl;\n try {\n parsedUrl = new URL(url);\n } catch (_error) {\n prefetchLogger.debug?.(`Invalid prefetch URL ${url}`);\n return;\n }\n const controller = new AbortController();\n this.controllers.set(url, controller);\n this.concurrent += 1;\n const timeoutId = this.options.timeout > 0 ? setTimeout(() => controller.abort(), this.options.timeout) : void 0;\n try {\n const response = await fetch(parsedUrl.toString(), {\n method: "GET",\n signal: controller.signal,\n headers: { "X-Veryfront-Prefetch": "1" }\n });\n if (!response.ok) {\n return;\n }\n if (this.isResponseTooLarge(response)) {\n prefetchLogger.debug?.(`Prefetch too large, skipping ${url}`);\n return;\n }\n this.prefetchedUrls.add(url);\n if (this.onResourcesFetched) {\n try {\n await this.onResourcesFetched(response, url);\n } catch (callbackError) {\n prefetchLogger.error?.(`Prefetch callback failed for ${url}`, callbackError);\n }\n }\n } catch (error) {\n if (!isAbortError(error)) {\n prefetchLogger.error?.(`Failed to prefetch ${url}`, error);\n }\n } finally {\n if (timeoutId !== void 0) {\n clearTimeout(timeoutId);\n }\n this.controllers.delete(url);\n this.concurrent = Math.max(0, this.concurrent - 1);\n }\n }\n async prefetch(url) {\n const link = typeof document !== "undefined" ? document.createElement("a") : { href: url };\n link.href = url;\n await this.prefetchLink(link);\n }\n stopAll() {\n for (const controller of this.controllers.values()) {\n controller.abort();\n }\n this.controllers.clear();\n this.concurrent = 0;\n }\n isResponseTooLarge(response) {\n const rawLength = response.headers.get("content-length");\n if (rawLength === null) {\n return false;\n }\n const size = Number.parseInt(rawLength, 10);\n if (!Number.isFinite(size)) {\n return false;\n }\n return size > this.options.maxSize;\n }\n};\nvar prefetchQueue = new PrefetchQueue();\n\n// src/rendering/client/prefetch/resource-hints.ts\nvar ResourceHintsManager = class {\n constructor() {\n this.appliedHints = /* @__PURE__ */ new Set();\n }\n applyResourceHints(hints) {\n for (const hint of hints) {\n const key = `${hint.type}:${hint.href}`;\n if (this.appliedHints.has(key))\n continue;\n const existing = document.querySelector(`link[rel="${hint.type}"][href="${hint.href}"]`);\n if (existing) {\n this.appliedHints.add(key);\n continue;\n }\n this.createAndAppendHint(hint);\n this.appliedHints.add(key);\n prefetchLogger.debug(`Added resource hint: ${hint.type} ${hint.href}`);\n }\n }\n createAndAppendHint(hint) {\n if (!document.head) {\n prefetchLogger.warn("document.head is not available, skipping resource hint");\n return;\n }\n const link = document.createElement("link");\n link.rel = hint.type;\n link.href = hint.href;\n if (hint.as)\n link.setAttribute("as", hint.as);\n if (hint.crossOrigin)\n link.setAttribute("crossorigin", hint.crossOrigin);\n if (hint.media)\n link.setAttribute("media", hint.media);\n document.head.appendChild(link);\n }\n extractResourceHints(html, prefetchedUrls) {\n try {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, "text/html");\n const hints = [];\n this.extractPreloadLinks(doc, prefetchedUrls, hints);\n this.extractScripts(doc, prefetchedUrls, hints);\n this.extractStylesheets(doc, prefetchedUrls, hints);\n return hints;\n } catch (error) {\n prefetchLogger.error("Failed to parse prefetched page", error);\n return [];\n }\n }\n isValidResourceHintType(rel) {\n return rel === "prefetch" || rel === "preload" || rel === "preconnect" || rel === "dns-prefetch";\n }\n extractPreloadLinks(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="preload"], link[rel="prefetch"]\').forEach((link) => {\n const htmlLink = link;\n const href = htmlLink.href;\n if (href && !prefetchedUrls.has(href) && this.isValidResourceHintType(htmlLink.rel)) {\n hints.push({\n type: htmlLink.rel,\n href,\n as: htmlLink.getAttribute("as") || void 0\n });\n }\n });\n }\n extractScripts(doc, prefetchedUrls, hints) {\n doc.querySelectorAll("script[src]").forEach((script) => {\n const src = script.src;\n if (src && !prefetchedUrls.has(src)) {\n hints.push({ type: "prefetch", href: src, as: "script" });\n }\n });\n }\n extractStylesheets(doc, prefetchedUrls, hints) {\n doc.querySelectorAll(\'link[rel="stylesheet"]\').forEach((link) => {\n const href = link.href;\n if (href && !prefetchedUrls.has(href)) {\n hints.push({ type: "prefetch", href, as: "style" });\n }\n });\n }\n static generateResourceHints(_route, assets) {\n const hints = [\n \'<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">\',\n \'<link rel="dns-prefetch" href="https://esm.sh">\',\n \'<link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>\'\n ];\n for (const asset of assets) {\n if (asset.endsWith(".js")) {\n hints.push(`<link rel="modulepreload" href="${asset}">`);\n } else if (asset.endsWith(".css")) {\n hints.push(`<link rel="preload" as="style" href="${asset}">`);\n } else if (asset.match(/\\.(woff2?|ttf|otf)$/)) {\n hints.push(`<link rel="preload" as="font" href="${asset}" crossorigin>`);\n }\n }\n return hints.join("\\n");\n }\n};\n\n// src/core/utils/runtime-guards.ts\nfunction hasDenoRuntime(global) {\n return typeof global === "object" && global !== null && "Deno" in global && typeof global.Deno?.env?.get === "function";\n}\nfunction hasNodeProcess(global) {\n return typeof global === "object" && global !== null && "process" in global && typeof global.process?.env === "object";\n}\n\n// src/core/utils/logger/env.ts\nfunction getEnvironmentVariable(name) {\n try {\n if (typeof Deno !== "undefined" && hasDenoRuntime(globalThis)) {\n const value = globalThis.Deno?.env.get(name);\n return value === "" ? void 0 : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = globalThis.process?.env[name];\n return value === "" ? void 0 : value;\n }\n } catch {\n return void 0;\n }\n return void 0;\n}\n\n// src/core/utils/logger/logger.ts\nvar cachedLogLevel;\nfunction resolveLogLevel(force = false) {\n if (force || cachedLogLevel === void 0) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\nvar ConsoleLogger = class {\n constructor(prefix, level = resolveLogLevel()) {\n this.prefix = prefix;\n this.level = level;\n }\n setLevel(level) {\n this.level = level;\n }\n getLevel() {\n return this.level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n async time(label, fn) {\n const start = performance.now();\n try {\n const result = await fn();\n const end = performance.now();\n this.debug(`${label} completed in ${(end - start).toFixed(2)}ms`);\n return result;\n } catch (error) {\n const end = performance.now();\n this.error(`${label} failed after ${(end - start).toFixed(2)}ms`, error);\n throw error;\n }\n }\n};\nfunction parseLogLevel(levelString) {\n if (!levelString)\n return void 0;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case "DEBUG":\n return 0 /* DEBUG */;\n case "WARN":\n return 2 /* WARN */;\n case "ERROR":\n return 3 /* ERROR */;\n case "INFO":\n return 1 /* INFO */;\n default:\n return void 0;\n }\n}\nvar getDefaultLevel = () => {\n const envLevel = getEnvironmentVariable("LOG_LEVEL");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== void 0)\n return parsedLevel;\n const debugFlag = getEnvironmentVariable("VERYFRONT_DEBUG");\n if (debugFlag === "1" || debugFlag === "true")\n return 0 /* DEBUG */;\n return 1 /* INFO */;\n};\nvar trackedLoggers = /* @__PURE__ */ new Set();\nfunction createLogger(prefix) {\n const logger2 = new ConsoleLogger(prefix);\n trackedLoggers.add(logger2);\n return logger2;\n}\nvar cliLogger = createLogger("CLI");\nvar serverLogger = createLogger("SERVER");\nvar rendererLogger = createLogger("RENDERER");\nvar bundlerLogger = createLogger("BUNDLER");\nvar agentLogger = createLogger("AGENT");\nvar logger = createLogger("VERYFRONT");\n\n// deno.json\nvar deno_default = {\n name: "veryfront",\n version: "0.0.8",\n nodeModulesDir: "auto",\n workspace: [\n "./examples/async-worker-redis",\n "./examples/knowledge-base",\n "./examples/form-handling",\n "./examples/middleware-demo",\n "./examples/coding-agent",\n "./examples/durable-workflows"\n ],\n exports: {\n ".": "./src/index.ts",\n "./cli": "./src/cli/main.ts",\n "./server": "./src/server/index.ts",\n "./middleware": "./src/middleware/index.ts",\n "./components": "./src/react/components/index.ts",\n "./data": "./src/data/index.ts",\n "./config": "./src/core/config/index.ts",\n "./ai": "./src/ai/index.ts",\n "./ai/client": "./src/ai/client.ts",\n "./ai/react": "./src/ai/react/index.ts",\n "./ai/primitives": "./src/ai/react/primitives/index.ts",\n "./ai/components": "./src/ai/react/components/index.ts",\n "./ai/production": "./src/ai/production/index.ts",\n "./ai/dev": "./src/ai/dev/index.ts",\n "./ai/workflow": "./src/ai/workflow/index.ts",\n "./ai/workflow/react": "./src/ai/workflow/react/index.ts"\n },\n imports: {\n "@veryfront": "./src/index.ts",\n "@veryfront/": "./src/",\n "@veryfront/ai": "./src/ai/index.ts",\n "@veryfront/ai/": "./src/ai/",\n "@veryfront/platform": "./src/platform/index.ts",\n "@veryfront/platform/": "./src/platform/",\n "@veryfront/types": "./src/core/types/index.ts",\n "@veryfront/types/": "./src/core/types/",\n "@veryfront/utils": "./src/core/utils/index.ts",\n "@veryfront/utils/": "./src/core/utils/",\n "@veryfront/middleware": "./src/middleware/index.ts",\n "@veryfront/middleware/": "./src/middleware/",\n "@veryfront/errors": "./src/core/errors/index.ts",\n "@veryfront/errors/": "./src/core/errors/",\n "@veryfront/config": "./src/core/config/index.ts",\n "@veryfront/config/": "./src/core/config/",\n "@veryfront/observability": "./src/observability/index.ts",\n "@veryfront/observability/": "./src/observability/",\n "@veryfront/routing": "./src/routing/index.ts",\n "@veryfront/routing/": "./src/routing/",\n "@veryfront/transforms": "./src/build/transforms/index.ts",\n "@veryfront/transforms/": "./src/build/transforms/",\n "@veryfront/data": "./src/data/index.ts",\n "@veryfront/data/": "./src/data/",\n "@veryfront/security": "./src/security/index.ts",\n "@veryfront/security/": "./src/security/",\n "@veryfront/components": "./src/react/components/index.ts",\n "@veryfront/react": "./src/react/index.ts",\n "@veryfront/react/": "./src/react/",\n "@veryfront/html": "./src/html/index.ts",\n "@veryfront/html/": "./src/html/",\n "@veryfront/rendering": "./src/rendering/index.ts",\n "@veryfront/rendering/": "./src/rendering/",\n "@veryfront/build": "./src/build/index.ts",\n "@veryfront/build/": "./src/build/",\n "@veryfront/server": "./src/server/index.ts",\n "@veryfront/server/": "./src/server/",\n "@veryfront/modules": "./src/module-system/index.ts",\n "@veryfront/modules/": "./src/module-system/",\n "@veryfront/compat/console": "./src/platform/compat/console/index.ts",\n "@veryfront/compat/": "./src/platform/compat/",\n "std/": "https://deno.land/std@0.220.0/",\n "@std/path": "https://deno.land/std@0.220.0/path/mod.ts",\n "@std/testing/bdd.ts": "https://deno.land/std@0.220.0/testing/bdd.ts",\n "@std/expect": "https://deno.land/std@0.220.0/expect/mod.ts",\n csstype: "https://esm.sh/csstype@3.2.3",\n "@types/react": "https://esm.sh/@types/react@18.3.27?deps=csstype@3.2.3",\n "@types/react-dom": "https://esm.sh/@types/react-dom@18.3.7?deps=csstype@3.2.3",\n react: "https://esm.sh/react@18.3.1",\n "react-dom": "https://esm.sh/react-dom@18.3.1",\n "react-dom/server": "https://esm.sh/react-dom@18.3.1/server",\n "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",\n "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",\n "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime",\n "@mdx-js/mdx": "https://esm.sh/@mdx-js/mdx@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "@mdx-js/react": "https://esm.sh/@mdx-js/react@3.0.0?deps=react@18.3.1,react-dom@18.3.1",\n "unist-util-visit": "https://esm.sh/unist-util-visit@5.0.0",\n "mdast-util-to-string": "https://esm.sh/mdast-util-to-string@4.0.0",\n "github-slugger": "https://esm.sh/github-slugger@2.0.0",\n "remark-gfm": "https://esm.sh/remark-gfm@4.0.1",\n "remark-frontmatter": "https://esm.sh/remark-frontmatter@5.0.0",\n "rehype-highlight": "https://esm.sh/rehype-highlight@7.0.2",\n "rehype-slug": "https://esm.sh/rehype-slug@6.0.0",\n esbuild: "https://deno.land/x/esbuild@v0.20.1/wasm.js",\n "esbuild/mod.js": "https://deno.land/x/esbuild@v0.20.1/mod.js",\n "es-module-lexer": "https://esm.sh/es-module-lexer@1.5.0",\n zod: "https://esm.sh/zod@3.22.0",\n "mime-types": "https://esm.sh/mime-types@2.1.35",\n mdast: "https://esm.sh/@types/mdast@4.0.3",\n hast: "https://esm.sh/@types/hast@3.0.3",\n unist: "https://esm.sh/@types/unist@3.0.2",\n unified: "https://esm.sh/unified@11.0.5?dts",\n ai: "https://esm.sh/ai@5.0.76",\n "ai/react": "https://esm.sh/@ai-sdk/react@2.0.59",\n "@ai-sdk/openai": "https://esm.sh/@ai-sdk/openai@2.0.1",\n "@ai-sdk/anthropic": "https://esm.sh/@ai-sdk/anthropic@2.0.4",\n unocss: "https://esm.sh/unocss@0.59.0",\n "@unocss/core": "https://esm.sh/@unocss/core@0.59.0",\n "@unocss/preset-wind": "https://esm.sh/@unocss/preset-wind@0.59.0"\n },\n compilerOptions: {\n jsx: "react-jsx",\n jsxImportSource: "react",\n strict: true,\n noImplicitAny: true,\n noUncheckedIndexedAccess: true,\n types: [],\n lib: [\n "deno.window",\n "dom",\n "dom.iterable",\n "dom.asynciterable",\n "deno.ns"\n ]\n },\n tasks: {\n setup: "deno run --allow-all scripts/setup.ts",\n dev: "deno run --allow-all --no-lock --unstable-net --unstable-worker-options src/cli/main.ts dev",\n build: "deno compile --allow-all --output ../../bin/veryfront src/cli/main.ts",\n "build:npm": "deno run -A scripts/build-npm.ts",\n release: "deno run -A scripts/release.ts",\n test: "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --unstable-worker-options --unstable-net",\n "test:unit": "DENO_JOBS=1 deno test --parallel --allow-all --v8-flags=--max-old-space-size=8192 --ignore=tests --unstable-worker-options --unstable-net",\n "test:integration": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all tests --unstable-worker-options --unstable-net",\n "test:batches": "deno run --allow-all scripts/test-batches.ts",\n "test:unsafe": "DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net",\n "test:coverage": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:unit": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage --ignore=tests --unstable-worker-options --unstable-net || exit 1",\n "test:coverage:integration": "rm -rf coverage && DENO_JOBS=1 deno test --parallel --fail-fast --allow-all --coverage=coverage tests --unstable-worker-options --unstable-net || exit 1",\n "coverage:report": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --lcov > coverage/lcov.info && deno run --allow-read scripts/check-coverage.ts 80",\n "coverage:html": "deno coverage coverage --include=src/ --exclude=tests --exclude=src/**/*_test.ts --exclude=src/**/*_test.tsx --exclude=src/**/*.test.ts --exclude=src/**/*.test.tsx --html",\n lint: "deno lint src/",\n fmt: "deno fmt src/",\n typecheck: "deno check src/index.ts src/cli/main.ts src/server/index.ts src/routing/api/index.ts src/rendering/index.ts src/platform/index.ts src/platform/adapters/index.ts src/build/index.ts src/build/production-build/index.ts src/build/transforms/index.ts src/core/config/index.ts src/core/utils/index.ts src/data/index.ts src/security/index.ts src/middleware/index.ts src/server/handlers/dev/index.ts src/server/handlers/request/api/index.ts src/rendering/cache/index.ts src/rendering/cache/stores/index.ts src/rendering/rsc/actions/index.ts src/html/index.ts src/module-system/index.ts",\n "docs:check-links": "deno run -A scripts/check-doc-links.ts",\n "lint:ban-console": "deno run --allow-read scripts/ban-console.ts",\n "lint:ban-deep-imports": "deno run --allow-read scripts/ban-deep-imports.ts",\n "lint:ban-internal-root-imports": "deno run --allow-read scripts/ban-internal-root-imports.ts",\n "lint:check-awaits": "deno run --allow-read scripts/check-unawaited-promises.ts",\n "check:circular": "deno run -A jsr:@cunarist/deno-circular-deps src/index.ts"\n },\n lint: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n rules: {\n tags: [\n "recommended"\n ],\n include: [\n "ban-untagged-todo"\n ],\n exclude: [\n "no-explicit-any",\n "no-process-global",\n "no-console"\n ]\n }\n },\n fmt: {\n include: [\n "src/**/*.ts",\n "src/**/*.tsx"\n ],\n exclude: [\n "dist/",\n "coverage/"\n ],\n options: {\n useTabs: false,\n lineWidth: 100,\n indentWidth: 2,\n semiColons: true,\n singleQuote: false,\n proseWrap: "preserve"\n }\n }\n};\n\n// src/core/utils/version.ts\nvar VERSION = typeof deno_default.version === "string" ? deno_default.version : "0.0.0";\n\n// src/core/utils/bundle-manifest.ts\nvar InMemoryBundleManifestStore = class {\n constructor() {\n this.metadata = /* @__PURE__ */ new Map();\n this.code = /* @__PURE__ */ new Map();\n this.sourceIndex = /* @__PURE__ */ new Map();\n }\n getBundleMetadata(key) {\n const entry = this.metadata.get(key);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleMetadata(key, metadata, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.metadata.set(key, { value: metadata, expiry });\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, /* @__PURE__ */ new Set());\n }\n this.sourceIndex.get(metadata.source).add(key);\n return Promise.resolve();\n }\n getBundleCode(hash) {\n const entry = this.code.get(hash);\n if (!entry)\n return Promise.resolve(void 0);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(void 0);\n }\n return Promise.resolve(entry.value);\n }\n setBundleCode(hash, code, ttlMs) {\n const expiry = ttlMs ? Date.now() + ttlMs : void 0;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n async deleteBundle(key) {\n const metadata = await this.getBundleMetadata(key);\n this.metadata.delete(key);\n if (metadata) {\n this.code.delete(metadata.codeHash);\n const sourceKeys = this.sourceIndex.get(metadata.source);\n if (sourceKeys) {\n sourceKeys.delete(key);\n if (sourceKeys.size === 0) {\n this.sourceIndex.delete(metadata.source);\n }\n }\n }\n }\n async invalidateSource(source) {\n const keys = this.sourceIndex.get(source);\n if (!keys)\n return 0;\n let count = 0;\n for (const key of Array.from(keys)) {\n await this.deleteBundle(key);\n count++;\n }\n this.sourceIndex.delete(source);\n return count;\n }\n clear() {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n isAvailable() {\n return Promise.resolve(true);\n }\n getStats() {\n let totalSize = 0;\n let oldest;\n let newest;\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest)\n oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest)\n newest = value.compiledAt;\n }\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest\n });\n }\n};\nvar manifestStore = new InMemoryBundleManifestStore();\n\n// src/rendering/client/prefetch.ts\nvar PrefetchManager = class {\n constructor(options = {}) {\n this.prefetchedUrls = /* @__PURE__ */ new Set();\n this.linkObserver = null;\n this.options = {\n rootMargin: options.rootMargin || "50px",\n delay: options.delay || PREFETCH_DEFAULT_DELAY_MS,\n maxConcurrent: options.maxConcurrent || 2,\n allowedNetworks: options.allowedNetworks || ["4g", "wifi", "ethernet"],\n maxSize: options.maxSize || PREFETCH_MAX_SIZE_BYTES,\n timeout: options.timeout || PREFETCH_DEFAULT_TIMEOUT_MS\n };\n this.networkUtils = new NetworkUtils(this.options.allowedNetworks);\n this.resourceHintsManager = new ResourceHintsManager();\n this.prefetchQueue = new PrefetchQueue(\n {\n maxConcurrent: this.options.maxConcurrent,\n maxSize: this.options.maxSize,\n timeout: this.options.timeout\n },\n this.prefetchedUrls\n );\n this.prefetchQueue.setResourceCallback(\n (response, url) => this.prefetchPageResources(response, url)\n );\n }\n init() {\n prefetchLogger.info("Initializing prefetch manager");\n if (!this.networkUtils.shouldPrefetch()) {\n prefetchLogger.info("Prefetching disabled due to network conditions");\n return;\n }\n this.linkObserver = new LinkObserver(\n {\n rootMargin: this.options.rootMargin,\n delay: this.options.delay,\n onLinkVisible: (link) => this.prefetchQueue.prefetchLink(link)\n },\n this.prefetchedUrls\n );\n this.linkObserver.init();\n this.networkUtils.onNetworkChange(() => {\n if (!this.networkUtils.shouldPrefetch()) {\n this.prefetchQueue.stopAll();\n }\n });\n }\n async prefetchPageResources(response, _pageUrl) {\n const html = await response.text();\n const hints = this.resourceHintsManager.extractResourceHints(html, this.prefetchedUrls);\n this.resourceHintsManager.applyResourceHints(hints);\n }\n applyResourceHints(hints) {\n this.resourceHintsManager.applyResourceHints(hints);\n }\n async prefetch(url) {\n await this.prefetchQueue.prefetch(url);\n }\n static generateResourceHints(route, assets) {\n return ResourceHintsManager.generateResourceHints(route, assets);\n }\n destroy() {\n this.linkObserver?.destroy();\n this.prefetchQueue.stopAll();\n this.prefetchedUrls.clear();\n }\n};\nif (typeof window !== "undefined") {\n const prefetchManager = new PrefetchManager();\n if (document.readyState === "loading") {\n document.addEventListener("DOMContentLoaded", () => prefetchManager.init());\n } else {\n prefetchManager.init();\n }\n globalThis.veryFrontPrefetch = prefetchManager;\n}\nexport {\n PrefetchManager\n};\n';
14089
14108
  }
14090
14109
  });
14091
14110
 
@@ -14225,9 +14244,9 @@ async function canResolveReactFromProject() {
14225
14244
  return false;
14226
14245
  }
14227
14246
  try {
14228
- const { createRequire } = await import("node:module");
14247
+ const { createRequire: createRequire2 } = await import("node:module");
14229
14248
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14230
- const projectRequire = createRequire(pathToFileURL2(process.cwd() + "/").href);
14249
+ const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
14231
14250
  const reactPath = projectRequire.resolve("react");
14232
14251
  const reactDomPath = projectRequire.resolve("react-dom/server");
14233
14252
  rendererLogger.debug("Project has both react and react-dom", {
@@ -14252,9 +14271,9 @@ async function getProjectReact() {
14252
14271
  const canUseProject = await canResolveReactFromProject();
14253
14272
  if (canUseProject) {
14254
14273
  try {
14255
- const { createRequire } = await import("node:module");
14274
+ const { createRequire: createRequire2 } = await import("node:module");
14256
14275
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14257
- const projectRequire = createRequire(pathToFileURL2(process.cwd() + "/").href);
14276
+ const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
14258
14277
  const reactPath = projectRequire.resolve("react");
14259
14278
  rendererLogger.debug("Resolved react from project", { path: reactPath });
14260
14279
  const projectReact = await import(pathToFileURL2(reactPath).href);
@@ -14271,9 +14290,9 @@ async function importReactDOMServerFromProject() {
14271
14290
  const canUseProject = await canResolveReactFromProject();
14272
14291
  if (canUseProject) {
14273
14292
  try {
14274
- const { createRequire } = await import("node:module");
14293
+ const { createRequire: createRequire2 } = await import("node:module");
14275
14294
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
14276
- const projectRequire = createRequire(pathToFileURL2(process.cwd() + "/").href);
14295
+ const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
14277
14296
  const reactDomServerPath = projectRequire.resolve("react-dom/server");
14278
14297
  rendererLogger.debug("Resolved react-dom/server from project", { path: reactDomServerPath });
14279
14298
  return await import(pathToFileURL2(reactDomServerPath).href);
@@ -15002,10 +15021,131 @@ var init_esm_module_loader = __esm({
15002
15021
  }
15003
15022
  });
15004
15023
 
15024
+ // src/build/transforms/mdx/module-loader/string-parser.ts
15025
+ function extractBalancedBlock(source, startIndex, open, close) {
15026
+ const closeCh = close || (open === "{" ? "}" : open === "[" ? "]" : ")");
15027
+ let depth = 0;
15028
+ let i = startIndex;
15029
+ while (i < source.length) {
15030
+ const ch = source[i];
15031
+ if (ch === '"' || ch === "'") {
15032
+ const quote = ch;
15033
+ i++;
15034
+ while (i < source.length) {
15035
+ const q = source[i];
15036
+ if (q === "\\") {
15037
+ i += 2;
15038
+ continue;
15039
+ }
15040
+ if (q === quote) {
15041
+ i++;
15042
+ break;
15043
+ }
15044
+ i++;
15045
+ }
15046
+ continue;
15047
+ }
15048
+ if (ch === open)
15049
+ depth++;
15050
+ if (ch === closeCh) {
15051
+ depth--;
15052
+ if (depth === 0) {
15053
+ return source.slice(startIndex, i + 1);
15054
+ }
15055
+ }
15056
+ i++;
15057
+ }
15058
+ return "";
15059
+ }
15060
+ function parseJsonish(value) {
15061
+ const jsonish = value.replace(/'([^']*)'/g, '"$1"').replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g, '$1"$2":');
15062
+ return JSON.parse(jsonish);
15063
+ }
15064
+ var init_string_parser = __esm({
15065
+ "src/build/transforms/mdx/module-loader/string-parser.ts"() {
15066
+ "use strict";
15067
+ }
15068
+ });
15069
+
15070
+ // src/build/transforms/mdx/module-loader/metadata-extractor.ts
15071
+ function extractFrontmatter(moduleCode) {
15072
+ try {
15073
+ const fmIndex = moduleCode.search(/(?:export\s+)?const\s+frontmatter\s*=\s*/);
15074
+ if (fmIndex < 0)
15075
+ return void 0;
15076
+ const braceStart = moduleCode.indexOf("{", fmIndex);
15077
+ if (braceStart < 0)
15078
+ return void 0;
15079
+ const raw = extractBalancedBlock(moduleCode, braceStart, "{", "}");
15080
+ if (!raw)
15081
+ return void 0;
15082
+ const jsonish = raw.replace(/([^\s"{[:,]+)\s*:/g, '"$1":').replace(/'([^']*)'/g, '"$1"');
15083
+ try {
15084
+ return JSON.parse(jsonish);
15085
+ } catch (e) {
15086
+ rendererLogger.debug("[mdx] frontmatter JSON parse failed", e);
15087
+ return void 0;
15088
+ }
15089
+ } catch (e) {
15090
+ rendererLogger.debug("[mdx] frontmatter extraction failed", e);
15091
+ return void 0;
15092
+ }
15093
+ }
15094
+ function extractMetadata(moduleCode) {
15095
+ const exports = {};
15096
+ METADATA_PATTERNS.forEach(({ regex, key }) => {
15097
+ const match = moduleCode.match(regex);
15098
+ if (!match)
15099
+ return;
15100
+ const value = match[1];
15101
+ switch (key) {
15102
+ case "title":
15103
+ case "description":
15104
+ case "date":
15105
+ exports[key] = value;
15106
+ break;
15107
+ case "layout":
15108
+ exports[key] = value === "true" ? true : value === "false" ? false : String(value).replace(/^"|"$/g, "");
15109
+ break;
15110
+ case "headings":
15111
+ case "tags":
15112
+ case "nested":
15113
+ try {
15114
+ exports[key] = parseJsonish(value);
15115
+ } catch (e) {
15116
+ rendererLogger.warn(`Failed to parse ${key}`, e);
15117
+ }
15118
+ break;
15119
+ case "draft":
15120
+ exports[key] = value === "true";
15121
+ break;
15122
+ }
15123
+ });
15124
+ return exports;
15125
+ }
15126
+ var METADATA_PATTERNS;
15127
+ var init_metadata_extractor = __esm({
15128
+ "src/build/transforms/mdx/module-loader/metadata-extractor.ts"() {
15129
+ "use strict";
15130
+ init_utils();
15131
+ init_string_parser();
15132
+ METADATA_PATTERNS = [
15133
+ { regex: /(?:export\s+)?const\s+title\s*=\s*["']([^"']+)["']/, key: "title" },
15134
+ { regex: /(?:export\s+)?const\s+description\s*=\s*["']([^"']+)["']/, key: "description" },
15135
+ { regex: /(?:export\s+)?const\s+layout\s*=\s*(true|false|["'][^"']+["'])/, key: "layout" },
15136
+ { regex: /(?:export\s+)?const\s+headings\s*=\s*(\[[\s\S]*?\])/, key: "headings" },
15137
+ { regex: /(?:export\s+)?const\s+nested\s*=\s*({[\s\S]*?})/, key: "nested" },
15138
+ { regex: /(?:export\s+)?const\s+tags\s*=\s*(\[[\s\S]*?\])/, key: "tags" },
15139
+ { regex: /(?:export\s+)?const\s+date\s*=\s*["']([^"']+)["']/, key: "date" },
15140
+ { regex: /(?:export\s+)?const\s+draft\s*=\s*(true|false)/, key: "draft" }
15141
+ ];
15142
+ }
15143
+ });
15144
+
15005
15145
  // src/build/transforms/mdx/parser.ts
15006
15146
  function parseMDXCode(compiledCode) {
15007
15147
  rendererLogger.debug("Parsing MDX code, first 200 chars:", compiledCode.substring(0, 200));
15008
- const importRegex = /import\s+(?:{([^}]+)}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;
15148
+ const importRegex = /^\s*import\s+(?:{([^}]+)}|(\w+))\s+from\s+['"]([^'"]+)['"]\s*;?\s*$/gm;
15009
15149
  const imports = /* @__PURE__ */ new Map();
15010
15150
  let match;
15011
15151
  while ((match = importRegex.exec(compiledCode)) !== null) {
@@ -15026,7 +15166,7 @@ function parseMDXCode(compiledCode) {
15026
15166
  }
15027
15167
  }
15028
15168
  }
15029
- const cleanedCode = compiledCode.replace(/import\s+.*?from\s+['"][^'"]+['"];?\s*/gm, "").replace(/export\s+\{[\s\S]*?\};?/gm, "").replace(/export\s+default\s+function/gm, "function").replace(/export\s+default\s+/gm, "").replace(/export\s+const\s+/gm, "const ").replace(/export\s+function\s+/gm, "function ").replace(/^const\s+React\s*=.*?;?\s*$/gm, "").replace(/^import\s+React\s+from.*?;?\s*$/gm, "").replace(/^const\s+(Fragment|Fragment2)\s*=.*?;?\s*$/gm, "").replace(/^const\s+(jsx|jsx2)\s*=.*?;?\s*$/gm, "").replace(/^const\s+(jsxs|jsxs2)\s*=.*?;?\s*$/gm, "");
15169
+ const cleanedCode = compiledCode.replace(importRegex, "").replace(/^\s*export\s+\{[\s\S]*?\};?\s*$/gm, "").replace(/^\s*export\s+default\s+function/gm, "function").replace(/^\s*export\s+default\s+/gm, "").replace(/^\s*export\s+const\s+/gm, "const ").replace(/^\s*export\s+function\s+/gm, "function ").replace(/^\s*const\s+React\s*=.*?;?\s*$/gm, "").replace(/^\s*import\s+React\s+from.*?;?\s*$/gm, "").replace(/^\s*const\s+(Fragment|Fragment2)\s*=.*?;?\s*$/gm, "").replace(/^\s*const\s+(jsx|jsx2)\s*=.*?;?\s*$/gm, "").replace(/^\s*const\s+(jsxs|jsxs2)\s*=.*?;?\s*$/gm, "");
15030
15170
  if (cleanedCode.includes("import React")) {
15031
15171
  rendererLogger.warn("Import React still in cleaned code");
15032
15172
  }
@@ -15035,52 +15175,23 @@ function parseMDXCode(compiledCode) {
15035
15175
  rendererLogger.debug("Code snippet:", cleanedCode.substring(0, 200));
15036
15176
  }
15037
15177
  const exports = {};
15038
- const frontmatterMatch = cleanedCode.match(/const\s+frontmatter\s*=\s*({[\s\S]*?});/);
15039
- if (frontmatterMatch) {
15040
- try {
15041
- const objectLiteral = (frontmatterMatch[1] ?? "{}").replace(/(\w+):/g, '"$1":').replace(/'/g, '"');
15042
- exports.frontmatter = JSON.parse(objectLiteral);
15043
- } catch {
15044
- rendererLogger.debug("[MDX] Could not parse frontmatter statically, will extract at runtime");
15045
- }
15178
+ const frontmatter = extractFrontmatter(cleanedCode);
15179
+ if (frontmatter) {
15180
+ exports.frontmatter = frontmatter;
15046
15181
  }
15047
- const exportMatches = [
15048
- { regex: /const\s+title\s*=\s*["']([^"']+)["']/, key: "title", parse: (v) => v },
15049
- {
15050
- regex: /const\s+description\s*=\s*["']([^"']+)["']/,
15051
- key: "description",
15052
- parse: (v) => v
15053
- },
15054
- { regex: /const\s+layout\s*=\s*true/, key: "layout", parse: () => true },
15055
- { regex: /const\s+layout\s*=\s*false/, key: "layout", parse: () => false },
15056
- { regex: /const\s+layout\s*=\s*["']([^"']+)["']/, key: "layout", parse: (v) => v },
15057
- {
15058
- regex: /const\s+headings\s*=\s*(\[[\s\S]*?\]);/,
15059
- key: "headings",
15060
- parse: (v) => {
15061
- try {
15062
- return JSON.parse(v.replace(/'/g, '"'));
15063
- } catch {
15064
- return [];
15065
- }
15066
- }
15182
+ const metadata = extractMetadata(cleanedCode);
15183
+ for (const [key, value] of Object.entries(metadata)) {
15184
+ if (value !== void 0) {
15185
+ exports[key] = value;
15067
15186
  }
15068
- ];
15069
- exportMatches.forEach(({ regex, key, parse: parse5 }) => {
15070
- const m = cleanedCode.match(regex);
15071
- if (m) {
15072
- try {
15073
- exports[key] = parse5(m[1] || m[0]);
15074
- } catch (_error) {
15075
- }
15076
- }
15077
- });
15187
+ }
15078
15188
  return { code: cleanedCode, imports, exports };
15079
15189
  }
15080
15190
  var init_parser = __esm({
15081
15191
  "src/build/transforms/mdx/parser.ts"() {
15082
15192
  "use strict";
15083
15193
  init_utils();
15194
+ init_metadata_extractor();
15084
15195
  }
15085
15196
  });
15086
15197
 
@@ -15695,9 +15806,9 @@ async function checkProjectHasReactDom() {
15695
15806
  return false;
15696
15807
  }
15697
15808
  try {
15698
- const { createRequire } = await import("node:module");
15809
+ const { createRequire: createRequire2 } = await import("node:module");
15699
15810
  const { pathToFileURL: pathToFileURL2 } = await import("node:url");
15700
- const projectRequire = createRequire(pathToFileURL2(process.cwd() + "/").href);
15811
+ const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
15701
15812
  projectRequire.resolve("react");
15702
15813
  projectRequire.resolve("react-dom/server");
15703
15814
  projectHasReactDom = true;
@@ -15712,8 +15823,8 @@ async function getBundledReactPath(subpath = "") {
15712
15823
  return null;
15713
15824
  }
15714
15825
  try {
15715
- const { createRequire } = await import("node:module");
15716
- const cliRequire = createRequire(import.meta.url);
15826
+ const { createRequire: createRequire2 } = await import("node:module");
15827
+ const cliRequire = createRequire2(import.meta.url);
15717
15828
  const moduleName = subpath ? `react${subpath}` : "react";
15718
15829
  return cliRequire.resolve(moduleName);
15719
15830
  } catch {
@@ -15723,22 +15834,35 @@ async function getBundledReactPath(subpath = "") {
15723
15834
  async function resolveReactImports(code, forSSR = false) {
15724
15835
  if (isNodeRuntime3() && forSSR) {
15725
15836
  const hasReactDom = await checkProjectHasReactDom();
15726
- if (!hasReactDom) {
15727
- const bundledReact = await getBundledReactPath();
15728
- const bundledJsxRuntime = await getBundledReactPath("/jsx-runtime");
15729
- const bundledJsxDevRuntime = await getBundledReactPath("/jsx-dev-runtime");
15730
- if (bundledReact && bundledJsxRuntime && bundledJsxDevRuntime) {
15731
- const { pathToFileURL: pathToFileURL2 } = await import("node:url");
15732
- const bundledImports = {
15733
- "react/jsx-runtime": pathToFileURL2(bundledJsxRuntime).href,
15734
- "react/jsx-dev-runtime": pathToFileURL2(bundledJsxDevRuntime).href,
15735
- "react": pathToFileURL2(bundledReact).href
15837
+ const { pathToFileURL: pathToFileURL2 } = await import("node:url");
15838
+ if (hasReactDom) {
15839
+ try {
15840
+ const { createRequire: createRequire2 } = await import("node:module");
15841
+ const projectRequire = createRequire2(pathToFileURL2(process.cwd() + "/").href);
15842
+ const projectImports = {
15843
+ "react/jsx-runtime": pathToFileURL2(projectRequire.resolve("react/jsx-runtime")).href,
15844
+ "react/jsx-dev-runtime": pathToFileURL2(projectRequire.resolve("react/jsx-dev-runtime")).href,
15845
+ "react": pathToFileURL2(projectRequire.resolve("react")).href
15736
15846
  };
15737
15847
  return replaceSpecifiers(code, (specifier) => {
15738
- return bundledImports[specifier] || null;
15848
+ return projectImports[specifier] || null;
15739
15849
  });
15850
+ } catch {
15740
15851
  }
15741
15852
  }
15853
+ const bundledReact = await getBundledReactPath();
15854
+ const bundledJsxRuntime = await getBundledReactPath("/jsx-runtime");
15855
+ const bundledJsxDevRuntime = await getBundledReactPath("/jsx-dev-runtime");
15856
+ if (bundledReact && bundledJsxRuntime && bundledJsxDevRuntime) {
15857
+ const bundledImports = {
15858
+ "react/jsx-runtime": pathToFileURL2(bundledJsxRuntime).href,
15859
+ "react/jsx-dev-runtime": pathToFileURL2(bundledJsxDevRuntime).href,
15860
+ "react": pathToFileURL2(bundledReact).href
15861
+ };
15862
+ return replaceSpecifiers(code, (specifier) => {
15863
+ return bundledImports[specifier] || null;
15864
+ });
15865
+ }
15742
15866
  return code;
15743
15867
  }
15744
15868
  if (isNodeRuntime3()) {
@@ -15778,6 +15902,17 @@ var init_react_imports = __esm({
15778
15902
  });
15779
15903
 
15780
15904
  // src/build/transforms/esm/path-resolver.ts
15905
+ async function resolveVeryfrontImports(code) {
15906
+ return replaceSpecifiers(code, (specifier) => {
15907
+ if (specifier.startsWith("@veryfront/")) {
15908
+ return specifier.replace("@veryfront/", "veryfront/");
15909
+ }
15910
+ if (specifier === "@veryfront") {
15911
+ return "veryfront";
15912
+ }
15913
+ return null;
15914
+ });
15915
+ }
15781
15916
  async function resolvePathAliases(code, filePath, projectDir) {
15782
15917
  const _normalizedProjectDir = projectDir.replace(/\\/g, "/").replace(/\/$/, "");
15783
15918
  let relativeFilePath = filePath;
@@ -16647,50 +16782,41 @@ __export(std_front_matter_exports, {
16647
16782
  extractAsync: () => extractAsync,
16648
16783
  test: () => test
16649
16784
  });
16785
+ import { createRequire } from "node:module";
16650
16786
  async function getGrayMatter() {
16651
16787
  if (!grayMatter) {
16652
16788
  grayMatter = await import("gray-matter");
16653
16789
  }
16654
16790
  return grayMatter;
16655
16791
  }
16792
+ function getGrayMatterSync() {
16793
+ if (grayMatter) {
16794
+ return grayMatter.default ?? grayMatter.default ?? grayMatter;
16795
+ }
16796
+ try {
16797
+ const mod = require2("gray-matter");
16798
+ grayMatter = mod;
16799
+ return mod.default ?? mod;
16800
+ } catch (_error) {
16801
+ return null;
16802
+ }
16803
+ }
16656
16804
  function extract(content) {
16657
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
16658
- if (!match) {
16805
+ const gm = getGrayMatterSync();
16806
+ if (gm) {
16807
+ const result = gm(content);
16659
16808
  return {
16660
- attrs: {},
16661
- body: content,
16662
- frontMatter: ""
16809
+ attrs: result.data,
16810
+ body: result.content,
16811
+ frontMatter: result.matter ?? ""
16663
16812
  };
16664
16813
  }
16665
- const [, frontMatterStr, body] = match;
16666
- const attrs = {};
16667
- if (frontMatterStr) {
16668
- const lines = frontMatterStr.split(/\r?\n/);
16669
- for (const line of lines) {
16670
- const colonIndex = line.indexOf(":");
16671
- if (colonIndex > 0) {
16672
- const key = line.slice(0, colonIndex).trim();
16673
- let value = line.slice(colonIndex + 1).trim();
16674
- if (value.startsWith('"') && value.endsWith('"')) {
16675
- value = value.slice(1, -1);
16676
- } else if (value.startsWith("'") && value.endsWith("'")) {
16677
- value = value.slice(1, -1);
16678
- } else if (value === "true") {
16679
- value = true;
16680
- } else if (value === "false") {
16681
- value = false;
16682
- } else if (!isNaN(Number(value)) && value !== "") {
16683
- value = Number(value);
16684
- }
16685
- attrs[key] = value;
16686
- }
16687
- }
16814
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
16815
+ if (!match) {
16816
+ return { attrs: {}, body: content, frontMatter: "" };
16688
16817
  }
16689
- return {
16690
- attrs,
16691
- body: body || "",
16692
- frontMatter: frontMatterStr || ""
16693
- };
16818
+ const [, frontMatterStr, body] = match;
16819
+ return { attrs: {}, body: body || "", frontMatter: frontMatterStr || "" };
16694
16820
  }
16695
16821
  function test(content) {
16696
16822
  return /^---\r?\n/.test(content);
@@ -16704,10 +16830,11 @@ async function extractAsync(content) {
16704
16830
  frontMatter: result.matter
16705
16831
  };
16706
16832
  }
16707
- var grayMatter;
16833
+ var grayMatter, require2;
16708
16834
  var init_std_front_matter = __esm({
16709
16835
  "src/_shims/std-front-matter.ts"() {
16710
16836
  grayMatter = null;
16837
+ require2 = createRequire(import.meta.url);
16711
16838
  }
16712
16839
  });
16713
16840
 
@@ -16742,7 +16869,7 @@ function extractExportConstants(body) {
16742
16869
  const cleanedBody = body.replace(exportRegex, "");
16743
16870
  return { body: cleanedBody, exports };
16744
16871
  }
16745
- async function extractFrontmatter(content, providedFrontmatter) {
16872
+ async function extractFrontmatter2(content, providedFrontmatter) {
16746
16873
  let body = content;
16747
16874
  let frontmatter = providedFrontmatter || {};
16748
16875
  if (!providedFrontmatter && content.trim().startsWith("---")) {
@@ -16860,7 +16987,7 @@ async function compileMDXRuntime(mode, projectDir, content, frontmatter, filePat
16860
16987
  const { compile } = await import("@mdx-js/mdx");
16861
16988
  const remarkPlugins = await getRemarkPlugins(projectDir);
16862
16989
  const rehypePlugins = await getRehypePlugins(projectDir);
16863
- const extracted = await extractFrontmatter(content, frontmatter);
16990
+ const extracted = await extractFrontmatter2(content, frontmatter);
16864
16991
  let { body } = extracted;
16865
16992
  const { frontmatter: extractedFrontmatter } = extracted;
16866
16993
  if (filePath && (target === "browser" || target === "server")) {
@@ -16955,6 +17082,7 @@ async function transformToESM(source, filePath, projectDir, _adapter, options) {
16955
17082
  code = await resolvePathAliases(code, filePath, projectDir);
16956
17083
  if (ssr) {
16957
17084
  if (isNodeRuntime3()) {
17085
+ code = await resolveVeryfrontImports(code);
16958
17086
  code = await resolveRelativeImportsForNodeSSR(code);
16959
17087
  } else {
16960
17088
  code = await resolveRelativeImportsToAbsolute(code, filePath, projectDir);
@@ -16972,7 +17100,6 @@ async function transformToESM(source, filePath, projectDir, _adapter, options) {
16972
17100
  }
16973
17101
  var init_transform_core = __esm({
16974
17102
  "src/build/transforms/esm/transform-core.ts"() {
16975
- "use strict";
16976
17103
  init_transform_cache();
16977
17104
  init_transform_utils();
16978
17105
  init_react_imports();
@@ -18720,16 +18847,7 @@ var init_app_route_resolver = __esm({
18720
18847
  });
18721
18848
 
18722
18849
  // src/routing/slug-mapper/dynamic-route-matcher.ts
18723
- var dynamic_route_matcher_exports = {};
18724
- __export(dynamic_route_matcher_exports, {
18725
- extractParams: () => extractParams2,
18726
- isDynamicRoute: () => isDynamicRoute,
18727
- matchesPattern: () => matchesPattern
18728
- });
18729
- function isDynamicRoute(pattern) {
18730
- return /\[[\w.]+\]/.test(pattern);
18731
- }
18732
- function extractParams2(pattern, slug) {
18850
+ function extractParams(pattern, slug) {
18733
18851
  const patternParts = pattern.split("/").filter(Boolean);
18734
18852
  const slugParts = slug.split("/").filter(Boolean);
18735
18853
  const params = {};
@@ -18776,18 +18894,15 @@ function extractParams2(pattern, slug) {
18776
18894
  }
18777
18895
  return params;
18778
18896
  }
18779
- function matchesPattern(pattern, slug) {
18780
- return extractParams2(pattern, slug) !== null;
18781
- }
18782
18897
  var init_dynamic_route_matcher = __esm({
18783
18898
  "src/routing/slug-mapper/dynamic-route-matcher.ts"() {
18899
+ "use strict";
18784
18900
  }
18785
18901
  });
18786
18902
 
18787
18903
  // src/rendering/route-params-extractor.ts
18788
18904
  async function extractAppRouteParams(projectDir, slug, adapter) {
18789
18905
  const { join: pathJoin } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
18790
- const { extractParams: extractParams4 } = await Promise.resolve().then(() => (init_dynamic_route_matcher(), dynamic_route_matcher_exports));
18791
18906
  const segments = slug ? slug.split("/").filter(Boolean) : [];
18792
18907
  let currentDir = pathJoin(projectDir, "app");
18793
18908
  const patternParts = [];
@@ -18830,7 +18945,7 @@ async function extractAppRouteParams(projectDir, slug, adapter) {
18830
18945
  }
18831
18946
  }
18832
18947
  const pattern = patternParts.join("/");
18833
- return extractParams4(pattern, slug);
18948
+ return extractParams(pattern, slug);
18834
18949
  }
18835
18950
  async function extractPagesRouteParams(projectDir, slug, adapter) {
18836
18951
  const { join: pathJoin } = await Promise.resolve().then(() => (init_std_path(), std_path_exports));
@@ -18891,6 +19006,7 @@ function isDynamicSegment2(name) {
18891
19006
  var init_route_params_extractor = __esm({
18892
19007
  "src/rendering/route-params-extractor.ts"() {
18893
19008
  "use strict";
19009
+ init_dynamic_route_matcher();
18894
19010
  }
18895
19011
  });
18896
19012
 
@@ -18914,68 +19030,91 @@ async function detectAppRouter(projectDir, config, adapter) {
18914
19030
  const pagesDir = join2(projectDir, pagesDirName);
18915
19031
  let hasAppRoutes = false;
18916
19032
  let hasPagesRoutes = false;
18917
- try {
18918
- const appStat = await adapter.fs.stat(appDir);
18919
- if (appStat.isDirectory) {
18920
- hasAppRoutes = await hasRouteFiles(appDir, adapter);
18921
- }
18922
- } catch {
19033
+ const appStat = await statWithFallback(appDir, adapter);
19034
+ if (appStat?.isDirectory) {
19035
+ hasAppRoutes = await hasRouteFiles(appDir, adapter);
18923
19036
  }
18924
- try {
18925
- const pagesStat = await adapter.fs.stat(pagesDir);
18926
- if (pagesStat.isDirectory) {
18927
- hasPagesRoutes = await hasRouteFiles(pagesDir, adapter);
18928
- }
18929
- } catch {
19037
+ const pagesStat = await statWithFallback(pagesDir, adapter);
19038
+ if (pagesStat?.isDirectory) {
19039
+ hasPagesRoutes = await hasRouteFiles(pagesDir, adapter);
18930
19040
  }
18931
19041
  if (hasAppRoutes)
18932
19042
  return true;
18933
19043
  if (hasPagesRoutes)
18934
19044
  return false;
18935
- let hasAppDir = false;
18936
- let hasPagesDir = false;
18937
- try {
18938
- await adapter.fs.stat(appDir);
18939
- hasAppDir = true;
18940
- } catch {
18941
- }
18942
- try {
18943
- await adapter.fs.stat(pagesDir);
18944
- hasPagesDir = true;
18945
- } catch {
18946
- }
19045
+ const hasAppDir = Boolean(appStat?.isDirectory);
19046
+ const hasPagesDir = Boolean(pagesStat?.isDirectory);
18947
19047
  if (hasAppDir)
18948
19048
  return true;
18949
19049
  if (hasPagesDir)
18950
19050
  return false;
18951
- return true;
19051
+ return false;
18952
19052
  }
18953
19053
  async function hasRouteFiles(dir, adapter) {
18954
19054
  const routeExtensions = [".mdx", ".tsx", ".jsx", ".ts", ".js"];
18955
19055
  const routePatterns = ["page", "layout", "error", "loading", "not-found"];
18956
- try {
18957
- const entries = await adapter.fs.readDir(dir);
18958
- for await (const entry of entries) {
18959
- if (entry.isFile) {
18960
- const name = entry.name.toLowerCase();
18961
- const hasRouteExtension = routeExtensions.some((ext) => name.endsWith(ext));
18962
- if (hasRouteExtension) {
18963
- const isRouteFile = routePatterns.some((pattern) => name.startsWith(pattern));
18964
- const isIndexFile = name.startsWith("index");
18965
- if (isRouteFile || isIndexFile) {
18966
- return true;
18967
- }
18968
- }
18969
- } else if (entry.isDirectory) {
18970
- const hasNested = await hasRouteFiles(join2(dir, entry.name), adapter);
18971
- if (hasNested)
19056
+ const entries = await readDirWithFallback(dir, adapter);
19057
+ for (const entry of entries) {
19058
+ if (entry.isFile) {
19059
+ const name = entry.name.toLowerCase();
19060
+ const hasRouteExtension = routeExtensions.some((ext) => name.endsWith(ext));
19061
+ if (hasRouteExtension) {
19062
+ const isRouteFile = routePatterns.some((pattern) => name.startsWith(pattern));
19063
+ const isIndexFile = name.startsWith("index");
19064
+ if (isRouteFile || isIndexFile) {
18972
19065
  return true;
19066
+ }
18973
19067
  }
19068
+ } else if (entry.isDirectory) {
19069
+ const hasNested = await hasRouteFiles(join2(dir, entry.name), adapter);
19070
+ if (hasNested)
19071
+ return true;
18974
19072
  }
18975
- } catch {
18976
19073
  }
18977
19074
  return false;
18978
19075
  }
19076
+ async function statWithFallback(path, adapter) {
19077
+ try {
19078
+ return await adapter.fs.stat(path);
19079
+ } catch {
19080
+ try {
19081
+ const stat2 = await Deno.stat(path);
19082
+ return {
19083
+ size: stat2.size,
19084
+ isFile: stat2.isFile,
19085
+ isDirectory: stat2.isDirectory,
19086
+ isSymlink: stat2.isSymlink,
19087
+ mtime: stat2.mtime
19088
+ };
19089
+ } catch {
19090
+ return null;
19091
+ }
19092
+ }
19093
+ }
19094
+ async function readDirWithFallback(dir, adapter) {
19095
+ try {
19096
+ const entries = [];
19097
+ for await (const entry of adapter.fs.readDir(dir)) {
19098
+ entries.push(entry);
19099
+ }
19100
+ return entries;
19101
+ } catch {
19102
+ try {
19103
+ const entries = [];
19104
+ for await (const entry of Deno.readDir(dir)) {
19105
+ entries.push({
19106
+ name: entry.name,
19107
+ isFile: entry.isFile,
19108
+ isDirectory: entry.isDirectory,
19109
+ isSymlink: entry.isSymlink
19110
+ });
19111
+ }
19112
+ return entries;
19113
+ } catch {
19114
+ return [];
19115
+ }
19116
+ }
19117
+ }
18979
19118
  var init_router_detection = __esm({
18980
19119
  "src/rendering/router-detection.ts"() {
18981
19120
  "use strict";
@@ -19261,7 +19400,7 @@ async function loadMDXLayout(bundle, projectDir, adapter) {
19261
19400
  const mod = await mdxRenderer.loadModuleESM(code);
19262
19401
  return mod.MDXLayout || mod.MainLayout || mod.default;
19263
19402
  }
19264
- async function applyTSXLayout(element, item, tsxLayoutModuleCache, projectDir, adapter) {
19403
+ async function applyTSXLayout(element, item, tsxLayoutModuleCache, projectDir, adapter, props) {
19265
19404
  const React11 = await getProjectReact();
19266
19405
  try {
19267
19406
  const LayoutComponent2 = await loadTSXComponent(
@@ -19270,7 +19409,7 @@ async function applyTSXLayout(element, item, tsxLayoutModuleCache, projectDir, a
19270
19409
  tsxLayoutModuleCache,
19271
19410
  adapter
19272
19411
  );
19273
- return React11.createElement(LayoutComponent2, {}, element);
19412
+ return React11.createElement(LayoutComponent2, props || {}, element);
19274
19413
  } catch (e) {
19275
19414
  rendererLogger.error("Failed to compile/import TSX layout", e);
19276
19415
  throw e;
@@ -19355,7 +19494,7 @@ var init_component_loader2 = __esm({
19355
19494
  });
19356
19495
 
19357
19496
  // src/rendering/layouts/utils/applicator.ts
19358
- async function applyLayoutsESM(pageElement, layoutBundle, nestedLayouts, providerItems, projectDir, mergedComponents, tsxLayoutModuleCache, adapter) {
19497
+ async function applyLayoutsESM(pageElement, layoutBundle, nestedLayouts, providerItems, projectDir, mergedComponents, tsxLayoutModuleCache, adapter, layoutDataMap) {
19359
19498
  let element = pageElement;
19360
19499
  if (nestedLayouts.length > 0) {
19361
19500
  for (let i = nestedLayouts.length - 1; i >= 0; i--) {
@@ -19372,7 +19511,15 @@ async function applyLayoutsESM(pageElement, layoutBundle, nestedLayouts, provide
19372
19511
  adapter
19373
19512
  );
19374
19513
  } else if (item.kind === "tsx") {
19375
- element = await applyTSXLayout(element, item, tsxLayoutModuleCache, projectDir, adapter);
19514
+ const props = item.componentPath ? layoutDataMap?.get(item.componentPath) : void 0;
19515
+ element = await applyTSXLayout(
19516
+ element,
19517
+ item,
19518
+ tsxLayoutModuleCache,
19519
+ projectDir,
19520
+ adapter,
19521
+ props
19522
+ );
19376
19523
  }
19377
19524
  } catch (e) {
19378
19525
  rendererLogger.error("Failed to apply nested layout:", e);
@@ -19395,7 +19542,7 @@ async function applyLayoutsESM(pageElement, layoutBundle, nestedLayouts, provide
19395
19542
  }
19396
19543
  return element;
19397
19544
  }
19398
- async function applyLayoutsFunctionBody(pageElement, layoutBundle, nestedLayouts, providerItems, mergedComponents, tsxLayoutModuleCache, projectDir, adapter) {
19545
+ async function applyLayoutsFunctionBody(pageElement, layoutBundle, nestedLayouts, providerItems, mergedComponents, tsxLayoutModuleCache, projectDir, adapter, layoutDataMap) {
19399
19546
  const React11 = await getProjectReact();
19400
19547
  let element = pageElement;
19401
19548
  rendererLogger.debug("Using function-body wrapping for layouts");
@@ -19434,7 +19581,8 @@ async function applyLayoutsFunctionBody(pageElement, layoutBundle, nestedLayouts
19434
19581
  layoutName: LayoutComponent2.name || "Anonymous",
19435
19582
  childType: React11.isValidElement(child) ? getElementTypeName(child) : typeof child
19436
19583
  });
19437
- element = React11.createElement(LayoutComponent2, void 0, child);
19584
+ const props = item.componentPath ? layoutDataMap?.get(item.componentPath) : void 0;
19585
+ element = React11.createElement(LayoutComponent2, props, child);
19438
19586
  rendererLogger.info("After TSX layout applied:", {
19439
19587
  pageElementType: React11.isValidElement(element) ? getElementTypeName(element) : typeof element
19440
19588
  });
@@ -19670,12 +19818,13 @@ var init_layout_applicator = __esm({
19670
19818
  this.mode = options.mode;
19671
19819
  this.moduleServerUrl = options.moduleServerUrl;
19672
19820
  }
19673
- async applyLayouts(pageElement, pageInfo, layoutBundle, nestedLayouts, providerItems) {
19821
+ async applyLayouts(pageElement, pageInfo, layoutBundle, nestedLayouts, providerItems, layoutDataMap) {
19674
19822
  let wrappedElement = await this.applyLayoutsAndProviders(
19675
19823
  pageElement,
19676
19824
  layoutBundle,
19677
19825
  nestedLayouts,
19678
- providerItems
19826
+ providerItems,
19827
+ layoutDataMap
19679
19828
  );
19680
19829
  const useAppRouter = await detectAppRouter(this.projectDir, this.config, this.adapter);
19681
19830
  const pageFilePath = pageInfo.entity.id;
@@ -19686,7 +19835,7 @@ var init_layout_applicator = __esm({
19686
19835
  }
19687
19836
  return wrappedElement;
19688
19837
  }
19689
- async applyLayoutsAndProviders(pageElement, layoutBundle, nestedLayouts, providerItems) {
19838
+ async applyLayoutsAndProviders(pageElement, layoutBundle, nestedLayouts, providerItems, layoutDataMap) {
19690
19839
  rendererLogger.info("Number of nested layouts found:", nestedLayouts.length);
19691
19840
  const useESMWrap = Boolean(this.config?.experimental?.esmLayouts);
19692
19841
  if (useESMWrap) {
@@ -19694,18 +19843,20 @@ var init_layout_applicator = __esm({
19694
19843
  pageElement,
19695
19844
  layoutBundle,
19696
19845
  nestedLayouts,
19697
- providerItems
19846
+ providerItems,
19847
+ layoutDataMap
19698
19848
  );
19699
19849
  } else {
19700
19850
  return await this.applyLayoutsFunctionBodyMode(
19701
19851
  pageElement,
19702
19852
  layoutBundle,
19703
19853
  nestedLayouts,
19704
- providerItems
19854
+ providerItems,
19855
+ layoutDataMap
19705
19856
  );
19706
19857
  }
19707
19858
  }
19708
- async applyLayoutsESMMode(pageElement, layoutBundle, nestedLayouts, providerItems) {
19859
+ async applyLayoutsESMMode(pageElement, layoutBundle, nestedLayouts, providerItems, layoutDataMap) {
19709
19860
  return await applyLayoutsESM(
19710
19861
  pageElement,
19711
19862
  layoutBundle,
@@ -19714,10 +19865,11 @@ var init_layout_applicator = __esm({
19714
19865
  this.projectDir,
19715
19866
  this.mergedComponents,
19716
19867
  this.layoutCache,
19717
- this.adapter
19868
+ this.adapter,
19869
+ layoutDataMap
19718
19870
  );
19719
19871
  }
19720
- async applyLayoutsFunctionBodyMode(pageElement, layoutBundle, nestedLayouts, providerItems) {
19872
+ async applyLayoutsFunctionBodyMode(pageElement, layoutBundle, nestedLayouts, providerItems, layoutDataMap) {
19721
19873
  return await applyLayoutsFunctionBody(
19722
19874
  pageElement,
19723
19875
  layoutBundle,
@@ -19726,7 +19878,8 @@ var init_layout_applicator = __esm({
19726
19878
  this.mergedComponents,
19727
19879
  this.layoutCache,
19728
19880
  this.projectDir,
19729
- this.adapter
19881
+ this.adapter,
19882
+ layoutDataMap
19730
19883
  );
19731
19884
  }
19732
19885
  async wrapWithAppComponent(pageElement) {
@@ -20137,19 +20290,54 @@ var init_page_rendering = __esm({
20137
20290
  }
20138
20291
  });
20139
20292
 
20140
- // src/html/html-escape.ts
20141
- function escapeHTML(str) {
20142
- if (str == null)
20143
- return "";
20144
- const strValue = String(str);
20145
- return strValue.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
20293
+ // src/html/dev-scripts.ts
20294
+ function getDevStyles(nonce) {
20295
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
20296
+ return `
20297
+ <style${nonceAttr}>
20298
+ .dev-indicator {
20299
+ position: fixed;
20300
+ bottom: 1rem;
20301
+ right: 1rem;
20302
+ background: #3b82f6;
20303
+ color: white;
20304
+ padding: 0.5rem 1rem;
20305
+ border-radius: 0.5rem;
20306
+ font-size: 0.875rem;
20307
+ z-index: 9999;
20308
+ }
20309
+
20310
+ #veryfront-error-overlay {
20311
+ position: fixed;
20312
+ top: 0;
20313
+ left: 0;
20314
+ right: 0;
20315
+ bottom: 0;
20316
+ z-index: 999999;
20317
+ background: rgba(0,0,0,0.85);
20318
+ color: white;
20319
+ font-family: monospace;
20320
+ overflow: auto;
20321
+ padding: 2rem;
20322
+ }
20323
+ </style>`;
20146
20324
  }
20147
- function buildAttributes(attrs) {
20148
- return Object.entries(attrs).map(([key, value]) => `${key}="${escapeHTML(String(value))}"`).join(" ");
20325
+ function getDevScripts(port = DEFAULT_DASHBOARD_PORT, nonce) {
20326
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
20327
+ return `
20328
+ <script type="module" src="/_veryfront/rsc/client.js"${nonceAttr}></script>
20329
+ <script type="module" src="/_veryfront/hmr.js?port=${port}"${nonceAttr}></script>`;
20149
20330
  }
20150
- var init_html_escape = __esm({
20151
- "src/html/html-escape.ts"() {
20331
+ function getProdScripts(slug, nonce) {
20332
+ const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
20333
+ return `
20334
+ <script type="module" src="/_veryfront/rsc/client.js"${nonceAttr}></script>
20335
+ <script type="module" src="/_veryfront/hydrate.js?slug=${encodeURIComponent(slug)}"${nonceAttr}></script>`;
20336
+ }
20337
+ var init_dev_scripts = __esm({
20338
+ "src/html/dev-scripts.ts"() {
20152
20339
  "use strict";
20340
+ init_server();
20153
20341
  }
20154
20342
  });
20155
20343
 
@@ -20164,61 +20352,18 @@ var init_html_detection = __esm({
20164
20352
  }
20165
20353
  });
20166
20354
 
20167
- // src/html/metadata-extraction.ts
20168
- function extractHTMLMetadata(pageFrontmatter, layoutFrontmatter) {
20169
- const base = { ...layoutFrontmatter || {} };
20170
- const merged = { ...base, ...pageFrontmatter };
20171
- if (merged.metadata && typeof merged.metadata === "object") {
20172
- Object.assign(merged, merged.metadata);
20173
- }
20174
- const metadata = {
20175
- title: merged.title || "Veryfront App",
20176
- description: merged.description || "",
20177
- viewport: merged.viewport,
20178
- themeColor: merged.themeColor,
20179
- meta: [],
20180
- links: [],
20181
- icons: merged.icons || [],
20182
- scripts: [],
20183
- styles: []
20184
- };
20185
- if (merged.meta && Array.isArray(merged.meta)) {
20186
- metadata.meta = merged.meta;
20187
- }
20188
- if (merged.og) {
20189
- Object.entries(merged.og).forEach(([key, value]) => {
20190
- metadata.meta?.push({
20191
- property: `og:${key}`,
20192
- content: String(value)
20193
- });
20194
- });
20195
- }
20196
- if (merged.twitter) {
20197
- Object.entries(merged.twitter).forEach(([key, value]) => {
20198
- metadata.meta?.push({
20199
- name: `twitter:${key}`,
20200
- content: String(value)
20201
- });
20202
- });
20203
- }
20204
- if (merged.links && Array.isArray(merged.links)) {
20205
- metadata.links = merged.links;
20206
- }
20207
- if (merged.scripts && Array.isArray(merged.scripts)) {
20208
- metadata.scripts = merged.scripts;
20209
- }
20210
- if (merged.styles && Array.isArray(merged.styles)) {
20211
- metadata.styles = merged.styles;
20212
- }
20213
- Object.keys(merged).forEach((key) => {
20214
- if (!["title", "description", "meta", "links", "scripts", "styles", "og", "twitter"].includes(key)) {
20215
- metadata[key] = merged[key];
20216
- }
20217
- });
20218
- return metadata;
20355
+ // src/html/html-escape.ts
20356
+ function escapeHTML(str) {
20357
+ if (str == null)
20358
+ return "";
20359
+ const strValue = String(str);
20360
+ return strValue.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
20219
20361
  }
20220
- var init_metadata_extraction = __esm({
20221
- "src/html/metadata-extraction.ts"() {
20362
+ function buildAttributes(attrs) {
20363
+ return Object.entries(attrs).map(([key, value]) => `${key}="${escapeHTML(String(value))}"`).join(" ");
20364
+ }
20365
+ var init_html_escape = __esm({
20366
+ "src/html/html-escape.ts"() {
20222
20367
  "use strict";
20223
20368
  }
20224
20369
  });
@@ -20317,78 +20462,6 @@ var init_tag_generators = __esm({
20317
20462
  }
20318
20463
  });
20319
20464
 
20320
- // src/html/dev-scripts.ts
20321
- function getDevStyles() {
20322
- return `
20323
- <style>
20324
- .dev-indicator {
20325
- position: fixed;
20326
- bottom: 1rem;
20327
- right: 1rem;
20328
- background: #3b82f6;
20329
- color: white;
20330
- padding: 0.5rem 1rem;
20331
- border-radius: 0.5rem;
20332
- font-size: 0.875rem;
20333
- z-index: 9999;
20334
- }
20335
-
20336
- #veryfront-error-overlay {
20337
- position: fixed;
20338
- top: 0;
20339
- left: 0;
20340
- right: 0;
20341
- bottom: 0;
20342
- z-index: 999999;
20343
- background: rgba(0,0,0,0.85);
20344
- color: white;
20345
- font-family: monospace;
20346
- overflow: auto;
20347
- padding: 2rem;
20348
- }
20349
- </style>`;
20350
- }
20351
- function getDevScripts(port = DEFAULT_DASHBOARD_PORT) {
20352
- const reloadDelay = HMR_CLIENT_RELOAD_DELAY_MS;
20353
- return `
20354
- <script>
20355
- const indicator = document.createElement('div');
20356
- indicator.className = 'dev-indicator';
20357
- indicator.textContent = 'Development Mode';
20358
- document.body.appendChild(indicator);
20359
-
20360
- const ws = new WebSocket('ws://localhost:${port}/_ws');
20361
- ws.onmessage = (event) => {
20362
- const data = JSON.parse(event.data);
20363
- if (data.type === 'reload') {
20364
- location.reload();
20365
- }
20366
- };
20367
- ws.onclose = () => {
20368
- setTimeout(() => location.reload(), ${reloadDelay});
20369
- };
20370
-
20371
- window.__veryfrontHMRWebSocket = ws;
20372
- </script>
20373
- <script type="module" src="/_veryfront/client.js"></script>`;
20374
- }
20375
- function getProdScripts(slug) {
20376
- return `
20377
- <script type="module">
20378
- import { hydrate } from '/_veryfront/client.js';
20379
- hydrate('${slug}', {
20380
- ssr: true
20381
- });
20382
- </script>`;
20383
- }
20384
- var init_dev_scripts = __esm({
20385
- "src/html/dev-scripts.ts"() {
20386
- "use strict";
20387
- init_hmr();
20388
- init_server();
20389
- }
20390
- });
20391
-
20392
20465
  // src/html/html-injection.ts
20393
20466
  function injectHTMLContent(template, content, metadata, options) {
20394
20467
  let html3 = template;
@@ -20411,16 +20484,45 @@ function injectHTMLContent(template, content, metadata, options) {
20411
20484
  const styleTags = generateStyleTags(metadata);
20412
20485
  html3 = html3.replace(/{{\s*styles\s*}}/gi, styleTags);
20413
20486
  }
20487
+ if (options.pagePath && options.isClientPage && /<\/body>/i.test(html3)) {
20488
+ const hydrationData = JSON.stringify({
20489
+ pagePath: options.pagePath,
20490
+ slug: options.slug,
20491
+ isClientPage: true
20492
+ });
20493
+ const hydrationScript = `<script id="veryfront-hydration-data" type="application/json">${hydrationData}</script>`;
20494
+ html3 = html3.replace(/<\/body>/i, `${hydrationScript}</body>`);
20495
+ }
20496
+ let devScriptsInjected = false;
20414
20497
  if (options.mode === "development") {
20415
- html3 = html3.replace(
20416
- /{{\s*devScripts\s*}}/gi,
20417
- getDevScripts(options.slug, options.devPort || DEFAULT_DASHBOARD_PORT)
20418
- );
20498
+ if (/{{\s*devScripts\s*}}/i.test(html3)) {
20499
+ html3 = html3.replace(
20500
+ /{{\s*devScripts\s*}}/gi,
20501
+ getDevScripts(options.devPort || DEFAULT_DASHBOARD_PORT)
20502
+ );
20503
+ devScriptsInjected = true;
20504
+ }
20419
20505
  html3 = html3.replace(/{{\s*devStyles\s*}}/gi, getDevStyles());
20506
+ if (!devScriptsInjected && /<\/body>/i.test(html3)) {
20507
+ const devScripts = getDevScripts(options.devPort || DEFAULT_DASHBOARD_PORT);
20508
+ const devStyles = getDevStyles();
20509
+ html3 = html3.replace(
20510
+ /<\/body>/i,
20511
+ `${devStyles}${devScripts}</body>`
20512
+ );
20513
+ }
20420
20514
  } else {
20421
20515
  html3 = html3.replace(/{{\s*devScripts\s*}}/gi, "");
20422
20516
  html3 = html3.replace(/{{\s*devStyles\s*}}/gi, "");
20423
- html3 = html3.replace(/{{\s*prodScripts\s*}}/gi, getProdScripts(options.slug));
20517
+ let prodScriptsInjected = false;
20518
+ if (/{{\s*prodScripts\s*}}/i.test(html3)) {
20519
+ html3 = html3.replace(/{{\s*prodScripts\s*}}/gi, getProdScripts(options.slug));
20520
+ prodScriptsInjected = true;
20521
+ }
20522
+ if (!prodScriptsInjected && /<\/body>/i.test(html3)) {
20523
+ const prodScripts = getProdScripts(options.slug);
20524
+ html3 = html3.replace(/<\/body>/i, `${prodScripts}</body>`);
20525
+ }
20424
20526
  }
20425
20527
  return html3;
20426
20528
  }
@@ -20433,77 +20535,6 @@ var init_html_injection = __esm({
20433
20535
  }
20434
20536
  });
20435
20537
 
20436
- // src/html/utils.ts
20437
- function buildRootAttributes(slug, mode, noLayout) {
20438
- const attributes = [
20439
- 'id="root"',
20440
- noLayout ? "" : 'class="vf-tailwind"',
20441
- `data-veryfront-slug="${escapeHTML(slug || "")}"`,
20442
- `data-veryfront-mode="${escapeHTML(mode || "production")}"`
20443
- ].filter(Boolean).join(" ");
20444
- return attributes;
20445
- }
20446
- function buildContentAttributes(slug, noLayout, ssrHash) {
20447
- const attrs = [
20448
- 'id="veryfront-content"',
20449
- `data-slug="${slug || ""}"`,
20450
- `data-layout="${noLayout ? "none" : "default"}"`,
20451
- ssrHash ? `data-ssr-hash="${escapeHTML(ssrHash)}"` : ""
20452
- ].filter(Boolean).join(" ");
20453
- return attrs;
20454
- }
20455
- function getDefaultHTMLImportMap() {
20456
- return {
20457
- "react": "https://esm.sh/react@18.3.1",
20458
- "react-dom": "https://esm.sh/react-dom@18.3.1",
20459
- "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",
20460
- "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",
20461
- "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime"
20462
- };
20463
- }
20464
- function buildImportMapJson(importMap) {
20465
- const imports = importMap || getDefaultHTMLImportMap();
20466
- return JSON.stringify({ imports }, null, 2);
20467
- }
20468
- function shouldDisableLayout(frontmatter) {
20469
- return frontmatter?.layout === false || frontmatter?.layout === "false";
20470
- }
20471
- var init_utils4 = __esm({
20472
- "src/html/utils.ts"() {
20473
- "use strict";
20474
- init_html_escape();
20475
- }
20476
- });
20477
-
20478
- // src/html/metadata-builder.ts
20479
- function processMetadata(meta) {
20480
- const metadata = extractHTMLMetadata(
20481
- meta.frontmatter || {},
20482
- meta.layoutFrontmatter || {}
20483
- );
20484
- const effectiveTitle = meta.frontmatter?.title || meta.title || metadata.title;
20485
- const metaTags = generateMetaTags(metadata);
20486
- const linkTags = generateLinkTags(metadata);
20487
- const scriptTags = generateScriptTags(metadata);
20488
- const styleTags = generateStyleTags(metadata);
20489
- return {
20490
- metadata,
20491
- effectiveTitle: effectiveTitle || "Veryfront App",
20492
- metaTags,
20493
- linkTags,
20494
- scriptTags,
20495
- styleTags,
20496
- lang: typeof metadata.lang === "string" ? metadata.lang : "en",
20497
- bodyClass: typeof metadata.bodyClass === "string" ? metadata.bodyClass : ""
20498
- };
20499
- }
20500
- var init_metadata_builder = __esm({
20501
- "src/html/metadata-builder.ts"() {
20502
- "use strict";
20503
- init_html2();
20504
- }
20505
- });
20506
-
20507
20538
  // src/html/hydration-script-builder/hydration-data-generator.ts
20508
20539
  function generateHydrationData(slug, params, props, options) {
20509
20540
  const data = {
@@ -20914,6 +20945,35 @@ var init_hydration_script_builder = __esm({
20914
20945
  }
20915
20946
  });
20916
20947
 
20948
+ // src/html/metadata-builder.ts
20949
+ function processMetadata(meta) {
20950
+ const metadata = extractHTMLMetadata(
20951
+ meta.frontmatter || {},
20952
+ meta.layoutFrontmatter || {}
20953
+ );
20954
+ const effectiveTitle = meta.frontmatter?.title || meta.title || metadata.title;
20955
+ const metaTags = generateMetaTags(metadata);
20956
+ const linkTags = generateLinkTags(metadata);
20957
+ const scriptTags = generateScriptTags(metadata);
20958
+ const styleTags = generateStyleTags(metadata);
20959
+ return {
20960
+ metadata,
20961
+ effectiveTitle: effectiveTitle || "Veryfront App",
20962
+ metaTags,
20963
+ linkTags,
20964
+ scriptTags,
20965
+ styleTags,
20966
+ lang: typeof metadata.lang === "string" ? metadata.lang : "en",
20967
+ bodyClass: typeof metadata.bodyClass === "string" ? metadata.bodyClass : ""
20968
+ };
20969
+ }
20970
+ var init_metadata_builder = __esm({
20971
+ "src/html/metadata-builder.ts"() {
20972
+ "use strict";
20973
+ init_html2();
20974
+ }
20975
+ });
20976
+
20917
20977
  // src/html/styles-builder/theme-variables.ts
20918
20978
  function generateThemeVariables() {
20919
20979
  return `
@@ -21288,7 +21348,8 @@ async function ensureInitialized() {
21288
21348
  ]
21289
21349
  });
21290
21350
  }
21291
- if (resetTailwind === null) {
21351
+ if (!resetInitialized) {
21352
+ resetInitialized = true;
21292
21353
  try {
21293
21354
  resetTailwind = await fetch(getUnoCSSTailwindResetUrl()).then((r) => r.text());
21294
21355
  } catch (error2) {
@@ -21312,20 +21373,63 @@ ${result.css}`;
21312
21373
  return "";
21313
21374
  }
21314
21375
  }
21315
- var resetTailwind, uno;
21376
+ var resetTailwind, resetInitialized, uno;
21316
21377
  var init_unocss_generator = __esm({
21317
21378
  "src/html/styles-builder/unocss-generator.ts"() {
21318
21379
  "use strict";
21319
21380
  init_utils();
21320
21381
  init_cdn();
21321
- resetTailwind = null;
21382
+ resetTailwind = "";
21383
+ resetInitialized = false;
21322
21384
  uno = null;
21323
21385
  }
21324
21386
  });
21325
21387
 
21388
+ // src/html/utils.ts
21389
+ function buildRootAttributes(slug, mode, noLayout) {
21390
+ const attributes = [
21391
+ 'id="root"',
21392
+ noLayout ? "" : 'class="vf-tailwind"',
21393
+ `data-veryfront-slug="${escapeHTML(slug || "")}"`,
21394
+ `data-veryfront-mode="${escapeHTML(mode || "production")}"`
21395
+ ].filter(Boolean).join(" ");
21396
+ return attributes;
21397
+ }
21398
+ function buildContentAttributes(slug, noLayout, ssrHash) {
21399
+ const attrs = [
21400
+ 'id="veryfront-content"',
21401
+ `data-slug="${slug || ""}"`,
21402
+ `data-layout="${noLayout ? "none" : "default"}"`,
21403
+ ssrHash ? `data-ssr-hash="${escapeHTML(ssrHash)}"` : ""
21404
+ ].filter(Boolean).join(" ");
21405
+ return attrs;
21406
+ }
21407
+ function getDefaultHTMLImportMap() {
21408
+ return {
21409
+ "react": "https://esm.sh/react@18.3.1",
21410
+ "react-dom": "https://esm.sh/react-dom@18.3.1",
21411
+ "react-dom/client": "https://esm.sh/react-dom@18.3.1/client",
21412
+ "react/jsx-runtime": "https://esm.sh/react@18.3.1/jsx-runtime",
21413
+ "react/jsx-dev-runtime": "https://esm.sh/react@18.3.1/jsx-dev-runtime"
21414
+ };
21415
+ }
21416
+ function buildImportMapJson(importMap) {
21417
+ const imports = importMap || getDefaultHTMLImportMap();
21418
+ return JSON.stringify({ imports }, null, 2);
21419
+ }
21420
+ function shouldDisableLayout(frontmatter) {
21421
+ return frontmatter?.layout === false || frontmatter?.layout === "false";
21422
+ }
21423
+ var init_utils4 = __esm({
21424
+ "src/html/utils.ts"() {
21425
+ "use strict";
21426
+ init_html_escape();
21427
+ }
21428
+ });
21429
+
21326
21430
  // src/html/html-shell-generator.ts
21327
- async function wrapInHTMLShell(content, meta, options, params, props) {
21328
- const tailwindCSS = await generateTailwindCSS(content);
21431
+ async function generateHTMLShellParts(meta, options, params, props, contentForTailwind) {
21432
+ const tailwindCSS = contentForTailwind ? await generateTailwindCSS(contentForTailwind) : "";
21329
21433
  const {
21330
21434
  effectiveTitle,
21331
21435
  metaTags,
@@ -21357,7 +21461,7 @@ async function wrapInHTMLShell(content, meta, options, params, props) {
21357
21461
  const modeScripts = options.mode === "development" ? getDevScripts2(meta.slug || "", options.config, params, props, nonce) : getProdScripts2(meta.slug || "", params, props, nonce);
21358
21462
  const modeStyles = options.mode === "development" ? getDevStyles2(nonce) : getProductionStyles(nonce);
21359
21463
  const syntaxHighlightTheme = options.mode === "development" ? "github-dark" : "github";
21360
- return `<!DOCTYPE html>
21464
+ const start = `<!DOCTYPE html>
21361
21465
  <html lang="${escapeHTML(lang)}">
21362
21466
  <head>
21363
21467
  ${metaTags}
@@ -21387,7 +21491,8 @@ ${tailwindCSS}
21387
21491
  <body${bodyClass ? ` class="${bodyClass}"` : ""}>
21388
21492
  <div ${rootAttributes}>
21389
21493
  <div ${contentAttributes}>
21390
- ${content}
21494
+ `;
21495
+ const end = `
21391
21496
  </div>
21392
21497
  </div>
21393
21498
  <div id="veryfront-portals"></div>
@@ -21401,32 +21506,102 @@ ${tailwindCSS}
21401
21506
  ${modeScripts}
21402
21507
  </body>
21403
21508
  </html>`;
21509
+ return { start, end };
21510
+ }
21511
+ async function wrapInHTMLShell(content, meta, options, params, props) {
21512
+ const { start, end } = await generateHTMLShellParts(
21513
+ meta,
21514
+ options,
21515
+ params,
21516
+ props,
21517
+ content
21518
+ );
21519
+ return `${start}${content}${end}`;
21404
21520
  }
21405
21521
  var init_html_shell_generator = __esm({
21406
21522
  "src/html/html-shell-generator.ts"() {
21407
21523
  "use strict";
21408
- init_utils4();
21409
21524
  init_html_escape();
21410
- init_metadata_builder();
21411
21525
  init_hydration_script_builder();
21526
+ init_metadata_builder();
21412
21527
  init_styles_builder();
21413
21528
  init_unocss_generator();
21529
+ init_utils4();
21530
+ }
21531
+ });
21532
+
21533
+ // src/html/metadata-extraction.ts
21534
+ function extractHTMLMetadata(pageFrontmatter, layoutFrontmatter) {
21535
+ const base = { ...layoutFrontmatter || {} };
21536
+ const merged = { ...base, ...pageFrontmatter };
21537
+ if (merged.metadata && typeof merged.metadata === "object") {
21538
+ Object.assign(merged, merged.metadata);
21539
+ }
21540
+ const metadata = {
21541
+ title: merged.title || "Veryfront App",
21542
+ description: merged.description || "",
21543
+ viewport: merged.viewport,
21544
+ themeColor: merged.themeColor,
21545
+ meta: [],
21546
+ links: [],
21547
+ icons: merged.icons || [],
21548
+ scripts: [],
21549
+ styles: []
21550
+ };
21551
+ if (merged.meta && Array.isArray(merged.meta)) {
21552
+ metadata.meta = merged.meta;
21553
+ }
21554
+ if (merged.og) {
21555
+ Object.entries(merged.og).forEach(([key, value]) => {
21556
+ metadata.meta?.push({
21557
+ property: `og:${key}`,
21558
+ content: String(value)
21559
+ });
21560
+ });
21561
+ }
21562
+ if (merged.twitter) {
21563
+ Object.entries(merged.twitter).forEach(([key, value]) => {
21564
+ metadata.meta?.push({
21565
+ name: `twitter:${key}`,
21566
+ content: String(value)
21567
+ });
21568
+ });
21569
+ }
21570
+ if (merged.links && Array.isArray(merged.links)) {
21571
+ metadata.links = merged.links;
21572
+ }
21573
+ if (merged.scripts && Array.isArray(merged.scripts)) {
21574
+ metadata.scripts = merged.scripts;
21575
+ }
21576
+ if (merged.styles && Array.isArray(merged.styles)) {
21577
+ metadata.styles = merged.styles;
21578
+ }
21579
+ Object.keys(merged).forEach((key) => {
21580
+ if (!["title", "description", "meta", "links", "scripts", "styles", "og", "twitter"].includes(key)) {
21581
+ metadata[key] = merged[key];
21582
+ }
21583
+ });
21584
+ return metadata;
21585
+ }
21586
+ var init_metadata_extraction = __esm({
21587
+ "src/html/metadata-extraction.ts"() {
21588
+ "use strict";
21414
21589
  }
21415
21590
  });
21416
21591
 
21417
21592
  // src/html/index.ts
21418
21593
  var init_html2 = __esm({
21419
21594
  "src/html/index.ts"() {
21420
- init_html_escape();
21595
+ init_dev_scripts();
21421
21596
  init_html_detection();
21422
- init_metadata_extraction();
21423
- init_tag_generators();
21597
+ init_html_escape();
21424
21598
  init_html_injection();
21425
21599
  init_html_shell_generator();
21426
- init_metadata_builder();
21427
21600
  init_hydration_script_builder();
21428
- init_dev_scripts();
21601
+ init_metadata_builder();
21602
+ init_metadata_extraction();
21429
21603
  init_styles_builder();
21604
+ init_tag_generators();
21430
21605
  init_utils4();
21431
21606
  }
21432
21607
  });
@@ -22762,9 +22937,9 @@ var SSRRenderer;
22762
22937
  var init_ssr_renderer = __esm({
22763
22938
  "src/rendering/ssr-renderer.ts"() {
22764
22939
  "use strict";
22765
- init_utils();
22766
22940
  init_errors();
22767
22941
  init_react();
22942
+ init_utils();
22768
22943
  init_utils3();
22769
22944
  SSRRenderer = class {
22770
22945
  constructor(mode, adapter) {
@@ -22784,15 +22959,18 @@ var init_ssr_renderer = __esm({
22784
22959
  * @returns HTML string and optional stream
22785
22960
  */
22786
22961
  async renderToHTML(pageElement, options) {
22787
- let html3;
22962
+ let html3 = "";
22788
22963
  let stream2 = null;
22789
22964
  const versionInfo = getReactVersionInfo();
22790
22965
  const useStreaming = !isCompiledBinary() && (this.mode === "production" || options.wantsStream) && (versionInfo.isReact18 || versionInfo.isReact19);
22791
22966
  if (isCompiledBinary() && (this.mode === "production" || options.wantsStream)) {
22792
- rendererLogger.info("Streaming SSR disabled in compiled binary (using string rendering)", {
22793
- reactVersion: versionInfo.version,
22794
- reason: "Workers with blob URLs not supported in deno compile binaries"
22795
- });
22967
+ rendererLogger.info(
22968
+ "Streaming SSR disabled in compiled binary (using string rendering)",
22969
+ {
22970
+ reactVersion: versionInfo.version,
22971
+ reason: "Workers with blob URLs not supported in deno compile binaries"
22972
+ }
22973
+ );
22796
22974
  }
22797
22975
  if (useStreaming) {
22798
22976
  rendererLogger.info("Rendering via streaming adapter", {
@@ -22801,18 +22979,27 @@ var init_ssr_renderer = __esm({
22801
22979
  });
22802
22980
  const renderResult = await renderToStreamAdapter(pageElement);
22803
22981
  if (renderResult.stream) {
22804
- let streamForBuffer = renderResult.stream;
22805
22982
  if (options.wantsStream && typeof renderResult.stream.tee === "function") {
22806
22983
  const [clientStream, bufferStream] = renderResult.stream.tee();
22807
22984
  stream2 = clientStream;
22808
- streamForBuffer = bufferStream;
22809
- }
22810
- html3 = await streamToString(streamForBuffer);
22811
- if (options.debugMode) {
22812
- rendererLogger.debug("Streaming SSR completed", { htmlLength: html3.length });
22985
+ html3 = await streamToString(bufferStream);
22986
+ if (options.debugMode) {
22987
+ rendererLogger.debug("Streaming SSR - teeing stream and buffering copy", {
22988
+ htmlLength: html3.length
22989
+ });
22990
+ }
22991
+ } else {
22992
+ html3 = await streamToString(renderResult.stream);
22993
+ if (options.debugMode) {
22994
+ rendererLogger.debug("Streaming SSR completed (buffered)", {
22995
+ htmlLength: html3.length
22996
+ });
22997
+ }
22813
22998
  }
22814
22999
  } else if (renderResult.pipe) {
22815
- rendererLogger.info("Converting pipeable stream to string (Node.js renderToPipeableStream)");
23000
+ rendererLogger.info(
23001
+ "Converting pipeable stream to string (Node.js renderToPipeableStream)"
23002
+ );
22816
23003
  html3 = await pipeToString(renderResult.pipe);
22817
23004
  if (options.debugMode) {
22818
23005
  rendererLogger.debug("Pipeable SSR completed", { htmlLength: html3.length });
@@ -22820,7 +23007,10 @@ var init_ssr_renderer = __esm({
22820
23007
  } else if (renderResult.html) {
22821
23008
  html3 = renderResult.html;
22822
23009
  } else {
22823
- throw new VeryfrontError("SSR failed - no output", "RENDER_ERROR" /* RENDER_ERROR */);
23010
+ throw new VeryfrontError(
23011
+ "SSR failed - no output",
23012
+ "RENDER_ERROR" /* RENDER_ERROR */
23013
+ );
22824
23014
  }
22825
23015
  } else {
22826
23016
  rendererLogger.debug("Using string SSR", {
@@ -23091,7 +23281,7 @@ var init_lifecycle = __esm({
23091
23281
  var compiler_exports = {};
23092
23282
  __export(compiler_exports, {
23093
23283
  compileMDXRuntime: () => compileMDXRuntime,
23094
- extractFrontmatter: () => extractFrontmatter,
23284
+ extractFrontmatter: () => extractFrontmatter2,
23095
23285
  rewriteBodyImports: () => rewriteBodyImports,
23096
23286
  rewriteCompiledImports: () => rewriteCompiledImports
23097
23287
  });
@@ -23163,7 +23353,7 @@ var init_layout = __esm({
23163
23353
  async collectProviders() {
23164
23354
  return await this.config.providerManager.collectProviders();
23165
23355
  }
23166
- async applyLayoutsAndWrappers(pageElement, pageInfo, layoutBundle, nestedLayouts, providerItems) {
23356
+ async applyLayoutsAndWrappers(pageElement, pageInfo, layoutBundle, nestedLayouts, providerItems, layoutDataMap) {
23167
23357
  const defaultComponents = createDefaultMDXComponents();
23168
23358
  const mergedComponents = { ...defaultComponents, ...this.config.componentRegistry };
23169
23359
  const layoutApplicator = new LayoutApplicator({
@@ -23180,7 +23370,8 @@ var init_layout = __esm({
23180
23370
  pageInfo,
23181
23371
  layoutBundle,
23182
23372
  nestedLayouts,
23183
- providerItems
23373
+ providerItems,
23374
+ layoutDataMap
23184
23375
  );
23185
23376
  }
23186
23377
  };
@@ -23193,30 +23384,110 @@ var init_html3 = __esm({
23193
23384
  "src/rendering/orchestrator/html.ts"() {
23194
23385
  "use strict";
23195
23386
  init_std_path();
23196
- init_utils();
23197
- init_html2();
23198
23387
  init_html2();
23199
- init_router_detection();
23200
23388
  init_utils();
23389
+ init_router_detection();
23201
23390
  HTMLGenerator = class {
23202
23391
  constructor(config) {
23203
23392
  this.config = config;
23204
23393
  }
23205
23394
  async generateFullHTML(context2) {
23206
23395
  if (isFullHTMLDocument(context2.html)) {
23207
- return this.handleFullHTMLDocument(context2);
23396
+ return await this.handleFullHTMLDocument(context2);
23208
23397
  }
23209
23398
  return await this.wrapHTMLFragment(context2);
23210
23399
  }
23211
- handleFullHTMLDocument(context2) {
23400
+ /**
23401
+ * Generate HTML stream for streaming SSR
23402
+ * Wraps the React stream with HTML shell parts
23403
+ */
23404
+ async generateHTMLStream(reactStream, context2) {
23405
+ const mergedFrontmatter = this.mergeFrontmatter(
23406
+ context2
23407
+ );
23408
+ const useAppRouter = await detectAppRouter(
23409
+ this.config.projectDir,
23410
+ this.config.config,
23411
+ this.config.adapter
23412
+ );
23413
+ const appComponentPath = await this.resolveAppComponentPath(useAppRouter);
23414
+ const htmlOptions = {
23415
+ mode: this.config.mode,
23416
+ config: this.config.config,
23417
+ nestedLayouts: context2.nestedLayouts.map((l) => ({
23418
+ kind: l.kind,
23419
+ path: l.path,
23420
+ componentPath: l.componentPath
23421
+ })),
23422
+ providerPaths: context2.providerInfos.map((p) => p.entity.id),
23423
+ appPath: appComponentPath,
23424
+ pagePath: context2.pageInfo.entity.id,
23425
+ nonce: context2.options?.nonce
23426
+ };
23427
+ const { start, end } = await generateHTMLShellParts(
23428
+ {
23429
+ title: mergedFrontmatter.title || "Veryfront App",
23430
+ description: mergedFrontmatter.description || "",
23431
+ slug: context2.slug,
23432
+ frontmatter: mergedFrontmatter,
23433
+ layoutFrontmatter: context2.layoutBundle?.frontmatter,
23434
+ ssrHash: context2.ssrHash
23435
+ },
23436
+ htmlOptions,
23437
+ context2.options?.params,
23438
+ context2.options?.props
23439
+ );
23440
+ const encoder = new TextEncoder();
23441
+ const startChunk = encoder.encode(start);
23442
+ const endChunk = encoder.encode(end);
23443
+ return new ReadableStream({
23444
+ start(controller) {
23445
+ controller.enqueue(startChunk);
23446
+ },
23447
+ async pull(controller) {
23448
+ const reader = reactStream.getReader();
23449
+ try {
23450
+ while (true) {
23451
+ const { done, value } = await reader.read();
23452
+ if (done) {
23453
+ controller.enqueue(endChunk);
23454
+ controller.close();
23455
+ break;
23456
+ }
23457
+ controller.enqueue(value);
23458
+ }
23459
+ } catch (error2) {
23460
+ controller.error(error2);
23461
+ } finally {
23462
+ reader.releaseLock();
23463
+ }
23464
+ }
23465
+ });
23466
+ }
23467
+ async handleFullHTMLDocument(context2) {
23212
23468
  const metadata = extractHTMLMetadata(
23213
23469
  context2.pageInfo.entity.frontmatter || {},
23214
23470
  context2.layoutBundle?.frontmatter || {}
23215
23471
  );
23472
+ let isClientPage = false;
23473
+ const pagePath = context2.pageInfo.entity.id;
23474
+ try {
23475
+ const pageContent = await this.config.adapter.fs.readFile(pagePath);
23476
+ isClientPage = /^\s*['"]use client['"];?\s*$/m.test(pageContent);
23477
+ if (isClientPage) {
23478
+ rendererLogger.info(`[HTMLGenerator] Detected 'use client' page: ${pagePath}`);
23479
+ }
23480
+ } catch (_e) {
23481
+ rendererLogger.debug(
23482
+ `[HTMLGenerator] Could not read page file for directive detection: ${pagePath}`
23483
+ );
23484
+ }
23216
23485
  const injectedHtml = injectHTMLContent(context2.html, "", metadata, {
23217
23486
  mode: this.config.mode,
23218
23487
  slug: context2.slug,
23219
- devPort: this.config.config?.dev?.port || DEFAULT_DASHBOARD_PORT
23488
+ devPort: this.config.config?.dev?.port || DEFAULT_DASHBOARD_PORT,
23489
+ pagePath: isClientPage ? pagePath : void 0,
23490
+ isClientPage
23220
23491
  });
23221
23492
  return injectedHtml.trimStart().toLowerCase().startsWith("<!doctype") ? injectedHtml : `<!DOCTYPE html>
23222
23493
  ${injectedHtml}`;
@@ -23572,23 +23843,39 @@ var init_pipeline = __esm({
23572
23843
  const hashArray = Array.from(new Uint8Array(hashBuffer));
23573
23844
  return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("").slice(0, 16);
23574
23845
  }
23846
+ async loadModule(filePath) {
23847
+ const fileContent = await this.config.adapter.fs.readFile(filePath);
23848
+ const { transformToESM: transformToESM2 } = await Promise.resolve().then(() => (init_esm_transform(), esm_transform_exports));
23849
+ const { getGlobalTmpDir: getGlobalTmpDir2 } = await Promise.resolve().then(() => (init_react_loader(), react_loader_exports));
23850
+ const transformedCode = await transformToESM2(
23851
+ fileContent,
23852
+ filePath,
23853
+ this.config.projectDir,
23854
+ this.config.adapter,
23855
+ {
23856
+ projectId: this.config.projectDir,
23857
+ dev: this.config.mode === "development",
23858
+ ssr: true
23859
+ // Required for Node.js SSR - prevents esm.sh URL transformation
23860
+ }
23861
+ );
23862
+ const tmpDir = await getGlobalTmpDir2();
23863
+ const hash = await this.generateHash(filePath);
23864
+ const tempFilePath = `${tmpDir}/mod-${hash}.js`;
23865
+ await this.config.adapter.fs.writeFile(tempFilePath, transformedCode);
23866
+ const moduleUrl = `file://${tempFilePath}?t=${Date.now()}`;
23867
+ return await import(moduleUrl);
23868
+ }
23575
23869
  async renderPage(slug, options) {
23576
23870
  const pageInfo = await this.config.pageResolver.resolvePage(slug);
23871
+ const layoutResult = await this.config.layoutOrchestrator.collectLayouts(pageInfo);
23872
+ const providerResult = await this.config.layoutOrchestrator.collectProviders();
23577
23873
  let dataFetchingProps;
23578
- let loadedPageModule;
23874
+ const layoutDataMap = /* @__PURE__ */ new Map();
23579
23875
  const fileExtension = pageInfo.entity.id.split(".").pop()?.toLowerCase() || "";
23580
23876
  const isComponentPage = ["tsx", "jsx", "ts", "js"].includes(fileExtension);
23581
23877
  const isInPagesDir = pageInfo.entity.id.includes("/pages/");
23582
- rendererLogger.info("[renderPage] Data fetching check", {
23583
- slug,
23584
- fileExtension,
23585
- isComponentPage,
23586
- isInPagesDir,
23587
- hasRequest: !!options?.request,
23588
- hasUrl: !!options?.url,
23589
- pageId: pageInfo.entity.id
23590
- });
23591
- if (isComponentPage && isInPagesDir && options?.request && options?.url) {
23878
+ if (options?.request && options?.url) {
23592
23879
  try {
23593
23880
  if (!options.params || Object.keys(options.params).length === 0) {
23594
23881
  rendererLogger.info("[renderPage] Attempting to extract Pages Router params", {
@@ -23641,82 +23928,77 @@ var init_pipeline = __esm({
23641
23928
  });
23642
23929
  }
23643
23930
  }
23644
- rendererLogger.info("[renderPage] Loading page module for data fetching", {
23645
- pageId: pageInfo.entity.id
23646
- });
23647
- const fileContent = await this.config.adapter.fs.readFile(pageInfo.entity.id);
23648
- const { transformToESM: transformToESM2 } = await Promise.resolve().then(() => (init_esm_transform(), esm_transform_exports));
23649
- const { getGlobalTmpDir: getGlobalTmpDir2 } = await Promise.resolve().then(() => (init_react_loader(), react_loader_exports));
23650
- const transformedCode = await transformToESM2(
23651
- fileContent,
23652
- pageInfo.entity.id,
23653
- this.config.projectDir,
23654
- this.config.adapter,
23655
- {
23656
- projectId: this.config.projectDir,
23657
- dev: this.config.mode === "development"
23658
- }
23659
- );
23660
- const tmpDir = await getGlobalTmpDir2();
23661
- const hash = await this.generateHash(pageInfo.entity.id);
23662
- const tempFilePath = `${tmpDir}/page-${hash}.js`;
23663
- await this.config.adapter.fs.writeFile(tempFilePath, transformedCode);
23664
- const moduleUrl = `file://${tempFilePath}?t=${Date.now()}`;
23665
- loadedPageModule = await import(moduleUrl);
23666
- rendererLogger.info("[renderPage] Page module loaded", {
23667
- hasModule: !!loadedPageModule,
23668
- hasGetServerData: !!loadedPageModule?.getServerData,
23669
- hasGetStaticData: !!loadedPageModule?.getStaticData
23670
- });
23671
- if (loadedPageModule && (loadedPageModule.getServerData || loadedPageModule.getStaticData)) {
23672
- const dataContext = {
23673
- params: options.params || {},
23674
- query: options.url.searchParams,
23675
- request: options.request,
23676
- url: options.url
23677
- };
23678
- rendererLogger.info("[renderPage] Calling data fetching with context", {
23679
- slug,
23680
- params: dataContext.params,
23681
- queryString: dataContext.url.search
23682
- });
23683
- const dataResult = await this.dataFetcher.fetchData(
23684
- loadedPageModule,
23685
- dataContext,
23686
- this.config.mode
23687
- );
23688
- rendererLogger.info("[renderPage] Data result", {
23689
- slug,
23690
- hasNotFound: !!dataResult.notFound,
23691
- hasRedirect: !!dataResult.redirect,
23692
- hasProps: !!dataResult.props
23931
+ const jobs = [];
23932
+ const dataContext = {
23933
+ params: options.params || {},
23934
+ query: options.url.searchParams,
23935
+ request: options.request,
23936
+ url: options.url
23937
+ };
23938
+ if (isComponentPage && isInPagesDir) {
23939
+ jobs.push({
23940
+ type: "page",
23941
+ id: pageInfo.entity.id,
23942
+ run: async () => {
23943
+ const mod = await this.loadModule(pageInfo.entity.id);
23944
+ if (mod && (mod.getServerData || mod.getStaticData)) {
23945
+ return this.dataFetcher.fetchData(mod, dataContext, this.config.mode);
23946
+ }
23947
+ return null;
23948
+ }
23693
23949
  });
23694
- if (dataResult.notFound) {
23695
- throw new VeryfrontError(
23696
- "Page returned notFound",
23697
- "FILE_NOT_FOUND" /* FILE_NOT_FOUND */,
23698
- { slug }
23699
- );
23950
+ }
23951
+ for (const layout of layoutResult.nestedLayouts) {
23952
+ if (layout.kind === "tsx" && layout.componentPath) {
23953
+ jobs.push({
23954
+ type: "layout",
23955
+ id: layout.componentPath,
23956
+ run: async () => {
23957
+ const mod = await this.loadModule(layout.componentPath);
23958
+ if (mod && (mod.getServerData || mod.getStaticData)) {
23959
+ return this.dataFetcher.fetchData(mod, dataContext, this.config.mode);
23960
+ }
23961
+ return null;
23962
+ }
23963
+ });
23700
23964
  }
23701
- if (dataResult.redirect) {
23702
- throw new VeryfrontError(
23703
- `Redirect to ${dataResult.redirect.destination}`,
23704
- "RENDER_ERROR" /* RENDER_ERROR */,
23705
- {
23706
- slug,
23707
- redirect: dataResult.redirect
23965
+ }
23966
+ rendererLogger.info("[renderPage] Executing parallel data fetching jobs", { count: jobs.length });
23967
+ const results = await Promise.all(jobs.map((j) => j.run()));
23968
+ for (let i = 0; i < jobs.length; i++) {
23969
+ const job = jobs[i];
23970
+ if (!job)
23971
+ continue;
23972
+ const result2 = results[i];
23973
+ if (result2) {
23974
+ if (result2.notFound) {
23975
+ throw new VeryfrontError(
23976
+ "Page/Layout returned notFound",
23977
+ "FILE_NOT_FOUND" /* FILE_NOT_FOUND */,
23978
+ { slug, component: job.id }
23979
+ );
23980
+ }
23981
+ if (result2.redirect) {
23982
+ throw new VeryfrontError(
23983
+ `Redirect to ${result2.redirect.destination}`,
23984
+ "RENDER_ERROR" /* RENDER_ERROR */,
23985
+ {
23986
+ slug,
23987
+ redirect: result2.redirect
23988
+ }
23989
+ );
23990
+ }
23991
+ if (result2.props) {
23992
+ if (job.type === "page") {
23993
+ dataFetchingProps = result2.props;
23994
+ } else {
23995
+ layoutDataMap.set(job.id, result2.props);
23708
23996
  }
23709
- );
23997
+ }
23710
23998
  }
23711
- dataFetchingProps = dataResult.props;
23712
- rendererLogger.info("[renderPage] Data fetching succeeded", {
23713
- slug,
23714
- hasProps: !!dataFetchingProps,
23715
- propKeys: dataFetchingProps ? Object.keys(dataFetchingProps) : []
23716
- });
23717
23999
  }
23718
24000
  } catch (error2) {
23719
- if (error2 instanceof VeryfrontError && error2.code === "FILE_NOT_FOUND" /* FILE_NOT_FOUND */) {
24001
+ if (error2 instanceof VeryfrontError) {
23720
24002
  throw error2;
23721
24003
  }
23722
24004
  rendererLogger.error("[renderPage] Data fetching error", {
@@ -23726,8 +24008,6 @@ var init_pipeline = __esm({
23726
24008
  throw error2;
23727
24009
  }
23728
24010
  }
23729
- const layoutResult = await this.config.layoutOrchestrator.collectLayouts(pageInfo);
23730
- const providerResult = await this.config.layoutOrchestrator.collectProviders();
23731
24011
  const cacheResult = await this.config.cacheCoordinator.checkCache(
23732
24012
  slug,
23733
24013
  pageInfo,
@@ -23756,7 +24036,8 @@ var init_pipeline = __esm({
23756
24036
  pageInfo,
23757
24037
  layoutResult.layoutBundle,
23758
24038
  layoutResult.nestedLayouts,
23759
- providerResult.providerItems
24039
+ providerResult.providerItems,
24040
+ layoutDataMap
23760
24041
  );
23761
24042
  const ssrResult = await this.config.ssrOrchestrator.performSSRRendering(
23762
24043
  wrappedElement,
@@ -23815,8 +24096,8 @@ var init_ssr_orchestrator = __esm({
23815
24096
  "src/rendering/orchestrator/ssr-orchestrator.ts"() {
23816
24097
  "use strict";
23817
24098
  init_utils();
23818
- init_utils3();
23819
24099
  init_veryfront_error();
24100
+ init_utils3();
23820
24101
  SSROrchestrator = class {
23821
24102
  constructor(config) {
23822
24103
  this.config = config;
@@ -23827,12 +24108,14 @@ var init_ssr_orchestrator = __esm({
23827
24108
  this.config.debugMode
23828
24109
  );
23829
24110
  const wantsStream = options?.delivery === "stream";
23830
- const { html: html3 } = await this.config.ssrRenderer.renderToHTML(validatedElement, {
23831
- mode: this.config.mode,
23832
- wantsStream,
23833
- debugMode: this.config.debugMode
23834
- });
23835
- const ssrHash = await getContentHash(html3);
24111
+ const { html: html3, stream: stream2 } = await this.config.ssrRenderer.renderToHTML(
24112
+ validatedElement,
24113
+ {
24114
+ mode: this.config.mode,
24115
+ wantsStream,
24116
+ debugMode: this.config.debugMode
24117
+ }
24118
+ );
23836
24119
  const mergedOptions = {
23837
24120
  ...generationContext.options,
23838
24121
  ...options,
@@ -23841,6 +24124,20 @@ var init_ssr_orchestrator = __esm({
23841
24124
  ...options?.props
23842
24125
  }
23843
24126
  };
24127
+ if (stream2 && wantsStream) {
24128
+ const ssrHash2 = await getContentHash(html3);
24129
+ const contextWithHash = {
24130
+ ...generationContext,
24131
+ ssrHash: ssrHash2,
24132
+ options: mergedOptions
24133
+ };
24134
+ const finalStream2 = await this.config.htmlGenerator.generateHTMLStream(
24135
+ stream2,
24136
+ contextWithHash
24137
+ );
24138
+ return { fullHtml: html3, finalStream: finalStream2, ssrHash: ssrHash2 };
24139
+ }
24140
+ const ssrHash = await getContentHash(html3);
23844
24141
  const fullHtml = await this.config.htmlGenerator.generateFullHTML({
23845
24142
  ...generationContext,
23846
24143
  html: html3,
@@ -23855,10 +24152,12 @@ var init_ssr_orchestrator = __esm({
23855
24152
  return new Response(html3).body ?? null;
23856
24153
  } catch (error2) {
23857
24154
  rendererLogger.error("Failed to create stream from HTML:", error2);
23858
- throw toError(createError({
23859
- type: "render",
23860
- message: `Unable to create response stream: ${error2 instanceof Error ? error2.message : String(error2)}`
23861
- }));
24155
+ throw toError(
24156
+ createError({
24157
+ type: "render",
24158
+ message: `Unable to create response stream: ${error2 instanceof Error ? error2.message : String(error2)}`
24159
+ })
24160
+ );
23862
24161
  }
23863
24162
  }
23864
24163
  };
@@ -25084,11 +25383,12 @@ async function bundleMdx(source, options, result, compileMDXForImport) {
25084
25383
  return null;
25085
25384
  }
25086
25385
  );
25386
+ const normalizePlugins = (plugins) => plugins === void 0 ? [] : Array.isArray(plugins) ? plugins.flat() : [plugins];
25087
25387
  const compiled = await compileMdx2(processedContent, {
25088
25388
  outputFormat: "function-body",
25089
25389
  development: options.mode === "development",
25090
- remarkPlugins,
25091
- rehypePlugins,
25390
+ remarkPlugins: normalizePlugins(remarkPlugins),
25391
+ rehypePlugins: normalizePlugins(rehypePlugins),
25092
25392
  providerImportSource: void 0
25093
25393
  });
25094
25394
  const slug = getSlugFromPath3(source.path);
@@ -25144,10 +25444,17 @@ async function bundleMDXWithOptions(options) {
25144
25444
  body = extracted.body;
25145
25445
  frontmatter = extracted.attrs;
25146
25446
  }
25447
+ const normalizePlugins = (plugins) => plugins === void 0 ? [] : Array.isArray(plugins) ? plugins.flat() : [plugins];
25147
25448
  const defaultRemarkPlugins = await getRemarkPlugins(projectDir);
25148
25449
  const defaultRehypePlugins = await getRehypePlugins(projectDir);
25149
- const allRemarkPlugins = [...defaultRemarkPlugins, ...remarkPlugins];
25150
- const allRehypePlugins = [...defaultRehypePlugins, ...rehypePlugins];
25450
+ const allRemarkPlugins = [
25451
+ ...normalizePlugins(defaultRemarkPlugins),
25452
+ ...normalizePlugins(remarkPlugins)
25453
+ ];
25454
+ const allRehypePlugins = [
25455
+ ...normalizePlugins(defaultRehypePlugins),
25456
+ ...normalizePlugins(rehypePlugins)
25457
+ ];
25151
25458
  const compiled = await compileMdx2(body, {
25152
25459
  outputFormat: "function-body",
25153
25460
  development: mode === "development",
@@ -25832,6 +26139,7 @@ var init_watcher = __esm({
25832
26139
  // src/build/compiler/mdx-compiler/index.ts
25833
26140
  var init_mdx_compiler2 = __esm({
25834
26141
  "src/build/compiler/mdx-compiler/index.ts"() {
26142
+ "use strict";
25835
26143
  init_compiler3();
25836
26144
  init_directory_compiler();
25837
26145
  init_watcher();
@@ -27779,6 +28087,12 @@ var init_registry2 = __esm({
27779
28087
  getAll() {
27780
28088
  return new Map(this.components);
27781
28089
  }
28090
+ /**
28091
+ * Loader accessor for compatibility with older tests; loader is not used in this registry.
28092
+ */
28093
+ getLoader() {
28094
+ return void 0;
28095
+ }
27782
28096
  /**
27783
28097
  * Get all components as MDXComponents record (for MDX rendering)
27784
28098
  */
@@ -28740,7 +29054,10 @@ function generateHMRClientTemplate(port, hostname, reloadDelay) {
28740
29054
  try {
28741
29055
  const message = JSON.parse(event.data);
28742
29056
  switch (message.type) {
28743
- case 'connected': reactRefreshEnabled = message.reactRefresh || false; break;
29057
+ case 'connected':
29058
+ reactRefreshEnabled = message.reactRefresh || false;
29059
+ if (reactRefreshEnabled) { setupReactRefresh(); }
29060
+ break;
28744
29061
  case 'update': handleUpdate(message); break;
28745
29062
  case 'reload': window.location.reload(); break;
28746
29063
  default: console.warn('[HMR] Unknown message type:', message);
@@ -28762,8 +29079,7 @@ function generateHMRClientTemplate(port, hostname, reloadDelay) {
28762
29079
  function handleUpdate(update) {
28763
29080
  if (!update.path) { console.warn('[HMR] Update message missing path'); return; }
28764
29081
  if (update.path.endsWith('.css')) { updateCSS(update.path); return; }
28765
- if (reactRefreshEnabled && window.$RefreshReg$) { window.$RefreshReg$(update.path); return; }
28766
- window.location.reload();
29082
+ updateJS(update.path);
28767
29083
  }
28768
29084
 
28769
29085
  function updateCSS(path) {
@@ -28779,6 +29095,28 @@ function generateHMRClientTemplate(port, hostname, reloadDelay) {
28779
29095
  });
28780
29096
  }
28781
29097
 
29098
+ function updateJS(path) {
29099
+ try {
29100
+ const cacheBusted = path + (path.includes('?') ? '&' : '?') + 't=' + Date.now();
29101
+ const script = document.createElement('script');
29102
+ script.type = 'module';
29103
+ script.crossOrigin = 'anonymous';
29104
+ script.onload = () => {
29105
+ if (reactRefreshEnabled && window.$RefreshRuntime$?.performReactRefresh) {
29106
+ window.$RefreshRuntime$.performReactRefresh();
29107
+ } else {
29108
+ window.location.reload();
29109
+ }
29110
+ };
29111
+ script.onerror = () => { window.location.reload(); };
29112
+ script.src = cacheBusted;
29113
+ document.head.appendChild(script);
29114
+ } catch (error) {
29115
+ console.error('[HMR] Failed to update JS module:', error);
29116
+ window.location.reload();
29117
+ }
29118
+ }
29119
+
28782
29120
  function setupReactRefresh() {
28783
29121
  if (typeof window.$RefreshRuntime$ !== 'undefined') {
28784
29122
  window.$RefreshRuntime$.injectIntoGlobalHook(window);
@@ -28846,7 +29184,7 @@ var init_hmr_server = __esm({
28846
29184
  * Start the HMR server
28847
29185
  * Sets up HTTP server with WebSocket upgrade and runtime script serving
28848
29186
  */
28849
- async start() {
29187
+ start() {
28850
29188
  const _handler = (req) => {
28851
29189
  const url = new URL(req.url);
28852
29190
  if (req.headers.get("upgrade") === "websocket") {
@@ -28896,13 +29234,19 @@ var init_hmr_server = __esm({
28896
29234
  const controller = new AbortController();
28897
29235
  const signal = this.options.signal || controller.signal;
28898
29236
  this.abortController = this.options.signal ? void 0 : controller;
28899
- this.server = await this.options.adapter.serve(_handler, {
29237
+ const startPromise = this.options.adapter.serve(_handler, {
28900
29238
  port: this.options.port,
28901
29239
  signal,
28902
29240
  onListen: ({ port }) => {
28903
29241
  serverLogger.info(`HMR server running on port ${port}`);
28904
29242
  }
29243
+ }).then((server) => {
29244
+ this.server = server;
29245
+ });
29246
+ startPromise.catch((error2) => {
29247
+ serverLogger.error("HMR server failed to start", error2);
28905
29248
  });
29249
+ return startPromise;
28906
29250
  }
28907
29251
  /**
28908
29252
  * Stop the HMR server gracefully
@@ -29028,13 +29372,15 @@ function generateRuntimeScript() {
29028
29372
 
29029
29373
  // Safely extract and escape error info
29030
29374
  const errorType = escapeHtml(errorInfo.type || 'unknown');
29031
- const errorName = escapeHtml(errorInfo.error?.name || 'Error');
29032
- const errorMessage = escapeHtml(errorInfo.error?.message || 'Unknown error');
29375
+ const errorName = escapeHtml((errorInfo.error && errorInfo.error.name) || 'Error');
29376
+ const errorMessage = escapeHtml((errorInfo.error && errorInfo.error.message) || 'Unknown error');
29033
29377
  const errorFile = errorInfo.file ? escapeHtml(String(errorInfo.file)) : '';
29034
29378
  const errorLine = errorInfo.line ? escapeHtml(String(errorInfo.line)) : '';
29035
29379
  const errorColumn = errorInfo.column ? escapeHtml(String(errorInfo.column)) : '';
29036
29380
  const errorSuggestion = errorInfo.suggestion ? escapeHtml(errorInfo.suggestion) : '';
29037
- const errorStack = errorInfo.error?.stack ? escapeHtml(errorInfo.error.stack) : '';
29381
+ const errorStack = errorInfo.error && errorInfo.error.stack
29382
+ ? escapeHtml(errorInfo.error.stack)
29383
+ : '';
29038
29384
 
29039
29385
  // Create error display
29040
29386
  const overlay = document.createElement('div');
@@ -30263,6 +30609,7 @@ var init_endpoints = __esm({
30263
30609
  "use strict";
30264
30610
  init_base2();
30265
30611
  init_constants4();
30612
+ init_hmr();
30266
30613
  DevEndpointsHandler = class extends BaseHandler {
30267
30614
  constructor() {
30268
30615
  super(...arguments);
@@ -30273,7 +30620,9 @@ var init_endpoints = __esm({
30273
30620
  patterns: [
30274
30621
  { pattern: "/_veryfront/hmr-runtime.js", exact: true },
30275
30622
  { pattern: "/_veryfront/error-overlay.js", exact: true },
30276
- { pattern: "/_veryfront/dev-loader.js", exact: true }
30623
+ { pattern: "/_veryfront/dev-loader.js", exact: true },
30624
+ { pattern: "/_veryfront/hmr.js", exact: true },
30625
+ { pattern: "/_veryfront/hydrate.js", exact: true }
30277
30626
  ],
30278
30627
  enabled: (ctx) => ctx.mode === "development"
30279
30628
  // Only in dev mode
@@ -30286,6 +30635,18 @@ var init_endpoints = __esm({
30286
30635
  return Promise.resolve(this.continue());
30287
30636
  }
30288
30637
  const builder = this.createResponseBuilder(ctx);
30638
+ if (pathname === "/_veryfront/hmr.js") {
30639
+ const port = url.searchParams.get("port") || "3000";
30640
+ const script = this.getHMRScript(parseInt(port, 10));
30641
+ const response = builder.withCache("no-cache").javascript(script, HTTP_OK);
30642
+ return Promise.resolve(this.respond(response));
30643
+ }
30644
+ if (pathname === "/_veryfront/hydrate.js") {
30645
+ const slug = url.searchParams.get("slug") || "";
30646
+ const script = this.getHydrateScript(slug);
30647
+ const response = builder.withCache("no-cache").javascript(script, HTTP_OK);
30648
+ return Promise.resolve(this.respond(response));
30649
+ }
30289
30650
  if (pathname === "/_veryfront/hmr-runtime.js") {
30290
30651
  const script = this.getHMRRuntime();
30291
30652
  const response = builder.withCache("no-cache").javascript(script, HTTP_OK);
@@ -30303,6 +30664,38 @@ var init_endpoints = __esm({
30303
30664
  }
30304
30665
  return Promise.resolve(this.continue());
30305
30666
  }
30667
+ getHMRScript(port) {
30668
+ const reloadDelay = HMR_CLIENT_RELOAD_DELAY_MS;
30669
+ return `
30670
+ // Veryfront HMR WebSocket Client
30671
+ const indicator = document.createElement('div');
30672
+ indicator.className = 'dev-indicator';
30673
+ indicator.textContent = 'Development Mode';
30674
+ document.body.appendChild(indicator);
30675
+
30676
+ const ws = new WebSocket('ws://localhost:${port}/_ws');
30677
+ ws.onmessage = (event) => {
30678
+ const data = JSON.parse(event.data);
30679
+ if (data.type === 'reload') {
30680
+ location.reload();
30681
+ }
30682
+ };
30683
+ ws.onclose = () => {
30684
+ setTimeout(() => location.reload(), ${reloadDelay});
30685
+ };
30686
+
30687
+ window.__veryfrontHMRWebSocket = ws;
30688
+ `.trim();
30689
+ }
30690
+ getHydrateScript(slug) {
30691
+ return `
30692
+ // Veryfront Hydration Script
30693
+ import { hydrate } from '/_veryfront/rsc/client.js';
30694
+ hydrate('${slug}', {
30695
+ ssr: true
30696
+ });
30697
+ `.trim();
30698
+ }
30306
30699
  getHMRRuntime() {
30307
30700
  return `
30308
30701
  // Veryfront HMR Runtime
@@ -30571,7 +30964,7 @@ function createRelativeFsPlugin(projectDir, adapter) {
30571
30964
  }
30572
30965
  };
30573
30966
  }
30574
- function createBareExternalPlugin() {
30967
+ function createBareExternalPlugin(bundle = false) {
30575
30968
  return {
30576
30969
  name: "veryfront-bare-ext",
30577
30970
  setup(build3) {
@@ -30580,17 +30973,56 @@ function createBareExternalPlugin() {
30580
30973
  if (!isBare)
30581
30974
  return void 0;
30582
30975
  if (args.kind === "import-statement" || args.kind === "dynamic-import") {
30583
- return { path: args.path, external: true };
30976
+ const esmUrl = ESM_PACKAGE_MAP[args.path];
30977
+ if (esmUrl) {
30978
+ if (bundle) {
30979
+ return { path: esmUrl, namespace: "https" };
30980
+ }
30981
+ return { path: esmUrl, external: true };
30982
+ }
30983
+ const fallbackUrl = `https://esm.sh/${args.path}`;
30984
+ if (bundle) {
30985
+ return { path: fallbackUrl, namespace: "https" };
30986
+ }
30987
+ return { path: fallbackUrl, external: true };
30584
30988
  }
30585
30989
  return void 0;
30586
30990
  });
30991
+ if (bundle) {
30992
+ build3.onLoad({ filter: /.*/, namespace: "https" }, async (args) => {
30993
+ try {
30994
+ const response = await fetch(args.path);
30995
+ if (!response.ok) {
30996
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
30997
+ }
30998
+ const contents = await response.text();
30999
+ return { contents, loader: "js" };
31000
+ } catch (error2) {
31001
+ return {
31002
+ errors: [{
31003
+ text: `Failed to fetch ${args.path}: ${String(error2)}`,
31004
+ location: null
31005
+ }]
31006
+ };
31007
+ }
31008
+ });
31009
+ }
30587
31010
  }
30588
31011
  };
30589
31012
  }
31013
+ var ESM_PACKAGE_MAP;
30590
31014
  var init_esbuild_plugins = __esm({
30591
31015
  "src/server/handlers/dev/files/esbuild-plugins.ts"() {
30592
31016
  "use strict";
30593
31017
  init_path_utils();
31018
+ init_cdn();
31019
+ ESM_PACKAGE_MAP = {
31020
+ "react": getReactCDNUrl(REACT_DEFAULT_VERSION),
31021
+ "react-dom": getReactDOMCDNUrl(REACT_DEFAULT_VERSION),
31022
+ "react-dom/client": getReactDOMClientCDNUrl(REACT_DEFAULT_VERSION),
31023
+ "react/jsx-runtime": getReactJSXRuntimeCDNUrl(REACT_DEFAULT_VERSION),
31024
+ "react/jsx-dev-runtime": getReactJSXDevRuntimeCDNUrl(REACT_DEFAULT_VERSION)
31025
+ };
30594
31026
  }
30595
31027
  });
30596
31028
 
@@ -31010,7 +31442,7 @@ async function analyzeComponent(filePath, fs5) {
31010
31442
  };
31011
31443
  }
31012
31444
  function detectDirective(content, directive) {
31013
- const directivePattern = new RegExp(`^\\s*['"]s*${directive}s*['"];?\\s*$`, "m");
31445
+ const directivePattern = new RegExp(`^\\s*['"]${directive}['"];?\\s*$`, "m");
31014
31446
  return directivePattern.test(content);
31015
31447
  }
31016
31448
  function extractExports2(content) {
@@ -31054,21 +31486,31 @@ function toPascalCase(str) {
31054
31486
  async function buildClientManifest(projectDir, appDir = "app", fs5) {
31055
31487
  const manifest = /* @__PURE__ */ new Map();
31056
31488
  const appPath = join2(projectDir, appDir);
31489
+ let fsAdapter = fs5;
31490
+ if (!fsAdapter) {
31491
+ try {
31492
+ const adapter = await getAdapter();
31493
+ fsAdapter = adapter.fs;
31494
+ } catch (error2) {
31495
+ serverLogger.warn(`Failed to get file system adapter:`, error2);
31496
+ return manifest;
31497
+ }
31498
+ }
31057
31499
  try {
31058
31500
  await walkDirectory2(appPath, async (filePath) => {
31059
31501
  if (!/\.(tsx?|jsx?)$/.test(filePath))
31060
31502
  return;
31061
- const analysis = await analyzeComponent(filePath, fs5);
31503
+ const analysis = await analyzeComponent(filePath, fsAdapter);
31062
31504
  if (analysis.type === "client") {
31063
31505
  const relativePath = relative2(projectDir, filePath);
31064
31506
  manifest.set(analysis.id, {
31065
31507
  id: analysis.id,
31066
- path: `/_veryfront/fs/${encodeURIComponent(filePath)}`,
31508
+ path: `/_veryfront/fs/${toBase64Url(filePath)}`,
31067
31509
  exports: analysis.exports
31068
31510
  });
31069
31511
  serverLogger.debug(`Found client component: ${analysis.id} at ${relativePath}`);
31070
31512
  }
31071
- }, fs5);
31513
+ }, fsAdapter);
31072
31514
  } catch (error2) {
31073
31515
  serverLogger.warn(`Failed to build client manifest:`, error2);
31074
31516
  }
@@ -31106,6 +31548,8 @@ var init_component_analyzer = __esm({
31106
31548
  "src/rendering/rsc/component-analyzer.ts"() {
31107
31549
  init_std_path();
31108
31550
  init_utils();
31551
+ init_path_utils();
31552
+ init_detect();
31109
31553
  }
31110
31554
  });
31111
31555
 
@@ -31750,7 +32194,7 @@ async function fileExists(path, fs5) {
31750
32194
  return false;
31751
32195
  }
31752
32196
  }
31753
- function extractParams3(_pathname) {
32197
+ function extractParams2(_pathname) {
31754
32198
  return {};
31755
32199
  }
31756
32200
  var FILE_PATTERNS, ROOT_PATTERNS;
@@ -31843,7 +32287,7 @@ var init_render_handler = __esm({
31843
32287
  }
31844
32288
  buildProps(pathname, searchParams) {
31845
32289
  return {
31846
- params: extractParams3(pathname),
32290
+ params: extractParams2(pathname),
31847
32291
  searchParams: Object.fromEntries(searchParams)
31848
32292
  };
31849
32293
  }
@@ -32200,36 +32644,173 @@ var init_action_handler = __esm({
32200
32644
  // src/server/handlers/request/rsc/endpoints/script-handlers.ts
32201
32645
  function handleClientScript() {
32202
32646
  const code = `import { getContainer, consumeNdjsonStream } from '/_veryfront/rsc/dom.js';
32203
- async function tryStream(q){
32204
- try{
32205
- const res = await fetch('/_veryfront/rsc/stream'+q);
32206
- if(!res.ok || !res.body) return false;
32207
- const ctrl = new AbortController();
32208
- addEventListener('pagehide', () => ctrl.abort(), { once:true });
32209
- await consumeNdjsonStream(res, document, ctrl.signal);
32210
- return true;
32211
- }catch(e){ console.debug?.('[RSC] tryStream failed', e); return false; }
32212
- }
32213
- async function hydrate(){ try{ await import('/_veryfront/rsc/hydrate.js').then(m=>m.bootHydration?.()); }catch(e){ console.debug?.('[RSC] hydrate import failed', e); } }
32214
- export async function boot(){
32215
- try{
32216
- const q = window.location.search || '';
32217
- const streamed = await tryStream(q);
32218
- if(streamed){ await hydrate(); return; }
32219
- const res = await fetch('/_veryfront/rsc/payload'+q);
32220
- const data = await res.json();
32221
- if(data && data.slots){ for(const [id, html] of Object.entries(data.slots)){ const el = getContainer(document, id); el.innerHTML = String(html||''); } } else { const el = getContainer(document, 'root'); el.innerHTML = String(data.html || ''); }
32222
- await hydrate();
32223
- }catch(e){ console.error('[RSC] boot failed', e); }
32224
- }`;
32647
+
32648
+ // Convert file path to base64url (matching server-side toBase64Url)
32649
+ function toBase64Url(str) {
32650
+ try {
32651
+ const base64 = btoa(unescape(encodeURIComponent(str)));
32652
+ return base64
32653
+ .replace(/\\+/g, "-")
32654
+ .replace(/\\/ / g, "_")
32655
+ .replace(/=+$/, "");
32656
+ } catch (e) {
32657
+ console.debug?.("[RSC] toBase64Url failed", e);
32658
+ return null;
32659
+ }
32660
+ }
32661
+
32662
+ // Get hydration data from the page
32663
+ function getHydrationData() {
32664
+ try {
32665
+ const el = document.getElementById("veryfront-hydration-data");
32666
+ if (!el) return null;
32667
+ return JSON.parse(el.textContent || "{}");
32668
+ } catch (e) {
32669
+ console.debug?.("[RSC] hydration data parse failed", e);
32670
+ return null;
32671
+ }
32672
+ }
32673
+
32674
+ // Try RSC streaming approach
32675
+ async function tryStream(q) {
32676
+ try {
32677
+ const res = await fetch("/_veryfront/rsc/stream" + q);
32678
+ if (!res.ok || !res.body) return false;
32679
+ const ctrl = new AbortController();
32680
+ addEventListener("pagehide", () => ctrl.abort(), { once: true });
32681
+ await consumeNdjsonStream(res, document, ctrl.signal);
32682
+ return true;
32683
+ } catch (e) {
32684
+ console.debug?.("[RSC] tryStream failed", e);
32685
+ return false;
32686
+ }
32687
+ }
32688
+
32689
+ // Hydrate using the hydrate.js script (for data-client-ref markers)
32690
+ async function hydrateMarkers() {
32691
+ try {
32692
+ await import("/_veryfront/rsc/hydrate.js").then((m) => m.bootHydration?.());
32693
+ } catch (e) {
32694
+ console.debug?.("[RSC] hydrate import failed", e);
32695
+ }
32696
+ }
32697
+
32698
+ // Direct React hydration for 'use client' page components
32699
+ async function hydratePageComponent(pagePath) {
32700
+ try {
32701
+ // Import React and ReactDOM
32702
+ const React = await import("${getReactCDNUrl(REACT_DEFAULT_VERSION)}");
32703
+ const ReactDOM = await import("${getReactDOMClientCDNUrl(REACT_DEFAULT_VERSION)}");
32704
+
32705
+ // Convert the page file path to the /_veryfront/fs/ URL format
32706
+ const base64Path = toBase64Url(pagePath);
32707
+ if (!base64Path) {
32708
+ console.debug?.("[RSC] Failed to encode page path");
32709
+ return false;
32710
+ }
32711
+ const moduleUrl = "/_veryfront/fs/" + base64Path + ".js";
32712
+
32713
+ console.debug?.("[RSC] Loading component from:", moduleUrl);
32714
+
32715
+ // Import the component module
32716
+ const mod = await import(moduleUrl);
32717
+ const Component = mod.default;
32718
+
32719
+ if (typeof Component !== "function") {
32720
+ console.debug?.("[RSC] Page component is not a function");
32721
+ return false;
32722
+ }
32723
+
32724
+ // Find the root element to hydrate
32725
+ // Look for body's first child div or the first child with content
32726
+ const root =
32727
+ document.body.querySelector("div[class]") ||
32728
+ document.body.firstElementChild ||
32729
+ document.body;
32730
+
32731
+ // Use hydrateRoot for proper React hydration
32732
+ ReactDOM.hydrateRoot(root, React.createElement(Component, {}));
32733
+ console.debug?.("[RSC] Page component hydrated successfully");
32734
+ return true;
32735
+ } catch (e) {
32736
+ console.error("[RSC] Page hydration failed", e);
32737
+ return false;
32738
+ }
32739
+ }
32740
+
32741
+ export async function boot() {
32742
+ try {
32743
+ const q = window.location.search || "";
32744
+
32745
+ // FIRST: Check hydration data for the pagePath
32746
+ // This handles 'use client' pages that need direct React hydration
32747
+ const hydrationData = getHydrationData();
32748
+ if (hydrationData && hydrationData.pagePath) {
32749
+ console.debug?.(
32750
+ "[RSC] Found page component in hydration data:",
32751
+ hydrationData.pagePath,
32752
+ );
32753
+ const hydrated = await hydratePageComponent(hydrationData.pagePath);
32754
+ if (hydrated) {
32755
+ console.debug?.("[RSC] Client component hydrated successfully");
32756
+ return;
32757
+ }
32758
+ }
32759
+
32760
+ // If no client page components, try RSC streaming for server components
32761
+ const streamed = await tryStream(q);
32762
+ if (streamed) {
32763
+ await hydrateMarkers();
32764
+ return;
32765
+ }
32766
+
32767
+ // Try payload-based approach
32768
+ try {
32769
+ const res = await fetch("/_veryfront/rsc/payload" + q);
32770
+ if (res.ok) {
32771
+ const data = await res.json();
32772
+ if (data && data.slots) {
32773
+ for (const [id, html] of Object.entries(data.slots)) {
32774
+ const el = getContainer(document, id);
32775
+ el.innerHTML = String(html || "");
32776
+ }
32777
+ } else {
32778
+ const el = getContainer(document, "root");
32779
+ el.innerHTML = String(data.html || "");
32780
+ }
32781
+ await hydrateMarkers();
32782
+ return;
32783
+ }
32784
+ } catch (e) {
32785
+ console.debug?.("[RSC] payload fetch failed", e);
32786
+ }
32787
+
32788
+ // Final fallback: just run marker-based hydration
32789
+ await hydrateMarkers();
32790
+ } catch (e) {
32791
+ console.error("[RSC] boot failed", e);
32792
+ }
32793
+ }
32794
+
32795
+ // Auto-boot on DOM ready
32796
+ if (document.readyState === "loading") {
32797
+ document.addEventListener("DOMContentLoaded", boot);
32798
+ } else {
32799
+ boot();
32800
+ }
32801
+ `;
32225
32802
  return new Response(code, {
32226
32803
  headers: { "content-type": "application/javascript" }
32227
32804
  });
32228
32805
  }
32229
32806
  async function handleDomScript(adapter) {
32807
+ const p = new URL(
32808
+ "../../../../../rendering/rsc/client-dom.ts",
32809
+ import.meta.url
32810
+ ).pathname;
32811
+ let esbuild6 = null;
32230
32812
  try {
32231
- const esbuild6 = await import("esbuild");
32232
- const p = new URL("../../../../../rendering/rsc/client-dom.ts", import.meta.url).pathname;
32813
+ esbuild6 = await import("esbuild");
32233
32814
  const src = await adapter.fs.readFile(p);
32234
32815
  const result = await esbuild6.build({
32235
32816
  bundle: true,
@@ -32245,25 +32826,38 @@ async function handleDomScript(adapter) {
32245
32826
  }
32246
32827
  });
32247
32828
  const out = result.outputFiles?.[0]?.text ?? src;
32248
- if (esbuild6.stop) {
32249
- esbuild6.stop();
32250
- }
32251
32829
  return new Response(out, {
32252
32830
  headers: { "content-type": "application/javascript" }
32253
32831
  });
32254
32832
  } catch (error2) {
32255
- serverLogger.debug("[ScriptHandlers] Build failed, serving raw TypeScript", error2);
32256
- const p = new URL("../../../../../rendering/rsc/client-dom.ts", import.meta.url).pathname;
32833
+ if (CLIENT_DOM_BUNDLE) {
32834
+ return new Response(CLIENT_DOM_BUNDLE, {
32835
+ headers: { "content-type": "application/javascript" }
32836
+ });
32837
+ }
32838
+ serverLogger.debug(
32839
+ "[ScriptHandlers] Build failed, serving raw TypeScript",
32840
+ error2
32841
+ );
32257
32842
  const src = await adapter.fs.readFile(p);
32258
32843
  return new Response(src, {
32259
32844
  headers: { "content-type": "application/typescript" }
32260
32845
  });
32846
+ } finally {
32847
+ try {
32848
+ esbuild6?.stop?.();
32849
+ } catch (stopError) {
32850
+ serverLogger.debug("[ScriptHandlers] esbuild stop failed", stopError);
32851
+ }
32261
32852
  }
32262
32853
  }
32854
+ var CLIENT_DOM_BUNDLE;
32263
32855
  var init_script_handlers = __esm({
32264
32856
  "src/server/handlers/request/rsc/endpoints/script-handlers.ts"() {
32265
32857
  "use strict";
32266
32858
  init_utils();
32859
+ init_cdn();
32860
+ CLIENT_DOM_BUNDLE = '// src/rendering/client/browser-logger.ts\nvar ConditionalBrowserLogger = class {\n constructor(prefix, level) {\n this.prefix = prefix;\n this.level = level;\n }\n debug(message, ...args) {\n if (this.level <= 0 /* DEBUG */) {\n console.debug?.(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n info(message, ...args) {\n if (this.level <= 1 /* INFO */) {\n console.log?.(`[${this.prefix}] ${message}`, ...args);\n }\n }\n warn(message, ...args) {\n if (this.level <= 2 /* WARN */) {\n console.warn?.(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n error(message, ...args) {\n if (this.level <= 3 /* ERROR */) {\n console.error?.(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n};\nfunction getBrowserLogLevel() {\n if (typeof window === "undefined") {\n return 2 /* WARN */;\n }\n const windowObject = window;\n const isDevelopment = windowObject.__VERYFRONT_DEV__ || windowObject.__RSC_DEV__;\n if (!isDevelopment) {\n return 2 /* WARN */;\n }\n const isDebugEnabled = windowObject.__VERYFRONT_DEBUG__ || windowObject.__RSC_DEBUG__;\n return isDebugEnabled ? 0 /* DEBUG */ : 1 /* INFO */;\n}\nvar defaultLevel = getBrowserLogLevel();\nvar rscLogger = new ConditionalBrowserLogger("RSC", defaultLevel);\nvar prefetchLogger = new ConditionalBrowserLogger("PREFETCH", defaultLevel);\nvar hydrateLogger = new ConditionalBrowserLogger("HYDRATE", defaultLevel);\nvar browserLogger = new ConditionalBrowserLogger("VERYFRONT", defaultLevel);\n\n// src/security/client/html-sanitizer.ts\nvar SUSPICIOUS_PATTERNS = [\n { pattern: /<script[^>]*>[\\s\\S]*?<\\/script>/gi, name: "inline script" },\n { pattern: /javascript:/gi, name: "javascript: URL" },\n { pattern: /\\bon\\w+\\s*=/gi, name: "event handler attribute" },\n { pattern: /data:\\s*text\\/html/gi, name: "data: HTML URL" }\n];\nfunction isDevMode() {\n if (typeof globalThis !== "undefined") {\n const g = globalThis;\n return g.__VERYFRONT_DEV__ === true || g.Deno?.env?.get?.("VERYFRONT_ENV") === "development";\n }\n return false;\n}\nfunction validateTrustedHtml(html, options = {}) {\n const { strict = false, warn = true } = options;\n for (const { pattern, name } of SUSPICIOUS_PATTERNS) {\n pattern.lastIndex = 0;\n if (pattern.test(html)) {\n const message = `[Security] Suspicious ${name} detected in server HTML`;\n if (warn) {\n console.warn(message);\n }\n if (strict || !isDevMode()) {\n throw new Error(`Potentially unsafe HTML: ${name} detected`);\n }\n }\n }\n return html;\n}\n\n// src/rendering/rsc/client-dom.ts\nfunction getContainer(doc, id) {\n if (id === "root") {\n let el2 = doc.getElementById("rsc-root");\n if (!el2) {\n el2 = doc.createElement("div");\n el2.id = "rsc-root";\n doc.body.appendChild(el2);\n }\n return el2;\n }\n const sid = `rsc-slot-${id}`;\n let el = doc.getElementById(sid);\n if (!el) {\n el = doc.createElement("div");\n el.id = sid;\n doc.body.appendChild(el);\n }\n return el;\n}\nfunction applySlotMessage(doc, msg) {\n if (msg.type !== "slot")\n return;\n const el = getContainer(doc, msg.id);\n el.innerHTML = validateTrustedHtml(String(msg.html || ""));\n}\nfunction processNdjsonChunk(doc, buffered) {\n const parts = buffered.split("\\n");\n const remainder = parts.pop() ?? "";\n const queue = [];\n for (const line of parts) {\n const s = line.trim();\n if (!s)\n continue;\n try {\n const msg = JSON.parse(s);\n if (msg && msg.type === "slot")\n queue.push(msg);\n } catch (e) {\n rscLogger.debug("[client-dom] malformed NDJSON line", {\n line: s,\n error: e instanceof Error ? e.message : String(e)\n });\n }\n }\n for (const msg of queue) {\n applySlotMessage(doc, msg);\n try {\n hydrateClientBoundaries(doc, msg.id || "root");\n } catch (e) {\n rscLogger.debug("[client-dom] hydration optional failed", e);\n }\n }\n return remainder;\n}\nfunction processNdjsonLines(doc, ndjson) {\n processNdjsonChunk(doc, ndjson.endsWith("\\n") ? ndjson : `${ndjson}\n`);\n}\nasync function consumeNdjsonStream(input, doc = document, signal) {\n const response = "body" in input ? input : null;\n const stream = response ? response.body : input;\n if (!stream)\n return;\n const reader = stream.getReader();\n const decoder = new TextDecoder();\n let buffer = "";\n let streamFinished = false;\n try {\n for (; ; ) {\n if (signal?.aborted)\n throw new DOMException("aborted", "AbortError");\n const readPromise = reader.read();\n if (signal) {\n const abortPromise = new Promise((_, reject) => {\n if (signal.aborted) {\n reject(new DOMException("aborted", "AbortError"));\n return;\n }\n const onAbort = () => {\n reject(new DOMException("aborted", "AbortError"));\n };\n signal.addEventListener("abort", onAbort, { once: true });\n });\n const { done, value } = await Promise.race([readPromise, abortPromise]);\n if (done) {\n streamFinished = true;\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n buffer = processNdjsonChunk(doc, buffer);\n } else {\n const { done, value } = await readPromise;\n if (done) {\n streamFinished = true;\n break;\n }\n buffer += decoder.decode(value, { stream: true });\n buffer = processNdjsonChunk(doc, buffer);\n }\n }\n if (buffer)\n processNdjsonChunk(doc, `${buffer}\n`);\n } catch (e) {\n if (e instanceof Error && e.name === "AbortError")\n throw e;\n rscLogger.debug("[client-dom] consumeNdjsonStream error", e);\n throw e;\n } finally {\n try {\n await reader.cancel();\n } catch (e) {\n if (!streamFinished) {\n rscLogger.debug("[client-dom] reader.cancel failed", e);\n }\n }\n try {\n reader.releaseLock();\n } catch (e) {\n rscLogger.debug("[client-dom] reader.releaseLock failed", e);\n }\n const streamCancel = stream.cancel;\n if (typeof streamCancel === "function") {\n try {\n await streamCancel.call(stream);\n } catch (e) {\n rscLogger.debug("[client-dom] stream.cancel failed", e);\n }\n }\n const responseStream = response?.body;\n if (response && responseStream) {\n const responseCancel = responseStream.cancel;\n if (typeof responseCancel === "function") {\n try {\n await responseCancel.call(responseStream);\n } catch (e) {\n rscLogger.debug("[client-dom] response.body.cancel failed", e);\n }\n }\n }\n }\n}\nfunction findClientBoundaries(doc, slotId) {\n const root = getContainer(doc, slotId);\n const out = [];\n const walker = (node) => {\n if (node.dataset?.clientRef) {\n out.push(node);\n }\n for (const child of Array.from(node.children))\n walker(child);\n };\n walker(root);\n return out;\n}\nfunction hydrateClientBoundaries(doc, slotId) {\n const nodes = findClientBoundaries(doc, slotId);\n for (const el of nodes) {\n if (!el.dataset)\n continue;\n const ref = el.dataset.clientRef;\n el.dataset.hydrated = "true";\n rscLogger.debug("[client-dom] marked for hydration", ref);\n }\n}\nexport {\n applySlotMessage,\n consumeNdjsonStream,\n findClientBoundaries,\n getContainer,\n hydrateClientBoundaries,\n processNdjsonChunk,\n processNdjsonLines\n};\n';
32267
32861
  }
32268
32862
  });
32269
32863
 
@@ -32272,10 +32866,16 @@ async function handleRSCEndpoint({ req, pathname, projectDir, adapter, config })
32272
32866
  if (!pathname.startsWith("/_veryfront/rsc/")) {
32273
32867
  return null;
32274
32868
  }
32869
+ const sub = pathname.replace("/_veryfront/rsc/", "");
32870
+ if (sub === "client.js") {
32871
+ return handleClientScript();
32872
+ }
32873
+ if (sub === "dom.js") {
32874
+ return handleDomScript(adapter);
32875
+ }
32275
32876
  if (!isRSCEnabled(config)) {
32276
32877
  return null;
32277
32878
  }
32278
- const sub = pathname.replace("/_veryfront/rsc/", "");
32279
32879
  const url = new URL(req.url);
32280
32880
  const handler = getRSCHandler(projectDir);
32281
32881
  try {
@@ -32632,7 +33232,9 @@ var init_rsc = __esm({
32632
33232
  if (!pathname.startsWith("/_veryfront/rsc/")) {
32633
33233
  return this.continue();
32634
33234
  }
32635
- if (!isRSCEnabled(ctx.config)) {
33235
+ const sub = pathname.replace("/_veryfront/rsc/", "");
33236
+ const isHydrationScript = sub === "client.js" || sub === "dom.js";
33237
+ if (!isRSCEnabled(ctx.config) && !isHydrationScript) {
32636
33238
  return this.respond(new Response("Not Found", { status: HTTP_NOT_FOUND }));
32637
33239
  }
32638
33240
  const res = await handleRSCEndpoint({
@@ -34577,6 +35179,7 @@ init_utils();
34577
35179
  // src/rendering/chunk-optimizer.ts
34578
35180
  init_std_path();
34579
35181
  init_utils();
35182
+ init_fs();
34580
35183
  var SIZE_LIMITS = {
34581
35184
  DEP_SIZE_ESTIMATE: 25e3,
34582
35185
  UI_LIB_SIZE_ESTIMATE: 15e4
@@ -34600,12 +35203,13 @@ function analyzeImports(content) {
34600
35203
  return { local, remote, shared };
34601
35204
  }
34602
35205
  async function analyzeProjectChunks(projectDir, fs5) {
35206
+ const fsAdapter = fs5 ?? createFileSystem();
34603
35207
  const pages = /* @__PURE__ */ new Map();
34604
35208
  const sharedDeps = /* @__PURE__ */ new Map();
34605
35209
  const mdxFiles = [];
34606
35210
  async function findMDX(dir) {
34607
35211
  try {
34608
- const entries = fs5.readDir(dir);
35212
+ const entries = fsAdapter.readDir(dir);
34609
35213
  for await (const entry of entries) {
34610
35214
  const path = join2(dir, entry.name);
34611
35215
  if (entry.isFile && entry.name.endsWith(".mdx")) {
@@ -34621,7 +35225,7 @@ async function analyzeProjectChunks(projectDir, fs5) {
34621
35225
  await findMDX(join2(projectDir, "pages"));
34622
35226
  for (const mdxPath of mdxFiles) {
34623
35227
  try {
34624
- const content = await fs5.readFile(mdxPath);
35228
+ const content = await fsAdapter.readFile(mdxPath);
34625
35229
  const imports = analyzeImports(content);
34626
35230
  const pageImports = {
34627
35231
  path: mdxPath,
@@ -34734,7 +35338,8 @@ init_process();
34734
35338
  async function analyzeChunksCommand(options) {
34735
35339
  const { projectDir, output } = options;
34736
35340
  try {
34737
- const analysis = await analyzeProjectChunks(projectDir);
35341
+ const fs5 = createFileSystem();
35342
+ const analysis = await analyzeProjectChunks(projectDir, fs5);
34738
35343
  if (analysis.sharedDeps.size > 0) {
34739
35344
  cliLogger.info("Top shared dependencies:");
34740
35345
  const sorted = Array.from(analysis.sharedDeps.entries()).sort((a, b) => b[1] - a[1]).slice(0, 10);
@@ -34756,7 +35361,6 @@ async function analyzeChunksCommand(options) {
34756
35361
  cliLogger.info("");
34757
35362
  }
34758
35363
  if (output) {
34759
- const fs5 = createFileSystem();
34760
35364
  const manifest = generateChunkManifest(analysis);
34761
35365
  await fs5.writeTextFile(output, JSON.stringify(manifest, null, 2));
34762
35366
  cliLogger.info(`Saved chunk manifest to ${output}`);
@@ -35238,7 +35842,9 @@ init_utils();
35238
35842
  init_paths();
35239
35843
  init_std_path();
35240
35844
  init_fs();
35845
+ init_cdn();
35241
35846
  async function createConfigFile(projectDir, name, template, cacheBackend) {
35847
+ const reactImports = getReactImportMap(REACT_DEFAULT_VERSION);
35242
35848
  const config = `export default {
35243
35849
  title: "${name || "My App"}",
35244
35850
  description: "Built with Veryfront",
@@ -35260,12 +35866,12 @@ async function createConfigFile(projectDir, name, template, cacheBackend) {
35260
35866
  resolve: {
35261
35867
  importMap: {
35262
35868
  imports: {
35263
- "react": "https://esm.sh/react@19.1.1",
35264
- "react/jsx-runtime": "https://esm.sh/react@19.1.1/jsx-runtime",
35265
- "react/jsx-dev-runtime": "https://esm.sh/react@19.1.1/jsx-dev-runtime",
35266
- "react-dom": "https://esm.sh/react-dom@19.1.1",
35267
- "react-dom/client": "https://esm.sh/react-dom@19.1.1/client",
35268
- "react-dom/server": "https://esm.sh/react-dom@19.1.1/server",
35869
+ "react": "${reactImports["react"]}",
35870
+ "react/jsx-runtime": "${reactImports["react/jsx-runtime"]}",
35871
+ "react/jsx-dev-runtime": "${reactImports["react/jsx-dev-runtime"]}",
35872
+ "react-dom": "${reactImports["react-dom"]}",
35873
+ "react-dom/client": "${reactImports["react-dom/client"]}",
35874
+ "react-dom/server": "${reactImports["react-dom/server"]}",
35269
35875
  },
35270
35876
  },
35271
35877
  },
@@ -35649,8 +36255,8 @@ async function routesCommand(projectDir, options = {}) {
35649
36255
  await apiHandler.initialize();
35650
36256
  const router = new DynamicRouter();
35651
36257
  try {
35652
- const entries = await fs3.readDir(pagesDir);
35653
- for (const entry of entries) {
36258
+ const entries = fs3.readDir(pagesDir);
36259
+ for await (const entry of entries) {
35654
36260
  if (!entry.isFile)
35655
36261
  continue;
35656
36262
  if (entry.name.endsWith(".mdx") || entry.name.endsWith(".tsx")) {
@@ -35685,8 +36291,8 @@ async function routesCommand(projectDir, options = {}) {
35685
36291
  }
35686
36292
  }
35687
36293
  async function collectApiPatterns(dir, prefix, out) {
35688
- const entries = await fs3.readDir(dir);
35689
- for (const entry of entries) {
36294
+ const entries = fs3.readDir(dir);
36295
+ for await (const entry of entries) {
35690
36296
  const fullPath = join2(dir, entry.name);
35691
36297
  const routePath = `${prefix}/${entry.name.replace(/\.(ts|js|tsx|jsx)$/i, "")}`;
35692
36298
  if (entry.isDirectory) {