veryfront 0.0.68 → 0.0.70

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/_shims/deno-env.ts", "../../src/core/utils/runtime-guards.ts", "../../src/core/utils/logger/env.ts", "../../src/core/utils/logger/logger.ts", "../../src/core/utils/logger/index.ts", "../../src/core/utils/constants/build.ts", "../../src/core/utils/constants/cache.ts", "../../deno.json", "../../src/platform/compat/runtime.ts", "../../src/platform/compat/process.ts", "../../src/core/utils/version.ts", "../../src/core/utils/constants/cdn.ts", "../../src/core/utils/constants/env.ts", "../../src/core/utils/constants/hash.ts", "../../src/core/utils/constants/http.ts", "../../src/core/utils/constants/hmr.ts", "../../src/core/utils/constants/html.ts", "../../src/core/utils/constants/network.ts", "../../src/core/utils/constants/security.ts", "../../src/core/config/defaults.ts", "../../src/core/utils/constants/server.ts", "../../src/core/utils/constants/index.ts", "../../src/core/utils/paths.ts", "../../src/core/utils/hash-utils.ts", "../../src/core/utils/memoize.ts", "../../src/core/utils/path-utils.ts", "../../src/core/utils/format-utils.ts", "../../src/core/utils/bundle-manifest.ts", "../../src/core/utils/bundle-manifest-init.ts", "../../src/core/utils/feature-flags.ts", "../../src/core/utils/platform.ts", "../../src/core/utils/index.ts", "../../src/core/errors/veryfront-error.ts", "../../src/core/config/schema.ts", "../../src/core/config/loader.ts", "../../src/core/config/define-config.ts", "../../src/core/config/network-defaults.ts", "../../src/core/config/index.ts", "../../src/platform/adapters/deno.ts", "../../src/platform/adapters/shared-watcher.ts", "../../src/platform/adapters/node/filesystem-adapter.ts", "../../src/platform/adapters/node/environment-adapter.ts", "../../src/platform/adapters/node/http-server.ts", "../../src/platform/adapters/node/websocket-adapter.ts", "../../src/platform/adapters/node/adapter.ts", "../../src/platform/adapters/node/index.ts", "../../src/platform/adapters/node.ts", "../../src/core/errors/types.ts", "../../src/core/errors/agent-errors.ts", "../../src/core/errors/build-errors.ts", "../../src/core/errors/runtime-errors.ts", "../../src/core/errors/system-errors.ts", "../../src/core/errors/error-handlers.ts", "../../src/core/errors/error-codes.ts", "../../src/core/errors/catalog/factory.ts", "../../src/core/errors/catalog/config-errors.ts", "../../src/core/errors/catalog/build-errors.ts", "../../src/core/errors/catalog/runtime-errors.ts", "../../src/core/errors/catalog/route-errors.ts", "../../src/core/errors/catalog/module-errors.ts", "../../src/core/errors/catalog/server-errors.ts", "../../src/core/errors/catalog/rsc-errors.ts", "../../src/core/errors/catalog/dev-errors.ts", "../../src/core/errors/catalog/deployment-errors.ts", "../../src/core/errors/catalog/general-errors.ts", "../../src/core/errors/catalog/index.ts", "../../src/core/errors/user-friendly/error-catalog.ts", "../../src/platform/compat/console/ansi.ts", "../../src/platform/compat/console/deno.ts", "../../src/platform/compat/console/node.ts", "../../src/platform/compat/console/index.ts", "../../src/core/errors/user-friendly/error-identifier.ts", "../../src/core/errors/user-friendly/error-formatter.ts", "../../src/core/errors/user-friendly/error-wrapper.ts", "../../src/core/errors/user-friendly/index.ts", "../../src/core/errors/index.ts", "../../src/platform/adapters/bun/filesystem-adapter.ts", "../../src/platform/adapters/bun/environment-adapter.ts", "../../src/platform/adapters/bun/websocket-adapter.ts", "../../src/platform/adapters/bun/http-server.ts", "../../src/platform/adapters/bun/adapter.ts", "../../src/platform/adapters/bun/index.ts", "../../src/platform/adapters/bun.ts", "../../src/platform/adapters/mock.ts", "../../src/platform/adapters/registry.ts", "../../src/platform/adapters/detect.ts", "../../src/react/components/index.ts", "../../src/react/components/AppWrapper.tsx", "../../src/react/components/LayoutComponent.tsx", "../../src/build/transforms/mdx/index.ts", "../../src/core/utils/lru-wrapper.ts", "../../src/core/utils/cache/stores/memory/lru-cache-adapter.ts", "../../src/core/utils/cache/stores/memory/lru-list-manager.ts", "../../src/core/utils/cache/eviction/eviction-manager.ts", "../../src/core/utils/cache/stores/memory/entry-manager.ts", "../../src/core/utils/cache/stores/memory/lru-node.ts", "../../src/build/transforms/mdx/esm-module-loader.ts", "../../src/core/utils/cache/keys/namespace.ts", "../../src/module-system/import-map/index.ts", "../../src/module-system/import-map/loader.ts", "../../src/module-system/import-map/default-import-map.ts", "../../src/module-system/import-map/resolver.ts", "../../src/module-system/import-map/transformer.ts", "../../src/module-system/import-map/merger.ts", "../../src/build/transforms/mdx/parser.ts", "../../src/build/transforms/mdx/module-loader/metadata-extractor.ts", "../../src/build/transforms/mdx/module-loader/string-parser.ts", "../../src/build/transforms/mdx/mdx-cache-adapter.ts", "../../src/react/components/ProviderComponent.tsx", "../../src/react/components/Head.tsx", "../../src/react/components/Link.tsx", "../../src/react/components/MDXProvider.tsx", "../../src/react/components/optimized-image/index.ts", "../../src/react/components/optimized-image/OptimizedImage.tsx", "../../src/react/components/optimized-image/helpers.ts", "../../src/react/components/optimized-image/SimpleOptimizedImage.tsx", "../../src/react/components/optimized-image/OptimizedBackgroundImage.tsx", "../../src/react/components/optimized-image/useOptimizedImage.ts", "../../src/react/components/optimized-image/utils.tsx"],
4
- "sourcesContent": ["/**\n * Shim for Deno.env in Node.js environment\n * This file is injected by esbuild to provide Deno.env compatibility\n */\n\n// @ts-ignore - Global Deno shim for Node.js\nglobalThis.Deno = globalThis.Deno || {\n env: {\n get(key: string): string | undefined {\n return process.env[key];\n },\n set(key: string, value: string): void {\n process.env[key] = value;\n },\n delete(key: string): void {\n delete process.env[key];\n },\n has(key: string): boolean {\n return key in process.env;\n },\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n },\n },\n};\n", "export interface GlobalWithDeno {\n Deno?: {\n env: {\n get(key: string): string | undefined;\n };\n };\n}\n\nexport interface GlobalWithProcess {\n process?: {\n env: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string>;\n };\n}\n\nexport interface GlobalWithBun {\n Bun?: {\n version: string;\n };\n}\n\nexport function hasDenoRuntime(global: unknown): global is GlobalWithDeno {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Deno\" in global &&\n typeof (global as GlobalWithDeno).Deno?.env?.get === \"function\"\n );\n}\n\nexport function hasNodeProcess(global: unknown): global is GlobalWithProcess {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"process\" in global &&\n typeof (global as GlobalWithProcess).process?.env === \"object\"\n );\n}\n\nexport function hasBunRuntime(global: unknown): global is GlobalWithBun {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Bun\" in global &&\n typeof (global as GlobalWithBun).Bun !== \"undefined\"\n );\n}\n", "import type { GlobalWithDeno, GlobalWithProcess } from \"../runtime-guards.ts\";\nimport { hasDenoRuntime, hasNodeProcess } from \"../runtime-guards.ts\";\n\nexport function getEnvironmentVariable(name: string): string | undefined {\n try {\n if (typeof Deno !== \"undefined\" && hasDenoRuntime(globalThis)) {\n const value = (globalThis as GlobalWithDeno).Deno?.env.get(name);\n return value === \"\" ? undefined : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = (globalThis as GlobalWithProcess).process?.env[name];\n return value === \"\" ? undefined : value;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport function isTestEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"test\";\n}\n\nexport function isProductionEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"production\";\n}\n\nexport function isDevelopmentEnvironment(): boolean {\n const env = getEnvironmentVariable(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n", "import { getEnvironmentVariable } from \"./env.ts\";\n\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n time<T>(label: string, fn: () => Promise<T>): Promise<T>;\n}\n\nconst originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error,\n};\n\nlet cachedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(force = false): LogLevel {\n if (force || cachedLogLevel === undefined) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\n\nclass ConsoleLogger implements Logger {\n constructor(\n private prefix: string,\n private level: LogLevel = resolveLogLevel(),\n ) {}\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n getLevel(): LogLevel {\n return this.level;\n }\n\n debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n\n async time<T>(label: string, fn: () => Promise<T>): Promise<T> {\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}\n\nfunction parseLogLevel(levelString: string | undefined): LogLevel | undefined {\n if (!levelString) return undefined;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case \"DEBUG\":\n return LogLevel.DEBUG;\n case \"WARN\":\n return LogLevel.WARN;\n case \"ERROR\":\n return LogLevel.ERROR;\n case \"INFO\":\n return LogLevel.INFO;\n default:\n return undefined;\n }\n}\n\nconst getDefaultLevel = (): LogLevel => {\n const envLevel = getEnvironmentVariable(\"LOG_LEVEL\");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== undefined) return parsedLevel;\n\n const debugFlag = getEnvironmentVariable(\"VERYFRONT_DEBUG\");\n if (debugFlag === \"1\" || debugFlag === \"true\") return LogLevel.DEBUG;\n\n return LogLevel.INFO;\n};\n\nconst trackedLoggers = new Set<ConsoleLogger>();\n\nfunction createLogger(prefix: string): ConsoleLogger {\n const logger = new ConsoleLogger(prefix);\n trackedLoggers.add(logger);\n return logger;\n}\n\nexport const cliLogger = createLogger(\"CLI\");\nexport const serverLogger = createLogger(\"SERVER\");\nexport const rendererLogger = createLogger(\"RENDERER\");\nexport const bundlerLogger = createLogger(\"BUNDLER\");\nexport const agentLogger = createLogger(\"AGENT\");\n\nexport const logger = createLogger(\"VERYFRONT\");\n\ntype LoggerResetOptions = {\n restoreConsole?: boolean;\n};\n\nexport function __loggerResetForTests(options: LoggerResetOptions = {}): void {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\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}\n", "export * from \"./logger.ts\";\nexport * from \"./env.ts\";\n", "export const DEFAULT_BUILD_CONCURRENCY = 4;\n\nexport const IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80,\n} as const;\n", "export const SECONDS_PER_MINUTE = 60;\n\nexport const MINUTES_PER_HOUR = 60;\n\nexport const HOURS_PER_DAY = 24;\n\nexport const MS_PER_SECOND = 1000;\n\nexport const DEFAULT_LRU_MAX_ENTRIES = 100;\n\nexport const COMPONENT_LOADER_MAX_ENTRIES = 100;\nexport const COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const MDX_RENDERER_MAX_ENTRIES = 200;\nexport const MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const RENDERER_CORE_MAX_ENTRIES = 100;\nexport const RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const TSX_LAYOUT_MAX_ENTRIES = 50;\nexport const TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const DATA_FETCHING_MAX_ENTRIES = 200;\nexport const DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE *\n MS_PER_SECOND;\nexport const MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR *\n SECONDS_PER_MINUTE * MS_PER_SECOND;\nexport const BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR *\n SECONDS_PER_MINUTE * MS_PER_SECOND;\nexport const BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const RSC_MANIFEST_CACHE_TTL_MS = 5000;\n\nexport const SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n\nexport const DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64_000;\n\nexport const HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\nexport const HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\nexport const HTTP_CACHE_LONG_MAX_AGE_SEC = 31536000;\n\nexport const ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const CACHE_CLEANUP_INTERVAL_MS = 60000;\n\nexport const LRU_DEFAULT_MAX_ENTRIES = 1000;\n\nexport const LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\nexport const CLEANUP_INTERVAL_MULTIPLIER = 2;\n", "{\n \"name\": \"veryfront\",\n \"version\": \"0.0.68\",\n \"nodeModulesDir\": \"auto\",\n \"exclude\": [\n \"npm/\",\n \"dist/\",\n \"coverage/\",\n \"scripts/\",\n \"examples/\",\n \"src/cli/templates/files/\",\n \"src/cli/templates/integrations/\"\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 \"./platform\": \"./src/platform/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 \"./oauth\": \"./src/core/oauth/index.ts\",\n \"./oauth/providers\": \"./src/core/oauth/providers/index.ts\",\n \"./oauth/handlers\": \"./src/core/oauth/handlers/index.ts\",\n \"./oauth/token-store\": \"./src/core/oauth/token-store/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 \"@veryfront/oauth\": \"./src/core/oauth/index.ts\",\n \"@veryfront/oauth/\": \"./src/core/oauth/\",\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\": \"npm:@mdx-js/mdx@3.0.0\",\n \"@mdx-js/react\": \"npm:@mdx-js/react@3.0.0\",\n \"unist-util-visit\": \"npm:unist-util-visit@5.0.0\",\n \"mdast-util-to-string\": \"npm:mdast-util-to-string@4.0.0\",\n \"github-slugger\": \"npm:github-slugger@2.0.0\",\n \"remark-gfm\": \"npm:remark-gfm@4.0.1\",\n \"remark-frontmatter\": \"npm:remark-frontmatter@5.0.0\",\n \"rehype-highlight\": \"npm:rehype-highlight@7.0.2\",\n \"rehype-slug\": \"npm: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\": \"npm:es-module-lexer@1.5.0\",\n \"zod\": \"npm:zod@3.23.8\",\n \"mime-types\": \"npm:mime-types@2.1.35\",\n \"mdast\": \"npm:@types/mdast@4.0.3\",\n \"hast\": \"npm:@types/hast@3.0.3\",\n \"unist\": \"npm:@types/unist@3.0.2\",\n \"unified\": \"npm:unified@11.0.5\",\n \"ai\": \"https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1\",\n \"ai/react\": \"https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1\",\n \"@ai-sdk/react\": \"https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1\",\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.1\",\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 \"redis\": \"npm:redis\",\n \"pg\": \"npm:pg\",\n \"@opentelemetry/api\": \"npm:@opentelemetry/api@1\",\n \"@opentelemetry/core\": \"npm:@opentelemetry/core@1\"\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: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_NO_PACKAGE_JSON=1 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 \"lint:platform\": \"deno run --allow-read scripts/lint-platform-agnostic.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", "export const isDeno = typeof Deno !== \"undefined\";\nexport const isNode =\n typeof (globalThis as { process?: { versions?: { node?: string } } }).process !== \"undefined\" &&\n (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node !==\n undefined;\nexport const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\nexport const isCloudflare = typeof globalThis !== \"undefined\" && \"caches\" in globalThis &&\n \"WebSocketPair\" in globalThis;\n\n/**\n * Detect if running in Node.js (vs Deno)\n * Use this function instead of the constant when runtime detection needs to happen\n * at call time (e.g., when bundled with esbuild's __esm lazy initialization pattern)\n */\nexport function isNodeRuntime(): boolean {\n // deno-lint-ignore no-explicit-any\n const _global = globalThis as any;\n return typeof Deno === \"undefined\" && typeof _global.process !== \"undefined\" &&\n !!_global.process?.versions?.node;\n}\n", "import { isDeno as IS_DENO } from \"./runtime.ts\";\n\nconst nodeProcess = (globalThis as { process?: typeof import(\"node:process\") }).process;\nconst hasNodeProcess = !!nodeProcess?.versions?.node;\n\nexport function getArgs(): string[] {\n if (IS_DENO) {\n return Deno.args;\n }\n if (hasNodeProcess) {\n return nodeProcess!.argv.slice(2);\n }\n return [];\n}\n\nexport function exit(code?: number): never {\n if (IS_DENO) {\n Deno.exit(code);\n }\n if (hasNodeProcess) {\n nodeProcess!.exit(code);\n }\n throw new Error(\"exit() is not supported in this runtime\");\n}\n\nexport function cwd(): string {\n if (IS_DENO) {\n return Deno.cwd();\n }\n if (hasNodeProcess) {\n return nodeProcess!.cwd();\n }\n throw new Error(\"cwd() is not supported in this runtime\");\n}\n\nexport function chdir(directory: string): void {\n if (IS_DENO) {\n Deno.chdir(directory);\n } else {\n if (hasNodeProcess) {\n nodeProcess!.chdir(directory);\n return;\n }\n throw new Error(\"chdir() is not supported in this runtime\");\n }\n}\n\nexport function env(): Record<string, string> {\n if (IS_DENO) {\n return Deno.env.toObject();\n }\n if (hasNodeProcess) {\n return nodeProcess!.env as Record<string, string>;\n }\n return {};\n}\n\nexport function getEnv(key: string): string | undefined {\n if (IS_DENO) {\n return Deno.env.get(key);\n }\n if (hasNodeProcess) {\n return nodeProcess!.env[key];\n }\n return undefined;\n}\n\n/**\n * Get an environment variable or throw if not set\n * @throws Error if the environment variable is not set\n */\nexport function requireEnv(key: string): string {\n const value = getEnv(key);\n if (value === undefined) {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n return value;\n}\n\nexport function setEnv(key: string, value: string): void {\n if (IS_DENO) {\n Deno.env.set(key, value);\n } else {\n if (hasNodeProcess) {\n nodeProcess!.env[key] = value;\n return;\n }\n throw new Error(\"setEnv() is not supported in this runtime\");\n }\n}\n\nexport function deleteEnv(key: string): void {\n if (IS_DENO) {\n Deno.env.delete(key);\n } else {\n if (hasNodeProcess) {\n delete nodeProcess!.env[key];\n return;\n }\n throw new Error(\"deleteEnv() is not supported in this runtime\");\n }\n}\n\nexport function pid(): number {\n if (IS_DENO) {\n return Deno.pid;\n }\n if (hasNodeProcess) {\n return nodeProcess!.pid;\n }\n return 0;\n}\n\nexport function ppid(): number {\n if (IS_DENO && \"ppid\" in Deno) {\n return Deno.ppid || 0;\n }\n if (hasNodeProcess) {\n return nodeProcess!.ppid || 0;\n }\n return 0;\n}\n\nexport function memoryUsage(): {\n rss: number;\n heapTotal: number;\n heapUsed: number;\n external: number;\n} {\n if (IS_DENO) {\n const usage = Deno.memoryUsage();\n return {\n rss: usage.rss,\n heapTotal: usage.heapTotal,\n heapUsed: usage.heapUsed,\n external: usage.external,\n };\n }\n\n if (!hasNodeProcess) {\n throw new Error(\"memoryUsage() is not supported in this runtime\");\n }\n\n const usage = nodeProcess!.memoryUsage();\n return {\n rss: usage.rss,\n heapTotal: usage.heapTotal,\n heapUsed: usage.heapUsed,\n external: usage.external || 0,\n };\n}\n\n/**\n * Check if stdin is a TTY (terminal)\n */\nexport function isInteractive(): boolean {\n if (IS_DENO) {\n return Deno.stdin.isTerminal();\n }\n if (hasNodeProcess) {\n return nodeProcess!.stdin.isTTY ?? false;\n }\n return false;\n}\n\n/**\n * Get network interfaces\n */\nexport async function getNetworkInterfaces(): Promise<\n Array<{ name: string; address: string; family: \"IPv4\" | \"IPv6\" }>\n> {\n if (IS_DENO) {\n const interfaces = Deno.networkInterfaces();\n return interfaces.map((iface) => ({\n name: iface.name,\n address: iface.address,\n family: iface.family as \"IPv4\" | \"IPv6\",\n }));\n }\n\n if (!hasNodeProcess) {\n throw new Error(\"networkInterfaces() is not supported in this runtime\");\n }\n\n const os = await import(\"node:os\");\n const interfaces = os.networkInterfaces();\n const result: Array<{ name: string; address: string; family: \"IPv4\" | \"IPv6\" }> = [];\n\n for (const [name, addrs] of Object.entries(interfaces)) {\n if (!addrs) continue;\n for (const addr of addrs) {\n result.push({\n name,\n address: addr.address,\n family: addr.family as \"IPv4\" | \"IPv6\",\n });\n }\n }\n\n return result;\n}\n\n/**\n * Get runtime version string\n */\nexport function getRuntimeVersion(): string {\n if (IS_DENO) {\n return `Deno ${Deno.version.deno}`;\n }\n if (\"Bun\" in globalThis) {\n return `Bun ${(globalThis as unknown as { Bun: { version: string } }).Bun.version}`;\n }\n if (hasNodeProcess) {\n return `Node.js ${nodeProcess!.version}`;\n }\n return \"unknown\";\n}\n\n/**\n * Register a signal handler (SIGINT, SIGTERM) for graceful shutdown\n */\nexport function onSignal(signal: \"SIGINT\" | \"SIGTERM\", handler: () => void): void {\n if (IS_DENO) {\n Deno.addSignalListener(signal, handler);\n } else if (hasNodeProcess) {\n nodeProcess!.on(signal, handler);\n }\n}\n\n/**\n * Unreference a timer to prevent it from keeping the process alive\n */\nexport function unrefTimer(timerId: ReturnType<typeof setInterval>): void {\n if (IS_DENO) {\n Deno.unrefTimer(timerId as number);\n } else if (timerId && typeof timerId === \"object\" && \"unref\" in timerId) {\n (timerId as { unref: () => void }).unref();\n }\n}\n\n/**\n * Get the executable path of the current runtime\n */\nexport function execPath(): string {\n if (IS_DENO) {\n return Deno.execPath();\n }\n if (hasNodeProcess) {\n return nodeProcess!.execPath;\n }\n return \"\";\n}\n\n/**\n * Get process uptime in seconds\n * Returns OS uptime on Deno, process uptime on Node.js\n */\nexport function uptime(): number {\n if (IS_DENO) {\n // Deno.osUptime() returns system uptime in seconds\n return Deno.osUptime?.() ?? 0;\n }\n if (hasNodeProcess) {\n // process.uptime() returns process uptime in seconds\n return nodeProcess!.uptime?.() ?? 0;\n }\n return 0;\n}\n\n/**\n * Get stdout stream for writing\n * Returns null if not available (e.g., in browser/workers)\n */\nexport function getStdout(): { write: (data: string) => void } | null {\n if (IS_DENO) {\n const encoder = new TextEncoder();\n return {\n write: (data: string) => {\n Deno.stdout.writeSync(encoder.encode(data));\n },\n };\n }\n if (hasNodeProcess && nodeProcess!.stdout) {\n return {\n write: (data: string) => {\n nodeProcess!.stdout.write(data);\n },\n };\n }\n return null;\n}\n\n// Cached Node.js modules for synchronous prompt\nlet cachedNodeFs: typeof import(\"node:fs\") | null = null;\n\n/**\n * Synchronous prompt function that works across Deno and Node.js\n * Displays a message and reads user input from stdin\n */\nexport function promptSync(message?: string): string | null {\n if (IS_DENO) {\n // Deno has a built-in prompt() function\n return prompt(message);\n }\n\n if (hasNodeProcess) {\n // Print the message\n if (message) {\n nodeProcess!.stdout.write(message + \" \");\n }\n\n // Lazy load fs module\n if (!cachedNodeFs) {\n // Dynamic import converted to sync require for bundling\n // @ts-ignore - dynamic require for Node.js\n cachedNodeFs = globalThis.require?.(\"node:fs\") || null;\n if (!cachedNodeFs) {\n // Try alternative approach\n try {\n // @ts-ignore: __require is injected by bundlers for Node.js require\n cachedNodeFs = __require(\"node:fs\");\n } catch {\n return null;\n }\n }\n }\n\n if (!cachedNodeFs) {\n return null;\n }\n\n // Read synchronously using fs\n // This works by reading from file descriptor 0 (stdin)\n // Use Uint8Array for cross-platform compatibility\n const bufferSize = 1024;\n const uint8Array = new Uint8Array(bufferSize);\n let input = \"\";\n\n try {\n // Read from stdin (fd 0) synchronously\n const bytesRead = cachedNodeFs.readSync(0, uint8Array, 0, bufferSize, null);\n if (bytesRead > 0) {\n const decoder = new TextDecoder(\"utf-8\");\n input = decoder.decode(uint8Array.subarray(0, bytesRead)).trim();\n }\n } catch {\n // If stdin is not available or EOF, return null\n return null;\n }\n\n return input || null;\n }\n\n return null;\n}\n", "import denoConfig from \"../../../deno.json\" with { type: \"json\" };\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport const VERSION: string = getEnv(\"VERYFRONT_VERSION\") ||\n (typeof denoConfig.version === \"string\" ? denoConfig.version : \"0.0.0\");\n", "export const ESM_CDN_BASE = \"https://esm.sh\";\n\nexport const JSDELIVR_CDN_BASE = \"https://cdn.jsdelivr.net\";\n\nexport const DENO_STD_BASE = \"https://deno.land\";\n\nexport const REACT_VERSION_17 = \"17.0.2\";\nexport const REACT_VERSION_18_2 = \"18.2.0\";\nexport const REACT_VERSION_18_3 = \"18.3.1\";\nexport const REACT_VERSION_19_RC = \"19.0.0-rc.0\";\nexport const REACT_VERSION_19 = \"19.1.1\";\n\nexport const REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n\nexport function getReactCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\n\nexport function getReactDOMCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\n\nexport function getReactDOMClientCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\n\nexport function getReactDOMServerCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\n\nexport function getReactJSXRuntimeCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\n\nexport function getReactJSXDevRuntimeCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\n\nexport function getReactImportMap(version: string = REACT_DEFAULT_VERSION): Record<string, string> {\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}\n\nexport const DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n\nexport const DENO_STD_VERSION = \"0.220.0\";\n\nexport function getDenoStdNodeBase(): string {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\n\n// UnoCSS constants\nexport const UNOCSS_VERSION = \"0.59.0\";\n\nexport function getUnoCSSTailwindResetUrl(): string {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\n\n// Veryfront package version - derived from deno.json (single source of truth)\nexport { VERSION as VERYFRONT_VERSION } from \"../version.ts\";\n", "/**\n * Environment variable utilities\n *\n * Centralized utilities for checking environment flags.\n * This ensures consistent behavior across the entire codebase.\n */\n\n/**\n * Environment variable names used by Veryfront\n */\nexport const ENV_VARS = {\n DEBUG: \"VERYFRONT_DEBUG\",\n DEEP_INSPECT: \"VERYFRONT_DEEP_INSPECT\",\n CACHE_DIR: \"VERYFRONT_CACHE_DIR\",\n PORT: \"VERYFRONT_PORT\",\n VERSION: \"VERYFRONT_VERSION\",\n} as const;\n\n/**\n * Check if a debug environment variable value is truthy.\n * Accepts: \"1\", \"true\", \"yes\" (case-insensitive)\n *\n * @param value - The environment variable value to check\n * @returns true if the value indicates debug mode should be enabled\n */\nexport function isTruthyEnvValue(value: string | undefined): boolean {\n if (!value) return false;\n const normalized = value.toLowerCase().trim();\n return normalized === \"1\" || normalized === \"true\" || normalized === \"yes\";\n}\n\n/**\n * Check if debug mode is enabled via environment variable.\n * Works with RuntimeAdapter's env interface.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if VERYFRONT_DEBUG is set to a truthy value\n */\nexport function isDebugEnabled(env: { get(key: string): string | undefined }): boolean {\n return isTruthyEnvValue(env.get(ENV_VARS.DEBUG));\n}\n\n/**\n * Check if deep inspect mode is enabled via environment variable.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if VERYFRONT_DEEP_INSPECT is set to a truthy value\n */\nexport function isDeepInspectEnabled(env: { get(key: string): string | undefined }): boolean {\n return isTruthyEnvValue(env.get(ENV_VARS.DEEP_INSPECT));\n}\n\n/**\n * Check if either debug or deep inspect mode is enabled.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if either debug flag is enabled\n */\nexport function isAnyDebugEnabled(env: { get(key: string): string | undefined }): boolean {\n return isDebugEnabled(env) || isDeepInspectEnabled(env);\n}\n", "export const HASH_SEED_DJB2 = 5381;\n\nexport const HASH_SEED_FNV1A = 2166136261;\n", "export const KB_IN_BYTES = 1024;\n\nexport const HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n\nexport const HMR_RECONNECT_DELAY_MS = 1000;\n\nexport const HMR_RELOAD_DELAY_MS = 1000;\n\nexport const HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n\nexport const HMR_KEEP_ALIVE_INTERVAL_MS = 30000;\n\nexport const DASHBOARD_RECONNECT_DELAY_MS = 3000;\n\nexport const SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 30000;\n\nexport const PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n\nexport const PREFETCH_DEFAULT_TIMEOUT_MS = 10000;\n\nexport const PREFETCH_DEFAULT_DELAY_MS = 200;\n\nexport const HTTP_OK = 200;\n\nexport const HTTP_NO_CONTENT = 204;\n\nexport const HTTP_CREATED = 201;\n\nexport const HTTP_REDIRECT_FOUND = 302;\n\nexport const HTTP_NOT_MODIFIED = 304;\n\nexport const HTTP_BAD_REQUEST = 400;\n\nexport const HTTP_UNAUTHORIZED = 401;\n\nexport const HTTP_FORBIDDEN = 403;\n\nexport const HTTP_NOT_FOUND = 404;\n\nexport const HTTP_METHOD_NOT_ALLOWED = 405;\n\nexport const HTTP_GONE = 410;\n\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\nexport const HTTP_URI_TOO_LONG = 414;\n\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\nexport const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n\nexport const HTTP_SERVER_ERROR = 500;\n\nexport const HTTP_INTERNAL_SERVER_ERROR = 500;\n\nexport const HTTP_BAD_GATEWAY = 502;\n\nexport const HTTP_NOT_IMPLEMENTED = 501;\n\nexport const HTTP_UNAVAILABLE = 503;\n\nexport const HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n\nexport const HTTP_STATUS_SUCCESS_MIN = 200;\n\nexport const HTTP_STATUS_REDIRECT_MIN = 300;\n\nexport const HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n\nexport const HTTP_STATUS_SERVER_ERROR_MIN = 500;\n\nexport const 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} as const;\n\nimport { MS_PER_SECOND, SECONDS_PER_MINUTE } from \"./cache.ts\";\n\nexport const MS_PER_MINUTE = 60000;\n\nexport { MS_PER_SECOND, SECONDS_PER_MINUTE };\n\nexport const HTTP_CONTENT_TYPE_IMAGE_PNG = \"image/png\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_JPEG = \"image/jpeg\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_WEBP = \"image/webp\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_AVIF = \"image/avif\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_SVG = \"image/svg+xml\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_GIF = \"image/gif\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_ICO = \"image/x-icon\";\n", "import { KB_IN_BYTES } from \"./http.ts\";\n\nexport const HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\nexport const HMR_MAX_MESSAGES_PER_MINUTE = 100;\n\nexport const HMR_CLIENT_RELOAD_DELAY_MS = 3000;\n\nexport const HMR_PORT_OFFSET = 1;\n\nexport const HMR_RATE_LIMIT_WINDOW_MS = 60000;\n\nexport const HMR_CLOSE_NORMAL = 1000;\n\nexport const HMR_CLOSE_RATE_LIMIT = 1008;\n\nexport const HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n\nexport const HMR_MESSAGE_TYPES = {\n CONNECTED: \"connected\",\n UPDATE: \"update\",\n RELOAD: \"reload\",\n PING: \"ping\",\n PONG: \"pong\",\n} as const;\n\nexport function isValidHMRMessageType(type: string): type is keyof typeof HMR_MESSAGE_TYPES {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type as typeof HMR_MESSAGE_TYPES[keyof typeof HMR_MESSAGE_TYPES],\n );\n}\n", "export const Z_INDEX_DEV_INDICATOR = 9998;\nexport const Z_INDEX_ERROR_OVERLAY = 9999;\n\nexport const BREAKPOINT_SM = 640;\nexport const BREAKPOINT_MD = 768;\nexport const BREAKPOINT_LG = 1024;\nexport const BREAKPOINT_XL = 1280;\n\nexport const PROSE_MAX_WIDTH = \"65ch\";\n", "export const DEFAULT_DEV_SERVER_PORT = 3000;\nexport const DEFAULT_REDIS_PORT = 6379;\nexport const DEFAULT_API_SERVER_PORT = 8080;\nexport const DEFAULT_PREVIEW_SERVER_PORT = 5000;\nexport const DEFAULT_METRICS_PORT = 9000;\n\nexport const BYTES_PER_KB = 1024;\nexport const BYTES_PER_MB = 1024 * 1024;\n\nexport const DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\nexport const DEFAULT_IMAGE_SMALL_SIZE = 512;\nexport const DEFAULT_IMAGE_LARGE_SIZE = 2048;\n\nexport const RESPONSIVE_IMAGE_WIDTH_XS = 320;\nexport const RESPONSIVE_IMAGE_WIDTH_SM = 640;\nexport const RESPONSIVE_IMAGE_WIDTH_MD = 1024;\nexport const RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n\nexport const RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG,\n] as const;\n\nexport const MAX_CHUNK_SIZE_KB = 4096;\n\nexport const MIN_PORT = 1;\n\nexport const MAX_PORT = 65535;\n\nexport const DEFAULT_SERVER_PORT = 8000;\n", "export const MAX_PATH_TRAVERSAL_DEPTH = 10;\n\nexport const FORBIDDEN_PATH_PATTERNS = [\n /\\0/, // Null bytes\n];\n\nexport const DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n\nexport const ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n\nexport const MAX_PATH_LENGTH = 4096;\n\nexport const DEFAULT_MAX_STRING_LENGTH = 1000;\n", "/**\n * Default port for veryfront dev server.\n * This is the single source of truth for the default port.\n */\nexport const DEFAULT_PORT = 3000;\n\nexport const DEFAULT_TIMEOUT_MS = 5000;\n\nexport const SSR_TIMEOUT_MS = 10000;\n\nexport const SANDBOX_TIMEOUT_MS = 5000;\n\nexport const DEFAULT_CACHE_MAX_SIZE = 100;\n\nexport const defaultConfig = {\n server: {\n port: DEFAULT_PORT,\n hostname: \"0.0.0.0\",\n },\n\n timeouts: {\n default: DEFAULT_TIMEOUT_MS,\n api: 30000,\n ssr: SSR_TIMEOUT_MS,\n hmr: 30000,\n sandbox: SANDBOX_TIMEOUT_MS,\n },\n\n cache: {\n jit: {\n maxSize: DEFAULT_CACHE_MAX_SIZE,\n tempDirPrefix: \"vf-bundle-\",\n },\n },\n\n metrics: {\n ssrBoundaries: [5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000],\n },\n} as const;\n\nexport const DEFAULT_PREFETCH_DELAY_MS = 100;\n\nexport const DEFAULT_METRICS_COLLECT_INTERVAL_MS = 60000;\n\nexport const DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000,\n];\n\nexport const SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1000,\n 2500,\n 5000,\n 10000,\n];\n\nexport const DEFAULT_REDIS_SCAN_COUNT = 100;\n\nexport const DEFAULT_REDIS_BATCH_DELETE_SIZE = 1000;\n\nexport const PAGE_TRANSITION_DELAY_MS = 150;\n\nexport type DefaultConfig = typeof defaultConfig;\n", "/**\n * Centralized server endpoints and paths registry\n *\n * All internal veryfront URLs should be defined here as the single source of truth.\n * This prevents hardcoding URLs across the codebase and makes refactoring easier.\n */\n\n// Re-export DEFAULT_PORT from config/defaults.ts (the single source of truth)\nexport { DEFAULT_PORT } from \"@veryfront/config/defaults.ts\";\n\n/** Default port for development dashboard */\nexport const DEFAULT_DASHBOARD_PORT = 3002;\n\n/** Internal URL prefix for all veryfront endpoints */\nexport const INTERNAL_PREFIX = \"/_veryfront\" as const;\n\n/**\n * All internal veryfront URL path prefixes (directories)\n */\nexport const INTERNAL_PATH_PREFIXES = {\n /** React Server Components endpoints */\n RSC: `${INTERNAL_PREFIX}/rsc/`,\n /** File system access endpoints (base64 encoded paths) */\n FS: `${INTERNAL_PREFIX}/fs/`,\n /** Virtual module system */\n MODULES: `${INTERNAL_PREFIX}/modules/`,\n /** Generated page modules */\n PAGES: `${INTERNAL_PREFIX}/pages/`,\n /** Data JSON endpoints */\n DATA: `${INTERNAL_PREFIX}/data/`,\n /** Library modules (AI SDK, etc.) */\n LIB: `${INTERNAL_PREFIX}/lib/`,\n /** Chunk assets */\n CHUNKS: `${INTERNAL_PREFIX}/chunks/`,\n /** Client component modules */\n CLIENT: `${INTERNAL_PREFIX}/client/`,\n} as const;\n\n/**\n * Specific internal endpoint URLs\n */\nexport const INTERNAL_ENDPOINTS = {\n // Development endpoints\n HMR_RUNTIME: `${INTERNAL_PREFIX}/hmr-runtime.js`,\n HMR: `${INTERNAL_PREFIX}/hmr.js`,\n HYDRATE: `${INTERNAL_PREFIX}/hydrate.js`,\n ERROR_OVERLAY: `${INTERNAL_PREFIX}/error-overlay.js`,\n DEV_LOADER: `${INTERNAL_PREFIX}/dev-loader.js`,\n CLIENT_LOG: `${INTERNAL_PREFIX}/log`,\n\n // Production endpoints\n CLIENT_JS: `${INTERNAL_PREFIX}/client.js`,\n ROUTER_JS: `${INTERNAL_PREFIX}/router.js`,\n PREFETCH_JS: `${INTERNAL_PREFIX}/prefetch.js`,\n MANIFEST_JSON: `${INTERNAL_PREFIX}/manifest.json`,\n APP_JS: `${INTERNAL_PREFIX}/app.js`,\n\n // RSC endpoints\n RSC_CLIENT: `${INTERNAL_PREFIX}/rsc/client.js`,\n RSC_MANIFEST: `${INTERNAL_PREFIX}/rsc/manifest`,\n RSC_STREAM: `${INTERNAL_PREFIX}/rsc/stream`,\n RSC_PAYLOAD: `${INTERNAL_PREFIX}/rsc/payload`,\n RSC_RENDER: `${INTERNAL_PREFIX}/rsc/render`,\n RSC_PAGE: `${INTERNAL_PREFIX}/rsc/page`,\n RSC_MODULE: `${INTERNAL_PREFIX}/rsc/module`,\n RSC_DOM: `${INTERNAL_PREFIX}/rsc/dom.js`,\n RSC_HYDRATOR: `${INTERNAL_PREFIX}/rsc/hydrator.js`,\n RSC_HYDRATE_CLIENT: `${INTERNAL_PREFIX}/rsc/hydrate-client.js`,\n\n // Library module endpoints\n LIB_AI_REACT: `${INTERNAL_PREFIX}/lib/ai/react.js`,\n LIB_AI_COMPONENTS: `${INTERNAL_PREFIX}/lib/ai/components.js`,\n LIB_AI_PRIMITIVES: `${INTERNAL_PREFIX}/lib/ai/primitives.js`,\n} as const;\n\n/**\n * Build output directory paths (relative)\n */\nexport const BUILD_DIRS = {\n /** Main build output directory */\n ROOT: \"_veryfront\",\n /** Chunks directory */\n CHUNKS: \"_veryfront/chunks\",\n /** Data directory */\n DATA: \"_veryfront/data\",\n /** Assets directory */\n ASSETS: \"_veryfront/assets\",\n} as const;\n\n/**\n * Local project directory paths (relative to project root)\n * These are .gitignore'd directories for caching and temporary files\n */\nexport const PROJECT_DIRS = {\n /** Base veryfront internal directory */\n ROOT: \".veryfront\",\n /** Cache directory for build artifacts, transforms, etc. */\n CACHE: \".veryfront/cache\",\n /** KV store directory */\n KV: \".veryfront/kv\",\n /** Log files directory */\n LOGS: \".veryfront/logs\",\n /** Temporary files directory */\n TMP: \".veryfront/tmp\",\n} as const;\n\n/** Default cache directory path */\nexport const DEFAULT_CACHE_DIR = PROJECT_DIRS.CACHE;\n\n/**\n * Helper to check if a pathname is an internal veryfront endpoint\n */\nexport function isInternalEndpoint(pathname: string): boolean {\n return pathname.startsWith(INTERNAL_PREFIX + \"/\");\n}\n\n/**\n * Helper to check if a pathname is a static asset (has extension or is internal)\n */\nexport function isStaticAsset(pathname: string): boolean {\n return pathname.includes(\".\") || isInternalEndpoint(pathname);\n}\n\n/**\n * Normalize a chunk path to include the base prefix\n */\nexport function normalizeChunkPath(\n filename: string,\n basePath: string = INTERNAL_PATH_PREFIXES.CHUNKS,\n): string {\n if (filename.startsWith(\"/\")) {\n return filename;\n }\n return `${basePath.replace(/\\/$/, \"\")}/${filename}`;\n}\n\n// Re-export for backward compatibility\nexport const DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: INTERNAL_ENDPOINTS.HMR_RUNTIME,\n ERROR_OVERLAY: INTERNAL_ENDPOINTS.ERROR_OVERLAY,\n} as const;\n", "export * from \"./build.ts\";\nexport * from \"./cache.ts\";\nexport * from \"./cdn.ts\";\nexport * from \"./env.ts\";\nexport * from \"./hash.ts\";\nexport * from \"./hmr.ts\";\nexport * from \"./html.ts\";\nexport * from \"./http.ts\";\nexport * from \"./network.ts\";\nexport * from \"./security.ts\";\nexport * from \"./server.ts\";\n", "/**\n * Project directory paths and file extensions\n *\n * For internal veryfront URL endpoints, see ./constants/server.ts\n */\n\nimport {\n BUILD_DIRS,\n INTERNAL_ENDPOINTS,\n INTERNAL_PATH_PREFIXES,\n INTERNAL_PREFIX,\n} from \"./constants/server.ts\";\n\nexport const 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} as const;\n\n/**\n * @deprecated Use INTERNAL_PREFIX, INTERNAL_ENDPOINTS, INTERNAL_PATH_PREFIXES from ./constants/server.ts\n */\nexport const VERYFRONT_PATHS = {\n INTERNAL_PREFIX: INTERNAL_PREFIX,\n BUILD_DIR: BUILD_DIRS.ROOT,\n CHUNKS_DIR: BUILD_DIRS.CHUNKS,\n DATA_DIR: BUILD_DIRS.DATA,\n ASSETS_DIR: BUILD_DIRS.ASSETS,\n HMR_RUNTIME: INTERNAL_ENDPOINTS.HMR_RUNTIME,\n CLIENT_JS: INTERNAL_ENDPOINTS.CLIENT_JS,\n ROUTER_JS: INTERNAL_ENDPOINTS.ROUTER_JS,\n ERROR_OVERLAY: INTERNAL_ENDPOINTS.ERROR_OVERLAY,\n} as const;\n\nexport const 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} as const;\n\n// Re-export for convenience\nexport { BUILD_DIRS, INTERNAL_ENDPOINTS, INTERNAL_PATH_PREFIXES, INTERNAL_PREFIX };\n", "export async function computeHash(content: string): Promise<string> {\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}\n\nexport function getContentHash(content: string): Promise<string> {\n return computeHash(content);\n}\n\nexport function computeContentHash(content: string): Promise<string> {\n return computeHash(content);\n}\n\nexport interface BundleCode {\n code: string;\n css?: string;\n sourceMap?: string;\n}\n\nexport function computeCodeHash(code: BundleCode): Promise<string> {\n const combined = code.code + (code.css || \"\") + (code.sourceMap || \"\");\n return computeHash(combined);\n}\n\nexport function simpleHash(str: string): number {\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}\n\nexport async function shortHash(content: string): Promise<string> {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\n", "export class MemoCache<V> {\n private cache = new Map<string, V>();\n\n get(key: string): V | undefined {\n return this.cache.get(key);\n }\n\n set(key: string, value: V): void {\n this.cache.set(key, value);\n }\n\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n keyHasher: (...args: Args) => string,\n): (...args: Args) => Promise<Result> {\n const cache = new MemoCache<Result>();\n\n return async (...args: Args): Promise<Result> => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\n\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n keyHasher: (...args: Args) => string,\n): (...args: Args) => Result {\n const cache = new MemoCache<Result>();\n\n return (...args: Args): Result => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\n\n/**\n * FNV-1a hash algorithm for fast cache key generation.\n * 10-15x faster than JSON.stringify() and uses 70-80% less memory.\n *\n * @param values - Values to hash\n * @returns Hash string\n */\nexport function simpleHash(...values: unknown[]): string {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n\n let hash = FNV_OFFSET_BASIS;\n\n for (const value of values) {\n const str = typeof value === \"string\" ? value : String(value);\n\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n\n // Convert to unsigned 32-bit and then to base-36 string\n return (hash >>> 0).toString(36);\n}\n", "import { logger } from \"./logger/logger.ts\";\n\nexport function normalizePath(pathname: string): string {\n pathname = pathname.replace(/\\\\+/g, \"/\").replace(/\\/\\.+\\//g, \"/\");\n\n if (pathname !== \"/\" && pathname.endsWith(\"/\")) {\n pathname = pathname.slice(0, -1);\n }\n\n return pathname;\n}\n\nexport function joinPath(a: string, b: string): string {\n return `${a.replace(/\\/$/, \"\")}/${b.replace(/^\\//, \"\")}`;\n}\n\nexport function isWithinDirectory(root: string, target: string): boolean {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\n\nexport function getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return \"\";\n }\n return path.slice(lastDot);\n}\n\nexport function getDirectory(path: string): string {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf(\"/\");\n return lastSlash <= 0 ? \"/\" : normalized.slice(0, lastSlash);\n}\n\nexport function hasHashedFilename(path: string): boolean {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\n\nexport function isAbsolutePath(path: string): boolean {\n return path.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\n\nexport function toBase64Url(s: string): string {\n const b64 = btoa(s);\n return b64.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nexport function fromBase64Url(encoded: string): string {\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 (error) {\n logger.debug(`Failed to decode base64url string \"${encoded}\":`, error);\n return \"\";\n }\n}\n", "import { logger } from \"./logger/logger.ts\";\n\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return \"0 Bytes\";\n\n const absBytes = Math.abs(bytes);\n\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\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\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\n\nexport function estimateSize(value: unknown): number {\n if (value === null || value === undefined) return 8;\n\n switch (typeof value) {\n case \"boolean\":\n return 4;\n case \"number\":\n return 8;\n case \"string\":\n return value.length * 2; // UTF-16\n case \"function\":\n return 0; // Functions not cached\n case \"object\":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\n\nexport function estimateSizeWithCircularHandling(value: unknown): number {\n const seen = new WeakSet();\n const encoder = new TextEncoder();\n\n const json = JSON.stringify(value, (_key, val) => {\n if (typeof val === \"object\" && val !== null) {\n if (seen.has(val as object)) return undefined;\n seen.add(val as object);\n\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\n if (typeof val === \"function\") return undefined;\n\n if (val instanceof Uint8Array) {\n return { __type: \"Uint8Array\", length: val.length };\n }\n\n return val;\n });\n\n return encoder.encode(json ?? \"\").length;\n}\n\nfunction estimateObjectSize(value: object): number {\n if (value instanceof ArrayBuffer) return value.byteLength;\n\n if (\n value instanceof Uint8Array || value instanceof Uint16Array ||\n value instanceof Uint32Array || value instanceof Int8Array ||\n value instanceof Int16Array || value instanceof Int32Array\n ) {\n return value.byteLength;\n }\n\n try {\n return JSON.stringify(value).length * 2;\n } catch (error) {\n logger.debug(\"Failed to estimate size of non-serializable object:\", error);\n return 1024; // Default estimate for non-serializable\n }\n}\n\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3600000) return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;\n return `${Math.floor(ms / 3600000)}h ${Math.floor((ms % 3600000) / 60000)}m`;\n}\n\nexport function formatNumber(num: number): string {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\nexport function truncateString(str: string, maxLength: number): string {\n if (str.length <= maxLength) return str;\n return str.slice(0, maxLength - 3) + \"...\";\n}\n", "import { serverLogger as logger } from \"./logger/index.ts\";\n\nexport interface BundleMetadata {\n hash: string;\n codeHash: string;\n size: number;\n compiledAt: number;\n source: string;\n mode: \"development\" | \"production\";\n meta?: {\n type?: \"mdx\" | \"component\" | \"layout\" | \"provider\";\n depsHash?: string;\n reactVersion?: string;\n };\n}\n\nexport interface BundleCode {\n code: string;\n sourceMap?: string;\n css?: string;\n}\n\nexport interface BundleManifestStore {\n getBundleMetadata(key: string): Promise<BundleMetadata | undefined>;\n\n setBundleMetadata(key: string, metadata: BundleMetadata, ttlMs?: number): Promise<void>;\n\n getBundleCode(hash: string): Promise<BundleCode | undefined>;\n\n setBundleCode(hash: string, code: BundleCode, ttlMs?: number): Promise<void>;\n\n deleteBundle(key: string): Promise<void>;\n\n invalidateSource(source: string): Promise<number>;\n\n clear(): Promise<void>;\n\n isAvailable(): Promise<boolean>;\n\n getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }>;\n}\n\nexport class InMemoryBundleManifestStore implements BundleManifestStore {\n private metadata = new Map<string, { value: BundleMetadata; expiry?: number }>();\n private code = new Map<string, { value: BundleCode; expiry?: number }>();\n private sourceIndex = new Map<string, Set<string>>();\n\n getBundleMetadata(key: string): Promise<BundleMetadata | undefined> {\n const entry = this.metadata.get(key);\n if (!entry) return Promise.resolve(undefined);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(entry.value);\n }\n\n setBundleMetadata(key: string, metadata: BundleMetadata, ttlMs?: number): Promise<void> {\n const expiry = ttlMs ? Date.now() + ttlMs : undefined;\n this.metadata.set(key, { value: metadata, expiry });\n\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, new Set());\n }\n this.sourceIndex.get(metadata.source)!.add(key);\n return Promise.resolve();\n }\n\n getBundleCode(hash: string): Promise<BundleCode | undefined> {\n const entry = this.code.get(hash);\n if (!entry) return Promise.resolve(undefined);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(entry.value);\n }\n\n setBundleCode(hash: string, code: BundleCode, ttlMs?: number): Promise<void> {\n const expiry = ttlMs ? Date.now() + ttlMs : undefined;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n\n async deleteBundle(key: string): Promise<void> {\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\n async invalidateSource(source: string): Promise<number> {\n const keys = this.sourceIndex.get(source);\n if (!keys) return 0;\n\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\n clear(): Promise<void> {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n\n isAvailable(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }> {\n let totalSize = 0;\n let oldest: number | undefined;\n let newest: number | undefined;\n\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest) oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest) newest = value.compiledAt;\n }\n\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest,\n });\n }\n}\n\nlet manifestStore: BundleManifestStore = new InMemoryBundleManifestStore();\n\nexport function setBundleManifestStore(store: BundleManifestStore): void {\n manifestStore = store;\n logger.info(\"[bundle-manifest] Bundle manifest store configured\", {\n type: store.constructor.name,\n });\n}\n\nexport function getBundleManifestStore(): BundleManifestStore {\n return manifestStore;\n}\n\nexport { computeCodeHash, computeContentHash } from \"./hash-utils.ts\";\n", "import type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport type { VeryfrontConfig } from \"@veryfront/config\";\nimport { serverLogger as logger } from \"./logger/index.ts\";\nimport {\n type BundleManifestStore,\n InMemoryBundleManifestStore,\n setBundleManifestStore,\n} from \"./bundle-manifest.ts\";\nimport { BUNDLE_MANIFEST_DEV_TTL_MS, BUNDLE_MANIFEST_PROD_TTL_MS } from \"./constants/cache.ts\";\n\nexport async function initializeBundleManifest(\n config: VeryfrontConfig,\n mode: \"development\" | \"production\",\n adapter?: RuntimeAdapter,\n): Promise<void> {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === \"production\";\n\n if (!enabled) {\n logger.info(\"[bundle-manifest] Bundle manifest disabled\");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n\n const envType = adapter?.env.get(\"VERYFRONT_BUNDLE_MANIFEST_TYPE\");\n const storeType = manifestConfig?.type || envType || \"memory\";\n\n logger.info(\"[bundle-manifest] Initializing bundle manifest\", {\n type: storeType,\n mode,\n });\n\n try {\n let store: BundleManifestStore;\n\n switch (storeType) {\n case \"redis\": {\n const { RedisBundleManifestStore } = await import(\"./bundle-manifest-redis.ts\");\n const redisUrl = manifestConfig?.redisUrl ||\n 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\n const available = await store.isAvailable();\n if (!available) {\n logger.warn(\"[bundle-manifest] Redis not available, falling back to in-memory\");\n store = new InMemoryBundleManifestStore();\n } else {\n logger.info(\"[bundle-manifest] Redis store initialized\");\n }\n break;\n }\n\n case \"kv\": {\n const { KVBundleManifestStore } = await import(\"./bundle-manifest-kv.ts\");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix,\n });\n\n const available = await store.isAvailable();\n if (!available) {\n logger.warn(\"[bundle-manifest] KV not available, falling back to in-memory\");\n store = new InMemoryBundleManifestStore();\n } else {\n logger.info(\"[bundle-manifest] KV store initialized\");\n }\n break;\n }\n\n case \"memory\":\n default: {\n store = new InMemoryBundleManifestStore();\n logger.info(\"[bundle-manifest] In-memory store initialized\");\n break;\n }\n }\n\n setBundleManifestStore(store);\n\n try {\n const stats = await store.getStats();\n logger.info(\"[bundle-manifest] Store statistics\", stats);\n } catch (error) {\n logger.debug(\"[bundle-manifest] Failed to get stats\", { error });\n }\n } catch (error) {\n logger.error(\"[bundle-manifest] Failed to initialize store, using in-memory fallback\", {\n error,\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\n\nexport function getBundleManifestTTL(\n config: VeryfrontConfig,\n mode: \"development\" | \"production\",\n): number | undefined {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n\n if (mode === \"production\") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\n\nexport async function warmupBundleManifest(\n store: BundleManifestStore,\n keys: string[],\n): Promise<void> {\n logger.info(\"[bundle-manifest] Warming up cache\", { keys: keys.length });\n\n let loaded = 0;\n let failed = 0;\n\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 (error) {\n logger.debug(\"[bundle-manifest] Failed to warm up key\", { key, error });\n failed++;\n }\n }\n\n logger.info(\"[bundle-manifest] Cache warmup complete\", { loaded, failed });\n}\n", "declare const process: { env: Record<string, string | undefined> } | undefined;\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\n/**\n * Checks if React Server Components (RSC) are enabled.\n *\n * Priority order:\n * 1. Config file (config.experimental.rsc)\n * 2. Environment variables (VERYFRONT_EXPERIMENTAL_RSC=1)\n * 3. Default (false)\n *\n * @param config - Optional config object to check first\n * @returns true if RSC is enabled, false otherwise\n */\nexport function isRSCEnabled(config?: { experimental?: { rsc?: boolean } }): boolean {\n // 1. Check config first (highest priority)\n if (config?.experimental?.rsc !== undefined) {\n return config.experimental.rsc;\n }\n\n // 2. Fallback to environment variables (backward compatibility)\n return getEnv(\"VERYFRONT_EXPERIMENTAL_RSC\") === \"1\";\n}\n", "/**\n * Platform detection utilities\n */\n\nimport { isDeno } from \"../../platform/compat/runtime.ts\";\nimport { execPath } from \"../../platform/compat/process.ts\";\n\n/**\n * Detect if the code is running in a compiled Deno binary\n * @returns true if running in a compiled binary, false otherwise\n */\nexport function isCompiledBinary(): boolean {\n if (!isDeno) return false;\n\n try {\n const path = execPath();\n return path.includes(\"veryfront\");\n } catch {\n return false;\n }\n}\n", "export * from \"./runtime-guards.ts\";\n\nexport * from \"./logger/index.ts\";\n\nexport * from \"./constants/index.ts\";\nexport { VERSION } from \"./version.ts\";\n\nexport * from \"./paths.ts\";\n\nexport {\n type BundleCode as HashBundleCode, // Alias to avoid conflict with bundle-manifest\n computeCodeHash,\n computeContentHash,\n computeHash,\n getContentHash,\n shortHash,\n simpleHash,\n simpleHash as numericHash, // Alias to avoid conflict with memoize\n} from \"./hash-utils.ts\";\n\nexport {\n MemoCache,\n memoize,\n memoizeAsync,\n simpleHash as memoizeHash, // Alias to distinguish from hash-utils version\n} from \"./memoize.ts\";\n\nexport * from \"./path-utils.ts\";\n\nexport * from \"./format-utils.ts\";\n\nexport * from \"./bundle-manifest.ts\";\nexport * from \"./bundle-manifest-init.ts\";\n\nexport * from \"./feature-flags.ts\";\n\nexport { isCompiledBinary } from \"./platform.ts\";\n", "export interface BuildContext {\n file?: string;\n line?: number;\n column?: number;\n moduleId?: string;\n phase?: \"parse\" | \"transform\" | \"bundle\" | \"optimize\";\n}\n\nexport interface APIContext {\n endpoint?: string;\n method?: string;\n statusCode?: number;\n headers?: Record<string, string>;\n}\n\nexport interface RenderContext {\n component?: string;\n route?: string;\n phase?: \"server\" | \"client\" | \"hydration\";\n props?: unknown;\n}\n\nexport interface ConfigContext {\n configFile?: string;\n field?: string;\n value?: unknown;\n expected?: string;\n}\n\nexport interface AgentContext {\n agentId?: string;\n intent?: string;\n timeout?: number;\n}\n\nexport interface FileContext {\n path?: string;\n operation?: \"read\" | \"write\" | \"delete\" | \"mkdir\";\n permissions?: string;\n}\n\nexport interface NetworkContext {\n url?: string;\n timeout?: number;\n retryCount?: number;\n}\n\nexport type VeryfrontError =\n | { type: \"build\"; message: string; context?: BuildContext }\n | { type: \"api\"; message: string; context?: APIContext }\n | { type: \"render\"; message: string; context?: RenderContext }\n | { type: \"config\"; message: string; context?: ConfigContext }\n | { type: \"agent\"; message: string; context?: AgentContext }\n | { type: \"file\"; message: string; context?: FileContext }\n | { type: \"network\"; message: string; context?: NetworkContext }\n | { type: \"permission\"; message: string; context?: FileContext }\n | { type: \"not_supported\"; message: string; feature?: string };\n\nexport function createError(error: VeryfrontError): VeryfrontError {\n return error;\n}\n\nexport function isBuildError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"build\" }> {\n return error.type === \"build\";\n}\n\nexport function isAPIError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"api\" }> {\n return error.type === \"api\";\n}\n\nexport function isRenderError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"render\" }> {\n return error.type === \"render\";\n}\n\nexport function isConfigError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"config\" }> {\n return error.type === \"config\";\n}\n\nexport function isAgentError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"agent\" }> {\n return error.type === \"agent\";\n}\n\nexport function isFileError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"file\" }> {\n return error.type === \"file\";\n}\n\nexport function isNetworkError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"network\" }> {\n return error.type === \"network\";\n}\n\nexport function toError(veryfrontError: VeryfrontError): Error {\n const error = new Error(veryfrontError.message);\n error.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error, \"context\", {\n value: veryfrontError,\n enumerable: false,\n configurable: true,\n });\n return error;\n}\n\nexport function fromError(error: unknown): VeryfrontError | null {\n if (error && typeof error === \"object\" && \"context\" in error) {\n // Safe access after 'in' check\n const context = (error as Record<string, unknown>).context;\n if (\n context &&\n typeof context === \"object\" &&\n \"type\" in context &&\n \"message\" in context\n ) {\n return context as VeryfrontError;\n }\n }\n return null;\n}\n\nexport function logError(\n error: VeryfrontError,\n logger?: { error: (msg: string, ...args: unknown[]) => void },\n): void {\n const log = logger || console;\n const context = \"context\" in error ? error.context || {} : {};\n log.error(`[${error.type}] ${error.message}`, context);\n}\n", "import { z } from \"zod\";\nimport type { VeryfrontConfig } from \"./types.ts\";\nimport { type ConfigContext, createError, toError } from \"../errors/veryfront-error.ts\";\n\nconst corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n\nexport const veryfrontConfigSchema = z\n .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\n .object({ colors: z.record(z.string()).optional() })\n .partial()\n .optional(),\n build: z\n .object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z\n .object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n cache: z\n .object({\n dir: z.string().optional(),\n bundleManifest: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n dev: z\n .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 })\n .partial()\n .optional(),\n resolve: z\n .object({\n importMap: z\n .object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n security: z\n .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 })\n .partial()\n .optional(),\n middleware: z\n .object({\n custom: z.array(z.function()).optional(),\n })\n .partial()\n .optional(),\n theming: z\n .object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional(),\n })\n .partial()\n .optional(),\n assetPipeline: z\n .object({\n images: z\n .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 })\n .partial()\n .optional(),\n css: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n observability: z\n .object({\n tracing: z\n .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 })\n .partial()\n .optional(),\n metrics: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n fs: z\n .object({\n type: z.enum([\"local\", \"veryfront-api\", \"memory\"]).optional(),\n local: z\n .object({\n baseDir: z.string().optional(),\n })\n .partial()\n .optional(),\n veryfront: z\n .object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z\n .object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional(),\n })\n .partial()\n .optional(),\n retry: z\n .object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n memory: z\n .object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n client: z\n .object({\n moduleResolution: z.enum([\"cdn\", \"self-hosted\", \"bundled\"]).optional(),\n cdn: z\n .object({\n provider: z.enum([\"esm.sh\", \"unpkg\", \"jsdelivr\"]).optional(),\n versions: z\n .union([\n z.literal(\"auto\"),\n z.object({\n react: z.string().optional(),\n veryfront: z.string().optional(),\n }),\n ])\n .optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n })\n .partial();\n\nexport type VeryfrontConfigInput = z.input<typeof veryfrontConfigSchema>;\n\nexport function validateVeryfrontConfig(input: unknown): VeryfrontConfig {\n const parsed = veryfrontConfigSchema.safeParse(input);\n if (!parsed.success) {\n const first = parsed.error.issues[0];\n const path = first?.path?.length ? first.path.join(\".\") : \"<root>\";\n const expected = first?.message || String(first);\n let hint = \"\";\n if (String(path).includes(\"security.cors\")) {\n hint = \" Expected boolean or { origin?: string }.\";\n }\n\n const context: ConfigContext = {\n field: path,\n expected: expected + hint,\n value: input,\n };\n\n throw toError(\n createError({\n type: \"config\",\n message: `Invalid veryfront.config at ${path}: ${expected}.${hint}`,\n context,\n }),\n );\n }\n return parsed.data as VeryfrontConfig;\n}\n\nexport function findUnknownTopLevelKeys(input: Record<string, unknown>): string[] {\n const known = new Set([\n \"title\",\n \"description\",\n \"experimental\",\n \"router\",\n \"defaultLayout\",\n \"theme\",\n \"build\",\n \"cache\",\n \"dev\",\n \"resolve\",\n \"security\",\n \"middleware\",\n \"theming\",\n \"assetPipeline\",\n \"observability\",\n \"fs\",\n \"client\",\n ]);\n return Object.keys(input).filter((k) => !known.has(k));\n}\n", "import type { VeryfrontConfig } from \"./types.ts\";\nimport { findUnknownTopLevelKeys, validateVeryfrontConfig } from \"./schema.ts\";\nimport { join } from \"std/path/mod.ts\";\nimport type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport { serverLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { getReactImportMap, REACT_DEFAULT_VERSION } from \"@veryfront/utils/constants/cdn.ts\";\nimport { DEFAULT_CACHE_DIR } from \"@veryfront/utils/constants/server.ts\";\nimport { DEFAULT_PORT } from \"./defaults.ts\";\n\nexport type { VeryfrontConfig } from \"./types.ts\";\n\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\n\nconst DEFAULT_CONFIG: Partial<VeryfrontConfig> = {\n title: \"Veryfront App\",\n description: \"Built with Veryfront\",\n experimental: {\n esmLayouts: true,\n },\n router: undefined,\n defaultLayout: undefined,\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: DEFAULT_CACHE_DIR,\n render: {\n type: \"memory\",\n ttl: undefined,\n maxEntries: 500,\n kvPath: undefined,\n redisUrl: undefined,\n redisKeyPrefix: undefined,\n },\n },\n dev: {\n port: DEFAULT_PORT,\n host: \"localhost\",\n open: false,\n },\n resolve: {\n importMap: getDefaultImportMapForConfig(),\n },\n client: {\n moduleResolution: \"cdn\",\n cdn: {\n provider: \"esm.sh\",\n versions: \"auto\",\n },\n },\n};\n\nconst configCacheByProject = new Map<string, { revision: number; config: VeryfrontConfig }>();\nlet cacheRevision = 0;\n\nfunction validateCorsConfig(userConfig: unknown): void {\n if (!userConfig || typeof userConfig !== \"object\") {\n return;\n }\n const config = userConfig as Record<string, unknown>;\n const security = config.security as Record<string, unknown> | undefined;\n const cors = security?.cors;\n if (!cors || typeof cors !== \"object\" || Array.isArray(cors)) {\n return;\n }\n\n const corsObj = cors as Record<string, unknown>;\n const origin = corsObj.origin;\n if (origin !== undefined && typeof origin !== \"string\") {\n throw new ConfigValidationError(\n \"security.cors.origin must be a string. Expected boolean or { origin?: string }\",\n );\n }\n}\n\nfunction validateConfigShape(userConfig: unknown): void {\n validateVeryfrontConfig(userConfig);\n const unknown = typeof userConfig === \"object\" && userConfig\n ? findUnknownTopLevelKeys(userConfig as Record<string, unknown>)\n : [];\n if (unknown.length > 0) {\n serverLogger.warn(`Unknown config keys: ${unknown.join(\", \")}. These will be ignored.`);\n }\n}\n\nfunction mergeConfigs(userConfig: Partial<VeryfrontConfig>): VeryfrontConfig {\n const merged: VeryfrontConfig = {\n ...DEFAULT_CONFIG,\n ...userConfig,\n dev: {\n ...DEFAULT_CONFIG.dev,\n ...userConfig.dev,\n },\n theme: {\n ...DEFAULT_CONFIG.theme,\n ...userConfig.theme,\n },\n build: {\n ...DEFAULT_CONFIG.build,\n ...userConfig.build,\n },\n cache: {\n ...DEFAULT_CONFIG.cache,\n ...userConfig.cache,\n },\n resolve: {\n ...DEFAULT_CONFIG.resolve,\n ...userConfig.resolve,\n },\n client: {\n ...DEFAULT_CONFIG.client,\n ...userConfig.client,\n cdn: {\n ...DEFAULT_CONFIG.client?.cdn,\n ...userConfig.client?.cdn,\n },\n },\n } as VeryfrontConfig;\n\n if (merged.resolve) {\n const defaultMap = DEFAULT_CONFIG.resolve?.importMap;\n const userMap = userConfig.resolve?.importMap;\n\n if (defaultMap || userMap) {\n merged.resolve.importMap = {\n imports: {\n ...(defaultMap?.imports ?? {}),\n ...(userMap?.imports ?? {}),\n },\n scopes: {\n ...(defaultMap?.scopes ?? {}),\n ...(userMap?.scopes ?? {}),\n },\n };\n }\n }\n\n return merged;\n}\n\nclass ConfigValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigValidationError\";\n }\n}\n\nasync function loadAndMergeConfig(\n configPath: string,\n projectDir: string,\n): Promise<VeryfrontConfig | null> {\n try {\n const configUrl = `file://${configPath}?t=${Date.now()}-${crypto.randomUUID()}`;\n const configModule = await import(configUrl);\n const userConfig = configModule.default || configModule;\n\n if (userConfig === null || typeof userConfig !== \"object\" || Array.isArray(userConfig)) {\n throw new ConfigValidationError(\n `Expected object, received ${userConfig === null ? \"null\" : typeof userConfig}`,\n );\n }\n\n validateCorsConfig(userConfig);\n validateConfigShape(userConfig);\n\n const merged = mergeConfigs(userConfig);\n configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });\n return merged;\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.startsWith(\"Invalid veryfront.config\")) {\n throw error;\n }\n\n throw error;\n }\n}\n\nexport async function getConfig(\n projectDir: string,\n adapter: RuntimeAdapter,\n): Promise<VeryfrontConfig> {\n const cached = configCacheByProject.get(projectDir);\n if (cached && cached.revision === cacheRevision) return cached.config;\n\n const configFiles = [\"veryfront.config.js\", \"veryfront.config.ts\", \"veryfront.config.mjs\"];\n\n for (const configFile of configFiles) {\n const configPath = join(projectDir, configFile);\n\n const exists = await adapter.fs.exists(configPath);\n if (!exists) continue;\n\n try {\n const merged = await loadAndMergeConfig(configPath, projectDir);\n if (merged) return merged;\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.startsWith(\"Invalid veryfront.config\")) {\n throw error;\n }\n\n // Only log at debug level - this is expected when .ts exists but .js is tried first\n const errorMessage = error instanceof Error ? error.message : String(error);\n serverLogger.debug(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {\n error: errorMessage,\n });\n\n continue;\n }\n }\n\n const defaultConfig = DEFAULT_CONFIG as VeryfrontConfig;\n configCacheByProject.set(projectDir, { revision: cacheRevision, config: defaultConfig });\n return defaultConfig;\n}\n\nexport function clearConfigCache() {\n configCacheByProject.clear();\n cacheRevision++;\n}\n", "import type { VeryfrontConfig } from \"./types.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport function defineConfig(config: VeryfrontConfig): VeryfrontConfig {\n return config;\n}\n\nexport function defineConfigWithEnv(\n factory: (env: string) => VeryfrontConfig,\n): VeryfrontConfig {\n const env = getEnv(\"NODE_ENV\") || \"development\";\n return factory(env);\n}\n\nexport function mergeConfigs(\n ...configs: Partial<VeryfrontConfig>[]\n): VeryfrontConfig {\n const merged: Partial<VeryfrontConfig> = {};\n\n for (const config of configs) {\n Object.assign(merged, config);\n }\n\n return merged as VeryfrontConfig;\n}\n\nexport async function validateConfig(config: unknown): Promise<void> {\n if (!config || typeof config !== \"object\") {\n throw toError(createError({\n type: \"config\",\n message: \"Configuration must be an object\",\n }));\n }\n\n const cfg = config as Record<string, unknown>;\n\n if (cfg.dev && typeof cfg.dev === \"object\") {\n const dev = cfg.dev as Record<string, unknown>;\n if (dev.port !== undefined) {\n const { MIN_PORT, MAX_PORT } = await import(\"../utils/constants/network.ts\");\n if (typeof dev.port !== \"number\" || dev.port < MIN_PORT || dev.port > MAX_PORT) {\n throw toError(createError({\n type: \"config\",\n message: `dev.port must be a number between ${MIN_PORT} and ${MAX_PORT}`,\n context: {\n field: \"dev.port\",\n value: dev.port,\n expected: `number between ${MIN_PORT} and ${MAX_PORT}`,\n },\n }));\n }\n }\n }\n\n if (cfg.build && typeof cfg.build === \"object\") {\n const build = cfg.build as Record<string, unknown>;\n if (build.outDir !== undefined && typeof build.outDir !== \"string\") {\n throw toError(createError({\n type: \"config\",\n message: \"build.outDir must be a string\",\n context: { field: \"build.outDir\", value: build.outDir, expected: \"string\" },\n }));\n }\n }\n}\n", "export const LOCALHOST = {\n IPV4: \"127.0.0.1\",\n IPV6: \"::1\",\n HOSTNAME: \"localhost\",\n} as const;\n\nexport const HTTP_DEFAULTS = {\n PORT: 3000,\n HOST: \"localhost\",\n PROD_HOST: \"0.0.0.0\",\n} as const;\n\nexport const REDIS_DEFAULTS = {\n URL: \"redis://127.0.0.1:6379\",\n PORT: 6379,\n HOST: \"127.0.0.1\",\n} as const;\n\nexport const DEV_LOCALHOST_ORIGINS = [\n \"http://localhost\",\n \"http://127.0.0.1\",\n \"https://localhost\",\n \"https://127.0.0.1\",\n] as const;\n\nexport const DEV_LOCALHOST_CSP = {\n WS: \"ws://localhost:* wss://localhost:*\",\n HTTP: \"http://localhost\",\n} as const;\n\nexport const LOCALHOST_URLS = {\n HTTP: \"http://localhost\",\n HTTPS: \"https://localhost\",\n HTTP_IPV4: \"http://127.0.0.1\",\n HTTPS_IPV4: \"https://127.0.0.1\",\n} as const;\n\nexport function buildLocalhostUrl(\n port: number,\n protocol: \"http\" | \"https\" = \"http\",\n): string {\n return `${protocol}://${LOCALHOST.HOSTNAME}:${port}`;\n}\n\nexport function buildIpv4Url(\n port: number,\n protocol: \"http\" | \"https\" = \"http\",\n): string {\n return `${protocol}://${LOCALHOST.IPV4}:${port}`;\n}\n", "export { clearConfigCache, getConfig } from \"./loader.ts\";\n\nexport { defineConfig } from \"./define-config.ts\";\n\nexport type { VeryfrontConfig } from \"./types.ts\";\n\nexport {\n findUnknownTopLevelKeys,\n validateVeryfrontConfig,\n veryfrontConfigSchema,\n} from \"./schema.ts\";\n\nexport {\n DEFAULT_CACHE_MAX_SIZE,\n DEFAULT_METRICS_COLLECT_INTERVAL_MS,\n DEFAULT_PORT,\n DEFAULT_PREFETCH_DELAY_MS,\n DEFAULT_REDIS_BATCH_DELETE_SIZE,\n DEFAULT_REDIS_SCAN_COUNT,\n DEFAULT_TIMEOUT_MS,\n type DefaultConfig,\n defaultConfig,\n DURATION_HISTOGRAM_BOUNDARIES_MS,\n PAGE_TRANSITION_DELAY_MS,\n SANDBOX_TIMEOUT_MS,\n SIZE_HISTOGRAM_BOUNDARIES_KB,\n SSR_TIMEOUT_MS,\n} from \"./defaults.ts\";\n\nexport {\n buildIpv4Url,\n buildLocalhostUrl,\n DEV_LOCALHOST_CSP,\n DEV_LOCALHOST_ORIGINS,\n HTTP_DEFAULTS,\n LOCALHOST,\n LOCALHOST_URLS,\n REDIS_DEFAULTS,\n} from \"./network-defaults.ts\";\n", "import { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport type {\n DirEntry,\n EnvironmentAdapter,\n FileChangeEvent,\n FileChangeKind,\n FileInfo,\n FileSystemAdapter,\n FileWatcher,\n RuntimeAdapter,\n RuntimeFeatures,\n ServeOptions,\n Server,\n ServerAdapter,\n ShellAdapter,\n WatchOptions,\n WebSocketUpgrade,\n} from \"./base.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nclass DenoFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n return await Deno.readTextFile(path);\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n return await Deno.readFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await Deno.writeTextFile(path, content);\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\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\n async stat(path: string): Promise<FileInfo> {\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\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await Deno.mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n await Deno.remove(path, options);\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n return await Deno.makeTempDir({ prefix });\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n\n const denoIterator = watcher[Symbol.asyncIterator]();\n\n const mapEventKind = (kind: string): FileChangeKind => {\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\n const iterator: AsyncIterator<FileChangeEvent> = {\n async next(): Promise<IteratorResult<FileChangeEvent>> {\n if (closed || signal?.aborted) {\n return { done: true, value: undefined };\n }\n\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths,\n },\n };\n } catch (error) {\n if (closed || signal?.aborted) {\n return { done: true, value: undefined };\n }\n throw error;\n }\n },\n\n async return(): Promise<IteratorResult<FileChangeEvent>> {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: undefined };\n },\n };\n\n const cleanup = () => {\n if (closed) return;\n closed = true;\n try {\n if (\"close\" in watcher && typeof watcher.close === \"function\") {\n watcher.close();\n }\n } catch (error) {\n serverLogger.debug(\"[Deno] Filesystem watcher cleanup failed\", { error });\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup,\n };\n }\n}\n\nclass DenoEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return Deno.env.get(key);\n }\n\n set(key: string, value: string): void {\n Deno.env.set(key, value);\n }\n\n toObject(): Record<string, string> {\n return Deno.env.toObject();\n }\n}\n\nclass DenoServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n}\n\nclass DenoShellAdapter implements ShellAdapter {\n statSync(path: string): { isFile: boolean; isDirectory: boolean } {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n };\n } catch (error) {\n throw toError(createError({\n type: \"file\",\n message: `Failed to stat file: ${error}`,\n }));\n }\n }\n\n readFileSync(path: string): string {\n try {\n return Deno.readTextFileSync(path);\n } catch (error) {\n throw toError(createError({\n type: \"file\",\n message: `Failed to read file: ${error}`,\n }));\n }\n }\n}\n\nclass DenoServer implements Server {\n constructor(\n private server: Deno.HttpServer,\n private hostname: string,\n private port: number,\n private abortController?: AbortController,\n ) {}\n\n async stop(): Promise<void> {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n\n await this.server.shutdown();\n } catch (error) {\n serverLogger.debug(\"[Deno] Server shutdown failed\", { error });\n }\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\nexport class DenoAdapter implements RuntimeAdapter {\n readonly id = \"deno\" as const;\n readonly name = \"deno\";\n /** @deprecated Use `id` instead */\n readonly platform = \"deno\" as const;\n\n fs = new DenoFileSystemAdapter();\n env = new DenoEnvironmentAdapter();\n server = new DenoServerAdapter();\n shell = new DenoShellAdapter();\n\n readonly 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, // Deno KV available\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n\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 (error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"Request handler error:\", error);\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\n const controllerToPass = options.signal ? undefined : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n}\n\nexport const denoAdapter = new DenoAdapter();\n", "import type { FileChangeEvent, FileChangeKind, FileWatcher } from \"./base.ts\";\nimport { join } from \"node:path\";\n\nexport async function setupNodeFsWatcher(\n path: string,\n options: {\n recursive: boolean;\n closed: () => boolean;\n signal: AbortSignal | undefined;\n eventQueue: FileChangeEvent[];\n getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null;\n setResolver: (resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void;\n watchers: Array<import(\"node:fs\").FSWatcher>;\n onError: (error: Error, path: string) => void;\n },\n): Promise<void> {\n try {\n const fs = await import(\"node:fs\");\n const fsPromises = await import(\"node:fs/promises\");\n\n const exists = await fsPromises.access(path).then(() => true).catch(() => false);\n if (!exists) return;\n\n const watcher = fs.watch(path, { recursive: options.recursive }, (eventType, filename) => {\n if (options.closed() || options.signal?.aborted) return;\n\n const kind: FileChangeKind = eventType === \"change\" ? \"modify\" : \"any\";\n const fullPath = filename ? join(path, filename) : path;\n\n enqueueWatchEvent(\n { kind, paths: [fullPath] },\n options.eventQueue,\n options.getResolver,\n options.setResolver,\n );\n });\n\n watcher.on(\"error\", (error: Error) => {\n if (!options.closed() && !options.signal?.aborted) {\n options.onError(error, path);\n }\n });\n\n options.watchers.push(watcher);\n } catch (error) {\n options.onError(error as Error, path);\n }\n}\n\nexport function createWatcherIterator(\n eventQueue: FileChangeEvent[],\n _getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null,\n setResolver: (r: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void,\n isClosed: () => boolean,\n isAborted: () => boolean,\n): AsyncIterator<FileChangeEvent> {\n return {\n next(): Promise<IteratorResult<FileChangeEvent>> {\n if (isClosed() || isAborted()) {\n return Promise.resolve({ done: true, value: undefined });\n }\n\n if (eventQueue.length > 0) {\n const event = eventQueue.shift()!;\n return Promise.resolve({ done: false, value: event });\n }\n\n return new Promise((resolve) => {\n if (isClosed() || isAborted()) {\n resolve({ done: true, value: undefined });\n return;\n }\n setResolver(resolve);\n });\n },\n\n return(): Promise<IteratorResult<FileChangeEvent>> {\n return Promise.resolve({ done: true, value: undefined });\n },\n };\n}\n\nexport function enqueueWatchEvent(\n event: FileChangeEvent,\n eventQueue: FileChangeEvent[],\n getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null,\n setResolver: (resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void,\n): void {\n const resolver = getResolver();\n if (resolver) {\n resolver({ done: false, value: event });\n setResolver(null);\n } else {\n eventQueue.push(event);\n }\n}\n\nexport function createFileWatcher(\n iterator: AsyncIterator<FileChangeEvent>,\n cleanup: () => void,\n): FileWatcher {\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup,\n };\n}\n", "import type { DirEntry, FileInfo, FileSystemAdapter, FileWatcher, WatchOptions } from \"../base.ts\";\nimport { createFileWatcher, createWatcherIterator, setupNodeFsWatcher } from \"../shared-watcher.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\nimport type { FileChangeEvent } from \"../base.ts\";\n\nexport class NodeFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n return await fs.readFile(path, \"utf-8\");\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n const fs = await import(\"node:fs/promises\");\n const buffer = await fs.readFile(path);\n return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.writeFile(path, content, \"utf-8\");\n }\n\n async exists(path: string): Promise<boolean> {\n const fs = await import(\"node:fs/promises\");\n try {\n await fs.access(path);\n return true;\n } catch (error) {\n serverLogger.debug(`File access check failed for ${path}:`, error);\n return false;\n }\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\n const fs = await import(\"node:fs/promises\");\n const entries = await fs.readdir(path, { withFileTypes: true });\n\n for (const entry of entries) {\n yield {\n name: entry.name,\n isFile: entry.isFile(),\n isDirectory: entry.isDirectory(),\n isSymlink: entry.isSymbolicLink(),\n };\n }\n }\n\n async stat(path: string): Promise<FileInfo> {\n const fs = await import(\"node:fs/promises\");\n const stats = await fs.stat(path);\n\n return {\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymlink: stats.isSymbolicLink(),\n mtime: stats.mtime,\n };\n }\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.rm(path, { recursive: options?.recursive, force: true });\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n const { join } = await import(\"node:path\");\n const { tmpdir } = await import(\"node:os\");\n return await mkdtemp(join(tmpdir(), prefix));\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n let closed = false;\n const watchers: Array<import(\"node:fs\").FSWatcher> = [];\n const eventQueue: FileChangeEvent[] = [];\n let resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null = null;\n\n Promise.all(\n pathArray.map((path) =>\n setupNodeFsWatcher(path, {\n recursive,\n closed: () => closed,\n signal,\n eventQueue,\n getResolver: () => resolver,\n setResolver: (r) => {\n resolver = r;\n },\n watchers,\n onError: (error, path) => serverLogger.error(`File watcher error for ${path}:`, error),\n })\n ),\n ).catch((error) => {\n serverLogger.error(\"Failed to setup file watchers:\", error);\n });\n\n const iterator = createWatcherIterator(\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n () => closed,\n () => signal?.aborted ?? false,\n );\n\n const cleanup = () => {\n closed = true;\n watchers.forEach((watcher) => {\n try {\n watcher.close();\n } catch (error) {\n serverLogger.debug(\"Error closing file watcher during cleanup:\", error);\n }\n });\n if (resolver) {\n resolver({ done: true, value: undefined });\n resolver = null;\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return createFileWatcher(iterator, cleanup);\n }\n}\n", "import process from \"node:process\";\nimport type { EnvironmentAdapter } from \"../base.ts\";\n\nexport class NodeEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return process.env[key];\n }\n\n set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n }\n}\n", "import type { ServeOptions, Server } from \"../base.ts\";\nimport type { NodeHttpServer, WSWebSocket, WSWebSocketServer } from \"./types.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\n\n// Track pending WebSocket upgrades by request ID\nconst pendingWebSocketUpgrades = new Map<string, {\n resolve: (ws: WSWebSocket) => void;\n reject: (error: Error) => void;\n}>();\n\n// Singleton WebSocket server instance (one per HTTP server)\nlet wsServer: WSWebSocketServer | null = null;\n\nexport class NodeServer implements Server {\n constructor(\n private server: NodeHttpServer,\n private hostname: string,\n private port: number,\n ) {}\n\n stop(): Promise<void> {\n return new Promise((resolve) => {\n // Close WebSocket server first\n if (wsServer) {\n wsServer.close();\n wsServer = null;\n }\n this.server.close(() => resolve());\n });\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\n/**\n * Create a request ID for matching WebSocket upgrades\n */\nfunction createRequestId(req: { headers: Record<string, string | string[] | undefined> }): string {\n const key = req.headers[\"sec-websocket-key\"];\n return typeof key === \"string\" ? key : (Array.isArray(key) ? key[0] : \"\") || crypto.randomUUID();\n}\n\n/**\n * Register a pending WebSocket upgrade\n * Called by NodeServerAdapter.upgradeWebSocket\n */\nexport function registerWebSocketUpgrade(requestId: string): Promise<WSWebSocket> {\n return new Promise((resolve, reject) => {\n pendingWebSocketUpgrades.set(requestId, { resolve, reject });\n // Cleanup after timeout (30 seconds)\n setTimeout(() => {\n if (pendingWebSocketUpgrades.has(requestId)) {\n pendingWebSocketUpgrades.delete(requestId);\n reject(new Error(\"WebSocket upgrade timed out\"));\n }\n }, 30000);\n });\n}\n\nexport async function createNodeServer(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n const { createServer } = await import(\"node:http\");\n\n const server = createServer(async (_req, _res) => {\n try {\n const url = new URL(_req.url || \"/\", `http://${_req.headers.host || hostname}`);\n const body = _req.method === \"GET\" || _req.method === \"HEAD\" ? null : _req;\n\n const headersRecord: Record<string, string> = {};\n for (const [key, value] of Object.entries(_req.headers)) {\n if (typeof value === \"string\") {\n headersRecord[key] = value;\n } else if (Array.isArray(value)) {\n headersRecord[key] = value[0] || \"\";\n }\n }\n\n // Node.js 18+ requires duplex: \"half\" when creating a Request with a streaming body\n const requestInit: RequestInit & { duplex?: string } = {\n method: _req.method,\n headers: headersRecord,\n body: body as BodyInit | null,\n };\n // Only add duplex for requests with a body (POST, PUT, PATCH, etc.)\n if (body !== null) {\n requestInit.duplex = \"half\";\n }\n const request = new Request(url.toString(), requestInit);\n\n const response = await handler(request);\n\n // Check if this is a WebSocket upgrade response (status 101)\n // The actual WebSocket handling is done in the 'upgrade' event\n if (response.status === 101) {\n // Don't end the response - the upgrade handler will take over\n return;\n }\n\n _res.statusCode = response.status;\n _res.statusMessage = response.statusText;\n\n response.headers.forEach((value, key) => {\n _res.setHeader(key, value);\n });\n\n if (response.body) {\n const reader = response.body.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n _res.write(value);\n }\n }\n\n _res.end();\n } catch (_error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"Request handler error:\", _error);\n _res.statusCode = 500;\n _res.end(\"Internal Server Error\");\n }\n });\n\n // Handle WebSocket upgrades\n server.on(\"upgrade\", async (request, socket, head) => {\n try {\n // Lazy load ws package\n const { WebSocketServer } = await import(\"ws\");\n\n // Create WebSocket server if not exists\n if (!wsServer) {\n wsServer = new WebSocketServer({ noServer: true }) as unknown as WSWebSocketServer;\n }\n\n // Get request ID to match with pending upgrade\n const requestId = createRequestId(request);\n\n // Handle the upgrade\n (wsServer as unknown as {\n handleUpgrade: (\n req: unknown,\n socket: unknown,\n head: unknown,\n callback: (ws: WSWebSocket) => void,\n ) => void;\n })\n .handleUpgrade(request, socket, head, (ws: WSWebSocket) => {\n const pending = pendingWebSocketUpgrades.get(requestId);\n if (pending) {\n pendingWebSocketUpgrades.delete(requestId);\n pending.resolve(ws);\n }\n // Emit connection event\n (wsServer as unknown as { emit: (event: string, ws: WSWebSocket, req: unknown) => void })\n .emit(\"connection\", ws, request);\n });\n } catch (error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"WebSocket upgrade error:\", error);\n socket.destroy();\n }\n });\n\n if (options.signal) {\n options.signal.addEventListener(\"abort\", () => {\n if (wsServer) {\n wsServer.close();\n wsServer = null;\n }\n server.close();\n });\n }\n\n return new Promise((resolve) => {\n server.listen(port, hostname, () => {\n onListen?.({ hostname, port });\n resolve(new NodeServer(server as unknown as NodeHttpServer, hostname, port));\n });\n });\n}\n", "import type { ServerAdapter, WebSocketUpgrade } from \"../base.ts\";\nimport type { WSMessageData, WSWebSocket } from \"./types.ts\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\nimport { registerWebSocketUpgrade } from \"./http-server.ts\";\nimport * as crypto from \"node:crypto\";\n\nexport class NodeServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const key = request.headers.get(\"sec-websocket-key\");\n const protocol = request.headers.get(\"sec-websocket-protocol\");\n\n if (!key) {\n throw toError(createError({\n type: \"network\",\n message: \"Missing Sec-WebSocket-Key header\",\n }));\n }\n\n // Create a proxy WebSocket that will be connected when the upgrade completes\n const socket = new NodeWebSocket();\n\n // Register the upgrade and connect when complete\n registerWebSocketUpgrade(key).then((ws) => {\n socket._attachRealSocket(ws);\n }).catch((error) => {\n serverLogger.error(\"WebSocket upgrade failed:\", error);\n socket._emitError(error);\n });\n\n // Return 101 response - the http-server upgrade handler will complete the handshake\n const response = new Response(null, {\n status: 101,\n statusText: \"Switching Protocols\",\n headers: {\n \"Upgrade\": \"websocket\",\n \"Connection\": \"Upgrade\",\n \"Sec-WebSocket-Accept\": this.generateAcceptKey(key),\n ...(protocol ? { \"Sec-WebSocket-Protocol\": protocol } : {}),\n },\n });\n\n return { socket: socket as unknown as WebSocket, response };\n }\n\n private generateAcceptKey(key: string): string {\n const GUID = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n return crypto.createHash(\"sha1\").update(key + GUID).digest(\"base64\");\n }\n}\n\n/**\n * NodeWebSocket - A WebSocket wrapper that works with Node.js\n * Proxies to the real ws WebSocket once the upgrade completes\n */\nexport class NodeWebSocket {\n private ws: WSWebSocket | null = null;\n public readyState = 0; // CONNECTING\n\n public onopen: ((event: Event) => void) | null = null;\n public onclose: ((event: CloseEvent) => void) | null = null;\n public onerror: ((event: Event) => void) | null = null;\n public onmessage: ((event: MessageEvent) => void) | null = null;\n\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n\n // Queue messages sent before the socket is ready\n private pendingMessages: Array<string | ArrayBuffer> = [];\n\n /**\n * Attach the real WebSocket after upgrade completes\n * Called by NodeServerAdapter\n */\n _attachRealSocket(ws: WSWebSocket) {\n this.ws = ws;\n this.readyState = 1; // OPEN\n\n // Set up event handlers\n ws.on(\"open\", () => {\n this.readyState = 1;\n this.onopen?.(new Event(\"open\"));\n });\n\n ws.on(\"message\", (data: WSMessageData) => {\n this.onmessage?.(new MessageEvent(\"message\", { data: data.toString() }));\n });\n\n ws.on(\"close\", () => {\n this.readyState = 3;\n this.onclose?.(new CloseEvent(\"close\"));\n });\n\n ws.on(\"error\", (error: Error) => {\n this.onerror?.(new ErrorEvent(\"error\", { error }));\n });\n\n // Send any pending messages\n for (const msg of this.pendingMessages) {\n ws.send(msg);\n }\n this.pendingMessages = [];\n\n // The socket is already open when we get it from handleUpgrade\n this.onopen?.(new Event(\"open\"));\n }\n\n /**\n * Emit an error when upgrade fails\n * Called by NodeServerAdapter\n */\n _emitError(error: Error) {\n this.readyState = 3; // CLOSED\n this.onerror?.(new ErrorEvent(\"error\", { error }));\n }\n\n send(data: string | ArrayBuffer) {\n if (this.ws && this.readyState === 1) {\n this.ws.send(data);\n } else if (this.readyState === 0) {\n // Queue the message until the socket is ready\n this.pendingMessages.push(data);\n } else {\n throw toError(createError({\n type: \"network\",\n message: \"WebSocket is not open\",\n }));\n }\n }\n\n close(code?: number, reason?: string) {\n if (this.ws) {\n this.ws.close(code, reason);\n }\n this.readyState = 2; // CLOSING\n }\n\n // WebSocket standard interface\n addEventListener(type: string, listener: EventListener) {\n switch (type) {\n case \"open\":\n this.onopen = listener as (event: Event) => void;\n break;\n case \"close\":\n this.onclose = listener as (event: CloseEvent) => void;\n break;\n case \"error\":\n this.onerror = listener as (event: Event) => void;\n break;\n case \"message\":\n this.onmessage = listener as (event: MessageEvent) => void;\n break;\n }\n }\n\n removeEventListener(_type: string, _listener: EventListener) {\n // Simplified - just null out the handler\n switch (_type) {\n case \"open\":\n this.onopen = null;\n break;\n case \"close\":\n this.onclose = null;\n break;\n case \"error\":\n this.onerror = null;\n break;\n case \"message\":\n this.onmessage = null;\n break;\n }\n }\n}\n", "import type {\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n ServeOptions,\n Server,\n} from \"../base.ts\";\nimport { NodeFileSystemAdapter } from \"./filesystem-adapter.ts\";\nimport { NodeEnvironmentAdapter } from \"./environment-adapter.ts\";\nimport { NodeServerAdapter } from \"./websocket-adapter.ts\";\nimport { createNodeServer } from \"./http-server.ts\";\n\nexport class NodeAdapter implements RuntimeAdapter {\n readonly id = \"node\" as const;\n readonly name = \"node\";\n /** @deprecated Use `id` instead */\n readonly platform = \"node\" as const;\n\n fs = new NodeFileSystemAdapter();\n env = new NodeEnvironmentAdapter();\n server = new NodeServerAdapter();\n\n readonly capabilities: RuntimeCapabilities = {\n typescript: false, // Requires compilation\n jsx: false, // Requires compilation\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: false,\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: false,\n typescript: false,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n return createNodeServer(handler, options);\n }\n}\n\nexport const nodeAdapter = new NodeAdapter();\n", "export { NodeAdapter, nodeAdapter } from \"./adapter.ts\";\nexport { NodeFileSystemAdapter } from \"./filesystem-adapter.ts\";\nexport { NodeEnvironmentAdapter } from \"./environment-adapter.ts\";\nexport { NodeServerAdapter, NodeWebSocket } from \"./websocket-adapter.ts\";\nexport { createNodeServer, NodeServer } from \"./http-server.ts\";\nexport type {\n NodeHttpServer,\n NodeIncomingMessage,\n NodeServerResponse,\n WSMessageData,\n WSWebSocket,\n} from \"./types.ts\";\n", "export {\n createNodeServer,\n NodeAdapter,\n nodeAdapter,\n NodeEnvironmentAdapter,\n NodeFileSystemAdapter,\n NodeServer,\n NodeServerAdapter,\n NodeWebSocket,\n} from \"./node/index.ts\";\n\nexport type {\n NodeHttpServer,\n NodeIncomingMessage,\n NodeServerResponse,\n WSMessageData,\n WSWebSocket,\n} from \"./node/index.ts\";\n", "export enum ErrorCode {\n FILE_NOT_FOUND = \"FILE_NOT_FOUND\",\n BUILD_ERROR = \"BUILD_ERROR\",\n CONFIG_ERROR = \"CONFIG_ERROR\",\n COMPILATION_ERROR = \"COMPILATION_ERROR\",\n NETWORK_ERROR = \"NETWORK_ERROR\",\n PERMISSION_ERROR = \"PERMISSION_ERROR\",\n RENDER_ERROR = \"RENDER_ERROR\",\n INITIALIZATION_ERROR = \"INITIALIZATION_ERROR\",\n AGENT_ERROR = \"AGENT_ERROR\",\n AGENT_NOT_FOUND = \"AGENT_NOT_FOUND\",\n AGENT_TIMEOUT = \"AGENT_TIMEOUT\",\n AGENT_INTENT_ERROR = \"AGENT_INTENT_ERROR\",\n ORCHESTRATION_ERROR = \"ORCHESTRATION_ERROR\",\n NOT_SUPPORTED = \"NOT_SUPPORTED\",\n}\n\nexport class VeryfrontError extends Error {\n public code: ErrorCode;\n public context?: unknown;\n\n constructor(message: string, code: ErrorCode, context?: unknown) {\n super(message);\n this.name = \"VeryfrontError\";\n this.code = code;\n this.context = context;\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class AgentError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_ERROR, context);\n this.name = \"AgentError\";\n }\n}\n\nexport class AgentNotFoundError extends VeryfrontError {\n constructor(agentId: string, context?: unknown) {\n super(`Agent with ID '${agentId}' not found`, ErrorCode.AGENT_NOT_FOUND, {\n agentId,\n ...(context as Record<string, unknown> | undefined),\n });\n this.name = \"AgentNotFoundError\";\n }\n}\n\nexport class AgentTimeoutError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_TIMEOUT, context);\n this.name = \"AgentTimeoutError\";\n }\n}\n\nexport class AgentIntentError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_INTENT_ERROR, context);\n this.name = \"AgentIntentError\";\n }\n}\n\nexport class OrchestrationError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.ORCHESTRATION_ERROR, context);\n this.name = \"OrchestrationError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class BuildError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.BUILD_ERROR, context);\n this.name = \"BuildError\";\n }\n}\n\nexport class CompilationError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.COMPILATION_ERROR, context);\n this.name = \"CompilationError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class RuntimeError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.RENDER_ERROR, context);\n this.name = \"RuntimeError\";\n }\n}\n\nexport class RenderError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.RENDER_ERROR, context);\n this.name = \"RenderError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class FileSystemError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.FILE_NOT_FOUND, context);\n this.name = \"FileSystemError\";\n }\n}\n\nexport class ConfigError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.CONFIG_ERROR, context);\n this.name = \"ConfigError\";\n }\n}\n\nexport class NetworkError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.NETWORK_ERROR, context);\n this.name = \"NetworkError\";\n }\n}\n\nexport class PermissionError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.PERMISSION_ERROR, context);\n this.name = \"PermissionError\";\n }\n}\n\nexport class NotSupportedError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.NOT_SUPPORTED, context);\n this.name = \"NotSupportedError\";\n }\n}\n", "import { serverLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { ErrorCode, VeryfrontError } from \"./types.ts\";\n\n/** Default max retries for retry operations */\nconst DEFAULT_MAX_RETRIES = 3;\n\n/** Default initial delay for exponential backoff (100ms) */\nconst DEFAULT_INITIAL_DELAY_MS = 100;\n\n/** Default max delay cap for exponential backoff (5 seconds) */\nconst DEFAULT_MAX_DELAY_MS = 5000;\n\nfunction safeLog(logFn: () => void): void {\n try {\n logFn();\n } catch (error) {\n try {\n serverLogger.warn(\"[errors] Logging failed:\", error);\n } catch {\n // Silently ignore if even warning fails\n }\n }\n}\n\nexport function handleError(error: Error): void {\n safeLog(() => serverLogger.error(`Error: ${error.message}`));\n\n if (error instanceof VeryfrontError && error.context) {\n safeLog(() => serverLogger.error(\"Context:\", error.context));\n }\n\n if (error.stack) {\n safeLog(() => serverLogger.error(error.stack as string));\n }\n}\n\nexport function wrapError(\n error: unknown,\n message: string,\n context?: unknown,\n): VeryfrontError {\n const originalError = error instanceof Error ? error : new Error(String(error));\n const errorMessage = `${message}: ${originalError.message}`;\n\n const wrappedContext = {\n originalError: {\n name: originalError.name,\n message: originalError.message,\n stack: originalError.stack,\n },\n ...(context as Record<string, unknown> | undefined),\n };\n\n const errorCode = error instanceof VeryfrontError ? error.code : ErrorCode.RENDER_ERROR;\n\n return new VeryfrontError(errorMessage, errorCode, wrappedContext);\n}\n\nexport function logAndThrow(\n error: unknown,\n message?: string,\n logger: typeof serverLogger = serverLogger,\n): never {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n const logMessage = message ? `${message}: ${errorObj.message}` : errorObj.message;\n\n safeLog(() => logger.error(logMessage, error));\n\n if (error instanceof Error) {\n throw error;\n }\n throw errorObj;\n}\n\nexport async function handleErrorWithFallback<T>(\n fn: () => T | Promise<T>,\n fallback: T,\n logger: typeof serverLogger = serverLogger,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n safeLog(() => logger.warn(\"Operation failed, using fallback\", error));\n return fallback;\n }\n}\n\nexport function handleErrorWithFallbackSync<T>(\n fn: () => T,\n fallback: T,\n logger: typeof serverLogger = serverLogger,\n): T {\n try {\n return fn();\n } catch (error) {\n safeLog(() => logger.warn(\"Operation failed, using fallback\", error));\n return fallback;\n }\n}\n\nexport async function retryWithBackoff<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries?: number;\n initialDelay?: number;\n maxDelay?: number;\n logger?: typeof serverLogger;\n } = {},\n): Promise<T> {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n initialDelay = DEFAULT_INITIAL_DELAY_MS,\n maxDelay = DEFAULT_MAX_DELAY_MS,\n logger: log = serverLogger,\n } = options;\n\n let lastError: unknown;\n let delay = initialDelay;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n safeLog(() => log.warn(`Attempt ${attempt + 1} failed, retrying...`, error));\n\n if (attempt < maxRetries - 1) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n delay = Math.min(delay * 2, maxDelay);\n }\n }\n }\n\n throw lastError;\n}\n", "export const ErrorCode = {\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\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\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\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\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\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\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\n DEV_SERVER_ERROR: \"VF700\",\n FAST_REFRESH_ERROR: \"VF701\",\n ERROR_OVERLAY_ERROR: \"VF702\",\n SOURCE_MAP_ERROR: \"VF703\",\n\n DEPLOYMENT_ERROR: \"VF800\",\n PLATFORM_ERROR: \"VF801\",\n ENV_VAR_MISSING: \"VF802\",\n PRODUCTION_BUILD_REQUIRED: \"VF803\",\n\n UNKNOWN_ERROR: \"VF900\",\n PERMISSION_DENIED: \"VF901\",\n FILE_NOT_FOUND: \"VF902\",\n INVALID_ARGUMENT: \"VF903\",\n TIMEOUT_ERROR: \"VF904\",\n} as const;\n\nexport type ErrorCodeType = typeof ErrorCode[keyof typeof ErrorCode];\n\nexport function getErrorDocsUrl(code: ErrorCodeType): string {\n return `https://veryfront.com/docs/errors/${code}`;\n}\n\nexport function inferErrorCode(error: Error): ErrorCodeType | null {\n const message = error.message.toLowerCase();\n\n if (message.includes(\"config\") && message.includes(\"not found\")) {\n return ErrorCode.CONFIG_NOT_FOUND;\n }\n if (message.includes(\"config\") && message.includes(\"invalid\")) return ErrorCode.CONFIG_INVALID;\n if (message.includes(\"cors\")) return ErrorCode.CORS_CONFIG_INVALID;\n\n if (message.includes(\"route\") && message.includes(\"conflict\")) return ErrorCode.ROUTE_CONFLICT;\n if (message.includes(\"route\") && message.includes(\"invalid\")) return ErrorCode.INVALID_ROUTE_FILE;\n\n if (message.includes(\"client\") && message.includes(\"boundary\")) {\n return ErrorCode.CLIENT_BOUNDARY_VIOLATION;\n }\n if (message.includes(\"server-only\") && message.includes(\"client\")) {\n return ErrorCode.SERVER_ONLY_IN_CLIENT;\n }\n\n if (message.includes(\"module not found\") || message.includes(\"cannot find module\")) {\n return ErrorCode.MODULE_NOT_FOUND;\n }\n if (message.includes(\"import\") || message.includes(\"resolve\")) {\n return ErrorCode.IMPORT_RESOLUTION_ERROR;\n }\n if (message.includes(\"react\") && message.includes(\"not found\")) {\n return ErrorCode.DEPENDENCY_MISSING;\n }\n\n if (message.includes(\"port\") && (message.includes(\"in use\") || message.includes(\"eaddrinuse\"))) {\n return ErrorCode.PORT_IN_USE;\n }\n if (message.includes(\"hydration\")) return ErrorCode.HYDRATION_MISMATCH;\n\n if (message.includes(\"build\") && message.includes(\"fail\")) return ErrorCode.BUILD_FAILED;\n if (message.includes(\"mdx\")) return ErrorCode.MDX_COMPILE_ERROR;\n if (message.includes(\"typescript\")) return ErrorCode.TYPESCRIPT_ERROR;\n\n return null;\n}\n", "import type { ErrorCodeType } from \"../error-codes.ts\";\nimport { getErrorDocsUrl } from \"../error-codes.ts\";\nimport type { ErrorSolution } from \"./types.ts\";\n\nexport function createErrorSolution(\n code: ErrorCodeType,\n config: Omit<ErrorSolution, \"code\" | \"docs\"> & { docs?: string },\n): ErrorSolution {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code),\n };\n}\n\nexport function createSimpleError(\n code: ErrorCodeType,\n title: string,\n message: string,\n steps: string[],\n): ErrorSolution {\n return createErrorSolution(code, { title, message, steps });\n}\n", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const CONFIG_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.CONFIG_INVALID]: createErrorSolution(ErrorCode.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\n [ErrorCode.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode.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\n [ErrorCode.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const BUILD_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.BUILD_FAILED]: createErrorSolution(ErrorCode.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\n [ErrorCode.BUNDLE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode.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\n [ErrorCode.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const RUNTIME_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode.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: [ErrorCode.RENDER_ERROR],\n }),\n\n [ErrorCode.RENDER_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.COMPONENT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode.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\n [ErrorCode.API_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const ROUTE_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode.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\n [ErrorCode.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode.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\n [ErrorCode.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const MODULE_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_IMPORT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode.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\n [ErrorCode.VERSION_MISMATCH]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const SERVER_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.PORT_IN_USE]: createErrorSolution(ErrorCode.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\n [ErrorCode.SERVER_START_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.HMR_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CACHE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.REQUEST_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const RSC_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode.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\n [ErrorCode.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode.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\n [ErrorCode.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode.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\n [ErrorCode.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const DEV_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const DEPLOYMENT_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PLATFORM_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const GENERAL_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PERMISSION_DENIED]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode.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", "import type { ErrorCodeType } from \"../error-codes.ts\";\nimport type { ErrorCatalog, ErrorSolution } from \"./types.ts\";\n\nimport { CONFIG_ERROR_CATALOG } from \"./config-errors.ts\";\nimport { BUILD_ERROR_CATALOG } from \"./build-errors.ts\";\nimport { RUNTIME_ERROR_CATALOG } from \"./runtime-errors.ts\";\nimport { ROUTE_ERROR_CATALOG } from \"./route-errors.ts\";\nimport { MODULE_ERROR_CATALOG } from \"./module-errors.ts\";\nimport { SERVER_ERROR_CATALOG } from \"./server-errors.ts\";\nimport { RSC_ERROR_CATALOG } from \"./rsc-errors.ts\";\nimport { DEV_ERROR_CATALOG } from \"./dev-errors.ts\";\nimport { DEPLOYMENT_ERROR_CATALOG } from \"./deployment-errors.ts\";\nimport { GENERAL_ERROR_CATALOG } from \"./general-errors.ts\";\n\nexport const 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} as ErrorCatalog;\n\nexport function getErrorSolution(code: ErrorCodeType): ErrorSolution | null {\n return ERROR_CATALOG[code] || null;\n}\n\nexport function searchErrors(query: string): ErrorSolution[] {\n const lowerQuery = query.toLowerCase();\n return Object.values(ERROR_CATALOG).filter(\n (error) =>\n error.title.toLowerCase().includes(lowerQuery) ||\n error.message.toLowerCase().includes(lowerQuery) ||\n error.steps?.some((step) => step.toLowerCase().includes(lowerQuery)),\n );\n}\n\nexport type { ErrorCatalog, ErrorSolution, PartialErrorCatalog } from \"./types.ts\";\n\nexport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport {\n BUILD_ERROR_CATALOG,\n CONFIG_ERROR_CATALOG,\n DEPLOYMENT_ERROR_CATALOG,\n DEV_ERROR_CATALOG,\n GENERAL_ERROR_CATALOG,\n MODULE_ERROR_CATALOG,\n ROUTE_ERROR_CATALOG,\n RSC_ERROR_CATALOG,\n RUNTIME_ERROR_CATALOG,\n SERVER_ERROR_CATALOG,\n};\n", "export interface ErrorSolution {\n message: string;\n steps?: string[];\n example?: string;\n docs?: string;\n}\n\nexport const ERROR_SOLUTIONS: Record<string, ErrorSolution> = {\n \"missing-config\": {\n message: \"No veryfront.config.js found in project directory\",\n steps: [\n \"Create a veryfront.config.js file in your project root\",\n \"Run 'veryfront init' to generate a default config\",\n \"Or create one manually with minimal configuration\",\n ],\n example: `export default {\n title: \"My App\",\n dev: { port: 3002 }\n};`,\n },\n\n \"invalid-config\": {\n message: \"Invalid configuration in veryfront.config.js\",\n steps: [\n \"Check that your config exports a default object\",\n \"Ensure all values are valid JavaScript\",\n \"Remove any trailing commas in objects\",\n ],\n example: `export default {\n title: \"My App\", // \u2713 Valid string\n dev: {\n port: 3002, // \u2713 Valid number\n open: true // \u2713 No trailing comma\n }\n};`,\n },\n\n \"invalid-route\": {\n message: \"Invalid route file format\",\n steps: [\n \"Route files must export handler functions (GET, POST, etc.)\",\n \"Each handler must return a Response object\",\n \"Check for syntax errors in your route file\",\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] });\n}\n\nexport async function POST(request: Request) {\n const body = await request.json();\n return Response.json({ created: true });\n}`,\n },\n\n \"client-boundary\": {\n message: \"Server-only code used in Client Component\",\n steps: [\n \"Move server-only imports to Server Components\",\n \"Use 'use server' directive for server actions\",\n \"Split component into server and client parts\",\n ],\n example: `// \u274C Wrong - database import in client component\n'use client';\nimport { db } from './database'; // Error!\n\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}`,\n docs: \"https://github.com/veryfront/veryfront/docs/rsc-boundaries\",\n },\n\n \"import-not-found\": {\n message: \"Failed to resolve import\",\n steps: [\n \"Check that the file path is correct\",\n \"Ensure the module is installed or available\",\n \"For remote imports, check network connectivity\",\n \"Add missing imports to veryfront.config.js importMap\",\n ],\n example: `// veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n \"my-lib\": \"https://esm.sh/my-lib@1.0.0\",\n \"@/utils\": \"./src/utils/index.ts\"\n }\n }\n}`,\n },\n\n \"port-in-use\": {\n message: \"Port is already in use\",\n steps: [\n \"Stop any other servers running on this port\",\n \"Use a different port with --port flag\",\n \"Check for zombie processes: lsof -i :PORT\",\n ],\n example: `veryfront dev --port 3003`,\n },\n\n \"build-failed\": {\n message: \"Build failed with errors\",\n steps: [\n \"Check the error messages above for details\",\n \"Fix any TypeScript or syntax errors\",\n \"Ensure all imports can be resolved\",\n \"Run 'veryfront doctor' to check system\",\n ],\n },\n\n \"missing-deps\": {\n message: \"Required dependencies not found\",\n steps: [\n \"Check that React is in your import map\",\n \"Ensure all peer dependencies are included\",\n \"Run 'veryfront doctor' to verify setup\",\n ],\n example: `// Minimum required imports\n\"react\": \"https://esm.sh/react@19.1.1\",\n\"react-dom\": \"https://esm.sh/react-dom@19.1.1\"`,\n },\n};\n", "/**\n * Pure ANSI escape code colors for npm/Node.js builds\n *\n * This file provides a zero-dependency color implementation using ANSI codes.\n * It's used in npm builds where std/fmt/colors.ts isn't available.\n */\n\nimport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nconst ansi = (open: number, close: number): ColorFunction => (text: string) =>\n `\\x1b[${open}m${text}\\x1b[${close}m`;\n\nexport const red: ColorFunction = ansi(31, 39);\nexport const green: ColorFunction = ansi(32, 39);\nexport const yellow: ColorFunction = ansi(33, 39);\nexport const blue: ColorFunction = ansi(34, 39);\nexport const magenta: ColorFunction = ansi(35, 39);\nexport const cyan: ColorFunction = ansi(36, 39);\nexport const white: ColorFunction = ansi(37, 39);\nexport const gray: ColorFunction = ansi(90, 39);\nexport const bold: ColorFunction = ansi(1, 22);\nexport const dim: ColorFunction = ansi(2, 22);\nexport const italic: ColorFunction = ansi(3, 23);\nexport const underline: ColorFunction = ansi(4, 24);\nexport const strikethrough: ColorFunction = ansi(9, 29);\nexport const reset: ColorFunction = (text: string) => `\\x1b[0m${text}`;\n\nexport const colors: ConsoleStyler = {\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 * Deno console styling implementation using std/fmt/colors.ts\n */\n\nimport {\n blue,\n bold,\n cyan,\n dim,\n gray,\n green,\n italic,\n magenta,\n red,\n reset,\n strikethrough,\n underline,\n white,\n yellow,\n} from \"std/fmt/colors.ts\";\n\nimport type { ConsoleStyler } from \"./types.ts\";\n\nexport const colors: ConsoleStyler = {\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\nexport {\n blue,\n bold,\n cyan,\n dim,\n gray,\n green,\n italic,\n magenta,\n red,\n reset,\n strikethrough,\n underline,\n white,\n yellow,\n};\n", "/**\n * Node.js console styling implementation using picocolors\n */\n\nimport type { ConsoleStyler } from \"./types.ts\";\n\n// Lazy-loaded picocolors instance\ntype PicoColors = {\n red: (s: string) => string;\n green: (s: string) => string;\n yellow: (s: string) => string;\n blue: (s: string) => string;\n cyan: (s: string) => string;\n magenta: (s: string) => string;\n white: (s: string) => string;\n gray: (s: string) => string;\n bold: (s: string) => string;\n dim: (s: string) => string;\n italic: (s: string) => string;\n underline: (s: string) => string;\n strikethrough: (s: string) => string;\n reset: (s: string) => string;\n};\n\nlet pc: PicoColors | null = null;\n\nasync function ensurePc(): Promise<PicoColors> {\n if (pc) return pc;\n // Construct module name dynamically to prevent Deno static analyzer\n // from trying to resolve this npm package during lint/check\n const picocolorsModule = [\"npm:\", \"picocolors\"].join(\"\");\n const mod = await import(picocolorsModule);\n pc = mod.default as PicoColors;\n return pc;\n}\n\n// Lazy wrapper that falls back to identity if not loaded\nconst lazyColor = (fn: keyof PicoColors) => (s: string) => pc?.[fn]?.(s) ?? s;\n\nexport const colors: ConsoleStyler = {\n red: lazyColor(\"red\"),\n green: lazyColor(\"green\"),\n yellow: lazyColor(\"yellow\"),\n blue: lazyColor(\"blue\"),\n cyan: lazyColor(\"cyan\"),\n magenta: lazyColor(\"magenta\"),\n white: lazyColor(\"white\"),\n gray: lazyColor(\"gray\"),\n bold: lazyColor(\"bold\"),\n dim: lazyColor(\"dim\"),\n italic: lazyColor(\"italic\"),\n underline: lazyColor(\"underline\"),\n strikethrough: lazyColor(\"strikethrough\"),\n reset: lazyColor(\"reset\"),\n};\n\nexport const red = lazyColor(\"red\");\nexport const green = lazyColor(\"green\");\nexport const yellow = lazyColor(\"yellow\");\nexport const blue = lazyColor(\"blue\");\nexport const cyan = lazyColor(\"cyan\");\nexport const magenta = lazyColor(\"magenta\");\nexport const white = lazyColor(\"white\");\nexport const gray = lazyColor(\"gray\");\nexport const bold = lazyColor(\"bold\");\nexport const dim = lazyColor(\"dim\");\nexport const italic = lazyColor(\"italic\");\nexport const underline = lazyColor(\"underline\");\nexport const strikethrough = lazyColor(\"strikethrough\");\nexport const reset = lazyColor(\"reset\");\n\n// Initialize picocolors on first use\nexport async function initColors(): Promise<void> {\n await ensurePc();\n}\n", "/**\n * Cross-runtime console styling\n *\n * Provides terminal colors that work in Deno, Node.js, and Bun.\n * Falls back to no-op functions in environments without terminal support.\n */\n\nimport { isDeno } from \"../runtime.ts\";\nimport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nexport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nconst noOp: ColorFunction = (text: string) => text;\n\nconst fallbackColors: ConsoleStyler = {\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\nlet _colors: ConsoleStyler | null = null;\n\nasync function loadColors(): Promise<ConsoleStyler> {\n if (_colors) return _colors;\n\n try {\n if (isDeno) {\n const mod = await import(\"./deno.ts\");\n _colors = mod.colors;\n } else {\n const mod = await import(\"./node.ts\");\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n\n return _colors;\n}\n\nconst colorsPromise = loadColors();\n\nfunction getColors(): ConsoleStyler {\n return _colors ?? fallbackColors;\n}\n\nexport const red: ColorFunction = (text) => getColors().red(text);\nexport const green: ColorFunction = (text) => getColors().green(text);\nexport const yellow: ColorFunction = (text) => getColors().yellow(text);\nexport const blue: ColorFunction = (text) => getColors().blue(text);\nexport const cyan: ColorFunction = (text) => getColors().cyan(text);\nexport const magenta: ColorFunction = (text) => getColors().magenta(text);\nexport const white: ColorFunction = (text) => getColors().white(text);\nexport const gray: ColorFunction = (text) => getColors().gray(text);\nexport const bold: ColorFunction = (text) => getColors().bold(text);\nexport const dim: ColorFunction = (text) => getColors().dim(text);\nexport const italic: ColorFunction = (text) => getColors().italic(text);\nexport const underline: ColorFunction = (text) => getColors().underline(text);\nexport const strikethrough: ColorFunction = (text) => getColors().strikethrough(text);\nexport const reset: ColorFunction = (text) => getColors().reset(text);\n\nexport const 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} satisfies ConsoleStyler;\n\nexport { colorsPromise };\n", "export function identifyError(error: Error): string {\n const message = error.message.toLowerCase();\n\n if (message.includes(\"veryfront.config\") && message.includes(\"not found\")) {\n return \"missing-config\";\n }\n if (message.includes(\"config\") && (message.includes(\"invalid\") || message.includes(\"parse\"))) {\n return \"invalid-config\";\n }\n\n if (message.includes(\"route\") && (message.includes(\"invalid\") || message.includes(\"export\"))) {\n return \"invalid-route\";\n }\n\n if (message.includes(\"client\") && (message.includes(\"boundary\") || message.includes(\"server\"))) {\n return \"client-boundary\";\n }\n\n if (\n message.includes(\"import\") ||\n message.includes(\"module not found\") ||\n message.includes(\"resolve\")\n ) {\n return \"import-not-found\";\n }\n\n if (message.includes(\"port\") && (message.includes(\"in use\") || message.includes(\"eaddrinuse\"))) {\n return \"port-in-use\";\n }\n\n if (message.includes(\"build\") && message.includes(\"fail\")) {\n return \"build-failed\";\n }\n\n if (message.includes(\"react\") && message.includes(\"not found\")) {\n return \"missing-deps\";\n }\n\n return \"unknown\";\n}\n", "import { bold, cyan, dim, red, yellow } from \"@veryfront/compat/console\";\nimport { ERROR_SOLUTIONS } from \"./error-catalog.ts\";\nimport { identifyError } from \"./error-identifier.ts\";\n\nexport function formatUserError(error: Error): string {\n const output: string[] = [];\n\n output.push(\"\");\n output.push(red(bold(\"\u2716 Error: \")) + bold(error.message));\n output.push(\"\");\n\n const errorKey = identifyError(error);\n const solution = ERROR_SOLUTIONS[errorKey];\n\n if (solution) {\n if (solution.message) {\n output.push(yellow(\"Problem: \") + solution.message);\n output.push(\"\");\n }\n\n if (solution.steps && solution.steps.length > 0) {\n output.push(cyan(\"How to fix:\"));\n solution.steps.forEach((step, i) => {\n output.push(` ${dim(`${i + 1}.`)} ${step}`);\n });\n output.push(\"\");\n }\n\n if (solution.example) {\n output.push(cyan(\"Example:\"));\n output.push(\"\");\n solution.example.split(\"\\n\").forEach((line) => {\n output.push(` ${dim(line)}`);\n });\n output.push(\"\");\n }\n\n if (solution.docs) {\n output.push(dim(\"Learn more: \") + cyan(solution.docs));\n output.push(\"\");\n }\n } else {\n if (error.stack) {\n output.push(yellow(\"Stack trace:\"));\n const stackLines = error.stack.split(\"\\n\").slice(1, 4);\n stackLines.forEach((line) => {\n output.push(dim(` ${line.trim()}`));\n });\n output.push(\"\");\n }\n\n output.push(dim(\"For help, run: \") + cyan(\"veryfront doctor\"));\n output.push(\"\");\n }\n\n return output.join(\"\\n\");\n}\n", "import { red } from \"@veryfront/compat/console\";\nimport { exit } from \"@veryfront/platform/compat/process.ts\";\nimport { cliLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { formatUserError } from \"./error-formatter.ts\";\n\nexport function wrapErrorHandler<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn> {\n return async (...args: TArgs): Promise<TReturn> => {\n try {\n return await fn(...args);\n } catch (error) {\n if (error instanceof Error) {\n cliLogger.error(formatUserError(error));\n } else {\n cliLogger.error(red(\"\u2716 Unknown error:\"), error);\n }\n if (import.meta.main) {\n exit(1);\n }\n throw error;\n }\n };\n}\n", "export { ERROR_SOLUTIONS, type ErrorSolution } from \"./error-catalog.ts\";\nexport { formatUserError } from \"./error-formatter.ts\";\nexport { identifyError } from \"./error-identifier.ts\";\nexport { wrapErrorHandler } from \"./error-wrapper.ts\";\n", "export { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport {\n AgentError,\n AgentIntentError,\n AgentNotFoundError,\n AgentTimeoutError,\n OrchestrationError,\n} from \"./agent-errors.ts\";\n\nexport { BuildError, CompilationError } from \"./build-errors.ts\";\n\nexport { RenderError, RuntimeError } from \"./runtime-errors.ts\";\n\nexport {\n ConfigError,\n FileSystemError,\n NetworkError,\n NotSupportedError,\n PermissionError,\n} from \"./system-errors.ts\";\n\nexport {\n handleError,\n handleErrorWithFallback,\n handleErrorWithFallbackSync,\n logAndThrow,\n retryWithBackoff,\n wrapError,\n} from \"./error-handlers.ts\";\n\nexport {\n BUILD_ERROR_CATALOG,\n CONFIG_ERROR_CATALOG,\n createErrorSolution,\n createSimpleError,\n DEPLOYMENT_ERROR_CATALOG,\n DEV_ERROR_CATALOG,\n ERROR_CATALOG,\n GENERAL_ERROR_CATALOG,\n getErrorSolution,\n MODULE_ERROR_CATALOG,\n ROUTE_ERROR_CATALOG,\n RSC_ERROR_CATALOG,\n RUNTIME_ERROR_CATALOG,\n searchErrors,\n SERVER_ERROR_CATALOG,\n} from \"./catalog/index.ts\";\n\nexport type { ErrorCatalog, ErrorSolution, PartialErrorCatalog } from \"./catalog/index.ts\";\n\nexport {\n ERROR_SOLUTIONS,\n formatUserError,\n identifyError,\n wrapErrorHandler,\n} from \"./user-friendly/index.ts\";\n\nexport type { ErrorSolution as UserFriendlyErrorSolution } from \"./user-friendly/index.ts\";\n\nexport type { ErrorCodeType } from \"./error-codes.ts\";\n", "import { FileSystemError } from \"@veryfront/errors\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\nimport type {\n DirEntry,\n FileChangeEvent,\n FileChangeKind,\n FileInfo,\n FileSystemAdapter,\n FileWatcher,\n WatchOptions,\n} from \"../base.ts\";\n\nimport { createFileWatcher, createWatcherIterator, enqueueWatchEvent } from \"../shared-watcher.ts\";\nimport type { BunFSWatcher, BunWatchEvent } from \"./types.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nexport class BunFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n const file = Bun.file(path);\n return await file.text();\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n const file = Bun.file(path);\n // deno-lint-ignore no-explicit-any\n const buffer = await (file as any).arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await Bun.write(path, content);\n }\n\n async exists(path: string): Promise<boolean> {\n const file = Bun.file(path);\n return await file.exists();\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\n const { readdir } = await import(\"node:fs/promises\");\n const entries = await readdir(path, { withFileTypes: true });\n\n for (const entry of entries) {\n yield {\n name: entry.name,\n isFile: entry.isFile(),\n isDirectory: entry.isDirectory(),\n isSymlink: entry.isSymbolicLink(),\n };\n }\n }\n\n async stat(path: string): Promise<FileInfo> {\n const file = Bun.file(path);\n const exists = await file.exists();\n if (!exists) {\n throw new FileSystemError(`File not found: ${path}`, { path });\n }\n\n const { stat } = await import(\"node:fs/promises\");\n const stats = await stat(path);\n\n return {\n size: file.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymlink: stats.isSymbolicLink(),\n mtime: stats.mtime,\n };\n }\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const { mkdir } = await import(\"node:fs/promises\");\n await mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n const { rm } = await import(\"node:fs/promises\");\n await rm(path, { recursive: options?.recursive, force: true });\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n const { join } = await import(\"node:path\");\n const { tmpdir } = await import(\"node:os\");\n return await mkdtemp(join(tmpdir(), prefix));\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n let closed = false;\n const watchers: Array<BunFSWatcher | import(\"node:fs\").FSWatcher> = [];\n const eventQueue: FileChangeEvent[] = [];\n let resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null = null;\n\n const mapBunEventKind = (type: string): FileChangeKind => {\n switch (type) {\n case \"create\":\n return \"create\";\n case \"change\":\n return \"modify\";\n case \"delete\":\n return \"delete\";\n default:\n return \"any\";\n }\n };\n\n const setupWatcher = (path: string) => {\n try {\n if (typeof Bun !== \"undefined\" && Bun.watch) {\n const watcher = Bun.watch(path, {\n recursive,\n onChange: (event: BunWatchEvent) => {\n if (closed || signal?.aborted) return;\n\n enqueueWatchEvent(\n { kind: mapBunEventKind(event.type), paths: [event.path] },\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n );\n },\n });\n watchers.push(watcher);\n } else {\n throw toError(createError({\n type: \"not_supported\",\n message: \"Bun.watch is not available in this environment\",\n feature: \"Bun.watch\",\n }));\n }\n } catch (error) {\n serverLogger.error(`Failed to watch ${path}:`, error);\n }\n };\n\n Promise.all(pathArray.map(setupWatcher)).catch((error) => {\n serverLogger.error(\"Failed to setup Bun file watchers:\", error);\n });\n\n const iterator = createWatcherIterator(\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n () => closed,\n () => signal?.aborted ?? false,\n );\n\n const cleanup = () => {\n closed = true;\n watchers.forEach((watcher) => {\n try {\n if (\"stop\" in watcher && typeof watcher.stop === \"function\") {\n watcher.stop();\n } else if (\"close\" in watcher && typeof watcher.close === \"function\") {\n watcher.close();\n }\n } catch (error) {\n serverLogger.debug(\"Error closing Bun file watcher during cleanup:\", error);\n }\n });\n if (resolver) {\n resolver({ done: true, value: undefined });\n resolver = null;\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return createFileWatcher(iterator, cleanup);\n }\n}\n", "import type { EnvironmentAdapter } from \"../base.ts\";\n\nexport class BunEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return Bun.env[key];\n }\n\n set(key: string, value: string): void {\n Bun.env[key] = value;\n }\n\n toObject(): Record<string, string> {\n return { ...Bun.env };\n }\n}\n", "import type { ServerAdapter, WebSocketUpgrade } from \"../base.ts\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\n\nexport class BunServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const success = Bun.upgrade(request);\n\n if (!success) {\n throw toError(createError({\n type: \"network\",\n message: \"Failed to upgrade WebSocket connection\",\n }));\n }\n\n const socket = new BunWebSocket();\n const response = new Response(null, {\n status: 101,\n statusText: \"Switching Protocols\",\n });\n\n return { socket: socket as unknown as WebSocket, response };\n }\n}\n\nexport class BunWebSocket {\n public readyState = 1;\n\n public onopen: ((event: Event) => void) | null = null;\n public onclose: ((event: Event) => void) | null = null;\n public onerror: ((event: Event) => void) | null = null;\n public onmessage: ((event: MessageEvent) => void) | null = null;\n\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n\n send(_data: string | ArrayBuffer) {\n throw toError(createError({\n type: \"network\",\n message: \"WebSocket send called on placeholder - use Bun.serve websocket handlers\",\n }));\n }\n\n close(_code?: number, _reason?: string) {\n this.readyState = 3;\n }\n}\n", "import type { ServeOptions, Server } from \"../base.ts\";\nimport type { BunServer as BunServerType } from \"./types.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nexport class BunServer implements Server {\n constructor(\n private server: BunServerType,\n private hostname: string,\n private port: number,\n ) {}\n\n stop(): Promise<void> {\n this.server.stop();\n return Promise.resolve();\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\nexport function createBunServer(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n\n const server = Bun.serve({\n port,\n hostname,\n async fetch(request: Request) {\n try {\n return await handler(request);\n } catch (error) {\n serverLogger.error(\"Request handler error:\", error);\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n },\n });\n\n onListen?.({ hostname, port });\n\n return Promise.resolve(new BunServer(server, hostname, port));\n}\n", "import type {\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n ServeOptions,\n Server,\n} from \"../base.ts\";\nimport { BunFileSystemAdapter } from \"./filesystem-adapter.ts\";\nimport { BunEnvironmentAdapter } from \"./environment-adapter.ts\";\nimport { BunServerAdapter } from \"./websocket-adapter.ts\";\nimport { createBunServer } from \"./http-server.ts\";\n\nexport class BunAdapter implements RuntimeAdapter {\n readonly id = \"bun\" as const;\n readonly name = \"bun\";\n /** @deprecated Use `id` instead */\n readonly platform = \"bun\" as const;\n\n fs = new BunFileSystemAdapter();\n env = new BunEnvironmentAdapter();\n server = new BunServerAdapter();\n\n readonly capabilities: RuntimeCapabilities = {\n typescript: true,\n jsx: true,\n http2: false, // Bun's HTTP/2 support is experimental\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: false,\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: false,\n workers: true,\n jsx: true,\n typescript: true,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n return createBunServer(handler, options);\n }\n}\n\nexport const bunAdapter = new BunAdapter();\n", "export { BunAdapter, bunAdapter } from \"./adapter.ts\";\nexport { BunFileSystemAdapter } from \"./filesystem-adapter.ts\";\nexport { BunEnvironmentAdapter } from \"./environment-adapter.ts\";\nexport { BunServerAdapter, BunWebSocket } from \"./websocket-adapter.ts\";\nexport { BunServer, createBunServer } from \"./http-server.ts\";\nexport type {\n BunFile,\n BunFSWatcher,\n BunNamespace,\n BunServeOptions,\n BunServer as BunServerType,\n BunWatchEvent,\n BunWatchOptions,\n} from \"./types.ts\";\n", "export {\n BunAdapter,\n bunAdapter,\n BunEnvironmentAdapter,\n BunFileSystemAdapter,\n BunServer,\n BunServerAdapter,\n BunWebSocket,\n createBunServer,\n} from \"./bun/index.ts\";\n\nexport type {\n BunFile,\n BunFSWatcher,\n BunNamespace,\n BunServeOptions,\n BunServerType,\n BunWatchEvent,\n BunWatchOptions,\n} from \"./bun/index.ts\";\n", "import { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport type { RuntimeAdapter } from \"./base.ts\";\n\nexport interface MockRuntimeAdapter extends RuntimeAdapter {\n fs: RuntimeAdapter[\"fs\"] & {\n files: Map<string, string>;\n directories: Set<string>;\n };\n}\n\n/**\n * Mock RuntimeAdapter for testing\n *\n * Provides an in-memory filesystem and environment for unit testing.\n * This adapter is useful for testing code that depends on the filesystem\n * without requiring actual file I/O.\n *\n * @example\n * ```typescript\n * const adapter = createMockAdapter();\n * adapter.fs.files.set(\"/project/pages/index.tsx\", \"export default () => <div>Home</div>\");\n * const content = await adapter.fs.readFile(\"/project/pages/index.tsx\");\n * ```\n */\n\n/**\n * Creates a mock RuntimeAdapter for testing\n *\n * The mock adapter uses in-memory Map and Set for file storage:\n * - `files`: Map<string, string> for file contents\n * - `directories`: Set<string> for tracking directories\n * - `envVars`: Map<string, string> for environment variables\n */\nexport function createMockAdapter(): MockRuntimeAdapter {\n const files = new Map<string, string>();\n const directories = new Set<string>();\n const envVars = new Map<string, string>();\n\n return {\n id: \"memory\" as const,\n name: \"mock\",\n /** @deprecated Use `id` instead */\n platform: \"memory\" as const,\n capabilities: {\n typescript: false,\n jsx: false,\n http2: false,\n websocket: false,\n workers: false,\n fileWatching: false,\n shell: false,\n kvStore: false,\n writableFs: true, // In-memory writes work\n },\n serve: (_handler, _options) => {\n return Promise.resolve({\n stop: () => Promise.resolve(),\n addr: { hostname: \"localhost\", port: 8000 },\n });\n },\n fs: {\n files,\n directories,\n readFile: (path: string) => {\n const content = files.get(path);\n if (!content) {\n throw toError(createError({\n type: \"file\",\n message: `File not found: ${path}`,\n }));\n }\n return Promise.resolve(content);\n },\n readFileBytes: (path: string) => {\n const content = files.get(path);\n if (!content) {\n throw toError(createError({\n type: \"file\",\n message: `File not found: ${path}`,\n }));\n }\n return Promise.resolve(new TextEncoder().encode(content));\n },\n writeFile: (path: string, content: string) => {\n files.set(path, content);\n return Promise.resolve();\n },\n exists: (path: string) => {\n if (files.has(path)) return Promise.resolve(true);\n if (directories.has(path)) return Promise.resolve(true);\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) return Promise.resolve(true);\n }\n return Promise.resolve(false);\n },\n readDir: async function* (path: string) {\n const entries = new Map<string, { isFile: boolean; isDirectory: boolean }>();\n\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) {\n const relativePath = filePath.slice(path.length + 1);\n const parts = relativePath.split(\"/\");\n const name = parts[0]!;\n\n if (!entries.has(name)) {\n entries.set(name, {\n isFile: parts.length === 1,\n isDirectory: parts.length > 1,\n });\n }\n }\n }\n\n for (const [name, meta] of entries.entries()) {\n yield { name, ...meta, isSymlink: false };\n }\n },\n stat: (path: string) => {\n if (files.has(path)) {\n const content = files.get(path)!;\n return Promise.resolve({\n size: content.length,\n isFile: true,\n isDirectory: false,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n\n if (directories.has(path)) {\n return Promise.resolve({\n size: 0,\n isFile: false,\n isDirectory: true,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) {\n return Promise.resolve({\n size: 0,\n isFile: false,\n isDirectory: true,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n }\n\n return Promise.reject(new Error(`Path not found: ${path}`));\n },\n mkdir: (_path: string) => Promise.resolve(),\n remove: (_path: string) => Promise.resolve(),\n makeTempDir: (prefix: string) =>\n Promise.resolve(`/tmp/${prefix}-${Math.random().toString(36).slice(2)}`),\n watch: () => ({\n async *[Symbol.asyncIterator]() {\n yield { kind: \"any\", paths: [] };\n },\n close: () => {},\n }),\n },\n env: {\n get: (key: string) => envVars.get(key),\n set: (key: string, value: string) => envVars.set(key, value),\n toObject: () => Object.fromEntries(envVars),\n },\n server: {\n upgradeWebSocket: (_request) => {\n throw new Error(\n \"WebSocket upgrade not available in mock adapter. \" +\n \"The mock adapter is designed for unit testing filesystem and environment operations. \" +\n \"For WebSocket testing, use integration tests with the actual Deno/Node/Bun adapter, \" +\n \"or mock the WebSocket behavior at a higher level in your tests.\",\n );\n },\n },\n features: {\n websocket: false,\n http2: false,\n workers: false,\n jsx: false,\n typescript: false,\n },\n };\n}\n", "/**\n * Adapter Registry - Singleton management for RuntimeAdapter\n *\n * Provides a centralized way to access and configure the runtime adapter.\n * Supports auto-detection, manual configuration, and testing overrides.\n *\n * @example\n * ```ts\n * // Auto-detect and get adapter\n * const adapter = await runtime.get();\n *\n * // Manual configuration (e.g., Cloudflare Workers)\n * await runtime.set(createCloudflareAdapter(env));\n *\n * // Testing override\n * await runtime.set(createMockAdapter());\n * ```\n */\n\nimport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\n\ntype AdapterLoader = () => Promise<RuntimeAdapter>;\n\n/**\n * Registry for managing RuntimeAdapter singleton\n */\nclass AdapterRegistry {\n private instance: RuntimeAdapter | null = null;\n private initialized = false;\n private loaders: Map<RuntimeId, AdapterLoader> = new Map();\n\n constructor() {\n // Register default loaders (lazy imports to avoid bundling unused adapters)\n this.loaders.set(\"deno\", async () => {\n const { denoAdapter } = await import(\"./deno.ts\");\n return denoAdapter;\n });\n\n this.loaders.set(\"node\", async () => {\n const { nodeAdapter } = await import(\"./node.ts\");\n return nodeAdapter;\n });\n\n this.loaders.set(\"bun\", async () => {\n const { bunAdapter } = await import(\"./bun.ts\");\n return bunAdapter;\n });\n\n // Note: Cloudflare requires manual initialization with env context\n // this.loaders.set(\"cloudflare\", ...) - not auto-detectable\n\n this.loaders.set(\"memory\", async () => {\n const { createMockAdapter } = await import(\"./mock.ts\");\n return createMockAdapter();\n });\n }\n\n /**\n * Get the current adapter, auto-detecting if needed\n */\n async get(): Promise<RuntimeAdapter> {\n if (this.instance) {\n return this.instance;\n }\n\n // Auto-detect runtime\n const runtimeId = this.detectRuntime();\n const loader = this.loaders.get(runtimeId);\n\n if (!loader) {\n throw new Error(\n `Unsupported runtime: ${runtimeId}. ` +\n `Supported runtimes: ${[...this.loaders.keys()].join(\", \")}. ` +\n `For Cloudflare Workers, use runtime.set(createCloudflareAdapter(env)).`,\n );\n }\n\n this.instance = await loader();\n await this.initialize();\n return this.instance;\n }\n\n /**\n * Manually set the adapter (for Cloudflare Workers, testing, etc.)\n */\n async set(adapter: RuntimeAdapter): Promise<void> {\n // Shutdown existing adapter if any\n if (this.instance && this.initialized) {\n await this.instance.shutdown?.();\n }\n\n this.instance = adapter;\n this.initialized = false;\n await this.initialize();\n }\n\n /**\n * Get adapter synchronously (throws if not initialized)\n */\n getSync(): RuntimeAdapter {\n if (!this.instance) {\n throw new Error(\n \"RuntimeAdapter not initialized. Call `await runtime.get()` first, \" +\n \"or use `await runtime.set(adapter)` to configure manually.\",\n );\n }\n return this.instance;\n }\n\n /**\n * Check if adapter is initialized\n */\n isInitialized(): boolean {\n return this.instance !== null && this.initialized;\n }\n\n /**\n * Reset the registry (for testing)\n */\n async reset(): Promise<void> {\n if (this.instance && this.initialized) {\n await this.instance.shutdown?.();\n }\n this.instance = null;\n this.initialized = false;\n }\n\n /**\n * Register a custom adapter loader\n */\n registerLoader(id: RuntimeId, loader: AdapterLoader): void {\n this.loaders.set(id, loader);\n }\n\n /**\n * Detect current runtime\n */\n private detectRuntime(): RuntimeId {\n // Deno\n if (typeof Deno !== \"undefined\" && typeof Deno.version === \"object\") {\n return \"deno\";\n }\n\n // Bun\n if (\"Bun\" in globalThis) {\n return \"bun\";\n }\n\n // Node.js\n if (typeof process !== \"undefined\" && process.versions?.node) {\n return \"node\";\n }\n\n // Cloudflare Workers (detected but requires manual init)\n if (\"caches\" in globalThis && \"WebSocketPair\" in globalThis) {\n throw new Error(\n \"Cloudflare Workers detected but requires manual initialization. \" +\n \"Use: await runtime.set(createCloudflareAdapter(env))\",\n );\n }\n\n throw new Error(\n \"Unsupported runtime detected. Supported runtimes: deno, node, bun. \" +\n \"For Cloudflare Workers, call runtime.set(createCloudflareAdapter(env)).\",\n );\n }\n\n /**\n * Initialize the adapter\n */\n private async initialize(): Promise<void> {\n if (!this.instance || this.initialized) {\n return;\n }\n\n await this.instance.initialize?.();\n this.initialized = true;\n }\n}\n\n/**\n * Global runtime adapter registry\n *\n * @example\n * ```ts\n * import { runtime } from \"@veryfront/platform/adapters/registry.ts\";\n *\n * // Get adapter (auto-detects runtime)\n * const adapter = await runtime.get();\n *\n * // Use filesystem\n * const content = await adapter.fs.readFile(\"./config.json\");\n * ```\n */\nexport const runtime = new AdapterRegistry();\n\n// Re-export for convenience\nexport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\n", "import { logger } from \"@veryfront/utils\";\nimport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n// Re-export the registry for convenient access\nexport { runtime } from \"./registry.ts\";\n\ninterface DenoGlobal {\n Deno: {\n version: { deno: string };\n [key: string]: unknown;\n };\n}\n\ninterface BunGlobal {\n Bun: {\n version: string;\n [key: string]: unknown;\n };\n}\n\ninterface CloudflareGlobal {\n caches: unknown;\n WebSocketPair: unknown;\n}\n\nfunction isDeno(global: typeof globalThis): global is typeof globalThis & DenoGlobal {\n return \"Deno\" in global && typeof (global as DenoGlobal).Deno === \"object\";\n}\n\nfunction isBun(global: typeof globalThis): global is typeof globalThis & BunGlobal {\n return \"Bun\" in global && typeof (global as BunGlobal).Bun === \"object\";\n}\n\nfunction isCloudflare(global: typeof globalThis): global is typeof globalThis & CloudflareGlobal {\n return \"caches\" in global && \"WebSocketPair\" in global;\n}\n\n/**\n * Detect the current runtime environment\n * @returns Runtime identifier\n */\nexport function detectRuntime(): RuntimeId | \"unknown\" {\n if (isDeno(globalThis)) {\n return \"deno\";\n }\n\n if (isBun(globalThis)) {\n return \"bun\";\n }\n\n const globalProcess = (globalThis as { process?: { versions?: { node?: string } } }).process;\n if (globalProcess?.versions?.node) {\n return \"node\";\n }\n\n if (isCloudflare(globalThis)) {\n return \"cloudflare\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Get the runtime adapter for the current environment\n *\n * @deprecated Use `runtime.get()` from `./registry.ts` instead for singleton management\n *\n * @example\n * ```ts\n * // Old way (deprecated)\n * const adapter = await getAdapter();\n *\n * // New way (recommended)\n * import { runtime } from \"@veryfront/platform/adapters/registry.ts\";\n * const adapter = await runtime.get();\n * ```\n */\nexport async function getAdapter(): Promise<RuntimeAdapter> {\n const runtimeId = detectRuntime();\n\n switch (runtimeId) {\n case \"deno\": {\n const { denoAdapter } = await import(\"./deno.ts\");\n return denoAdapter;\n }\n\n case \"bun\": {\n const { bunAdapter } = await import(\"./bun.ts\");\n return bunAdapter;\n }\n\n case \"node\": {\n const { nodeAdapter } = await import(\"./node.ts\");\n return nodeAdapter;\n }\n\n case \"cloudflare\": {\n const errorMsg = \"Cloudflare adapter requires manual initialization with environment. \" +\n \"Please use createCloudflareAdapter() with your environment context.\";\n logger.error(\"[Adapter Detection]\", errorMsg);\n throw toError(createError({\n type: \"config\",\n message: errorMsg,\n }));\n }\n\n default: {\n const supportedRuntimes = [\"deno\", \"bun\", \"node\", \"cloudflare\"];\n const errorMsg = `Unsupported runtime: ${runtimeId}. Supported runtimes: ${\n supportedRuntimes.join(\", \")\n }`;\n logger.error(\"[Adapter Detection]\", errorMsg);\n throw toError(createError({\n type: \"config\",\n message: errorMsg,\n }));\n }\n }\n}\n\nexport { denoAdapter } from \"./deno.ts\";\nexport { nodeAdapter } from \"./node.ts\";\nexport { bunAdapter } from \"./bun.ts\";\n\nexport type {\n EnvironmentAdapter,\n FileSystemAdapter,\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n RuntimeId,\n} from \"./base.ts\";\n", "export { AppWrapper } from \"./AppWrapper.tsx\";\nexport type { AppWrapperProps } from \"./AppWrapper.tsx\";\n\nexport { Head } from \"./Head.tsx\";\n\nexport { LayoutComponent } from \"./LayoutComponent.tsx\";\nexport type { LayoutComponentProps } from \"./LayoutComponent.tsx\";\n\nexport { Link } from \"./Link.tsx\";\nexport type { LinkProps } from \"./Link.tsx\";\n\nexport { MDXProvider, useMDXComponents } from \"./MDXProvider.tsx\";\nexport type { MDXProviderProps } from \"./MDXProvider.tsx\";\n\nexport { ProviderComponent } from \"./ProviderComponent.tsx\";\nexport type { ProviderComponentProps } from \"./ProviderComponent.tsx\";\n\nexport * from \"./optimized-image/index.ts\";\n", "import type * as React from \"react\";\nimport type { MDXComponents, PageContext as TypedPageContext } from \"@veryfront/types\";\nimport type { MdxBundle } from \"./LayoutComponent.tsx\";\nimport { LayoutComponent } from \"./LayoutComponent.tsx\";\nimport { ProviderComponent } from \"./ProviderComponent.tsx\";\n\nexport interface AppWrapperProps {\n children: React.ReactNode;\n providers?: MdxBundle[];\n layout?: MdxBundle;\n components?: MDXComponents;\n mode?: string;\n studioEnabled?: boolean;\n pageContext?: TypedPageContext;\n}\n\nexport function AppWrapper({\n children,\n providers = [],\n layout,\n components = {},\n mode: _mode,\n studioEnabled: _studioEnabled,\n pageContext,\n}: AppWrapperProps) {\n let content = children;\n\n if (layout) {\n content = (\n <LayoutComponent mdxBundle={layout} components={components} pageContext={pageContext}>\n {content}\n </LayoutComponent>\n );\n }\n\n for (const provider of [...providers].reverse()) {\n content = (\n <ProviderComponent mdxBundle={provider} components={components}>\n {content}\n </ProviderComponent>\n );\n }\n\n return content;\n}\n", "import type React from \"react\";\nimport { useMemo, useRef } from \"react\";\nimport { mdxRenderer } from \"@veryfront/transforms/mdx/index.ts\";\nimport type { MdxBundle, MDXComponents, PageContext as TypedPageContext } from \"@veryfront/types\";\nimport { rendererLogger as logger } from \"@veryfront/utils\";\n\nexport type { MdxBundle } from \"@veryfront/types\";\n\nexport interface LayoutComponentProps {\n mdxBundle: MdxBundle;\n children: React.ReactNode;\n components?: MDXComponents;\n pageContext?: TypedPageContext;\n}\n\nfunction useStableObject<T>(obj: T): T {\n const ref = useRef(obj);\n const serialized = JSON.stringify(obj);\n const prevSerialized = useRef(serialized);\n\n if (prevSerialized.current !== serialized) {\n ref.current = obj;\n prevSerialized.current = serialized;\n }\n\n return ref.current;\n}\n\nexport function LayoutComponent({\n mdxBundle,\n children,\n components = {},\n pageContext,\n}: LayoutComponentProps) {\n const stableFrontmatter = useStableObject(mdxBundle.frontmatter);\n const stablePageContext = useStableObject(pageContext);\n\n const element = useMemo(() => {\n try {\n return mdxRenderer.render(mdxBundle.compiledCode, {\n components,\n frontmatter: { ...(stableFrontmatter || {}), pageContext: stablePageContext },\n globals: mdxBundle.globals,\n extractLayout: true,\n children,\n });\n } catch (error) {\n logger.error(\"[LayoutComponent] Render failed:\", error);\n return <>{children}</>;\n }\n }, [\n mdxBundle.compiledCode,\n stableFrontmatter,\n components,\n children,\n stablePageContext,\n mdxBundle.globals,\n ]);\n\n if (!element) return <>{children}</>;\n return element as React.ReactElement;\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { LRUCache } from \"@veryfront/utils/lru-wrapper.ts\";\nimport React from \"react\";\nimport { MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS } from \"@veryfront/utils/constants/cache.ts\";\nimport { type ESMLoaderContext, loadModuleESM } from \"./esm-module-loader.ts\";\nimport {\n executeModule as _executeModule,\n selectComponent as _selectComponent,\n} from \"./module-executor.ts\";\nimport { type ParsedMDX, parseMDXCode } from \"./parser.ts\";\nimport type { MDXComponents, MDXFrontmatter, MDXGlobals, MDXModule } from \"./types.ts\";\n\nexport interface MDXRenderOptions {\n components?: MDXComponents;\n frontmatter?: MDXFrontmatter;\n globals?: MDXGlobals;\n extractLayout?: boolean;\n children?: React.ReactNode;\n}\n\nexport class MDXRenderer {\n private esmCacheDir?: string;\n private moduleCache: LRUCache<string, MDXModule> = new LRUCache({\n maxEntries: MDX_RENDERER_MAX_ENTRIES,\n ttlMs: MDX_RENDERER_TTL_MS,\n });\n\n constructor() {\n }\n\n async clearCache() {\n this.moduleCache.destroy();\n\n if (this.esmCacheDir) {\n try {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n const adapter = await getAdapter();\n await adapter.fs.remove(this.esmCacheDir, { recursive: true });\n } catch (_error) {\n void _error;\n }\n this.esmCacheDir = undefined;\n }\n }\n\n async loadModuleESM(compiledProgramCode: string): Promise<MDXModule> {\n const context: ESMLoaderContext = {\n esmCacheDir: this.esmCacheDir,\n moduleCache: this.moduleCache,\n };\n const result = await loadModuleESM(compiledProgramCode, context);\n this.esmCacheDir = context.esmCacheDir;\n return result;\n }\n\n render(\n _compiledCode: string,\n _options: MDXRenderOptions = {},\n ): React.ReactElement {\n logger.error(\n \"[MDX] Synchronous render() called but string-based factories are disabled for security. \" +\n \"Please use: await mdxRenderer.loadModuleESM(compiledCode) instead.\",\n );\n\n return React.createElement(\n \"div\",\n {\n style: {\n padding: \"1rem\",\n backgroundColor: \"#fff3cd\",\n border: \"1px solid #ffc107\",\n borderRadius: \"0.375rem\",\n color: \"#856404\",\n },\n },\n React.createElement(\"strong\", {}, \"Migration Required: \"),\n \"Synchronous render() is no longer supported for security reasons. \",\n React.createElement(\"br\"),\n \"Please update to: \",\n React.createElement(\"code\", {}, \"await mdxRenderer.loadModuleESM(compiledCode)\"),\n );\n }\n\n private parseMDXCode(compiledCode: string): ParsedMDX {\n return parseMDXCode(compiledCode);\n }\n}\n\nlet _mdxRendererInstance: MDXRenderer | undefined;\n\nfunction getMDXRendererInstance(): MDXRenderer {\n if (!_mdxRendererInstance) {\n _mdxRendererInstance = new MDXRenderer();\n }\n return _mdxRendererInstance;\n}\n\nexport const mdxRenderer = new Proxy({} as MDXRenderer, {\n get(_target, prop) {\n const instance = getMDXRendererInstance();\n const value = instance[prop as keyof MDXRenderer];\n if (typeof value === \"function\") {\n return value.bind(instance);\n }\n return value;\n },\n set(_target, prop, value) {\n const instance = getMDXRendererInstance();\n (instance as any)[prop] = value;\n return true;\n },\n has(_target, prop) {\n const instance = getMDXRendererInstance();\n return prop in instance;\n },\n ownKeys(_target) {\n const instance = getMDXRendererInstance();\n return Reflect.ownKeys(instance);\n },\n getOwnPropertyDescriptor(_target, prop) {\n const instance = getMDXRendererInstance();\n return Reflect.getOwnPropertyDescriptor(instance, prop);\n },\n});\n\nexport async function clearMDXRendererCache() {\n await getMDXRendererInstance().clearCache();\n}\n\nexport {\n MDXCacheAdapter,\n type MDXCacheAdapterOptions,\n type MDXCompilationResult,\n} from \"./mdx-cache-adapter.ts\";\n", "import { LRUCacheAdapter } from \"./cache/stores/memory/lru-cache-adapter.ts\";\nimport type { LRUCacheOptions } from \"./cache/stores/memory/types.ts\";\nimport { DEFAULT_LRU_MAX_ENTRIES } from \"@veryfront/utils\";\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport interface LRUOptions {\n maxEntries?: number;\n ttlMs?: number;\n cleanupIntervalMs?: number;\n}\n\nexport class LRUCache<K, V> {\n private adapter: LRUCacheAdapter;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n private cleanupIntervalMs: number;\n private ttlMs?: number;\n\n constructor(options: LRUOptions = {}) {\n const adapterOptions: LRUCacheOptions = {\n maxEntries: options.maxEntries ?? DEFAULT_LRU_MAX_ENTRIES,\n ttlMs: options.ttlMs,\n };\n\n this.adapter = new LRUCacheAdapter(adapterOptions);\n this.ttlMs = options.ttlMs;\n this.cleanupIntervalMs = options.cleanupIntervalMs ?? 60000;\n\n if (this.ttlMs && this.ttlMs > 0) {\n this.startPeriodicCleanup();\n }\n }\n\n private startPeriodicCleanup(): void {\n if (shouldDisableInterval()) {\n return;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n const timer = setInterval(() => {\n this.adapter.cleanupExpired();\n }, this.cleanupIntervalMs);\n this.cleanupTimer = timer;\n }\n\n private toStringKey(key: K): string {\n if (typeof key === \"string\") {\n return key;\n }\n return String(key);\n }\n\n get size(): number {\n return this.adapter.getStats().entries;\n }\n\n has(key: K): boolean {\n return this.adapter.get(this.toStringKey(key)) !== undefined;\n }\n\n get(key: K): V | undefined {\n return this.adapter.get<V>(this.toStringKey(key));\n }\n\n set(key: K, value: V): void {\n this.adapter.set(this.toStringKey(key), value);\n }\n\n delete(key: K): boolean {\n const stringKey = this.toStringKey(key);\n const had = this.adapter.get(stringKey) !== undefined;\n this.adapter.delete(stringKey);\n return had;\n }\n\n clear(): void {\n this.adapter.clear();\n }\n\n cleanup(): void {\n this.adapter.cleanupExpired();\n }\n\n destroy(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n\n this.adapter.clear();\n }\n\n keys(): IterableIterator<K> {\n return this.adapter.keys() as IterableIterator<K>;\n }\n}\n\nfunction shouldDisableInterval(): boolean {\n if ((globalThis as Record<string, unknown>).__vfDisableLruInterval === true) {\n return true;\n }\n try {\n return getEnv(\"VF_DISABLE_LRU_INTERVAL\") === \"1\";\n } catch {\n return false;\n }\n}\n", "import type { CacheAdapter, LRUCacheOptions, LRUCacheStats, LRUEntry } from \"./types.ts\";\nimport { LRUNode } from \"./lru-node.ts\";\nimport { LRUListManager } from \"./lru-list-manager.ts\";\nimport { EvictionManager } from \"../../eviction/eviction-manager.ts\";\nimport { EntryManager } from \"./entry-manager.ts\";\n\nfunction defaultSizeEstimator(value: unknown): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"string\") return value.length * 2;\n if (typeof value === \"number\" || typeof value === \"bigint\") return 8;\n if (typeof value === \"boolean\") return 4;\n if (value instanceof Uint8Array || ArrayBuffer.isView(value)) return value.byteLength;\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return value.size;\n\n try {\n return JSON.stringify(value).length * 2;\n } catch {\n return 0;\n }\n}\n\nexport class LRUCacheAdapter implements CacheAdapter {\n private readonly store = new Map<string, LRUNode<unknown>>();\n private readonly tagIndex = new Map<string, Set<string>>();\n private readonly listManager = new LRUListManager<unknown>();\n private readonly evictionManager: EvictionManager<LRUEntry<unknown>>;\n private readonly entryManager: EntryManager;\n private currentSize = 0;\n private readonly maxEntries: number;\n private readonly maxSizeBytes: number;\n private readonly defaultTtlMs?: number;\n private readonly onEvict?: (key: string, value: unknown) => void;\n\n constructor(options: LRUCacheOptions = {}) {\n this.maxEntries = options.maxEntries || 1000;\n this.maxSizeBytes = options.maxSizeBytes || 50 * 1024 * 1024; // 50MB default\n this.defaultTtlMs = options.ttlMs;\n this.onEvict = options.onEvict;\n\n const estimateSizeOf = options.estimateSizeOf || defaultSizeEstimator;\n\n this.evictionManager = new EvictionManager({\n onEvict: this.onEvict,\n loggerContext: \"MemoryCache\",\n });\n this.entryManager = new EntryManager(estimateSizeOf);\n }\n\n get<T>(key: string): T | undefined {\n const node = this.store.get(key);\n if (!node) return undefined;\n\n if (this.evictionManager.isExpired(node.entry)) {\n this.delete(key);\n return undefined;\n }\n\n this.listManager.moveToFront(node);\n return node.entry.value as T;\n }\n\n set<T>(key: string, value: T, ttlMs?: number, tags?: string[]): void {\n const existingNode = this.store.get(key);\n\n if (existingNode) {\n const sizeDelta = this.entryManager.updateExistingEntry(\n existingNode,\n value,\n ttlMs,\n tags,\n this.defaultTtlMs,\n this.listManager,\n this.tagIndex,\n key,\n );\n this.currentSize += sizeDelta;\n } else {\n const [_node, size] = this.entryManager.createNewEntry(\n key,\n value,\n ttlMs,\n tags,\n this.defaultTtlMs,\n this.listManager,\n this.store,\n );\n this.currentSize += size;\n }\n\n if (tags && tags.length > 0) {\n this.entryManager.updateTagIndex(tags, key, this.tagIndex);\n }\n\n this.currentSize = this.evictionManager.enforceMemoryLimits(\n this.listManager,\n this.store,\n this.tagIndex,\n this.currentSize,\n this.maxEntries,\n this.maxSizeBytes,\n );\n }\n\n delete(key: string): void {\n const node = this.store.get(key);\n if (!node) return;\n\n this.listManager.removeNode(node);\n this.store.delete(key);\n this.currentSize -= node.entry.size;\n\n if (node.entry.tags) {\n this.entryManager.cleanupTags(node.entry.tags, key, this.tagIndex);\n }\n\n if (this.onEvict) {\n this.onEvict(key, node.entry.value);\n }\n }\n\n invalidateTag(tag: string): number {\n const set = this.tagIndex.get(tag);\n if (!set) return 0;\n\n let count = 0;\n for (const key of set) {\n this.delete(key);\n count++;\n }\n this.tagIndex.delete(tag);\n return count;\n }\n\n clear(): void {\n if (this.onEvict) {\n for (const [key, node] of this.store) {\n this.onEvict(key, node.entry.value);\n }\n }\n\n this.store.clear();\n this.tagIndex.clear();\n this.listManager.clear();\n this.currentSize = 0;\n }\n\n getStats(): LRUCacheStats {\n return {\n entries: this.store.size,\n sizeBytes: this.currentSize,\n maxEntries: this.maxEntries,\n maxSizeBytes: this.maxSizeBytes,\n tags: this.tagIndex.size,\n };\n }\n\n cleanupExpired(): number {\n const now = Date.now();\n let cleaned = 0;\n\n for (const [key, node] of this.store) {\n if (typeof node.entry.expiry === \"number\" && now > node.entry.expiry) {\n this.delete(key);\n cleaned++;\n }\n }\n\n return cleaned;\n }\n\n keys(): IterableIterator<string> {\n return this.store.keys();\n }\n\n has(key: string): boolean {\n return this.get(key) !== undefined;\n }\n}\n", "import type { LRUNode } from \"./lru-node.ts\";\n\nexport class LRUListManager<T> {\n private head: LRUNode<T> | null = null;\n private tail: LRUNode<T> | null = null;\n\n getHead(): LRUNode<T> | null {\n return this.head;\n }\n\n getTail(): LRUNode<T> | null {\n return this.tail;\n }\n\n moveToFront(node: LRUNode<T>): void {\n if (node === this.head) {\n node.entry.lastAccessed = Date.now();\n return;\n }\n\n this.removeNode(node);\n\n this.addToFront(node);\n }\n\n addToFront(node: LRUNode<T>): void {\n node.next = this.head;\n node.prev = null;\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n if (!this.tail) {\n this.tail = node;\n }\n node.entry.lastAccessed = Date.now();\n }\n\n removeNode(node: LRUNode<T>): void {\n if (node.prev) {\n node.prev.next = node.next;\n }\n if (node.next) {\n node.next.prev = node.prev;\n }\n if (node === this.head) {\n this.head = node.next;\n }\n if (node === this.tail) {\n this.tail = node.prev;\n }\n }\n\n clear(): void {\n this.head = null;\n this.tail = null;\n }\n}\n", "export interface EvictableEntry {\n size: number;\n timestamp?: number;\n expiry?: number;\n value?: unknown;\n tags?: string[];\n}\n\nexport interface LRUTrackerInterface {\n getLRU(): string | undefined;\n remove(key: string): void;\n}\n\nexport interface LRUNodeInterface<T> {\n key: string;\n entry: T;\n prev: LRUNodeInterface<T> | null;\n next: LRUNodeInterface<T> | null;\n}\n\nexport interface LRUListManagerInterface<T> {\n getTail(): LRUNodeInterface<T> | null;\n removeNode(node: LRUNodeInterface<T>): void;\n}\n\nexport interface EvictionManagerOptions {\n onEvict?: (key: string, value: unknown) => void;\n loggerContext?: string;\n}\n\nexport class EvictionManager<TEntry extends EvictableEntry> {\n private readonly onEvict?: (key: string, value: unknown) => void;\n\n constructor(options: EvictionManagerOptions = {}) {\n this.onEvict = options.onEvict;\n }\n\n evictIfNeeded(\n cache: Map<string, TEntry>,\n lruTracker: LRUTrackerInterface,\n newEntrySize: number,\n maxSize: number,\n maxMemory: number,\n ): void {\n while (cache.size >= maxSize) {\n this.evictLRU(cache, lruTracker);\n }\n\n let memoryUsed = Array.from(cache.values()).reduce((sum, entry) => sum + entry.size, 0);\n\n while (memoryUsed + newEntrySize > maxMemory && cache.size > 0) {\n const evictedSize = this.evictLRU(cache, lruTracker);\n memoryUsed -= evictedSize;\n }\n }\n\n evictLRU(cache: Map<string, TEntry>, lruTracker: LRUTrackerInterface): number {\n const keyToEvict = lruTracker.getLRU();\n\n if (!keyToEvict) {\n return 0;\n }\n\n const entry = cache.get(keyToEvict);\n const size = entry?.size || 0;\n const value = entry?.value;\n\n cache.delete(keyToEvict);\n lruTracker.remove(keyToEvict);\n\n if (this.onEvict && entry) {\n this.onEvict(keyToEvict, value);\n }\n\n return size;\n }\n\n evictLRUFromList<T extends TEntry>(\n listManager: LRUListManagerInterface<T>,\n store: Map<string, LRUNodeInterface<T>>,\n tagIndex: Map<string, Set<string>>,\n currentSize: number,\n ): number {\n const tail = listManager.getTail();\n if (!tail) return currentSize;\n\n const node = tail;\n listManager.removeNode(node);\n store.delete(node.key);\n const newSize = currentSize - node.entry.size;\n\n if (node.entry.tags) {\n this.cleanupTags(node.entry.tags, node.key, tagIndex);\n }\n\n if (this.onEvict) {\n this.onEvict(node.key, node.entry.value);\n }\n\n return newSize;\n }\n\n enforceMemoryLimits<T extends TEntry>(\n listManager: LRUListManagerInterface<T>,\n store: Map<string, LRUNodeInterface<T>>,\n tagIndex: Map<string, Set<string>>,\n currentSize: number,\n maxEntries: number,\n maxSizeBytes: number,\n ): number {\n let size = currentSize;\n while ((store.size > maxEntries || size > maxSizeBytes) && listManager.getTail()) {\n size = this.evictLRUFromList(listManager, store, tagIndex, size);\n }\n return size;\n }\n\n private cleanupTags(tags: string[], key: string, tagIndex: Map<string, Set<string>>): void {\n for (const tag of tags) {\n const set = tagIndex.get(tag);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n tagIndex.delete(tag);\n }\n }\n }\n }\n\n evictExpired(cache: Map<string, TEntry>, lruTracker: LRUTrackerInterface, ttl: number): number {\n const now = Date.now();\n let evicted = 0;\n\n for (const [key, entry] of cache.entries()) {\n if (this.isExpired(entry, ttl, now)) {\n cache.delete(key);\n lruTracker.remove(key);\n evicted++;\n }\n }\n\n return evicted;\n }\n\n isExpired(entry: TEntry, ttl?: number, now: number = Date.now()): boolean {\n if (typeof entry.expiry === \"number\") {\n return now > entry.expiry;\n }\n\n if (typeof entry.timestamp === \"number\" && typeof ttl === \"number\") {\n const age = now - entry.timestamp;\n return age > ttl;\n }\n\n return false;\n }\n}\n", "import type { LRUEntry } from \"./types.ts\";\nimport { LRUNode } from \"./lru-node.ts\";\nimport type { LRUListManager } from \"./lru-list-manager.ts\";\n\nexport class EntryManager {\n constructor(\n private readonly estimateSizeOf: (value: unknown) => number,\n ) {}\n\n updateExistingEntry<T>(\n node: LRUNode<unknown>,\n value: T,\n ttlMs: number | undefined,\n tags: string[] | undefined,\n defaultTtlMs: number | undefined,\n listManager: LRUListManager<unknown>,\n tagIndex: Map<string, Set<string>>,\n key: string,\n ): number {\n const oldSize = node.entry.size;\n const newSize = this.estimateSizeOf(value);\n const expiry = this.calculateExpiry(ttlMs, defaultTtlMs);\n\n if (node.entry.tags) {\n this.cleanupTags(node.entry.tags, key, tagIndex);\n }\n\n node.entry = {\n value,\n size: newSize,\n expiry,\n tags,\n lastAccessed: Date.now(),\n };\n\n listManager.moveToFront(node);\n\n return newSize - oldSize;\n }\n\n createNewEntry<T>(\n key: string,\n value: T,\n ttlMs: number | undefined,\n tags: string[] | undefined,\n defaultTtlMs: number | undefined,\n listManager: LRUListManager<unknown>,\n store: Map<string, LRUNode<unknown>>,\n ): [LRUNode<unknown>, number] {\n const size = this.estimateSizeOf(value);\n const expiry = this.calculateExpiry(ttlMs, defaultTtlMs);\n\n const entry: LRUEntry<unknown> = {\n value,\n size,\n expiry,\n tags,\n lastAccessed: Date.now(),\n };\n\n const node = new LRUNode(key, entry);\n store.set(key, node);\n listManager.addToFront(node);\n\n return [node, size];\n }\n\n updateTagIndex(\n tags: string[],\n key: string,\n tagIndex: Map<string, Set<string>>,\n ): void {\n for (const tag of tags) {\n if (!tagIndex.has(tag)) {\n tagIndex.set(tag, new Set());\n }\n tagIndex.get(tag)?.add(key);\n }\n }\n\n cleanupTags(\n tags: string[],\n key: string,\n tagIndex: Map<string, Set<string>>,\n ): void {\n for (const tag of tags) {\n const set = tagIndex.get(tag);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n tagIndex.delete(tag);\n }\n }\n }\n }\n\n private calculateExpiry(\n ttlMs: number | undefined,\n defaultTtlMs: number | undefined,\n ): number | undefined {\n if (typeof ttlMs === \"number\") {\n return Date.now() + ttlMs;\n }\n if (defaultTtlMs) {\n return Date.now() + defaultTtlMs;\n }\n return undefined;\n }\n}\n", "import type { LRUEntry } from \"./types.ts\";\n\nexport class LRUNode<T> {\n constructor(\n public key: string,\n public entry: LRUEntry<T>,\n public prev: LRUNode<T> | null = null,\n public next: LRUNode<T> | null = null,\n ) {}\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { LRUCache } from \"@veryfront/utils/lru-wrapper.ts\";\nimport React from \"react\";\nimport { getCacheNamespace } from \"@veryfront/utils/cache/keys/namespace.ts\";\nimport {\n getDefaultImportMap,\n transformImportsWithMap,\n} from \"@veryfront/modules/import-map/index.ts\";\nimport type { MDXFrontmatter, MDXModule } from \"./types.ts\";\nimport { join } from \"https://deno.land/std@0.220.0/path/mod.ts\";\nimport { isDeno, isNode } from \"../../../platform/compat/runtime.ts\";\nimport { cwd } from \"../../../platform/compat/process.ts\";\n\n// True Node.js runtime (not Deno with Node.js compat)\nconst IS_TRUE_NODE = isNode && !isDeno;\n\n// Constants\nconst LOG_PREFIX_MDX_LOADER = \"[mdx-loader]\";\nconst LOG_PREFIX_MDX_RENDERER = \"[mdx-renderer]\";\nconst JSX_IMPORT_PATTERN = /import\\s+([^'\"]+)\\s+from\\s+['\"]file:\\/\\/([^'\"]+\\.(jsx|tsx))['\"];?/g;\nconst REACT_IMPORT_PATTERN = /import\\s+.*React.*\\s+from\\s+['\"]react['\"]/;\nconst HTTP_IMPORT_PATTERN = /['\"]https?:\\/\\/[^'\"]+['\"]/;\nconst ESBUILD_JSX_FACTORY = \"React.createElement\";\nconst ESBUILD_JSX_FRAGMENT = \"React.Fragment\";\nconst HTTP_MODULE_FETCH_TIMEOUT_MS = 30000;\n\n// Cache for resolved react package paths (Node.js only)\nconst _resolvedPaths: Record<string, string | null> = {};\n\n/**\n * Resolve a Node.js package path using require.resolve\n * Returns null if resolution fails\n */\nasync function resolveNodePackage(packageSpec: string): Promise<string | null> {\n if (!IS_TRUE_NODE) return null;\n if (packageSpec in _resolvedPaths) return _resolvedPaths[packageSpec]!;\n\n try {\n // Use Node.js createRequire to resolve the package from THIS file's location\n // This ensures react is found from veryfront's node_modules, not the project's\n const { createRequire } = await import(\"node:module\");\n const require = createRequire(import.meta.url);\n const resolved = require.resolve(packageSpec);\n _resolvedPaths[packageSpec] = resolved;\n return resolved;\n } catch {\n _resolvedPaths[packageSpec] = null;\n return null;\n }\n}\n\n/**\n * Transform react imports to absolute file:// paths for Node.js.\n * This is needed because MDX modules are cached in arbitrary directories\n * (like temp dirs) where Node.js cannot resolve bare 'react' imports.\n */\nasync function transformReactImportsToAbsolute(code: string): Promise<string> {\n if (!IS_TRUE_NODE) return code;\n\n // Resolve the actual react package paths\n const reactPath = await resolveNodePackage(\"react\");\n const reactJsxPath = await resolveNodePackage(\"react/jsx-runtime\");\n const reactJsxDevPath = await resolveNodePackage(\"react/jsx-dev-runtime\");\n const reactDomPath = await resolveNodePackage(\"react-dom\");\n\n let result = code;\n\n // Replace bare react imports with absolute file:// paths\n if (reactJsxPath) {\n result = result.replace(\n /from\\s+['\"]react\\/jsx-runtime['\"]/g,\n `from \"file://${reactJsxPath}\"`,\n );\n }\n if (reactJsxDevPath) {\n result = result.replace(\n /from\\s+['\"]react\\/jsx-dev-runtime['\"]/g,\n `from \"file://${reactJsxDevPath}\"`,\n );\n }\n if (reactDomPath) {\n result = result.replace(\n /from\\s+['\"]react-dom['\"]/g,\n `from \"file://${reactDomPath}\"`,\n );\n }\n if (reactPath) {\n result = result.replace(\n /from\\s+['\"]react['\"]/g,\n `from \"file://${reactPath}\"`,\n );\n }\n\n return result;\n}\n\nexport interface ESMLoaderContext {\n esmCacheDir?: string;\n moduleCache: LRUCache<string, MDXModule>;\n}\n\nexport function hashString(input: string): string {\n const HASH_SEED_FNV1A = 2166136261;\n let hash = HASH_SEED_FNV1A >>> 0; // FNV-1a\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16);\n}\n\n/**\n * Creates an esbuild plugin to fetch and bundle HTTP/HTTPS imports.\n * This allows Node.js to use remote imports via esbuild bundling.\n */\nfunction createHTTPPluginForMDX(): import(\"esbuild\").Plugin {\n return {\n name: \"vf-mdx-http-fetch\",\n setup(build) {\n // Intercept HTTP/HTTPS imports\n build.onResolve({ filter: /^(http|https):\\/\\// }, (args) => ({\n path: args.path,\n namespace: \"http-url\",\n }));\n\n // Resolve relative imports within HTTP modules\n build.onResolve({ filter: /.*/, namespace: \"http-url\" }, (args) => {\n if (args.path.startsWith(\"http://\") || args.path.startsWith(\"https://\")) {\n return { path: args.path, namespace: \"http-url\" };\n }\n try {\n const resolved = new URL(args.path, args.importer).toString();\n return { path: resolved, namespace: \"http-url\" };\n } catch {\n return undefined;\n }\n });\n\n // Fetch and return HTTP module contents\n build.onLoad({ filter: /.*/, namespace: \"http-url\" }, async (args) => {\n let requestUrl = args.path;\n try {\n const u = new URL(args.path);\n // Optimize esm.sh URLs\n if (u.hostname === \"esm.sh\") {\n if (u.pathname.includes(\"/denonext/\")) {\n u.pathname = u.pathname.replace(\"/denonext/\", \"/\");\n }\n u.searchParams.set(\"target\", \"es2020\");\n u.searchParams.set(\"bundle\", \"true\");\n requestUrl = u.toString();\n }\n } catch {\n // Use original URL if parsing fails\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), HTTP_MODULE_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(requestUrl, {\n headers: { \"user-agent\": \"Mozilla/5.0 Veryfront/1.0\" },\n signal: controller.signal,\n });\n clearTimeout(timeout);\n\n if (!res.ok) {\n return {\n errors: [{ text: `Failed to fetch ${args.path}: ${res.status}` }],\n };\n }\n\n const text = await res.text();\n return { contents: text, loader: \"js\" };\n } catch (e) {\n clearTimeout(timeout);\n return {\n errors: [{\n text: `Failed to fetch ${args.path}: ${e instanceof Error ? e.message : String(e)}`,\n }],\n };\n }\n });\n },\n };\n}\n\nexport async function loadModuleESM(\n compiledProgramCode: string,\n context: ESMLoaderContext,\n): Promise<MDXModule> {\n try {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n const adapter = await getAdapter();\n\n if (!context.esmCacheDir) {\n if (IS_TRUE_NODE) {\n // On Node.js, use a cache dir inside the project so module resolution works\n // Node.js resolves bare imports relative to the file location\n const projectCacheDir = join(\n cwd(),\n \"node_modules\",\n \".cache\",\n \"veryfront-mdx\",\n );\n await adapter.fs.mkdir(projectCacheDir, { recursive: true });\n context.esmCacheDir = projectCacheDir;\n } else {\n // On Deno, system temp dir is fine\n context.esmCacheDir = await adapter.fs.makeTempDir(\"veryfront-mdx-esm-\");\n }\n }\n\n // Transform imports with import map\n let rewritten: string;\n if (IS_TRUE_NODE) {\n // On Node.js, transform react imports to absolute file:// paths\n // This is needed because MDX modules are cached in temp directories\n // where Node.js cannot resolve bare imports\n rewritten = await transformReactImportsToAbsolute(compiledProgramCode);\n } else {\n // On Deno/browser, transform to esm.sh URLs\n rewritten = transformImportsWithMap(\n compiledProgramCode,\n getDefaultImportMap(),\n undefined,\n { resolveBare: true },\n );\n }\n\n // Transform JSX/TSX imports using esbuild\n // This handles user components that use JSX syntax\n let jsxMatch;\n const jsxTransforms: Array<{ original: string; transformed: string }> = [];\n\n // Import esbuild once outside the loop for better performance\n const { transform } = await import(\"esbuild/mod.js\");\n\n while ((jsxMatch = JSX_IMPORT_PATTERN.exec(rewritten)) !== null) {\n const [fullMatch, importClause, filePath, ext] = jsxMatch;\n\n if (!filePath) {\n logger.warn(`${LOG_PREFIX_MDX_LOADER} Skipping JSX import with undefined file path`, {\n fullMatch,\n });\n continue;\n }\n\n try {\n // Read the JSX file (filePath already includes full path)\n const jsxCode = await adapter.fs.readFile(filePath);\n\n // Use esbuild to transform JSX to JavaScript\n const result = await transform(jsxCode as string, {\n loader: ext === \"tsx\" ? \"tsx\" : \"jsx\",\n jsx: \"transform\",\n jsxFactory: ESBUILD_JSX_FACTORY,\n jsxFragment: ESBUILD_JSX_FRAGMENT,\n format: \"esm\",\n });\n\n let transformed = result.code;\n\n // Add React import if not present\n if (!REACT_IMPORT_PATTERN.test(transformed)) {\n transformed = `import React from 'react';\\n${transformed}`;\n }\n\n // Write transformed code to temp file\n const transformedFileName = `jsx-${hashString(filePath)}.mjs`;\n const transformedPath = join(context.esmCacheDir!, transformedFileName);\n await adapter.fs.writeFile(transformedPath, transformed);\n\n jsxTransforms.push({\n original: fullMatch,\n transformed: `import ${importClause} from \"file://${transformedPath}\";`,\n });\n\n logger.info(\n `${LOG_PREFIX_MDX_LOADER} Transformed JSX import using esbuild: ${filePath} -> ${transformedPath}`,\n );\n } catch (error) {\n logger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to transform JSX import: ${filePath}`, error);\n // Keep original import if transformation fails\n }\n }\n\n // Apply all JSX transformations\n for (const { original, transformed } of jsxTransforms) {\n rewritten = rewritten.replace(original, transformed);\n }\n\n if (/\\bconst\\s+MDXLayout\\b/.test(rewritten) && !/export\\s+\\{[^}]*MDXLayout/.test(rewritten)) {\n rewritten += \"\\nexport { MDXLayout as __vfLayout };\\n\";\n }\n\n // On Node.js, bundle HTTP imports via esbuild instead of trying to import them directly\n if (IS_TRUE_NODE && HTTP_IMPORT_PATTERN.test(rewritten)) {\n logger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild for Node.js`);\n const { build } = await import(\"esbuild/mod.js\");\n\n // Write temp source file for esbuild to process\n const tempSourcePath = join(context.esmCacheDir!, `temp-${hashString(rewritten)}.mjs`);\n await adapter.fs.writeFile(tempSourcePath, rewritten);\n\n try {\n const result = await build({\n entryPoints: [tempSourcePath],\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2020\",\n write: false,\n plugins: [createHTTPPluginForMDX()],\n // Mark npm packages as external so they're not bundled\n external: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n });\n\n const bundledCode = result.outputFiles?.[0]?.text;\n if (bundledCode) {\n rewritten = bundledCode;\n logger.info(`${LOG_PREFIX_MDX_LOADER} Successfully bundled HTTP imports`);\n }\n } catch (bundleError) {\n logger.warn(\n `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports, falling back to original code`,\n bundleError,\n );\n // Keep original code if bundling fails\n } finally {\n // Clean up temp file (use unlink since rm may not exist on all adapters)\n try {\n // deno-lint-ignore no-explicit-any\n const fsAny = adapter.fs as any;\n if (typeof fsAny.rm === \"function\") {\n await fsAny.rm(tempSourcePath);\n } else if (typeof fsAny.unlink === \"function\") {\n await fsAny.unlink(tempSourcePath);\n }\n // If neither exists, just leave the temp file (it's in a cache dir anyway)\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n\n const codeHash = hashString(rewritten);\n const namespace = getCacheNamespace() || \"default\";\n const compositeKey = `${namespace}:${codeHash}`;\n\n const cached = context.moduleCache.get(compositeKey);\n if (cached) return cached as MDXModule;\n\n const nsDir = join(context.esmCacheDir, namespace);\n try {\n await adapter.fs.mkdir(nsDir, { recursive: true });\n } catch (e) {\n logger.debug(\n `${LOG_PREFIX_MDX_RENDERER} mkdir nsDir failed`,\n e instanceof Error ? e : String(e),\n );\n }\n\n const filePath = join(nsDir, `${codeHash}.mjs`);\n try {\n const stat = await adapter.fs.stat(filePath);\n if (!stat?.isFile) {\n await adapter.fs.writeFile(filePath, rewritten);\n }\n } catch (error) {\n logger.debug(`${LOG_PREFIX_MDX_RENDERER} Writing temporary MDX module file:`, error);\n await adapter.fs.writeFile(filePath, rewritten);\n }\n\n logger.info(`${LOG_PREFIX_MDX_RENDERER} Loading MDX module`, {\n filePath,\n codePreview: rewritten.substring(0, 300),\n });\n const mod = await import(`file://${filePath}?v=${codeHash}`) as Record<string, unknown> & {\n __vfLayout?: React.ComponentType;\n };\n\n const result: MDXModule = {\n ...mod,\n default: mod?.default as React.ComponentType<unknown> | undefined,\n MDXContent: mod?.MDXContent as React.ComponentType<unknown> | undefined,\n frontmatter: mod?.frontmatter as MDXFrontmatter | undefined,\n headings: mod?.headings as Array<{ text: string; level: number }> | undefined,\n title: mod?.title as string | undefined,\n description: mod?.description as string | undefined,\n layout: mod?.layout as string | boolean | React.ComponentType | undefined,\n MDXLayout: (mod?.MDXLayout || mod?.__vfLayout) as React.ComponentType<unknown> | undefined,\n MainLayout: mod?.MainLayout as React.ComponentType<unknown> | undefined,\n };\n context.moduleCache.set(compositeKey, result);\n return result;\n } catch (error) {\n logger.error(`${LOG_PREFIX_MDX_RENDERER} MDX ESM load failed:`, error);\n throw error;\n }\n}\n", "import { serverLogger as logger } from \"../../logger/logger.ts\";\nimport { getEnvironmentVariable } from \"../../logger/env.ts\";\nimport type { GlobalWithVeryFrontCache } from \"@veryfront/types/global-guards.ts\";\n\nlet cacheNamespace: string | undefined =\n (globalThis as GlobalWithVeryFrontCache).__VF_CACHE_NAMESPACE__ ||\n getEnvironmentVariable(\"VF_CACHE_NAMESPACE\");\n\nexport function setCacheNamespace(namespace?: string): void {\n cacheNamespace = namespace || undefined;\n try {\n (globalThis as GlobalWithVeryFrontCache).__VF_CACHE_NAMESPACE__ = cacheNamespace;\n } catch (e) {\n logger.debug(\"[cache] setCacheNamespace failed\", e);\n }\n}\n\nexport function getCacheNamespace(): string | undefined {\n return cacheNamespace;\n}\n", "export { loadImportMap } from \"./loader.ts\";\nexport { getDefaultImportMap } from \"./default-import-map.ts\";\nexport { resolveImport } from \"./resolver.ts\";\nexport { transformImportsWithMap } from \"./transformer.ts\";\nexport { mergeImportMaps } from \"./merger.ts\";\n\nexport type { ImportMapConfig, TransformOptions } from \"./types.ts\";\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { dirname, join } from \"std/path/mod.ts\";\nimport type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport { getConfig } from \"@veryfront/config\";\nimport type { ImportMapConfig } from \"./types.ts\";\nimport { getDefaultImportMap } from \"./default-import-map.ts\";\n\nexport async function loadImportMap(\n startPath: string,\n adapter?: RuntimeAdapter,\n): Promise<ImportMapConfig> {\n let runtimeAdapter = adapter;\n if (!runtimeAdapter) {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n runtimeAdapter = await getAdapter();\n }\n\n try {\n const cfg = await getConfig(startPath, runtimeAdapter!);\n if (cfg?.resolve?.importMap && typeof cfg.resolve.importMap === \"object\") {\n return {\n imports: cfg.resolve.importMap.imports ?? {},\n scopes: cfg.resolve.importMap.scopes ?? {},\n };\n }\n } catch {\n // Config not found or invalid, fall through to file-based discovery\n }\n\n let currentPath = startPath;\n\n while (currentPath !== \"/\" && currentPath !== \"\") {\n const denoJsonPath = join(currentPath, \"deno.json\");\n\n try {\n const content = await runtimeAdapter!.fs.readFile(denoJsonPath);\n const config = JSON.parse(content);\n\n if (config.imports || config.scopes) {\n logger.debug(`Loaded import map from ${denoJsonPath}`);\n return {\n imports: config.imports ?? {},\n scopes: config.scopes ?? {},\n };\n }\n } catch {\n // deno.json not found in this directory, continue searching\n }\n\n const parent = dirname(currentPath);\n if (parent === currentPath) break; // Reached root\n currentPath = parent;\n }\n\n return getDefaultImportMap();\n}\n", "import { getReactImportMap, REACT_DEFAULT_VERSION } from \"@veryfront/utils\";\nimport type { ImportMapConfig } from \"./types.ts\";\n\nexport function getDefaultImportMap(): ImportMapConfig {\n const reactVersion = REACT_DEFAULT_VERSION;\n\n const importMap = getReactImportMap(reactVersion);\n importMap[\"react/\"] = `https://esm.sh/react@${reactVersion}/`;\n\n return { imports: importMap };\n}\n", "import type { ImportMapConfig } from \"./types.ts\";\n\nexport function resolveImport(\n specifier: string,\n importMap: ImportMapConfig,\n scope?: string,\n): string {\n if (scope && importMap.scopes?.[scope]?.[specifier]) {\n return importMap.scopes[scope][specifier];\n }\n\n if (importMap.imports?.[specifier]) {\n return importMap.imports[specifier];\n }\n\n if (\n specifier.endsWith(\".js\") || specifier.endsWith(\".mjs\") ||\n specifier.endsWith(\".cjs\")\n ) {\n const base = specifier.replace(/\\.(m|c)?js$/, \"\");\n if (importMap.imports?.[base]) {\n return importMap.imports[base];\n }\n }\n\n if (importMap.imports) {\n for (const [key, value] of Object.entries(importMap.imports)) {\n if (key.endsWith(\"/\") && specifier.startsWith(key)) {\n return value + specifier.slice(key.length);\n }\n }\n }\n\n return specifier;\n}\n", "import type { ImportMapConfig, TransformOptions } from \"./types.ts\";\nimport { resolveImport } from \"./resolver.ts\";\n\nexport function transformImportsWithMap(\n code: string,\n importMap: ImportMapConfig,\n scope?: string,\n options?: TransformOptions,\n): string {\n let transformedCode = code;\n\n transformedCode = transformedCode.replace(\n /((?:import|export)\\s+(?:[\\w,{}\\s*]+\\s+from\\s+)?|export\\s+(?:\\*|\\{[^}]+\\})\\s+from\\s+)[\"']([^\"']+)[\"']/g,\n (_match, prefix, specifier) => {\n const isBare = !specifier.startsWith(\"http\") &&\n !specifier.startsWith(\"/\") &&\n !specifier.startsWith(\".\");\n if (isBare && !options?.resolveBare) {\n return `${prefix}\"${specifier}\"`;\n }\n const resolved = resolveImport(specifier, importMap, scope);\n return `${prefix}\"${resolved}\"`;\n },\n );\n\n transformedCode = transformedCode.replace(\n /from\\s+[\"']([^\"']+)[\"']/g,\n (match, specifier) => {\n const isBare = !specifier.startsWith(\"http\") &&\n !specifier.startsWith(\"/\") &&\n !specifier.startsWith(\".\");\n if (isBare && !options?.resolveBare) {\n return match;\n }\n const resolved = resolveImport(specifier, importMap, scope);\n return `from \"${resolved}\"`;\n },\n );\n\n transformedCode = transformedCode.replace(\n /import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g,\n (_match, specifier) => {\n const resolved = resolveImport(specifier, importMap, scope);\n return `import(\"${resolved}\")`;\n },\n );\n\n return transformedCode;\n}\n", "import type { ImportMapConfig } from \"./types.ts\";\n\nexport function mergeImportMaps(...maps: ImportMapConfig[]): ImportMapConfig {\n const merged: ImportMapConfig = {\n imports: {},\n scopes: {},\n };\n\n for (const map of maps) {\n if (map.imports) {\n Object.assign(merged.imports!, map.imports);\n }\n\n if (map.scopes) {\n for (const [scope, imports] of Object.entries(map.scopes)) {\n if (!merged.scopes![scope]) {\n merged.scopes![scope] = {};\n }\n Object.assign(merged.scopes![scope], imports);\n }\n }\n }\n\n return merged;\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport type { MDXExports, MDXImportInfo, ParsedMDX } from \"./types.ts\";\nimport { extractFrontmatter, extractMetadata } from \"./module-loader/metadata-extractor.ts\";\n\nexport type { ParsedMDX };\n\nexport function parseMDXCode(compiledCode: string): ParsedMDX {\n logger.debug(\"Parsing MDX code, first 200 chars:\", compiledCode.substring(0, 200));\n const importRegex = /^\\s*import\\s+(?:{([^}]+)}|(\\w+))\\s+from\\s+['\"]([^'\"]+)['\"]\\s*;?\\s*$/gm;\n const imports = new Map<string, MDXImportInfo>();\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(compiledCode)) !== null) {\n if (match[1]) {\n const names = match[1].split(\",\").map((n: string) => n.trim());\n names.forEach((name: string) => {\n if (match?.[3]) {\n imports.set(name, { name, path: match[3], isDefault: false });\n }\n });\n } else if (match[2]) {\n if (match[2] && match[3]) {\n imports.set(match[2], {\n name: match[2],\n path: match[3],\n isDefault: true,\n });\n }\n }\n }\n\n const cleanedCode = compiledCode\n .replace(importRegex, \"\") // Remove top-level imports\n .replace(/^\\s*export\\s+\\{[\\s\\S]*?\\};?\\s*$/gm, \"\") // Remove named exports (including multi-line)\n .replace(/^\\s*export\\s+default\\s+function/gm, \"function\") // Convert default export function\n .replace(/^\\s*export\\s+default\\s+/gm, \"\") // Remove other default exports\n .replace(/^\\s*export\\s+const\\s+/gm, \"const \") // Convert export const to const\n .replace(/^\\s*export\\s+function\\s+/gm, \"function \") // Convert export function to function\n .replace(/^\\s*const\\s+React\\s*=.*?;?\\s*$/gm, \"\") // Remove React declarations\n .replace(/^\\s*import\\s+React\\s+from.*?;?\\s*$/gm, \"\") // Remove React imports\n .replace(/^\\s*const\\s+(Fragment|Fragment2)\\s*=.*?;?\\s*$/gm, \"\") // Remove Fragment declarations\n .replace(/^\\s*const\\s+(jsx|jsx2)\\s*=.*?;?\\s*$/gm, \"\") // Remove jsx declarations\n .replace(/^\\s*const\\s+(jsxs|jsxs2)\\s*=.*?;?\\s*$/gm, \"\"); // Remove jsxs declarations\n\n if (cleanedCode.includes(\"import React\")) {\n logger.warn(\"Import React still in cleaned code\");\n }\n if (cleanedCode.includes(\"const React\") || cleanedCode.includes(\"var React\")) {\n logger.warn(\"React declaration found in cleaned code\");\n logger.debug(\"Code snippet:\", cleanedCode.substring(0, 200));\n }\n\n const exports: MDXExports = {};\n\n const frontmatter = extractFrontmatter(cleanedCode);\n if (frontmatter) {\n exports.frontmatter = frontmatter;\n }\n\n const metadata = extractMetadata(cleanedCode);\n for (const [key, value] of Object.entries(metadata)) {\n if (value !== undefined) {\n (exports as Record<string, unknown>)[key] = value;\n }\n }\n\n return { code: cleanedCode, imports, exports };\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport type { FrontmatterMetadata, LogContext, MDXModule } from \"./types.ts\";\nimport { extractBalancedBlock, parseJsonish } from \"./string-parser.ts\";\n\nexport function extractFrontmatter(moduleCode: string): FrontmatterMetadata | undefined {\n try {\n const fmIndex = moduleCode.search(/(?:export\\s+)?const\\s+frontmatter\\s*=\\s*/);\n if (fmIndex < 0) return undefined;\n\n const braceStart = moduleCode.indexOf(\"{\", fmIndex);\n if (braceStart < 0) return undefined;\n\n const raw = extractBalancedBlock(moduleCode, braceStart, \"{\", \"}\");\n if (!raw) return undefined;\n\n const jsonish = raw\n .replace(/([^\\s\"{[:,]+)\\s*:/g, '\"$1\":')\n .replace(/'([^']*)'/g, '\"$1\"');\n\n try {\n return JSON.parse(jsonish) as FrontmatterMetadata;\n } catch (e) {\n logger.debug(\"[mdx] frontmatter JSON parse failed\", e as LogContext);\n return undefined;\n }\n } catch (e) {\n logger.debug(\"[mdx] frontmatter extraction failed\", e as LogContext);\n return undefined;\n }\n}\n\ninterface MetadataPattern {\n regex: RegExp;\n key: string;\n}\n\nconst METADATA_PATTERNS: MetadataPattern[] = [\n { regex: /(?:export\\s+)?const\\s+title\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"title\" },\n { regex: /(?:export\\s+)?const\\s+description\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"description\" },\n { regex: /(?:export\\s+)?const\\s+layout\\s*=\\s*(true|false|[\"'][^\"']+[\"'])/, key: \"layout\" },\n { regex: /(?:export\\s+)?const\\s+headings\\s*=\\s*(\\[[\\s\\S]*?\\])/, key: \"headings\" },\n { regex: /(?:export\\s+)?const\\s+nested\\s*=\\s*({[\\s\\S]*?})/, key: \"nested\" },\n { regex: /(?:export\\s+)?const\\s+tags\\s*=\\s*(\\[[\\s\\S]*?\\])/, key: \"tags\" },\n { regex: /(?:export\\s+)?const\\s+date\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"date\" },\n { regex: /(?:export\\s+)?const\\s+draft\\s*=\\s*(true|false)/, key: \"draft\" },\n];\n\nexport function extractMetadata(moduleCode: string): Partial<MDXModule> {\n const exports: Partial<MDXModule> = {};\n\n METADATA_PATTERNS.forEach(({ regex, key }) => {\n const match = moduleCode.match(regex);\n if (!match) return;\n\n const value = match[1] as string;\n\n switch (key) {\n case \"title\":\n case \"description\":\n case \"date\":\n exports[key] = value;\n break;\n\n case \"layout\":\n exports[key] = value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : String(value).replace(/^\"|\"$/g, \"\");\n break;\n\n case \"headings\":\n case \"tags\":\n case \"nested\":\n try {\n exports[key] = parseJsonish(value) as never;\n } catch (e) {\n logger.warn(`Failed to parse ${key}`, e);\n }\n break;\n\n case \"draft\":\n exports[key] = value === \"true\";\n break;\n }\n });\n\n return exports;\n}\n\nexport function mergeFrontmatter(result: MDXModule): void {\n result.frontmatter = result.frontmatter || {};\n\n const keys = [\"title\", \"description\", \"layout\", \"headings\", \"tags\", \"date\", \"draft\", \"nested\"];\n for (const key of keys) {\n if (result[key] !== undefined && result.frontmatter[key] === undefined) {\n result.frontmatter[key] = result[key];\n }\n }\n}\n", "export function extractBalancedBlock(\n source: string,\n startIndex: number,\n open: \"{\" | \"[\" | \"(\",\n close?: \"}\" | \"]\" | \")\",\n): string {\n const closeCh = close || (open === \"{\" ? \"}\" : open === \"[\" ? \"]\" : \")\");\n let depth = 0;\n let i = startIndex;\n\n while (i < source.length) {\n const ch = source[i] as string;\n\n if (ch === '\"' || ch === \"'\") {\n const quote = ch;\n i++;\n while (i < source.length) {\n const q = source[i] as string;\n if (q === \"\\\\\") {\n i += 2;\n continue;\n }\n if (q === quote) {\n i++;\n break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === open) depth++;\n if (ch === closeCh) {\n depth--;\n if (depth === 0) {\n return source.slice(startIndex, i + 1);\n }\n }\n i++;\n }\n\n return \"\";\n}\n\nexport function cleanModuleCode(moduleCode: string): string {\n return moduleCode\n .replace(/import\\s+.*?from\\s+['\"][^'\"]+['\"];?\\s*/gm, \"\")\n .replace(/export\\s+\\{[\\s\\S]*?\\};?$/gm, \"\")\n .replace(/export\\s+default\\s+/gm, \"\")\n .replace(/export\\s+const\\s+/gm, \"const \")\n .replace(/export\\s+function\\s+/gm, \"function \");\n}\n\nexport function parseJsonish(value: string): unknown {\n const jsonish = value\n .replace(/'([^']*)'/g, '\"$1\"')\n .replace(/([{,]\\s*)([A-Za-z_$][\\w$]*)\\s*:/g, '$1\"$2\":');\n return JSON.parse(jsonish);\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { wrapError as _wrapError } from \"@veryfront/errors\";\nimport {\n type BundleCode,\n type BundleMetadata,\n computeCodeHash,\n computeContentHash,\n getBundleManifestStore,\n getBundleManifestTTL,\n} from \"@veryfront/utils\";\nimport type { VeryfrontConfig } from \"@veryfront/config\";\nimport type { MdxBundle } from \"@veryfront/types\";\n\nexport interface MDXCompilationResult extends MdxBundle {\n headings?: Array<{ id: string; text: string; level: number }>;\n nodeMap?: Map<number, unknown>;\n}\n\nexport interface MDXCacheAdapterOptions {\n config: VeryfrontConfig;\n mode: \"development\" | \"production\";\n}\n\nexport class MDXCacheAdapter {\n private config: VeryfrontConfig;\n private mode: \"development\" | \"production\";\n private manifestStore = getBundleManifestStore();\n\n constructor(options: MDXCacheAdapterOptions) {\n this.config = options.config;\n this.mode = options.mode;\n }\n\n private getCacheKey(contentHash: string): string {\n return `mdx:${this.mode}:${contentHash}`;\n }\n\n private getTTL(): number | undefined {\n return getBundleManifestTTL(this.config, this.mode);\n }\n\n async computeHash(content: string): Promise<string> {\n return await computeContentHash(content);\n }\n\n async getCachedBundle(\n content: string,\n frontmatter?: Record<string, unknown>,\n filePath?: string,\n ): Promise<MDXCompilationResult | undefined> {\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n\n const metadata = await this.manifestStore.getBundleMetadata(cacheKey);\n if (!metadata) {\n return undefined;\n }\n\n const bundleCode = await this.manifestStore.getBundleCode(metadata.codeHash);\n if (!bundleCode) {\n logger.debug(\"[mdx-cache] Metadata found but code missing\", {\n filePath,\n codeHash: metadata.codeHash,\n });\n return undefined;\n }\n\n logger.debug(\"[mdx-cache] Cache hit for MDX compilation\", {\n filePath,\n codeHash: metadata.codeHash,\n size: metadata.size,\n });\n\n return {\n compiledCode: bundleCode.code,\n frontmatter: (frontmatter || {}) as Record<string, string | number | boolean | string[]>,\n headings: [],\n nodeMap: new Map(),\n };\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to retrieve cached bundle\", {\n error,\n filePath,\n });\n return undefined;\n }\n }\n\n async setCachedBundle(\n content: string,\n bundle: MDXCompilationResult,\n filePath?: string,\n ): Promise<void> {\n if (!bundle.compiledCode) {\n logger.debug(\"[mdx-cache] No compiled code to cache\", { filePath });\n return;\n }\n\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n\n const bundleCode: BundleCode = {\n code: bundle.compiledCode,\n };\n\n const codeHash = await computeCodeHash(bundleCode);\n\n const encoder = new TextEncoder();\n const size = encoder.encode(bundle.compiledCode).length;\n\n const metadata: BundleMetadata = {\n hash: contentHash,\n codeHash,\n size,\n compiledAt: Date.now(),\n source: filePath || \"unknown\",\n mode: this.mode,\n meta: {\n type: \"mdx\",\n reactVersion: (await import(\"react\")).version,\n },\n };\n\n const ttl = this.getTTL();\n\n await this.manifestStore.setBundleCode(codeHash, bundleCode, ttl);\n await this.manifestStore.setBundleMetadata(cacheKey, metadata, ttl);\n\n logger.debug(\"[mdx-cache] Cached compiled MDX\", {\n filePath,\n cacheKey,\n codeHash,\n size,\n ttl,\n });\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to cache bundle\", {\n error,\n filePath,\n });\n }\n }\n\n async invalidateBundle(content: string): Promise<void> {\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n await this.manifestStore.deleteBundle(cacheKey);\n logger.debug(\"[mdx-cache] Invalidated cached bundle\", { cacheKey });\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to invalidate bundle\", { error });\n }\n }\n\n async invalidateSource(source: string): Promise<number> {\n try {\n const count = await this.manifestStore.invalidateSource(source);\n logger.debug(\"[mdx-cache] Invalidated bundles for source\", {\n source,\n count,\n });\n return count;\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to invalidate source\", {\n error,\n source,\n });\n return 0;\n }\n }\n\n async clearAll(): Promise<void> {\n try {\n await this.manifestStore.clear();\n logger.debug(\"[mdx-cache] Cleared all cached bundles\");\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to clear cache\", { error });\n }\n }\n\n async getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }> {\n try {\n return await this.manifestStore.getStats();\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to get stats\", { error });\n return {\n totalBundles: 0,\n totalSize: 0,\n };\n }\n }\n}\n", "import type * as React from \"react\";\nimport { useMemo, useRef } from \"react\";\nimport { mdxRenderer } from \"@veryfront/transforms/mdx/index.ts\";\nimport type { MDXComponents } from \"@veryfront/types\";\nimport type { MdxBundle } from \"./LayoutComponent.tsx\";\nimport { rendererLogger as logger } from \"@veryfront/utils\";\n\nexport interface ProviderComponentProps {\n mdxBundle: MdxBundle;\n children: React.ReactNode;\n components?: MDXComponents;\n}\n\nfunction useStableFrontmatter(frontmatter: MdxBundle[\"frontmatter\"]): MdxBundle[\"frontmatter\"] {\n const ref = useRef(frontmatter);\n const serialized = JSON.stringify(frontmatter);\n const prevSerialized = useRef(serialized);\n\n if (prevSerialized.current !== serialized) {\n ref.current = frontmatter;\n prevSerialized.current = serialized;\n }\n\n return ref.current;\n}\n\nexport function ProviderComponent({\n mdxBundle,\n children,\n components = {},\n}: ProviderComponentProps) {\n const stableFrontmatter = useStableFrontmatter(mdxBundle.frontmatter);\n\n const element = useMemo(() => {\n try {\n return mdxRenderer.render(mdxBundle.compiledCode, {\n components,\n frontmatter: stableFrontmatter,\n globals: mdxBundle.globals,\n extractLayout: true,\n children,\n });\n } catch (error) {\n logger.error(\"[ProviderComponent] Render failed:\", error);\n return <>{children}</>;\n }\n }, [mdxBundle.compiledCode, stableFrontmatter, components, children, mdxBundle.globals]);\n\n if (!element) return <>{children}</>;\n return element as React.ReactElement;\n}\n", "import React from \"react\";\n\nexport function Head({ children }: { children: React.ReactNode }) {\n return React.createElement(\n \"div\",\n {\n \"data-veryfront-head\": \"1\",\n style: { display: \"none\" },\n },\n children,\n );\n}\n", "import React from \"react\";\n\nexport type LinkProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {\n prefetch?: boolean;\n};\n\nexport function Link({ prefetch = true, children, ...rest }: LinkProps) {\n const props: React.AnchorHTMLAttributes<HTMLAnchorElement> = {\n ...rest,\n ...(prefetch ? { \"data-prefetch\": \"true\" } : {}),\n };\n return <a {...props}>{children}</a>;\n}\n", "import type React from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { MDXComponents } from \"@veryfront/types\";\n\nconst MDXContext = createContext<MDXComponents>({});\n\nexport interface MDXProviderProps {\n components?: MDXComponents;\n children: React.ReactNode;\n}\n\nexport function MDXProvider({\n components = {},\n children,\n}: MDXProviderProps) {\n return <MDXContext.Provider value={components}>{children}</MDXContext.Provider>;\n}\n\nexport function useMDXComponents(components?: MDXComponents): MDXComponents {\n const contextComponents = useContext(MDXContext);\n return { ...contextComponents, ...components };\n}\n", "export { OptimizedImage } from \"./OptimizedImage.tsx\";\nexport type { OptimizedImageProps } from \"./OptimizedImage.tsx\";\nexport { SimpleOptimizedImage } from \"./SimpleOptimizedImage.tsx\";\nexport { OptimizedBackgroundImage } from \"./OptimizedBackgroundImage.tsx\";\nexport { useOptimizedImage } from \"./useOptimizedImage.ts\";\nexport { generateBlurDataURL, getAspectRatioPadding, ResponsiveImageContainer } from \"./utils.tsx\";\n", "import React from \"react\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getExtension, getOptimizedPath } from \"./helpers.ts\";\n\nexport interface OptimizedImageProps {\n src: string;\n alt: string;\n width?: number;\n height?: number;\n sizes?: string;\n formats?: (\"avif\" | \"webp\" | \"jpeg\" | \"png\")[];\n quality?: number;\n loading?: \"lazy\" | \"eager\";\n priority?: boolean;\n className?: string;\n style?: React.CSSProperties;\n placeholder?: \"blur\" | \"empty\";\n blurDataURL?: string;\n onClick?: (event: React.MouseEvent<HTMLImageElement>) => void;\n onLoad?: (event: React.SyntheticEvent<HTMLImageElement>) => void;\n onError?: (event: React.SyntheticEvent<HTMLImageElement>) => void;\n}\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\nconst DEFAULT_FORMATS: (\"avif\" | \"webp\" | \"jpeg\")[] = [\"avif\", \"webp\", \"jpeg\"];\n\nexport function OptimizedImage({\n src,\n alt,\n width,\n height,\n sizes = \"100vw\",\n formats = DEFAULT_FORMATS,\n quality = 80,\n loading,\n priority = false,\n className,\n style,\n placeholder = \"empty\",\n blurDataURL,\n onClick,\n onLoad,\n onError,\n}: OptimizedImageProps) {\n const loadingStrategy = priority ? \"eager\" : loading || \"lazy\";\n\n const originalFormat = getExtension(src);\n\n const imgStyle: React.CSSProperties = {\n ...style,\n ...(placeholder === \"blur\" && blurDataURL\n ? { backgroundImage: `url(${blurDataURL})`, backgroundSize: \"cover\" }\n : {}),\n };\n\n return (\n <picture>\n {formats.map((format) => (\n <source\n key={format}\n type={`image/${format}`}\n srcSet={generateSrcSet(src, format, DEFAULT_SIZES, quality)}\n sizes={sizes}\n />\n ))}\n\n <img\n src={getOptimizedPath(src, originalFormat, width || RESPONSIVE_IMAGE_WIDTH_LG, quality)}\n alt={alt}\n width={width}\n height={height}\n loading={loadingStrategy}\n decoding=\"async\"\n className={className}\n style={imgStyle}\n onClick={onClick}\n onLoad={onLoad}\n onError={onError}\n />\n </picture>\n );\n}\n", "export function getOptimizedPath(\n src: string,\n format: string,\n size: number,\n _quality: number = 80,\n): string {\n const basePath = src.replace(/\\.[^.]+$/, \"\");\n const optimizedDir = \".veryfront/optimized-images\";\n\n return `/${optimizedDir}${basePath}-${size}w.${format}`;\n}\n\nexport function generateSrcSet(\n src: string,\n format: string,\n sizes: number[],\n quality: number,\n): string {\n return sizes\n .map((size) => {\n const path = getOptimizedPath(src, format, size, quality);\n return `${path} ${size}w`;\n })\n .join(\", \");\n}\n\nexport function getExtension(src: string): string {\n const match = src.match(/\\.([^.]+)$/);\n const extension = match?.[1];\n return extension ? extension.toLowerCase() : \"jpeg\";\n}\n", "import React from \"react\";\nimport type { OptimizedImageProps } from \"./OptimizedImage.tsx\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getOptimizedPath } from \"./helpers.ts\";\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\n\nexport function SimpleOptimizedImage({\n src,\n alt,\n width,\n height,\n format = \"webp\",\n quality = 80,\n loading = \"lazy\",\n className,\n style,\n onClick,\n onLoad,\n onError,\n}: Omit<OptimizedImageProps, \"formats\" | \"sizes\" | \"priority\" | \"placeholder\" | \"blurDataURL\"> & {\n format?: \"webp\" | \"avif\" | \"jpeg\" | \"png\";\n}) {\n const srcSet = generateSrcSet(src, format, DEFAULT_SIZES, quality);\n\n return (\n <img\n src={getOptimizedPath(src, format, width || RESPONSIVE_IMAGE_WIDTH_LG, quality)}\n srcSet={srcSet}\n alt={alt}\n width={width}\n height={height}\n loading={loading}\n decoding=\"async\"\n className={className}\n style={style as React.CSSProperties}\n onClick={onClick}\n onLoad={onLoad}\n onError={onError}\n />\n );\n}\n", "import React from \"react\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG } from \"@veryfront/utils/constants/network.ts\";\nimport { getOptimizedPath } from \"./helpers.ts\";\n\nexport function OptimizedBackgroundImage({\n src,\n children,\n format = \"webp\",\n quality = 80,\n size = RESPONSIVE_IMAGE_WIDTH_LG,\n className,\n style,\n}: {\n src: string;\n children?: React.ReactNode;\n format?: \"webp\" | \"avif\" | \"jpeg\" | \"png\";\n quality?: number;\n size?: number;\n className?: string;\n style?: React.CSSProperties;\n}) {\n const optimizedSrc = getOptimizedPath(src, format, size, quality);\n\n const bgStyle: React.CSSProperties = {\n backgroundImage: `url(${optimizedSrc})`,\n backgroundSize: \"cover\",\n backgroundPosition: \"center\",\n backgroundRepeat: \"no-repeat\",\n ...style,\n };\n\n return (\n <div className={className} style={bgStyle}>\n {children}\n </div>\n );\n}\n", "import { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getExtension, getOptimizedPath } from \"./helpers.ts\";\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\nconst DEFAULT_FORMATS: (\"avif\" | \"webp\" | \"jpeg\")[] = [\"avif\", \"webp\", \"jpeg\"];\n\nexport function useOptimizedImage(\n src: string,\n options: {\n formats?: (\"avif\" | \"webp\" | \"jpeg\" | \"png\")[];\n quality?: number;\n } = {},\n) {\n const formats = options.formats || DEFAULT_FORMATS;\n const quality = options.quality || 80;\n\n const sources = formats.map((format) => ({\n format,\n srcSet: generateSrcSet(src, format, DEFAULT_SIZES, quality),\n type: `image/${format}`,\n }));\n\n const fallback = getOptimizedPath(\n src,\n getExtension(src),\n RESPONSIVE_IMAGE_WIDTH_LG,\n quality,\n );\n\n return {\n sources,\n fallback,\n };\n}\n", "import React from \"react\";\n\nexport function generateBlurDataURL(\n width: number = 10,\n height: number = 10,\n color: string = \"#cccccc\",\n): string {\n const svg = `\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${width} ${height}\">\n <rect width=\"${width}\" height=\"${height}\" fill=\"${color}\"/>\n </svg>\n `;\n\n return `data:image/svg+xml;base64,${btoa(svg)}`;\n}\n\nexport function getAspectRatioPadding(width: number, height: number): string {\n return `${(height / width) * 100}%`;\n}\n\nexport function ResponsiveImageContainer({\n width,\n height,\n children,\n className,\n style,\n}: {\n width: number;\n height: number;\n children: React.ReactNode;\n className?: string;\n style?: React.CSSProperties;\n}) {\n const containerStyle = {\n position: \"relative\" as const,\n width: \"100%\",\n paddingBottom: getAspectRatioPadding(width, height),\n ...style,\n };\n\n const contentStyle = {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n } as const;\n\n return (\n <div className={className} style={containerStyle}>\n <div style={contentStyle}>{children}</div>\n </div>\n );\n}\n"],
4
+ "sourcesContent": ["/**\n * Shim for Deno.env in Node.js environment\n * This file is injected by esbuild to provide Deno.env compatibility\n */\n\n// @ts-ignore - Global Deno shim for Node.js\nglobalThis.Deno = globalThis.Deno || {\n env: {\n get(key: string): string | undefined {\n return process.env[key];\n },\n set(key: string, value: string): void {\n process.env[key] = value;\n },\n delete(key: string): void {\n delete process.env[key];\n },\n has(key: string): boolean {\n return key in process.env;\n },\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n },\n },\n};\n", "export interface GlobalWithDeno {\n Deno?: {\n env: {\n get(key: string): string | undefined;\n };\n };\n}\n\nexport interface GlobalWithProcess {\n process?: {\n env: Record<string, string | undefined>;\n version?: string;\n versions?: Record<string, string>;\n };\n}\n\nexport interface GlobalWithBun {\n Bun?: {\n version: string;\n };\n}\n\nexport function hasDenoRuntime(global: unknown): global is GlobalWithDeno {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Deno\" in global &&\n typeof (global as GlobalWithDeno).Deno?.env?.get === \"function\"\n );\n}\n\nexport function hasNodeProcess(global: unknown): global is GlobalWithProcess {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"process\" in global &&\n typeof (global as GlobalWithProcess).process?.env === \"object\"\n );\n}\n\nexport function hasBunRuntime(global: unknown): global is GlobalWithBun {\n return (\n typeof global === \"object\" &&\n global !== null &&\n \"Bun\" in global &&\n typeof (global as GlobalWithBun).Bun !== \"undefined\"\n );\n}\n", "import type { GlobalWithDeno, GlobalWithProcess } from \"../runtime-guards.ts\";\nimport { hasDenoRuntime, hasNodeProcess } from \"../runtime-guards.ts\";\n\nexport function getEnvironmentVariable(name: string): string | undefined {\n try {\n if (typeof Deno !== \"undefined\" && hasDenoRuntime(globalThis)) {\n const value = (globalThis as GlobalWithDeno).Deno?.env.get(name);\n return value === \"\" ? undefined : value;\n }\n if (hasNodeProcess(globalThis)) {\n const value = (globalThis as GlobalWithProcess).process?.env[name];\n return value === \"\" ? undefined : value;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nexport function isTestEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"test\";\n}\n\nexport function isProductionEnvironment(): boolean {\n return getEnvironmentVariable(\"NODE_ENV\") === \"production\";\n}\n\nexport function isDevelopmentEnvironment(): boolean {\n const env = getEnvironmentVariable(\"NODE_ENV\");\n return env === \"development\" || env === undefined;\n}\n", "import { getEnvironmentVariable } from \"./env.ts\";\n\nexport enum LogLevel {\n DEBUG = 0,\n INFO = 1,\n WARN = 2,\n ERROR = 3,\n}\n\nexport interface Logger {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n time<T>(label: string, fn: () => Promise<T>): Promise<T>;\n}\n\nconst originalConsole = {\n debug: console.debug,\n log: console.log,\n warn: console.warn,\n error: console.error,\n};\n\nlet cachedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(force = false): LogLevel {\n if (force || cachedLogLevel === undefined) {\n cachedLogLevel = getDefaultLevel();\n }\n return cachedLogLevel;\n}\n\nclass ConsoleLogger implements Logger {\n constructor(\n private prefix: string,\n private level: LogLevel = resolveLogLevel(),\n ) {}\n\n setLevel(level: LogLevel): void {\n this.level = level;\n }\n\n getLevel(): LogLevel {\n return this.level;\n }\n\n debug(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.DEBUG) {\n console.debug(`[${this.prefix}] DEBUG: ${message}`, ...args);\n }\n }\n\n info(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.INFO) {\n console.log(`[${this.prefix}] ${message}`, ...args);\n }\n }\n\n warn(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.WARN) {\n console.warn(`[${this.prefix}] WARN: ${message}`, ...args);\n }\n }\n\n error(message: string, ...args: unknown[]): void {\n if (this.level <= LogLevel.ERROR) {\n console.error(`[${this.prefix}] ERROR: ${message}`, ...args);\n }\n }\n\n async time<T>(label: string, fn: () => Promise<T>): Promise<T> {\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}\n\nfunction parseLogLevel(levelString: string | undefined): LogLevel | undefined {\n if (!levelString) return undefined;\n const upper = levelString.toUpperCase();\n switch (upper) {\n case \"DEBUG\":\n return LogLevel.DEBUG;\n case \"WARN\":\n return LogLevel.WARN;\n case \"ERROR\":\n return LogLevel.ERROR;\n case \"INFO\":\n return LogLevel.INFO;\n default:\n return undefined;\n }\n}\n\nconst getDefaultLevel = (): LogLevel => {\n const envLevel = getEnvironmentVariable(\"LOG_LEVEL\");\n const parsedLevel = parseLogLevel(envLevel);\n if (parsedLevel !== undefined) return parsedLevel;\n\n const debugFlag = getEnvironmentVariable(\"VERYFRONT_DEBUG\");\n if (debugFlag === \"1\" || debugFlag === \"true\") return LogLevel.DEBUG;\n\n return LogLevel.INFO;\n};\n\nconst trackedLoggers = new Set<ConsoleLogger>();\n\nfunction createLogger(prefix: string): ConsoleLogger {\n const logger = new ConsoleLogger(prefix);\n trackedLoggers.add(logger);\n return logger;\n}\n\nexport const cliLogger = createLogger(\"CLI\");\nexport const serverLogger = createLogger(\"SERVER\");\nexport const rendererLogger = createLogger(\"RENDERER\");\nexport const bundlerLogger = createLogger(\"BUNDLER\");\nexport const agentLogger = createLogger(\"AGENT\");\n\nexport const logger = createLogger(\"VERYFRONT\");\n\ntype LoggerResetOptions = {\n restoreConsole?: boolean;\n};\n\nexport function __loggerResetForTests(options: LoggerResetOptions = {}): void {\n const updatedLevel = resolveLogLevel(true);\n for (const instance of trackedLoggers) {\n instance.setLevel(updatedLevel);\n }\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}\n", "export * from \"./logger.ts\";\nexport * from \"./env.ts\";\n", "export const DEFAULT_BUILD_CONCURRENCY = 4;\n\nexport const IMAGE_OPTIMIZATION = {\n DEFAULT_SIZES: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],\n DEFAULT_QUALITY: 80,\n} as const;\n", "export const SECONDS_PER_MINUTE = 60;\n\nexport const MINUTES_PER_HOUR = 60;\n\nexport const HOURS_PER_DAY = 24;\n\nexport const MS_PER_SECOND = 1000;\n\nexport const DEFAULT_LRU_MAX_ENTRIES = 100;\n\nexport const COMPONENT_LOADER_MAX_ENTRIES = 100;\nexport const COMPONENT_LOADER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const MDX_RENDERER_MAX_ENTRIES = 200;\nexport const MDX_RENDERER_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const RENDERER_CORE_MAX_ENTRIES = 100;\nexport const RENDERER_CORE_TTL_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const TSX_LAYOUT_MAX_ENTRIES = 50;\nexport const TSX_LAYOUT_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const DATA_FETCHING_MAX_ENTRIES = 200;\nexport const DATA_FETCHING_TTL_MS = 10 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const MDX_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE *\n MS_PER_SECOND;\nexport const MDX_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const BUNDLE_CACHE_TTL_PRODUCTION_MS = HOURS_PER_DAY * MINUTES_PER_HOUR *\n SECONDS_PER_MINUTE * MS_PER_SECOND;\nexport const BUNDLE_CACHE_TTL_DEVELOPMENT_MS = 5 * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const BUNDLE_MANIFEST_PROD_TTL_MS = 7 * HOURS_PER_DAY * MINUTES_PER_HOUR *\n SECONDS_PER_MINUTE * MS_PER_SECOND;\nexport const BUNDLE_MANIFEST_DEV_TTL_MS = MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const RSC_MANIFEST_CACHE_TTL_MS = 5000;\n\nexport const SERVER_ACTION_DEFAULT_TTL_SEC = MINUTES_PER_HOUR * SECONDS_PER_MINUTE;\n\nexport const DENO_KV_SAFE_SIZE_LIMIT_BYTES = 64_000;\n\nexport const HTTP_CACHE_SHORT_MAX_AGE_SEC = 60;\nexport const HTTP_CACHE_MEDIUM_MAX_AGE_SEC = 3600;\nexport const HTTP_CACHE_LONG_MAX_AGE_SEC = 31536000;\n\nexport const ONE_DAY_MS = HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE * MS_PER_SECOND;\n\nexport const CACHE_CLEANUP_INTERVAL_MS = 60000;\n\nexport const LRU_DEFAULT_MAX_ENTRIES = 1000;\n\nexport const LRU_DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;\n\nexport const CLEANUP_INTERVAL_MULTIPLIER = 2;\n", "{\n \"name\": \"veryfront\",\n \"version\": \"0.0.70\",\n \"nodeModulesDir\": \"auto\",\n \"exclude\": [\n \"npm/\",\n \"dist/\",\n \"coverage/\",\n \"scripts/\",\n \"examples/\",\n \"src/cli/templates/files/\",\n \"src/cli/templates/integrations/\"\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 \"./platform\": \"./src/platform/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 \"./oauth\": \"./src/core/oauth/index.ts\",\n \"./oauth/providers\": \"./src/core/oauth/providers/index.ts\",\n \"./oauth/handlers\": \"./src/core/oauth/handlers/index.ts\",\n \"./oauth/token-store\": \"./src/core/oauth/token-store/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 \"@veryfront/oauth\": \"./src/core/oauth/index.ts\",\n \"@veryfront/oauth/\": \"./src/core/oauth/\",\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\": \"npm:@mdx-js/mdx@3.0.0\",\n \"@mdx-js/react\": \"npm:@mdx-js/react@3.0.0\",\n \"unist-util-visit\": \"npm:unist-util-visit@5.0.0\",\n \"mdast-util-to-string\": \"npm:mdast-util-to-string@4.0.0\",\n \"github-slugger\": \"npm:github-slugger@2.0.0\",\n \"remark-gfm\": \"npm:remark-gfm@4.0.1\",\n \"remark-frontmatter\": \"npm:remark-frontmatter@5.0.0\",\n \"rehype-highlight\": \"npm:rehype-highlight@7.0.2\",\n \"rehype-slug\": \"npm: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\": \"npm:es-module-lexer@1.5.0\",\n \"zod\": \"npm:zod@3.23.8\",\n \"mime-types\": \"npm:mime-types@2.1.35\",\n \"mdast\": \"npm:@types/mdast@4.0.3\",\n \"hast\": \"npm:@types/hast@3.0.3\",\n \"unist\": \"npm:@types/unist@3.0.2\",\n \"unified\": \"npm:unified@11.0.5\",\n \"ai\": \"https://esm.sh/ai@5.0.76?deps=react@18.3.1,react-dom@18.3.1\",\n \"ai/react\": \"https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1\",\n \"@ai-sdk/react\": \"https://esm.sh/@ai-sdk/react@2.0.1?deps=react@18.3.1,react-dom@18.3.1\",\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.1\",\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 \"redis\": \"npm:redis\",\n \"pg\": \"npm:pg\",\n \"@opentelemetry/api\": \"npm:@opentelemetry/api@1\",\n \"@opentelemetry/core\": \"npm:@opentelemetry/core@1\"\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: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_NO_PACKAGE_JSON=1 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 \"lint:platform\": \"deno run --allow-read scripts/lint-platform-agnostic.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", "export const isDeno = typeof Deno !== \"undefined\";\nexport const isNode =\n typeof (globalThis as { process?: { versions?: { node?: string } } }).process !== \"undefined\" &&\n (globalThis as { process?: { versions?: { node?: string } } }).process?.versions?.node !==\n undefined;\nexport const isBun = typeof (globalThis as { Bun?: unknown }).Bun !== \"undefined\";\nexport const isCloudflare = typeof globalThis !== \"undefined\" && \"caches\" in globalThis &&\n \"WebSocketPair\" in globalThis;\n\n/**\n * Detect if running in Node.js (vs Deno)\n * Use this function instead of the constant when runtime detection needs to happen\n * at call time (e.g., when bundled with esbuild's __esm lazy initialization pattern)\n */\nexport function isNodeRuntime(): boolean {\n // deno-lint-ignore no-explicit-any\n const _global = globalThis as any;\n return typeof Deno === \"undefined\" && typeof _global.process !== \"undefined\" &&\n !!_global.process?.versions?.node;\n}\n", "import { isDeno as IS_DENO } from \"./runtime.ts\";\n\nconst nodeProcess = (globalThis as { process?: typeof import(\"node:process\") }).process;\nconst hasNodeProcess = !!nodeProcess?.versions?.node;\n\nexport function getArgs(): string[] {\n if (IS_DENO) {\n return Deno.args;\n }\n if (hasNodeProcess) {\n return nodeProcess!.argv.slice(2);\n }\n return [];\n}\n\nexport function exit(code?: number): never {\n if (IS_DENO) {\n Deno.exit(code);\n }\n if (hasNodeProcess) {\n nodeProcess!.exit(code);\n }\n throw new Error(\"exit() is not supported in this runtime\");\n}\n\nexport function cwd(): string {\n if (IS_DENO) {\n return Deno.cwd();\n }\n if (hasNodeProcess) {\n return nodeProcess!.cwd();\n }\n throw new Error(\"cwd() is not supported in this runtime\");\n}\n\nexport function chdir(directory: string): void {\n if (IS_DENO) {\n Deno.chdir(directory);\n } else {\n if (hasNodeProcess) {\n nodeProcess!.chdir(directory);\n return;\n }\n throw new Error(\"chdir() is not supported in this runtime\");\n }\n}\n\nexport function env(): Record<string, string> {\n if (IS_DENO) {\n return Deno.env.toObject();\n }\n if (hasNodeProcess) {\n return nodeProcess!.env as Record<string, string>;\n }\n return {};\n}\n\nexport function getEnv(key: string): string | undefined {\n if (IS_DENO) {\n return Deno.env.get(key);\n }\n if (hasNodeProcess) {\n return nodeProcess!.env[key];\n }\n return undefined;\n}\n\n/**\n * Get an environment variable or throw if not set\n * @throws Error if the environment variable is not set\n */\nexport function requireEnv(key: string): string {\n const value = getEnv(key);\n if (value === undefined) {\n throw new Error(`Required environment variable \"${key}\" is not set`);\n }\n return value;\n}\n\nexport function setEnv(key: string, value: string): void {\n if (IS_DENO) {\n Deno.env.set(key, value);\n } else {\n if (hasNodeProcess) {\n nodeProcess!.env[key] = value;\n return;\n }\n throw new Error(\"setEnv() is not supported in this runtime\");\n }\n}\n\nexport function deleteEnv(key: string): void {\n if (IS_DENO) {\n Deno.env.delete(key);\n } else {\n if (hasNodeProcess) {\n delete nodeProcess!.env[key];\n return;\n }\n throw new Error(\"deleteEnv() is not supported in this runtime\");\n }\n}\n\nexport function pid(): number {\n if (IS_DENO) {\n return Deno.pid;\n }\n if (hasNodeProcess) {\n return nodeProcess!.pid;\n }\n return 0;\n}\n\nexport function ppid(): number {\n if (IS_DENO && \"ppid\" in Deno) {\n return Deno.ppid || 0;\n }\n if (hasNodeProcess) {\n return nodeProcess!.ppid || 0;\n }\n return 0;\n}\n\nexport function memoryUsage(): {\n rss: number;\n heapTotal: number;\n heapUsed: number;\n external: number;\n} {\n if (IS_DENO) {\n const usage = Deno.memoryUsage();\n return {\n rss: usage.rss,\n heapTotal: usage.heapTotal,\n heapUsed: usage.heapUsed,\n external: usage.external,\n };\n }\n\n if (!hasNodeProcess) {\n throw new Error(\"memoryUsage() is not supported in this runtime\");\n }\n\n const usage = nodeProcess!.memoryUsage();\n return {\n rss: usage.rss,\n heapTotal: usage.heapTotal,\n heapUsed: usage.heapUsed,\n external: usage.external || 0,\n };\n}\n\n/**\n * Check if stdin is a TTY (terminal)\n */\nexport function isInteractive(): boolean {\n if (IS_DENO) {\n return Deno.stdin.isTerminal();\n }\n if (hasNodeProcess) {\n return nodeProcess!.stdin.isTTY ?? false;\n }\n return false;\n}\n\n/**\n * Get network interfaces\n */\nexport async function getNetworkInterfaces(): Promise<\n Array<{ name: string; address: string; family: \"IPv4\" | \"IPv6\" }>\n> {\n if (IS_DENO) {\n const interfaces = Deno.networkInterfaces();\n return interfaces.map((iface) => ({\n name: iface.name,\n address: iface.address,\n family: iface.family as \"IPv4\" | \"IPv6\",\n }));\n }\n\n if (!hasNodeProcess) {\n throw new Error(\"networkInterfaces() is not supported in this runtime\");\n }\n\n const os = await import(\"node:os\");\n const interfaces = os.networkInterfaces();\n const result: Array<{ name: string; address: string; family: \"IPv4\" | \"IPv6\" }> = [];\n\n for (const [name, addrs] of Object.entries(interfaces)) {\n if (!addrs) continue;\n for (const addr of addrs) {\n result.push({\n name,\n address: addr.address,\n family: addr.family as \"IPv4\" | \"IPv6\",\n });\n }\n }\n\n return result;\n}\n\n/**\n * Get runtime version string\n */\nexport function getRuntimeVersion(): string {\n if (IS_DENO) {\n return `Deno ${Deno.version.deno}`;\n }\n if (\"Bun\" in globalThis) {\n return `Bun ${(globalThis as unknown as { Bun: { version: string } }).Bun.version}`;\n }\n if (hasNodeProcess) {\n return `Node.js ${nodeProcess!.version}`;\n }\n return \"unknown\";\n}\n\n/**\n * Register a signal handler (SIGINT, SIGTERM) for graceful shutdown\n */\nexport function onSignal(signal: \"SIGINT\" | \"SIGTERM\", handler: () => void): void {\n if (IS_DENO) {\n Deno.addSignalListener(signal, handler);\n } else if (hasNodeProcess) {\n nodeProcess!.on(signal, handler);\n }\n}\n\n/**\n * Unreference a timer to prevent it from keeping the process alive\n */\nexport function unrefTimer(timerId: ReturnType<typeof setInterval>): void {\n if (IS_DENO) {\n Deno.unrefTimer(timerId as number);\n } else if (timerId && typeof timerId === \"object\" && \"unref\" in timerId) {\n (timerId as { unref: () => void }).unref();\n }\n}\n\n/**\n * Get the executable path of the current runtime\n */\nexport function execPath(): string {\n if (IS_DENO) {\n return Deno.execPath();\n }\n if (hasNodeProcess) {\n return nodeProcess!.execPath;\n }\n return \"\";\n}\n\n/**\n * Get process uptime in seconds\n * Returns OS uptime on Deno, process uptime on Node.js\n */\nexport function uptime(): number {\n if (IS_DENO) {\n // Deno.osUptime() returns system uptime in seconds\n return Deno.osUptime?.() ?? 0;\n }\n if (hasNodeProcess) {\n // process.uptime() returns process uptime in seconds\n return nodeProcess!.uptime?.() ?? 0;\n }\n return 0;\n}\n\n/**\n * Get stdout stream for writing\n * Returns null if not available (e.g., in browser/workers)\n */\nexport function getStdout(): { write: (data: string) => void } | null {\n if (IS_DENO) {\n const encoder = new TextEncoder();\n return {\n write: (data: string) => {\n Deno.stdout.writeSync(encoder.encode(data));\n },\n };\n }\n if (hasNodeProcess && nodeProcess!.stdout) {\n return {\n write: (data: string) => {\n nodeProcess!.stdout.write(data);\n },\n };\n }\n return null;\n}\n\n// Cached Node.js modules for synchronous prompt\nlet cachedNodeFs: typeof import(\"node:fs\") | null = null;\n\n/**\n * Synchronous prompt function that works across Deno and Node.js\n * Displays a message and reads user input from stdin\n */\nexport function promptSync(message?: string): string | null {\n if (IS_DENO) {\n // Deno has a built-in prompt() function\n return prompt(message);\n }\n\n if (hasNodeProcess) {\n // Print the message\n if (message) {\n nodeProcess!.stdout.write(message + \" \");\n }\n\n // Lazy load fs module\n if (!cachedNodeFs) {\n // Dynamic import converted to sync require for bundling\n // @ts-ignore - dynamic require for Node.js\n cachedNodeFs = globalThis.require?.(\"node:fs\") || null;\n if (!cachedNodeFs) {\n // Try alternative approach\n try {\n // @ts-ignore: __require is injected by bundlers for Node.js require\n cachedNodeFs = __require(\"node:fs\");\n } catch {\n return null;\n }\n }\n }\n\n if (!cachedNodeFs) {\n return null;\n }\n\n // Read synchronously using fs\n // This works by reading from file descriptor 0 (stdin)\n // Use Uint8Array for cross-platform compatibility\n const bufferSize = 1024;\n const uint8Array = new Uint8Array(bufferSize);\n let input = \"\";\n\n try {\n // Read from stdin (fd 0) synchronously\n const bytesRead = cachedNodeFs.readSync(0, uint8Array, 0, bufferSize, null);\n if (bytesRead > 0) {\n const decoder = new TextDecoder(\"utf-8\");\n input = decoder.decode(uint8Array.subarray(0, bytesRead)).trim();\n }\n } catch {\n // If stdin is not available or EOF, return null\n return null;\n }\n\n return input || null;\n }\n\n return null;\n}\n", "import denoConfig from \"../../../deno.json\" with { type: \"json\" };\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport const VERSION: string = getEnv(\"VERYFRONT_VERSION\") ||\n (typeof denoConfig.version === \"string\" ? denoConfig.version : \"0.0.0\");\n", "export const ESM_CDN_BASE = \"https://esm.sh\";\n\nexport const JSDELIVR_CDN_BASE = \"https://cdn.jsdelivr.net\";\n\nexport const DENO_STD_BASE = \"https://deno.land\";\n\nexport const REACT_VERSION_17 = \"17.0.2\";\nexport const REACT_VERSION_18_2 = \"18.2.0\";\nexport const REACT_VERSION_18_3 = \"18.3.1\";\nexport const REACT_VERSION_19_RC = \"19.0.0-rc.0\";\nexport const REACT_VERSION_19 = \"19.1.1\";\n\nexport const REACT_DEFAULT_VERSION = REACT_VERSION_18_3;\n\nexport function getReactCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}`;\n}\n\nexport function getReactDOMCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}`;\n}\n\nexport function getReactDOMClientCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}/client`;\n}\n\nexport function getReactDOMServerCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react-dom@${version}/server`;\n}\n\nexport function getReactJSXRuntimeCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}/jsx-runtime`;\n}\n\nexport function getReactJSXDevRuntimeCDNUrl(version: string = REACT_DEFAULT_VERSION): string {\n return `${ESM_CDN_BASE}/react@${version}/jsx-dev-runtime`;\n}\n\nexport function getReactImportMap(version: string = REACT_DEFAULT_VERSION): Record<string, string> {\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}\n\nexport const DEFAULT_ALLOWED_CDN_HOSTS = [ESM_CDN_BASE, DENO_STD_BASE];\n\nexport const DENO_STD_VERSION = \"0.220.0\";\n\nexport function getDenoStdNodeBase(): string {\n return `${DENO_STD_BASE}/std@${DENO_STD_VERSION}/node`;\n}\n\n// UnoCSS constants\nexport const UNOCSS_VERSION = \"0.59.0\";\n\nexport function getUnoCSSTailwindResetUrl(): string {\n return `${ESM_CDN_BASE}/@unocss/reset@${UNOCSS_VERSION}/tailwind.css`;\n}\n\n// Veryfront package version - derived from deno.json (single source of truth)\nexport { VERSION as VERYFRONT_VERSION } from \"../version.ts\";\n", "/**\n * Environment variable utilities\n *\n * Centralized utilities for checking environment flags.\n * This ensures consistent behavior across the entire codebase.\n */\n\n/**\n * Environment variable names used by Veryfront\n */\nexport const ENV_VARS = {\n DEBUG: \"VERYFRONT_DEBUG\",\n DEEP_INSPECT: \"VERYFRONT_DEEP_INSPECT\",\n CACHE_DIR: \"VERYFRONT_CACHE_DIR\",\n PORT: \"VERYFRONT_PORT\",\n VERSION: \"VERYFRONT_VERSION\",\n} as const;\n\n/**\n * Check if a debug environment variable value is truthy.\n * Accepts: \"1\", \"true\", \"yes\" (case-insensitive)\n *\n * @param value - The environment variable value to check\n * @returns true if the value indicates debug mode should be enabled\n */\nexport function isTruthyEnvValue(value: string | undefined): boolean {\n if (!value) return false;\n const normalized = value.toLowerCase().trim();\n return normalized === \"1\" || normalized === \"true\" || normalized === \"yes\";\n}\n\n/**\n * Check if debug mode is enabled via environment variable.\n * Works with RuntimeAdapter's env interface.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if VERYFRONT_DEBUG is set to a truthy value\n */\nexport function isDebugEnabled(env: { get(key: string): string | undefined }): boolean {\n return isTruthyEnvValue(env.get(ENV_VARS.DEBUG));\n}\n\n/**\n * Check if deep inspect mode is enabled via environment variable.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if VERYFRONT_DEEP_INSPECT is set to a truthy value\n */\nexport function isDeepInspectEnabled(env: { get(key: string): string | undefined }): boolean {\n return isTruthyEnvValue(env.get(ENV_VARS.DEEP_INSPECT));\n}\n\n/**\n * Check if either debug or deep inspect mode is enabled.\n *\n * @param env - Environment accessor object with get() method\n * @returns true if either debug flag is enabled\n */\nexport function isAnyDebugEnabled(env: { get(key: string): string | undefined }): boolean {\n return isDebugEnabled(env) || isDeepInspectEnabled(env);\n}\n", "export const HASH_SEED_DJB2 = 5381;\n\nexport const HASH_SEED_FNV1A = 2166136261;\n", "export const KB_IN_BYTES = 1024;\n\nexport const HTTP_MODULE_FETCH_TIMEOUT_MS = 2500;\n\nexport const HMR_RECONNECT_DELAY_MS = 1000;\n\nexport const HMR_RELOAD_DELAY_MS = 1000;\n\nexport const HMR_FILE_WATCHER_DEBOUNCE_MS = 100;\n\nexport const HMR_KEEP_ALIVE_INTERVAL_MS = 30000;\n\nexport const DASHBOARD_RECONNECT_DELAY_MS = 3000;\n\nexport const SERVER_FUNCTION_DEFAULT_TIMEOUT_MS = 30000;\n\nexport const PREFETCH_MAX_SIZE_BYTES = 200 * KB_IN_BYTES;\n\nexport const PREFETCH_DEFAULT_TIMEOUT_MS = 10000;\n\nexport const PREFETCH_DEFAULT_DELAY_MS = 200;\n\nexport const HTTP_OK = 200;\n\nexport const HTTP_NO_CONTENT = 204;\n\nexport const HTTP_CREATED = 201;\n\nexport const HTTP_REDIRECT_FOUND = 302;\n\nexport const HTTP_NOT_MODIFIED = 304;\n\nexport const HTTP_BAD_REQUEST = 400;\n\nexport const HTTP_UNAUTHORIZED = 401;\n\nexport const HTTP_FORBIDDEN = 403;\n\nexport const HTTP_NOT_FOUND = 404;\n\nexport const HTTP_METHOD_NOT_ALLOWED = 405;\n\nexport const HTTP_GONE = 410;\n\nexport const HTTP_PAYLOAD_TOO_LARGE = 413;\n\nexport const HTTP_URI_TOO_LONG = 414;\n\nexport const HTTP_TOO_MANY_REQUESTS = 429;\n\nexport const HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431;\n\nexport const HTTP_SERVER_ERROR = 500;\n\nexport const HTTP_INTERNAL_SERVER_ERROR = 500;\n\nexport const HTTP_BAD_GATEWAY = 502;\n\nexport const HTTP_NOT_IMPLEMENTED = 501;\n\nexport const HTTP_UNAVAILABLE = 503;\n\nexport const HTTP_NETWORK_CONNECT_TIMEOUT = 599;\n\nexport const HTTP_STATUS_SUCCESS_MIN = 200;\n\nexport const HTTP_STATUS_REDIRECT_MIN = 300;\n\nexport const HTTP_STATUS_CLIENT_ERROR_MIN = 400;\n\nexport const HTTP_STATUS_SERVER_ERROR_MIN = 500;\n\nexport const 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} as const;\n\nimport { MS_PER_SECOND, SECONDS_PER_MINUTE } from \"./cache.ts\";\n\nexport const MS_PER_MINUTE = 60000;\n\nexport { MS_PER_SECOND, SECONDS_PER_MINUTE };\n\nexport const HTTP_CONTENT_TYPE_IMAGE_PNG = \"image/png\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_JPEG = \"image/jpeg\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_WEBP = \"image/webp\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_AVIF = \"image/avif\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_SVG = \"image/svg+xml\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_GIF = \"image/gif\";\n\nexport const HTTP_CONTENT_TYPE_IMAGE_ICO = \"image/x-icon\";\n", "import { KB_IN_BYTES } from \"./http.ts\";\n\nexport const HMR_MAX_MESSAGE_SIZE_BYTES = 1024 * KB_IN_BYTES;\n\nexport const HMR_MAX_MESSAGES_PER_MINUTE = 100;\n\nexport const HMR_CLIENT_RELOAD_DELAY_MS = 3000;\n\nexport const HMR_PORT_OFFSET = 1;\n\nexport const HMR_RATE_LIMIT_WINDOW_MS = 60000;\n\nexport const HMR_CLOSE_NORMAL = 1000;\n\nexport const HMR_CLOSE_RATE_LIMIT = 1008;\n\nexport const HMR_CLOSE_MESSAGE_TOO_LARGE = 1009;\n\nexport const HMR_MESSAGE_TYPES = {\n CONNECTED: \"connected\",\n UPDATE: \"update\",\n RELOAD: \"reload\",\n PING: \"ping\",\n PONG: \"pong\",\n} as const;\n\nexport function isValidHMRMessageType(type: string): type is keyof typeof HMR_MESSAGE_TYPES {\n return Object.values(HMR_MESSAGE_TYPES).includes(\n type as typeof HMR_MESSAGE_TYPES[keyof typeof HMR_MESSAGE_TYPES],\n );\n}\n", "export const Z_INDEX_DEV_INDICATOR = 9998;\nexport const Z_INDEX_ERROR_OVERLAY = 9999;\n\nexport const BREAKPOINT_SM = 640;\nexport const BREAKPOINT_MD = 768;\nexport const BREAKPOINT_LG = 1024;\nexport const BREAKPOINT_XL = 1280;\n\nexport const PROSE_MAX_WIDTH = \"65ch\";\n", "export const DEFAULT_DEV_SERVER_PORT = 3000;\nexport const DEFAULT_REDIS_PORT = 6379;\nexport const DEFAULT_API_SERVER_PORT = 8080;\nexport const DEFAULT_PREVIEW_SERVER_PORT = 5000;\nexport const DEFAULT_METRICS_PORT = 9000;\n\nexport const BYTES_PER_KB = 1024;\nexport const BYTES_PER_MB = 1024 * 1024;\n\nexport const DEFAULT_IMAGE_THUMBNAIL_SIZE = 256;\nexport const DEFAULT_IMAGE_SMALL_SIZE = 512;\nexport const DEFAULT_IMAGE_LARGE_SIZE = 2048;\n\nexport const RESPONSIVE_IMAGE_WIDTH_XS = 320;\nexport const RESPONSIVE_IMAGE_WIDTH_SM = 640;\nexport const RESPONSIVE_IMAGE_WIDTH_MD = 1024;\nexport const RESPONSIVE_IMAGE_WIDTH_LG = 1920;\n\nexport const RESPONSIVE_IMAGE_WIDTHS = [\n RESPONSIVE_IMAGE_WIDTH_XS,\n RESPONSIVE_IMAGE_WIDTH_SM,\n RESPONSIVE_IMAGE_WIDTH_MD,\n RESPONSIVE_IMAGE_WIDTH_LG,\n] as const;\n\nexport const MAX_CHUNK_SIZE_KB = 4096;\n\nexport const MIN_PORT = 1;\n\nexport const MAX_PORT = 65535;\n\nexport const DEFAULT_SERVER_PORT = 8000;\n", "export const MAX_PATH_TRAVERSAL_DEPTH = 10;\n\nexport const FORBIDDEN_PATH_PATTERNS = [\n /\\0/, // Null bytes\n];\n\nexport const DIRECTORY_TRAVERSAL_PATTERN = /\\.\\.[\\/\\\\]/;\n\nexport const ABSOLUTE_PATH_PATTERN = /^[\\/\\\\]/;\n\nexport const MAX_PATH_LENGTH = 4096;\n\nexport const DEFAULT_MAX_STRING_LENGTH = 1000;\n", "/**\n * Default port for veryfront dev server.\n * This is the single source of truth for the default port.\n */\nexport const DEFAULT_PORT = 3000;\n\nexport const DEFAULT_TIMEOUT_MS = 5000;\n\nexport const SSR_TIMEOUT_MS = 10000;\n\nexport const SANDBOX_TIMEOUT_MS = 5000;\n\nexport const DEFAULT_CACHE_MAX_SIZE = 100;\n\nexport const defaultConfig = {\n server: {\n port: DEFAULT_PORT,\n hostname: \"0.0.0.0\",\n },\n\n timeouts: {\n default: DEFAULT_TIMEOUT_MS,\n api: 30000,\n ssr: SSR_TIMEOUT_MS,\n hmr: 30000,\n sandbox: SANDBOX_TIMEOUT_MS,\n },\n\n cache: {\n jit: {\n maxSize: DEFAULT_CACHE_MAX_SIZE,\n tempDirPrefix: \"vf-bundle-\",\n },\n },\n\n metrics: {\n ssrBoundaries: [5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000],\n },\n} as const;\n\nexport const DEFAULT_PREFETCH_DELAY_MS = 100;\n\nexport const DEFAULT_METRICS_COLLECT_INTERVAL_MS = 60000;\n\nexport const DURATION_HISTOGRAM_BOUNDARIES_MS = [\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000,\n];\n\nexport const SIZE_HISTOGRAM_BOUNDARIES_KB = [\n 1,\n 5,\n 10,\n 25,\n 50,\n 100,\n 250,\n 500,\n 1000,\n 2500,\n 5000,\n 10000,\n];\n\nexport const DEFAULT_REDIS_SCAN_COUNT = 100;\n\nexport const DEFAULT_REDIS_BATCH_DELETE_SIZE = 1000;\n\nexport const PAGE_TRANSITION_DELAY_MS = 150;\n\nexport type DefaultConfig = typeof defaultConfig;\n", "/**\n * Centralized server endpoints and paths registry\n *\n * All internal veryfront URLs should be defined here as the single source of truth.\n * This prevents hardcoding URLs across the codebase and makes refactoring easier.\n */\n\n// Re-export DEFAULT_PORT from config/defaults.ts (the single source of truth)\nexport { DEFAULT_PORT } from \"@veryfront/config/defaults.ts\";\n\n/** Default port for development dashboard */\nexport const DEFAULT_DASHBOARD_PORT = 3002;\n\n/** Internal URL prefix for all veryfront endpoints */\nexport const INTERNAL_PREFIX = \"/_veryfront\" as const;\n\n/**\n * All internal veryfront URL path prefixes (directories)\n */\nexport const INTERNAL_PATH_PREFIXES = {\n /** React Server Components endpoints */\n RSC: `${INTERNAL_PREFIX}/rsc/`,\n /** File system access endpoints (base64 encoded paths) */\n FS: `${INTERNAL_PREFIX}/fs/`,\n /** Virtual module system */\n MODULES: `${INTERNAL_PREFIX}/modules/`,\n /** Generated page modules */\n PAGES: `${INTERNAL_PREFIX}/pages/`,\n /** Data JSON endpoints */\n DATA: `${INTERNAL_PREFIX}/data/`,\n /** Library modules (AI SDK, etc.) */\n LIB: `${INTERNAL_PREFIX}/lib/`,\n /** Chunk assets */\n CHUNKS: `${INTERNAL_PREFIX}/chunks/`,\n /** Client component modules */\n CLIENT: `${INTERNAL_PREFIX}/client/`,\n} as const;\n\n/**\n * Specific internal endpoint URLs\n */\nexport const INTERNAL_ENDPOINTS = {\n // Development endpoints\n HMR_RUNTIME: `${INTERNAL_PREFIX}/hmr-runtime.js`,\n HMR: `${INTERNAL_PREFIX}/hmr.js`,\n HYDRATE: `${INTERNAL_PREFIX}/hydrate.js`,\n ERROR_OVERLAY: `${INTERNAL_PREFIX}/error-overlay.js`,\n DEV_LOADER: `${INTERNAL_PREFIX}/dev-loader.js`,\n CLIENT_LOG: `${INTERNAL_PREFIX}/log`,\n\n // Production endpoints\n CLIENT_JS: `${INTERNAL_PREFIX}/client.js`,\n ROUTER_JS: `${INTERNAL_PREFIX}/router.js`,\n PREFETCH_JS: `${INTERNAL_PREFIX}/prefetch.js`,\n MANIFEST_JSON: `${INTERNAL_PREFIX}/manifest.json`,\n APP_JS: `${INTERNAL_PREFIX}/app.js`,\n\n // RSC endpoints\n RSC_CLIENT: `${INTERNAL_PREFIX}/rsc/client.js`,\n RSC_MANIFEST: `${INTERNAL_PREFIX}/rsc/manifest`,\n RSC_STREAM: `${INTERNAL_PREFIX}/rsc/stream`,\n RSC_PAYLOAD: `${INTERNAL_PREFIX}/rsc/payload`,\n RSC_RENDER: `${INTERNAL_PREFIX}/rsc/render`,\n RSC_PAGE: `${INTERNAL_PREFIX}/rsc/page`,\n RSC_MODULE: `${INTERNAL_PREFIX}/rsc/module`,\n RSC_DOM: `${INTERNAL_PREFIX}/rsc/dom.js`,\n RSC_HYDRATOR: `${INTERNAL_PREFIX}/rsc/hydrator.js`,\n RSC_HYDRATE_CLIENT: `${INTERNAL_PREFIX}/rsc/hydrate-client.js`,\n\n // Library module endpoints\n LIB_AI_REACT: `${INTERNAL_PREFIX}/lib/ai/react.js`,\n LIB_AI_COMPONENTS: `${INTERNAL_PREFIX}/lib/ai/components.js`,\n LIB_AI_PRIMITIVES: `${INTERNAL_PREFIX}/lib/ai/primitives.js`,\n} as const;\n\n/**\n * Build output directory paths (relative)\n */\nexport const BUILD_DIRS = {\n /** Main build output directory */\n ROOT: \"_veryfront\",\n /** Chunks directory */\n CHUNKS: \"_veryfront/chunks\",\n /** Data directory */\n DATA: \"_veryfront/data\",\n /** Assets directory */\n ASSETS: \"_veryfront/assets\",\n} as const;\n\n/**\n * Local project directory paths (relative to project root)\n * These are .gitignore'd directories for caching and temporary files\n */\nexport const PROJECT_DIRS = {\n /** Base veryfront internal directory */\n ROOT: \".veryfront\",\n /** Cache directory for build artifacts, transforms, etc. */\n CACHE: \".veryfront/cache\",\n /** KV store directory */\n KV: \".veryfront/kv\",\n /** Log files directory */\n LOGS: \".veryfront/logs\",\n /** Temporary files directory */\n TMP: \".veryfront/tmp\",\n} as const;\n\n/** Default cache directory path */\nexport const DEFAULT_CACHE_DIR = PROJECT_DIRS.CACHE;\n\n/**\n * Helper to check if a pathname is an internal veryfront endpoint\n */\nexport function isInternalEndpoint(pathname: string): boolean {\n return pathname.startsWith(INTERNAL_PREFIX + \"/\");\n}\n\n/**\n * Helper to check if a pathname is a static asset (has extension or is internal)\n */\nexport function isStaticAsset(pathname: string): boolean {\n return pathname.includes(\".\") || isInternalEndpoint(pathname);\n}\n\n/**\n * Normalize a chunk path to include the base prefix\n */\nexport function normalizeChunkPath(\n filename: string,\n basePath: string = INTERNAL_PATH_PREFIXES.CHUNKS,\n): string {\n if (filename.startsWith(\"/\")) {\n return filename;\n }\n return `${basePath.replace(/\\/$/, \"\")}/${filename}`;\n}\n\n// Re-export for backward compatibility\nexport const DEV_SERVER_ENDPOINTS = {\n HMR_RUNTIME: INTERNAL_ENDPOINTS.HMR_RUNTIME,\n ERROR_OVERLAY: INTERNAL_ENDPOINTS.ERROR_OVERLAY,\n} as const;\n", "export * from \"./build.ts\";\nexport * from \"./cache.ts\";\nexport * from \"./cdn.ts\";\nexport * from \"./env.ts\";\nexport * from \"./hash.ts\";\nexport * from \"./hmr.ts\";\nexport * from \"./html.ts\";\nexport * from \"./http.ts\";\nexport * from \"./network.ts\";\nexport * from \"./security.ts\";\nexport * from \"./server.ts\";\n", "/**\n * Project directory paths and file extensions\n *\n * For internal veryfront URL endpoints, see ./constants/server.ts\n */\n\nimport {\n BUILD_DIRS,\n INTERNAL_ENDPOINTS,\n INTERNAL_PATH_PREFIXES,\n INTERNAL_PREFIX,\n} from \"./constants/server.ts\";\n\nexport const 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} as const;\n\n/**\n * @deprecated Use INTERNAL_PREFIX, INTERNAL_ENDPOINTS, INTERNAL_PATH_PREFIXES from ./constants/server.ts\n */\nexport const VERYFRONT_PATHS = {\n INTERNAL_PREFIX: INTERNAL_PREFIX,\n BUILD_DIR: BUILD_DIRS.ROOT,\n CHUNKS_DIR: BUILD_DIRS.CHUNKS,\n DATA_DIR: BUILD_DIRS.DATA,\n ASSETS_DIR: BUILD_DIRS.ASSETS,\n HMR_RUNTIME: INTERNAL_ENDPOINTS.HMR_RUNTIME,\n CLIENT_JS: INTERNAL_ENDPOINTS.CLIENT_JS,\n ROUTER_JS: INTERNAL_ENDPOINTS.ROUTER_JS,\n ERROR_OVERLAY: INTERNAL_ENDPOINTS.ERROR_OVERLAY,\n} as const;\n\nexport const 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} as const;\n\n// Re-export for convenience\nexport { BUILD_DIRS, INTERNAL_ENDPOINTS, INTERNAL_PATH_PREFIXES, INTERNAL_PREFIX };\n", "export async function computeHash(content: string): Promise<string> {\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}\n\nexport function getContentHash(content: string): Promise<string> {\n return computeHash(content);\n}\n\nexport function computeContentHash(content: string): Promise<string> {\n return computeHash(content);\n}\n\nexport interface BundleCode {\n code: string;\n css?: string;\n sourceMap?: string;\n}\n\nexport function computeCodeHash(code: BundleCode): Promise<string> {\n const combined = code.code + (code.css || \"\") + (code.sourceMap || \"\");\n return computeHash(combined);\n}\n\nexport function simpleHash(str: string): number {\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}\n\nexport async function shortHash(content: string): Promise<string> {\n const fullHash = await computeHash(content);\n return fullHash.slice(0, 8);\n}\n", "export class MemoCache<V> {\n private cache = new Map<string, V>();\n\n get(key: string): V | undefined {\n return this.cache.get(key);\n }\n\n set(key: string, value: V): void {\n this.cache.set(key, value);\n }\n\n has(key: string): boolean {\n return this.cache.has(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n size(): number {\n return this.cache.size;\n }\n}\n\nexport function memoizeAsync<Args extends unknown[], Result>(\n fn: (...args: Args) => Promise<Result>,\n keyHasher: (...args: Args) => string,\n): (...args: Args) => Promise<Result> {\n const cache = new MemoCache<Result>();\n\n return async (...args: Args): Promise<Result> => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const result = await fn(...args);\n cache.set(key, result);\n return result;\n };\n}\n\nexport function memoize<Args extends unknown[], Result>(\n fn: (...args: Args) => Result,\n keyHasher: (...args: Args) => string,\n): (...args: Args) => Result {\n const cache = new MemoCache<Result>();\n\n return (...args: Args): Result => {\n const key = keyHasher(...args);\n if (cache.has(key)) {\n return cache.get(key)!;\n }\n\n const result = fn(...args);\n cache.set(key, result);\n return result;\n };\n}\n\n/**\n * FNV-1a hash algorithm for fast cache key generation.\n * 10-15x faster than JSON.stringify() and uses 70-80% less memory.\n *\n * @param values - Values to hash\n * @returns Hash string\n */\nexport function simpleHash(...values: unknown[]): string {\n const FNV_OFFSET_BASIS = 2166136261;\n const FNV_PRIME = 16777619;\n\n let hash = FNV_OFFSET_BASIS;\n\n for (const value of values) {\n const str = typeof value === \"string\" ? value : String(value);\n\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i);\n hash = Math.imul(hash, FNV_PRIME);\n }\n }\n\n // Convert to unsigned 32-bit and then to base-36 string\n return (hash >>> 0).toString(36);\n}\n", "import { logger } from \"./logger/logger.ts\";\n\nexport function normalizePath(pathname: string): string {\n pathname = pathname.replace(/\\\\+/g, \"/\").replace(/\\/\\.+\\//g, \"/\");\n\n if (pathname !== \"/\" && pathname.endsWith(\"/\")) {\n pathname = pathname.slice(0, -1);\n }\n\n return pathname;\n}\n\nexport function joinPath(a: string, b: string): string {\n return `${a.replace(/\\/$/, \"\")}/${b.replace(/^\\//, \"\")}`;\n}\n\nexport function isWithinDirectory(root: string, target: string): boolean {\n const normalizedRoot = normalizePath(root);\n const normalizedTarget = normalizePath(target);\n return normalizedTarget.startsWith(`${normalizedRoot}/`) || normalizedTarget === normalizedRoot;\n}\n\nexport function getExtension(path: string): string {\n const lastDot = path.lastIndexOf(\".\");\n if (lastDot === -1 || lastDot === path.length - 1) {\n return \"\";\n }\n return path.slice(lastDot);\n}\n\nexport function getDirectory(path: string): string {\n const normalized = normalizePath(path);\n const lastSlash = normalized.lastIndexOf(\"/\");\n return lastSlash <= 0 ? \"/\" : normalized.slice(0, lastSlash);\n}\n\nexport function hasHashedFilename(path: string): boolean {\n return /\\.[a-f0-9]{8,}\\./.test(path);\n}\n\nexport function isAbsolutePath(path: string): boolean {\n return path.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\n\nexport function toBase64Url(s: string): string {\n const b64 = btoa(s);\n return b64.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replaceAll(\"=\", \"\");\n}\n\nexport function fromBase64Url(encoded: string): string {\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 (error) {\n logger.debug(`Failed to decode base64url string \"${encoded}\":`, error);\n return \"\";\n }\n}\n", "import { logger } from \"./logger/logger.ts\";\n\nexport function formatBytes(bytes: number): string {\n if (bytes === 0) return \"0 Bytes\";\n\n const absBytes = Math.abs(bytes);\n\n if (absBytes < 1) {\n return `${absBytes} Bytes`;\n }\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\n const index = Math.max(0, Math.min(i, sizes.length - 1));\n\n return `${parseFloat((absBytes / Math.pow(k, index)).toFixed(2))} ${sizes[index]}`;\n}\n\nexport function estimateSize(value: unknown): number {\n if (value === null || value === undefined) return 8;\n\n switch (typeof value) {\n case \"boolean\":\n return 4;\n case \"number\":\n return 8;\n case \"string\":\n return value.length * 2; // UTF-16\n case \"function\":\n return 0; // Functions not cached\n case \"object\":\n return estimateObjectSize(value);\n default:\n return 32;\n }\n}\n\nexport function estimateSizeWithCircularHandling(value: unknown): number {\n const seen = new WeakSet();\n const encoder = new TextEncoder();\n\n const json = JSON.stringify(value, (_key, val) => {\n if (typeof val === \"object\" && val !== null) {\n if (seen.has(val as object)) return undefined;\n seen.add(val as object);\n\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\n if (typeof val === \"function\") return undefined;\n\n if (val instanceof Uint8Array) {\n return { __type: \"Uint8Array\", length: val.length };\n }\n\n return val;\n });\n\n return encoder.encode(json ?? \"\").length;\n}\n\nfunction estimateObjectSize(value: object): number {\n if (value instanceof ArrayBuffer) return value.byteLength;\n\n if (\n value instanceof Uint8Array || value instanceof Uint16Array ||\n value instanceof Uint32Array || value instanceof Int8Array ||\n value instanceof Int16Array || value instanceof Int32Array\n ) {\n return value.byteLength;\n }\n\n try {\n return JSON.stringify(value).length * 2;\n } catch (error) {\n logger.debug(\"Failed to estimate size of non-serializable object:\", error);\n return 1024; // Default estimate for non-serializable\n }\n}\n\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${ms}ms`;\n if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;\n if (ms < 3600000) return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;\n return `${Math.floor(ms / 3600000)}h ${Math.floor((ms % 3600000) / 60000)}m`;\n}\n\nexport function formatNumber(num: number): string {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\nexport function truncateString(str: string, maxLength: number): string {\n if (str.length <= maxLength) return str;\n return str.slice(0, maxLength - 3) + \"...\";\n}\n", "import { serverLogger as logger } from \"./logger/index.ts\";\n\nexport interface BundleMetadata {\n hash: string;\n codeHash: string;\n size: number;\n compiledAt: number;\n source: string;\n mode: \"development\" | \"production\";\n meta?: {\n type?: \"mdx\" | \"component\" | \"layout\" | \"provider\";\n depsHash?: string;\n reactVersion?: string;\n };\n}\n\nexport interface BundleCode {\n code: string;\n sourceMap?: string;\n css?: string;\n}\n\nexport interface BundleManifestStore {\n getBundleMetadata(key: string): Promise<BundleMetadata | undefined>;\n\n setBundleMetadata(key: string, metadata: BundleMetadata, ttlMs?: number): Promise<void>;\n\n getBundleCode(hash: string): Promise<BundleCode | undefined>;\n\n setBundleCode(hash: string, code: BundleCode, ttlMs?: number): Promise<void>;\n\n deleteBundle(key: string): Promise<void>;\n\n invalidateSource(source: string): Promise<number>;\n\n clear(): Promise<void>;\n\n isAvailable(): Promise<boolean>;\n\n getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }>;\n}\n\nexport class InMemoryBundleManifestStore implements BundleManifestStore {\n private metadata = new Map<string, { value: BundleMetadata; expiry?: number }>();\n private code = new Map<string, { value: BundleCode; expiry?: number }>();\n private sourceIndex = new Map<string, Set<string>>();\n\n getBundleMetadata(key: string): Promise<BundleMetadata | undefined> {\n const entry = this.metadata.get(key);\n if (!entry) return Promise.resolve(undefined);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.metadata.delete(key);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(entry.value);\n }\n\n setBundleMetadata(key: string, metadata: BundleMetadata, ttlMs?: number): Promise<void> {\n const expiry = ttlMs ? Date.now() + ttlMs : undefined;\n this.metadata.set(key, { value: metadata, expiry });\n\n if (!this.sourceIndex.has(metadata.source)) {\n this.sourceIndex.set(metadata.source, new Set());\n }\n this.sourceIndex.get(metadata.source)!.add(key);\n return Promise.resolve();\n }\n\n getBundleCode(hash: string): Promise<BundleCode | undefined> {\n const entry = this.code.get(hash);\n if (!entry) return Promise.resolve(undefined);\n if (entry.expiry && Date.now() > entry.expiry) {\n this.code.delete(hash);\n return Promise.resolve(undefined);\n }\n return Promise.resolve(entry.value);\n }\n\n setBundleCode(hash: string, code: BundleCode, ttlMs?: number): Promise<void> {\n const expiry = ttlMs ? Date.now() + ttlMs : undefined;\n this.code.set(hash, { value: code, expiry });\n return Promise.resolve();\n }\n\n async deleteBundle(key: string): Promise<void> {\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\n async invalidateSource(source: string): Promise<number> {\n const keys = this.sourceIndex.get(source);\n if (!keys) return 0;\n\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\n clear(): Promise<void> {\n this.metadata.clear();\n this.code.clear();\n this.sourceIndex.clear();\n return Promise.resolve();\n }\n\n isAvailable(): Promise<boolean> {\n return Promise.resolve(true);\n }\n\n getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }> {\n let totalSize = 0;\n let oldest: number | undefined;\n let newest: number | undefined;\n\n for (const { value } of this.metadata.values()) {\n totalSize += value.size;\n if (!oldest || value.compiledAt < oldest) oldest = value.compiledAt;\n if (!newest || value.compiledAt > newest) newest = value.compiledAt;\n }\n\n return Promise.resolve({\n totalBundles: this.metadata.size,\n totalSize,\n oldestBundle: oldest,\n newestBundle: newest,\n });\n }\n}\n\nlet manifestStore: BundleManifestStore = new InMemoryBundleManifestStore();\n\nexport function setBundleManifestStore(store: BundleManifestStore): void {\n manifestStore = store;\n logger.info(\"[bundle-manifest] Bundle manifest store configured\", {\n type: store.constructor.name,\n });\n}\n\nexport function getBundleManifestStore(): BundleManifestStore {\n return manifestStore;\n}\n\nexport { computeCodeHash, computeContentHash } from \"./hash-utils.ts\";\n", "import type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport type { VeryfrontConfig } from \"@veryfront/config\";\nimport { serverLogger as logger } from \"./logger/index.ts\";\nimport {\n type BundleManifestStore,\n InMemoryBundleManifestStore,\n setBundleManifestStore,\n} from \"./bundle-manifest.ts\";\nimport { BUNDLE_MANIFEST_DEV_TTL_MS, BUNDLE_MANIFEST_PROD_TTL_MS } from \"./constants/cache.ts\";\n\nexport async function initializeBundleManifest(\n config: VeryfrontConfig,\n mode: \"development\" | \"production\",\n adapter?: RuntimeAdapter,\n): Promise<void> {\n const manifestConfig = config.cache?.bundleManifest;\n const enabled = manifestConfig?.enabled ?? mode === \"production\";\n\n if (!enabled) {\n logger.info(\"[bundle-manifest] Bundle manifest disabled\");\n setBundleManifestStore(new InMemoryBundleManifestStore());\n return;\n }\n\n const envType = adapter?.env.get(\"VERYFRONT_BUNDLE_MANIFEST_TYPE\");\n const storeType = manifestConfig?.type || envType || \"memory\";\n\n logger.info(\"[bundle-manifest] Initializing bundle manifest\", {\n type: storeType,\n mode,\n });\n\n try {\n let store: BundleManifestStore;\n\n switch (storeType) {\n case \"redis\": {\n const { RedisBundleManifestStore } = await import(\"./bundle-manifest-redis.ts\");\n const redisUrl = manifestConfig?.redisUrl ||\n 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\n const available = await store.isAvailable();\n if (!available) {\n logger.warn(\"[bundle-manifest] Redis not available, falling back to in-memory\");\n store = new InMemoryBundleManifestStore();\n } else {\n logger.info(\"[bundle-manifest] Redis store initialized\");\n }\n break;\n }\n\n case \"kv\": {\n const { KVBundleManifestStore } = await import(\"./bundle-manifest-kv.ts\");\n store = new KVBundleManifestStore({\n keyPrefix: manifestConfig?.keyPrefix,\n });\n\n const available = await store.isAvailable();\n if (!available) {\n logger.warn(\"[bundle-manifest] KV not available, falling back to in-memory\");\n store = new InMemoryBundleManifestStore();\n } else {\n logger.info(\"[bundle-manifest] KV store initialized\");\n }\n break;\n }\n\n case \"memory\":\n default: {\n store = new InMemoryBundleManifestStore();\n logger.info(\"[bundle-manifest] In-memory store initialized\");\n break;\n }\n }\n\n setBundleManifestStore(store);\n\n try {\n const stats = await store.getStats();\n logger.info(\"[bundle-manifest] Store statistics\", stats);\n } catch (error) {\n logger.debug(\"[bundle-manifest] Failed to get stats\", { error });\n }\n } catch (error) {\n logger.error(\"[bundle-manifest] Failed to initialize store, using in-memory fallback\", {\n error,\n });\n setBundleManifestStore(new InMemoryBundleManifestStore());\n }\n}\n\nexport function getBundleManifestTTL(\n config: VeryfrontConfig,\n mode: \"development\" | \"production\",\n): number | undefined {\n const manifestConfig = config.cache?.bundleManifest;\n if (manifestConfig?.ttl) {\n return manifestConfig.ttl;\n }\n\n if (mode === \"production\") {\n return BUNDLE_MANIFEST_PROD_TTL_MS;\n } else {\n return BUNDLE_MANIFEST_DEV_TTL_MS;\n }\n}\n\nexport async function warmupBundleManifest(\n store: BundleManifestStore,\n keys: string[],\n): Promise<void> {\n logger.info(\"[bundle-manifest] Warming up cache\", { keys: keys.length });\n\n let loaded = 0;\n let failed = 0;\n\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 (error) {\n logger.debug(\"[bundle-manifest] Failed to warm up key\", { key, error });\n failed++;\n }\n }\n\n logger.info(\"[bundle-manifest] Cache warmup complete\", { loaded, failed });\n}\n", "declare const process: { env: Record<string, string | undefined> } | undefined;\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\n/**\n * Checks if React Server Components (RSC) are enabled.\n *\n * Priority order:\n * 1. Config file (config.experimental.rsc)\n * 2. Environment variables (VERYFRONT_EXPERIMENTAL_RSC=1)\n * 3. Default (false)\n *\n * @param config - Optional config object to check first\n * @returns true if RSC is enabled, false otherwise\n */\nexport function isRSCEnabled(config?: { experimental?: { rsc?: boolean } }): boolean {\n // 1. Check config first (highest priority)\n if (config?.experimental?.rsc !== undefined) {\n return config.experimental.rsc;\n }\n\n // 2. Fallback to environment variables (backward compatibility)\n return getEnv(\"VERYFRONT_EXPERIMENTAL_RSC\") === \"1\";\n}\n", "/**\n * Platform detection utilities\n */\n\nimport { isDeno } from \"../../platform/compat/runtime.ts\";\nimport { execPath } from \"../../platform/compat/process.ts\";\n\n/**\n * Detect if the code is running in a compiled Deno binary\n * @returns true if running in a compiled binary, false otherwise\n */\nexport function isCompiledBinary(): boolean {\n if (!isDeno) return false;\n\n try {\n const path = execPath();\n return path.includes(\"veryfront\");\n } catch {\n return false;\n }\n}\n", "export * from \"./runtime-guards.ts\";\n\nexport * from \"./logger/index.ts\";\n\nexport * from \"./constants/index.ts\";\nexport { VERSION } from \"./version.ts\";\n\nexport * from \"./paths.ts\";\n\nexport {\n type BundleCode as HashBundleCode, // Alias to avoid conflict with bundle-manifest\n computeCodeHash,\n computeContentHash,\n computeHash,\n getContentHash,\n shortHash,\n simpleHash,\n simpleHash as numericHash, // Alias to avoid conflict with memoize\n} from \"./hash-utils.ts\";\n\nexport {\n MemoCache,\n memoize,\n memoizeAsync,\n simpleHash as memoizeHash, // Alias to distinguish from hash-utils version\n} from \"./memoize.ts\";\n\nexport * from \"./path-utils.ts\";\n\nexport * from \"./format-utils.ts\";\n\nexport * from \"./bundle-manifest.ts\";\nexport * from \"./bundle-manifest-init.ts\";\n\nexport * from \"./feature-flags.ts\";\n\nexport { isCompiledBinary } from \"./platform.ts\";\n", "export interface BuildContext {\n file?: string;\n line?: number;\n column?: number;\n moduleId?: string;\n phase?: \"parse\" | \"transform\" | \"bundle\" | \"optimize\";\n}\n\nexport interface APIContext {\n endpoint?: string;\n method?: string;\n statusCode?: number;\n headers?: Record<string, string>;\n}\n\nexport interface RenderContext {\n component?: string;\n route?: string;\n phase?: \"server\" | \"client\" | \"hydration\";\n props?: unknown;\n}\n\nexport interface ConfigContext {\n configFile?: string;\n field?: string;\n value?: unknown;\n expected?: string;\n}\n\nexport interface AgentContext {\n agentId?: string;\n intent?: string;\n timeout?: number;\n}\n\nexport interface FileContext {\n path?: string;\n operation?: \"read\" | \"write\" | \"delete\" | \"mkdir\";\n permissions?: string;\n}\n\nexport interface NetworkContext {\n url?: string;\n timeout?: number;\n retryCount?: number;\n}\n\nexport type VeryfrontError =\n | { type: \"build\"; message: string; context?: BuildContext }\n | { type: \"api\"; message: string; context?: APIContext }\n | { type: \"render\"; message: string; context?: RenderContext }\n | { type: \"config\"; message: string; context?: ConfigContext }\n | { type: \"agent\"; message: string; context?: AgentContext }\n | { type: \"file\"; message: string; context?: FileContext }\n | { type: \"network\"; message: string; context?: NetworkContext }\n | { type: \"permission\"; message: string; context?: FileContext }\n | { type: \"not_supported\"; message: string; feature?: string };\n\nexport function createError(error: VeryfrontError): VeryfrontError {\n return error;\n}\n\nexport function isBuildError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"build\" }> {\n return error.type === \"build\";\n}\n\nexport function isAPIError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"api\" }> {\n return error.type === \"api\";\n}\n\nexport function isRenderError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"render\" }> {\n return error.type === \"render\";\n}\n\nexport function isConfigError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"config\" }> {\n return error.type === \"config\";\n}\n\nexport function isAgentError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"agent\" }> {\n return error.type === \"agent\";\n}\n\nexport function isFileError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"file\" }> {\n return error.type === \"file\";\n}\n\nexport function isNetworkError(\n error: VeryfrontError,\n): error is Extract<VeryfrontError, { type: \"network\" }> {\n return error.type === \"network\";\n}\n\nexport function toError(veryfrontError: VeryfrontError): Error {\n const error = new Error(veryfrontError.message);\n error.name = `VeryfrontError[${veryfrontError.type}]`;\n Object.defineProperty(error, \"context\", {\n value: veryfrontError,\n enumerable: false,\n configurable: true,\n });\n return error;\n}\n\nexport function fromError(error: unknown): VeryfrontError | null {\n if (error && typeof error === \"object\" && \"context\" in error) {\n // Safe access after 'in' check\n const context = (error as Record<string, unknown>).context;\n if (\n context &&\n typeof context === \"object\" &&\n \"type\" in context &&\n \"message\" in context\n ) {\n return context as VeryfrontError;\n }\n }\n return null;\n}\n\nexport function logError(\n error: VeryfrontError,\n logger?: { error: (msg: string, ...args: unknown[]) => void },\n): void {\n const log = logger || console;\n const context = \"context\" in error ? error.context || {} : {};\n log.error(`[${error.type}] ${error.message}`, context);\n}\n", "import { z } from \"zod\";\nimport type { VeryfrontConfig } from \"./types.ts\";\nimport { type ConfigContext, createError, toError } from \"../errors/veryfront-error.ts\";\n\nconst corsSchema = z.union([z.boolean(), z.object({ origin: z.string().optional() }).strict()]);\n\nexport const veryfrontConfigSchema = z\n .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\n .object({ colors: z.record(z.string()).optional() })\n .partial()\n .optional(),\n build: z\n .object({\n outDir: z.string().optional(),\n trailingSlash: z.boolean().optional(),\n esbuild: z\n .object({\n wasmURL: z.string().url().optional(),\n worker: z.boolean().optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n cache: z\n .object({\n dir: z.string().optional(),\n bundleManifest: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n dev: z\n .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 })\n .partial()\n .optional(),\n resolve: z\n .object({\n importMap: z\n .object({\n imports: z.record(z.string()).optional(),\n scopes: z.record(z.record(z.string())).optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n security: z\n .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 })\n .partial()\n .optional(),\n middleware: z\n .object({\n custom: z.array(z.function()).optional(),\n })\n .partial()\n .optional(),\n theming: z\n .object({\n brandName: z.string().optional(),\n logoHtml: z.string().optional(),\n })\n .partial()\n .optional(),\n assetPipeline: z\n .object({\n images: z\n .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 })\n .partial()\n .optional(),\n css: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n observability: z\n .object({\n tracing: z\n .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 })\n .partial()\n .optional(),\n metrics: z\n .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 })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n fs: z\n .object({\n type: z.enum([\"local\", \"veryfront-api\", \"memory\"]).optional(),\n local: z\n .object({\n baseDir: z.string().optional(),\n })\n .partial()\n .optional(),\n veryfront: z\n .object({\n apiBaseUrl: z.string().url(),\n apiToken: z.string(),\n projectSlug: z.string(),\n cache: z\n .object({\n enabled: z.boolean().optional(),\n ttl: z.number().int().positive().optional(),\n maxSize: z.number().int().positive().optional(),\n })\n .partial()\n .optional(),\n retry: z\n .object({\n maxRetries: z.number().int().min(0).optional(),\n initialDelay: z.number().int().positive().optional(),\n maxDelay: z.number().int().positive().optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n memory: z\n .object({\n files: z.record(z.union([z.string(), z.instanceof(Uint8Array)])).optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n client: z\n .object({\n moduleResolution: z.enum([\"cdn\", \"self-hosted\", \"bundled\"]).optional(),\n cdn: z\n .object({\n provider: z.enum([\"esm.sh\", \"unpkg\", \"jsdelivr\"]).optional(),\n versions: z\n .union([\n z.literal(\"auto\"),\n z.object({\n react: z.string().optional(),\n veryfront: z.string().optional(),\n }),\n ])\n .optional(),\n })\n .partial()\n .optional(),\n })\n .partial()\n .optional(),\n })\n .partial();\n\nexport type VeryfrontConfigInput = z.input<typeof veryfrontConfigSchema>;\n\nexport function validateVeryfrontConfig(input: unknown): VeryfrontConfig {\n const parsed = veryfrontConfigSchema.safeParse(input);\n if (!parsed.success) {\n const first = parsed.error.issues[0];\n const path = first?.path?.length ? first.path.join(\".\") : \"<root>\";\n const expected = first?.message || String(first);\n let hint = \"\";\n if (String(path).includes(\"security.cors\")) {\n hint = \" Expected boolean or { origin?: string }.\";\n }\n\n const context: ConfigContext = {\n field: path,\n expected: expected + hint,\n value: input,\n };\n\n throw toError(\n createError({\n type: \"config\",\n message: `Invalid veryfront.config at ${path}: ${expected}.${hint}`,\n context,\n }),\n );\n }\n return parsed.data as VeryfrontConfig;\n}\n\nexport function findUnknownTopLevelKeys(input: Record<string, unknown>): string[] {\n const known = new Set([\n \"title\",\n \"description\",\n \"experimental\",\n \"router\",\n \"defaultLayout\",\n \"theme\",\n \"build\",\n \"cache\",\n \"dev\",\n \"resolve\",\n \"security\",\n \"middleware\",\n \"theming\",\n \"assetPipeline\",\n \"observability\",\n \"fs\",\n \"client\",\n ]);\n return Object.keys(input).filter((k) => !known.has(k));\n}\n", "import type { VeryfrontConfig } from \"./types.ts\";\nimport { findUnknownTopLevelKeys, validateVeryfrontConfig } from \"./schema.ts\";\nimport { join } from \"std/path/mod.ts\";\nimport type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport { serverLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { getReactImportMap, REACT_DEFAULT_VERSION } from \"@veryfront/utils/constants/cdn.ts\";\nimport { DEFAULT_CACHE_DIR } from \"@veryfront/utils/constants/server.ts\";\nimport { DEFAULT_PORT } from \"./defaults.ts\";\n\nexport type { VeryfrontConfig } from \"./types.ts\";\n\nfunction getDefaultImportMapForConfig() {\n return { imports: getReactImportMap(REACT_DEFAULT_VERSION) };\n}\n\nconst DEFAULT_CONFIG: Partial<VeryfrontConfig> = {\n title: \"Veryfront App\",\n description: \"Built with Veryfront\",\n experimental: {\n esmLayouts: true,\n },\n router: undefined,\n defaultLayout: undefined,\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: DEFAULT_CACHE_DIR,\n render: {\n type: \"memory\",\n ttl: undefined,\n maxEntries: 500,\n kvPath: undefined,\n redisUrl: undefined,\n redisKeyPrefix: undefined,\n },\n },\n dev: {\n port: DEFAULT_PORT,\n host: \"localhost\",\n open: false,\n },\n resolve: {\n importMap: getDefaultImportMapForConfig(),\n },\n client: {\n moduleResolution: \"cdn\",\n cdn: {\n provider: \"esm.sh\",\n versions: \"auto\",\n },\n },\n};\n\nconst configCacheByProject = new Map<string, { revision: number; config: VeryfrontConfig }>();\nlet cacheRevision = 0;\n\nfunction validateCorsConfig(userConfig: unknown): void {\n if (!userConfig || typeof userConfig !== \"object\") {\n return;\n }\n const config = userConfig as Record<string, unknown>;\n const security = config.security as Record<string, unknown> | undefined;\n const cors = security?.cors;\n if (!cors || typeof cors !== \"object\" || Array.isArray(cors)) {\n return;\n }\n\n const corsObj = cors as Record<string, unknown>;\n const origin = corsObj.origin;\n if (origin !== undefined && typeof origin !== \"string\") {\n throw new ConfigValidationError(\n \"security.cors.origin must be a string. Expected boolean or { origin?: string }\",\n );\n }\n}\n\nfunction validateConfigShape(userConfig: unknown): void {\n validateVeryfrontConfig(userConfig);\n const unknown = typeof userConfig === \"object\" && userConfig\n ? findUnknownTopLevelKeys(userConfig as Record<string, unknown>)\n : [];\n if (unknown.length > 0) {\n serverLogger.warn(`Unknown config keys: ${unknown.join(\", \")}. These will be ignored.`);\n }\n}\n\nfunction mergeConfigs(userConfig: Partial<VeryfrontConfig>): VeryfrontConfig {\n const merged: VeryfrontConfig = {\n ...DEFAULT_CONFIG,\n ...userConfig,\n dev: {\n ...DEFAULT_CONFIG.dev,\n ...userConfig.dev,\n },\n theme: {\n ...DEFAULT_CONFIG.theme,\n ...userConfig.theme,\n },\n build: {\n ...DEFAULT_CONFIG.build,\n ...userConfig.build,\n },\n cache: {\n ...DEFAULT_CONFIG.cache,\n ...userConfig.cache,\n },\n resolve: {\n ...DEFAULT_CONFIG.resolve,\n ...userConfig.resolve,\n },\n client: {\n ...DEFAULT_CONFIG.client,\n ...userConfig.client,\n cdn: {\n ...DEFAULT_CONFIG.client?.cdn,\n ...userConfig.client?.cdn,\n },\n },\n } as VeryfrontConfig;\n\n if (merged.resolve) {\n const defaultMap = DEFAULT_CONFIG.resolve?.importMap;\n const userMap = userConfig.resolve?.importMap;\n\n if (defaultMap || userMap) {\n merged.resolve.importMap = {\n imports: {\n ...(defaultMap?.imports ?? {}),\n ...(userMap?.imports ?? {}),\n },\n scopes: {\n ...(defaultMap?.scopes ?? {}),\n ...(userMap?.scopes ?? {}),\n },\n };\n }\n }\n\n return merged;\n}\n\nclass ConfigValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigValidationError\";\n }\n}\n\nasync function loadAndMergeConfig(\n configPath: string,\n projectDir: string,\n): Promise<VeryfrontConfig | null> {\n try {\n const configUrl = `file://${configPath}?t=${Date.now()}-${crypto.randomUUID()}`;\n const configModule = await import(configUrl);\n const userConfig = configModule.default || configModule;\n\n if (userConfig === null || typeof userConfig !== \"object\" || Array.isArray(userConfig)) {\n throw new ConfigValidationError(\n `Expected object, received ${userConfig === null ? \"null\" : typeof userConfig}`,\n );\n }\n\n validateCorsConfig(userConfig);\n validateConfigShape(userConfig);\n\n const merged = mergeConfigs(userConfig);\n configCacheByProject.set(projectDir, { revision: cacheRevision, config: merged });\n return merged;\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.startsWith(\"Invalid veryfront.config\")) {\n throw error;\n }\n\n throw error;\n }\n}\n\nexport async function getConfig(\n projectDir: string,\n adapter: RuntimeAdapter,\n): Promise<VeryfrontConfig> {\n const cached = configCacheByProject.get(projectDir);\n if (cached && cached.revision === cacheRevision) return cached.config;\n\n const configFiles = [\"veryfront.config.js\", \"veryfront.config.ts\", \"veryfront.config.mjs\"];\n\n for (const configFile of configFiles) {\n const configPath = join(projectDir, configFile);\n\n const exists = await adapter.fs.exists(configPath);\n if (!exists) continue;\n\n try {\n const merged = await loadAndMergeConfig(configPath, projectDir);\n if (merged) return merged;\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n if (error instanceof Error && error.message.startsWith(\"Invalid veryfront.config\")) {\n throw error;\n }\n\n // Only log at debug level - this is expected when .ts exists but .js is tried first\n const errorMessage = error instanceof Error ? error.message : String(error);\n serverLogger.debug(`[CONFIG] Failed to load ${configFile}, trying next config file:`, {\n error: errorMessage,\n });\n\n continue;\n }\n }\n\n const defaultConfig = DEFAULT_CONFIG as VeryfrontConfig;\n configCacheByProject.set(projectDir, { revision: cacheRevision, config: defaultConfig });\n return defaultConfig;\n}\n\nexport function clearConfigCache() {\n configCacheByProject.clear();\n cacheRevision++;\n}\n", "import type { VeryfrontConfig } from \"./types.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport function defineConfig(config: VeryfrontConfig): VeryfrontConfig {\n return config;\n}\n\nexport function defineConfigWithEnv(\n factory: (env: string) => VeryfrontConfig,\n): VeryfrontConfig {\n const env = getEnv(\"NODE_ENV\") || \"development\";\n return factory(env);\n}\n\nexport function mergeConfigs(\n ...configs: Partial<VeryfrontConfig>[]\n): VeryfrontConfig {\n const merged: Partial<VeryfrontConfig> = {};\n\n for (const config of configs) {\n Object.assign(merged, config);\n }\n\n return merged as VeryfrontConfig;\n}\n\nexport async function validateConfig(config: unknown): Promise<void> {\n if (!config || typeof config !== \"object\") {\n throw toError(createError({\n type: \"config\",\n message: \"Configuration must be an object\",\n }));\n }\n\n const cfg = config as Record<string, unknown>;\n\n if (cfg.dev && typeof cfg.dev === \"object\") {\n const dev = cfg.dev as Record<string, unknown>;\n if (dev.port !== undefined) {\n const { MIN_PORT, MAX_PORT } = await import(\"../utils/constants/network.ts\");\n if (typeof dev.port !== \"number\" || dev.port < MIN_PORT || dev.port > MAX_PORT) {\n throw toError(createError({\n type: \"config\",\n message: `dev.port must be a number between ${MIN_PORT} and ${MAX_PORT}`,\n context: {\n field: \"dev.port\",\n value: dev.port,\n expected: `number between ${MIN_PORT} and ${MAX_PORT}`,\n },\n }));\n }\n }\n }\n\n if (cfg.build && typeof cfg.build === \"object\") {\n const build = cfg.build as Record<string, unknown>;\n if (build.outDir !== undefined && typeof build.outDir !== \"string\") {\n throw toError(createError({\n type: \"config\",\n message: \"build.outDir must be a string\",\n context: { field: \"build.outDir\", value: build.outDir, expected: \"string\" },\n }));\n }\n }\n}\n", "export const LOCALHOST = {\n IPV4: \"127.0.0.1\",\n IPV6: \"::1\",\n HOSTNAME: \"localhost\",\n} as const;\n\nexport const HTTP_DEFAULTS = {\n PORT: 3000,\n HOST: \"localhost\",\n PROD_HOST: \"0.0.0.0\",\n} as const;\n\nexport const REDIS_DEFAULTS = {\n URL: \"redis://127.0.0.1:6379\",\n PORT: 6379,\n HOST: \"127.0.0.1\",\n} as const;\n\nexport const DEV_LOCALHOST_ORIGINS = [\n \"http://localhost\",\n \"http://127.0.0.1\",\n \"https://localhost\",\n \"https://127.0.0.1\",\n] as const;\n\nexport const DEV_LOCALHOST_CSP = {\n WS: \"ws://localhost:* wss://localhost:*\",\n HTTP: \"http://localhost\",\n} as const;\n\nexport const LOCALHOST_URLS = {\n HTTP: \"http://localhost\",\n HTTPS: \"https://localhost\",\n HTTP_IPV4: \"http://127.0.0.1\",\n HTTPS_IPV4: \"https://127.0.0.1\",\n} as const;\n\nexport function buildLocalhostUrl(\n port: number,\n protocol: \"http\" | \"https\" = \"http\",\n): string {\n return `${protocol}://${LOCALHOST.HOSTNAME}:${port}`;\n}\n\nexport function buildIpv4Url(\n port: number,\n protocol: \"http\" | \"https\" = \"http\",\n): string {\n return `${protocol}://${LOCALHOST.IPV4}:${port}`;\n}\n", "export { clearConfigCache, getConfig } from \"./loader.ts\";\n\nexport { defineConfig } from \"./define-config.ts\";\n\nexport type { VeryfrontConfig } from \"./types.ts\";\n\nexport {\n findUnknownTopLevelKeys,\n validateVeryfrontConfig,\n veryfrontConfigSchema,\n} from \"./schema.ts\";\n\nexport {\n DEFAULT_CACHE_MAX_SIZE,\n DEFAULT_METRICS_COLLECT_INTERVAL_MS,\n DEFAULT_PORT,\n DEFAULT_PREFETCH_DELAY_MS,\n DEFAULT_REDIS_BATCH_DELETE_SIZE,\n DEFAULT_REDIS_SCAN_COUNT,\n DEFAULT_TIMEOUT_MS,\n type DefaultConfig,\n defaultConfig,\n DURATION_HISTOGRAM_BOUNDARIES_MS,\n PAGE_TRANSITION_DELAY_MS,\n SANDBOX_TIMEOUT_MS,\n SIZE_HISTOGRAM_BOUNDARIES_KB,\n SSR_TIMEOUT_MS,\n} from \"./defaults.ts\";\n\nexport {\n buildIpv4Url,\n buildLocalhostUrl,\n DEV_LOCALHOST_CSP,\n DEV_LOCALHOST_ORIGINS,\n HTTP_DEFAULTS,\n LOCALHOST,\n LOCALHOST_URLS,\n REDIS_DEFAULTS,\n} from \"./network-defaults.ts\";\n", "import { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport type {\n DirEntry,\n EnvironmentAdapter,\n FileChangeEvent,\n FileChangeKind,\n FileInfo,\n FileSystemAdapter,\n FileWatcher,\n RuntimeAdapter,\n RuntimeFeatures,\n ServeOptions,\n Server,\n ServerAdapter,\n ShellAdapter,\n WatchOptions,\n WebSocketUpgrade,\n} from \"./base.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nclass DenoFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n return await Deno.readTextFile(path);\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n return await Deno.readFile(path);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await Deno.writeTextFile(path, content);\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n await Deno.stat(path);\n return true;\n } catch (_error) {\n return false;\n }\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\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\n async stat(path: string): Promise<FileInfo> {\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\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n await Deno.mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n await Deno.remove(path, options);\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n return await Deno.makeTempDir({ prefix });\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n const watcher = Deno.watchFs(pathArray, { recursive });\n let closed = false;\n\n const denoIterator = watcher[Symbol.asyncIterator]();\n\n const mapEventKind = (kind: string): FileChangeKind => {\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\n const iterator: AsyncIterator<FileChangeEvent> = {\n async next(): Promise<IteratorResult<FileChangeEvent>> {\n if (closed || signal?.aborted) {\n return { done: true, value: undefined };\n }\n\n try {\n const result = await denoIterator.next();\n if (result.done) {\n return { done: true, value: undefined };\n }\n\n return {\n done: false,\n value: {\n kind: mapEventKind(result.value.kind),\n paths: result.value.paths,\n },\n };\n } catch (error) {\n if (closed || signal?.aborted) {\n return { done: true, value: undefined };\n }\n throw error;\n }\n },\n\n async return(): Promise<IteratorResult<FileChangeEvent>> {\n closed = true;\n if (denoIterator.return) {\n await denoIterator.return();\n }\n return { done: true, value: undefined };\n },\n };\n\n const cleanup = () => {\n if (closed) return;\n closed = true;\n try {\n if (\"close\" in watcher && typeof watcher.close === \"function\") {\n watcher.close();\n }\n } catch (error) {\n serverLogger.debug(\"[Deno] Filesystem watcher cleanup failed\", { error });\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup,\n };\n }\n}\n\nclass DenoEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return Deno.env.get(key);\n }\n\n set(key: string, value: string): void {\n Deno.env.set(key, value);\n }\n\n toObject(): Record<string, string> {\n return Deno.env.toObject();\n }\n}\n\nclass DenoServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const { socket, response } = Deno.upgradeWebSocket(request);\n return { socket, response };\n }\n}\n\nclass DenoShellAdapter implements ShellAdapter {\n statSync(path: string): { isFile: boolean; isDirectory: boolean } {\n try {\n const stat = Deno.statSync(path);\n return {\n isFile: stat.isFile,\n isDirectory: stat.isDirectory,\n };\n } catch (error) {\n throw toError(createError({\n type: \"file\",\n message: `Failed to stat file: ${error}`,\n }));\n }\n }\n\n readFileSync(path: string): string {\n try {\n return Deno.readTextFileSync(path);\n } catch (error) {\n throw toError(createError({\n type: \"file\",\n message: `Failed to read file: ${error}`,\n }));\n }\n }\n}\n\nclass DenoServer implements Server {\n constructor(\n private server: Deno.HttpServer,\n private hostname: string,\n private port: number,\n private abortController?: AbortController,\n ) {}\n\n async stop(): Promise<void> {\n try {\n if (this.abortController) {\n this.abortController.abort();\n }\n\n await this.server.shutdown();\n } catch (error) {\n serverLogger.debug(\"[Deno] Server shutdown failed\", { error });\n }\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\nexport class DenoAdapter implements RuntimeAdapter {\n readonly id = \"deno\" as const;\n readonly name = \"deno\";\n /** @deprecated Use `id` instead */\n readonly platform = \"deno\" as const;\n\n fs = new DenoFileSystemAdapter();\n env = new DenoEnvironmentAdapter();\n server = new DenoServerAdapter();\n shell = new DenoShellAdapter();\n\n readonly 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, // Deno KV available\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: true,\n typescript: true,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n\n const controller = new AbortController();\n const signal = options.signal || controller.signal;\n\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 (error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"Request handler error:\", error);\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\n const controllerToPass = options.signal ? undefined : controller;\n return Promise.resolve(new DenoServer(server, hostname, port, controllerToPass));\n }\n}\n\nexport const denoAdapter = new DenoAdapter();\n", "import type { FileChangeEvent, FileChangeKind, FileWatcher } from \"./base.ts\";\nimport { join } from \"node:path\";\n\nexport async function setupNodeFsWatcher(\n path: string,\n options: {\n recursive: boolean;\n closed: () => boolean;\n signal: AbortSignal | undefined;\n eventQueue: FileChangeEvent[];\n getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null;\n setResolver: (resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void;\n watchers: Array<import(\"node:fs\").FSWatcher>;\n onError: (error: Error, path: string) => void;\n },\n): Promise<void> {\n try {\n const fs = await import(\"node:fs\");\n const fsPromises = await import(\"node:fs/promises\");\n\n const exists = await fsPromises.access(path).then(() => true).catch(() => false);\n if (!exists) return;\n\n const watcher = fs.watch(path, { recursive: options.recursive }, (eventType, filename) => {\n if (options.closed() || options.signal?.aborted) return;\n\n const kind: FileChangeKind = eventType === \"change\" ? \"modify\" : \"any\";\n const fullPath = filename ? join(path, filename) : path;\n\n enqueueWatchEvent(\n { kind, paths: [fullPath] },\n options.eventQueue,\n options.getResolver,\n options.setResolver,\n );\n });\n\n watcher.on(\"error\", (error: Error) => {\n if (!options.closed() && !options.signal?.aborted) {\n options.onError(error, path);\n }\n });\n\n options.watchers.push(watcher);\n } catch (error) {\n options.onError(error as Error, path);\n }\n}\n\nexport function createWatcherIterator(\n eventQueue: FileChangeEvent[],\n _getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null,\n setResolver: (r: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void,\n isClosed: () => boolean,\n isAborted: () => boolean,\n): AsyncIterator<FileChangeEvent> {\n return {\n next(): Promise<IteratorResult<FileChangeEvent>> {\n if (isClosed() || isAborted()) {\n return Promise.resolve({ done: true, value: undefined });\n }\n\n if (eventQueue.length > 0) {\n const event = eventQueue.shift()!;\n return Promise.resolve({ done: false, value: event });\n }\n\n return new Promise((resolve) => {\n if (isClosed() || isAborted()) {\n resolve({ done: true, value: undefined });\n return;\n }\n setResolver(resolve);\n });\n },\n\n return(): Promise<IteratorResult<FileChangeEvent>> {\n return Promise.resolve({ done: true, value: undefined });\n },\n };\n}\n\nexport function enqueueWatchEvent(\n event: FileChangeEvent,\n eventQueue: FileChangeEvent[],\n getResolver: () => ((value: IteratorResult<FileChangeEvent>) => void) | null,\n setResolver: (resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null) => void,\n): void {\n const resolver = getResolver();\n if (resolver) {\n resolver({ done: false, value: event });\n setResolver(null);\n } else {\n eventQueue.push(event);\n }\n}\n\nexport function createFileWatcher(\n iterator: AsyncIterator<FileChangeEvent>,\n cleanup: () => void,\n): FileWatcher {\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n close: cleanup,\n };\n}\n", "import type { DirEntry, FileInfo, FileSystemAdapter, FileWatcher, WatchOptions } from \"../base.ts\";\nimport { createFileWatcher, createWatcherIterator, setupNodeFsWatcher } from \"../shared-watcher.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\nimport type { FileChangeEvent } from \"../base.ts\";\n\nexport class NodeFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n return await fs.readFile(path, \"utf-8\");\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n const fs = await import(\"node:fs/promises\");\n const buffer = await fs.readFile(path);\n return buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.writeFile(path, content, \"utf-8\");\n }\n\n async exists(path: string): Promise<boolean> {\n const fs = await import(\"node:fs/promises\");\n try {\n await fs.access(path);\n return true;\n } catch (error) {\n serverLogger.debug(`File access check failed for ${path}:`, error);\n return false;\n }\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\n const fs = await import(\"node:fs/promises\");\n const entries = await fs.readdir(path, { withFileTypes: true });\n\n for (const entry of entries) {\n yield {\n name: entry.name,\n isFile: entry.isFile(),\n isDirectory: entry.isDirectory(),\n isSymlink: entry.isSymbolicLink(),\n };\n }\n }\n\n async stat(path: string): Promise<FileInfo> {\n const fs = await import(\"node:fs/promises\");\n const stats = await fs.stat(path);\n\n return {\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymlink: stats.isSymbolicLink(),\n mtime: stats.mtime,\n };\n }\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n const fs = await import(\"node:fs/promises\");\n await fs.rm(path, { recursive: options?.recursive, force: true });\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n const { join } = await import(\"node:path\");\n const { tmpdir } = await import(\"node:os\");\n return await mkdtemp(join(tmpdir(), prefix));\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n let closed = false;\n const watchers: Array<import(\"node:fs\").FSWatcher> = [];\n const eventQueue: FileChangeEvent[] = [];\n let resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null = null;\n\n Promise.all(\n pathArray.map((path) =>\n setupNodeFsWatcher(path, {\n recursive,\n closed: () => closed,\n signal,\n eventQueue,\n getResolver: () => resolver,\n setResolver: (r) => {\n resolver = r;\n },\n watchers,\n onError: (error, path) => serverLogger.error(`File watcher error for ${path}:`, error),\n })\n ),\n ).catch((error) => {\n serverLogger.error(\"Failed to setup file watchers:\", error);\n });\n\n const iterator = createWatcherIterator(\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n () => closed,\n () => signal?.aborted ?? false,\n );\n\n const cleanup = () => {\n closed = true;\n watchers.forEach((watcher) => {\n try {\n watcher.close();\n } catch (error) {\n serverLogger.debug(\"Error closing file watcher during cleanup:\", error);\n }\n });\n if (resolver) {\n resolver({ done: true, value: undefined });\n resolver = null;\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return createFileWatcher(iterator, cleanup);\n }\n}\n", "import process from \"node:process\";\nimport type { EnvironmentAdapter } from \"../base.ts\";\n\nexport class NodeEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return process.env[key];\n }\n\n set(key: string, value: string): void {\n process.env[key] = value;\n }\n\n toObject(): Record<string, string> {\n return { ...process.env } as Record<string, string>;\n }\n}\n", "import type { ServeOptions, Server } from \"../base.ts\";\nimport type { NodeHttpServer, WSWebSocket, WSWebSocketServer } from \"./types.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\n\n// Track pending WebSocket upgrades by request ID\nconst pendingWebSocketUpgrades = new Map<string, {\n resolve: (ws: WSWebSocket) => void;\n reject: (error: Error) => void;\n}>();\n\n// Singleton WebSocket server instance (one per HTTP server)\nlet wsServer: WSWebSocketServer | null = null;\n\nexport class NodeServer implements Server {\n constructor(\n private server: NodeHttpServer,\n private hostname: string,\n private port: number,\n ) {}\n\n stop(): Promise<void> {\n return new Promise((resolve) => {\n // Close WebSocket server first\n if (wsServer) {\n wsServer.close();\n wsServer = null;\n }\n this.server.close(() => resolve());\n });\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\n/**\n * Create a request ID for matching WebSocket upgrades\n */\nfunction createRequestId(req: { headers: Record<string, string | string[] | undefined> }): string {\n const key = req.headers[\"sec-websocket-key\"];\n return typeof key === \"string\" ? key : (Array.isArray(key) ? key[0] : \"\") || crypto.randomUUID();\n}\n\n/**\n * Register a pending WebSocket upgrade\n * Called by NodeServerAdapter.upgradeWebSocket\n */\nexport function registerWebSocketUpgrade(requestId: string): Promise<WSWebSocket> {\n return new Promise((resolve, reject) => {\n pendingWebSocketUpgrades.set(requestId, { resolve, reject });\n // Cleanup after timeout (30 seconds)\n setTimeout(() => {\n if (pendingWebSocketUpgrades.has(requestId)) {\n pendingWebSocketUpgrades.delete(requestId);\n reject(new Error(\"WebSocket upgrade timed out\"));\n }\n }, 30000);\n });\n}\n\nexport async function createNodeServer(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n const { createServer } = await import(\"node:http\");\n\n const server = createServer(async (_req, _res) => {\n try {\n const url = new URL(_req.url || \"/\", `http://${_req.headers.host || hostname}`);\n const body = _req.method === \"GET\" || _req.method === \"HEAD\" ? null : _req;\n\n const headersRecord: Record<string, string> = {};\n for (const [key, value] of Object.entries(_req.headers)) {\n if (typeof value === \"string\") {\n headersRecord[key] = value;\n } else if (Array.isArray(value)) {\n headersRecord[key] = value[0] || \"\";\n }\n }\n\n // Node.js 18+ requires duplex: \"half\" when creating a Request with a streaming body\n const requestInit: RequestInit & { duplex?: string } = {\n method: _req.method,\n headers: headersRecord,\n body: body as BodyInit | null,\n };\n // Only add duplex for requests with a body (POST, PUT, PATCH, etc.)\n if (body !== null) {\n requestInit.duplex = \"half\";\n }\n const request = new Request(url.toString(), requestInit);\n\n const response = await handler(request);\n\n // Check if this is a WebSocket upgrade response (status 101)\n // The actual WebSocket handling is done in the 'upgrade' event\n if (response.status === 101) {\n // Don't end the response - the upgrade handler will take over\n return;\n }\n\n _res.statusCode = response.status;\n _res.statusMessage = response.statusText;\n\n response.headers.forEach((value, key) => {\n _res.setHeader(key, value);\n });\n\n if (response.body) {\n const reader = response.body.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n _res.write(value);\n }\n }\n\n _res.end();\n } catch (_error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"Request handler error:\", _error);\n _res.statusCode = 500;\n _res.end(\"Internal Server Error\");\n }\n });\n\n // Handle WebSocket upgrades\n server.on(\"upgrade\", async (request, socket, head) => {\n try {\n // Lazy load ws package\n const { WebSocketServer } = await import(\"ws\");\n\n // Create WebSocket server if not exists\n if (!wsServer) {\n wsServer = new WebSocketServer({ noServer: true }) as unknown as WSWebSocketServer;\n }\n\n // Get request ID to match with pending upgrade\n const requestId = createRequestId(request);\n\n // Handle the upgrade\n (wsServer as unknown as {\n handleUpgrade: (\n req: unknown,\n socket: unknown,\n head: unknown,\n callback: (ws: WSWebSocket) => void,\n ) => void;\n })\n .handleUpgrade(request, socket, head, (ws: WSWebSocket) => {\n const pending = pendingWebSocketUpgrades.get(requestId);\n if (pending) {\n pendingWebSocketUpgrades.delete(requestId);\n pending.resolve(ws);\n }\n // Emit connection event\n (wsServer as unknown as { emit: (event: string, ws: WSWebSocket, req: unknown) => void })\n .emit(\"connection\", ws, request);\n });\n } catch (error) {\n const { serverLogger } = await import(\"@veryfront/utils\");\n serverLogger.error(\"WebSocket upgrade error:\", error);\n socket.destroy();\n }\n });\n\n if (options.signal) {\n options.signal.addEventListener(\"abort\", () => {\n if (wsServer) {\n wsServer.close();\n wsServer = null;\n }\n server.close();\n });\n }\n\n return new Promise((resolve) => {\n server.listen(port, hostname, () => {\n onListen?.({ hostname, port });\n resolve(new NodeServer(server as unknown as NodeHttpServer, hostname, port));\n });\n });\n}\n", "import type { ServerAdapter, WebSocketUpgrade } from \"../base.ts\";\nimport type { WSMessageData, WSWebSocket } from \"./types.ts\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\nimport { registerWebSocketUpgrade } from \"./http-server.ts\";\nimport * as crypto from \"node:crypto\";\n\nexport class NodeServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const key = request.headers.get(\"sec-websocket-key\");\n const protocol = request.headers.get(\"sec-websocket-protocol\");\n\n if (!key) {\n throw toError(createError({\n type: \"network\",\n message: \"Missing Sec-WebSocket-Key header\",\n }));\n }\n\n // Create a proxy WebSocket that will be connected when the upgrade completes\n const socket = new NodeWebSocket();\n\n // Register the upgrade and connect when complete\n registerWebSocketUpgrade(key).then((ws) => {\n socket._attachRealSocket(ws);\n }).catch((error) => {\n serverLogger.error(\"WebSocket upgrade failed:\", error);\n socket._emitError(error);\n });\n\n // Return 101 response - the http-server upgrade handler will complete the handshake\n const response = new Response(null, {\n status: 101,\n statusText: \"Switching Protocols\",\n headers: {\n \"Upgrade\": \"websocket\",\n \"Connection\": \"Upgrade\",\n \"Sec-WebSocket-Accept\": this.generateAcceptKey(key),\n ...(protocol ? { \"Sec-WebSocket-Protocol\": protocol } : {}),\n },\n });\n\n return { socket: socket as unknown as WebSocket, response };\n }\n\n private generateAcceptKey(key: string): string {\n const GUID = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\n return crypto.createHash(\"sha1\").update(key + GUID).digest(\"base64\");\n }\n}\n\n/**\n * NodeWebSocket - A WebSocket wrapper that works with Node.js\n * Proxies to the real ws WebSocket once the upgrade completes\n */\nexport class NodeWebSocket {\n private ws: WSWebSocket | null = null;\n public readyState = 0; // CONNECTING\n\n public onopen: ((event: Event) => void) | null = null;\n public onclose: ((event: CloseEvent) => void) | null = null;\n public onerror: ((event: Event) => void) | null = null;\n public onmessage: ((event: MessageEvent) => void) | null = null;\n\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n\n // Queue messages sent before the socket is ready\n private pendingMessages: Array<string | ArrayBuffer> = [];\n\n /**\n * Attach the real WebSocket after upgrade completes\n * Called by NodeServerAdapter\n */\n _attachRealSocket(ws: WSWebSocket) {\n this.ws = ws;\n this.readyState = 1; // OPEN\n\n // Set up event handlers\n ws.on(\"open\", () => {\n this.readyState = 1;\n this.onopen?.(new Event(\"open\"));\n });\n\n ws.on(\"message\", (data: WSMessageData) => {\n this.onmessage?.(new MessageEvent(\"message\", { data: data.toString() }));\n });\n\n ws.on(\"close\", () => {\n this.readyState = 3;\n this.onclose?.(new CloseEvent(\"close\"));\n });\n\n ws.on(\"error\", (error: Error) => {\n this.onerror?.(new ErrorEvent(\"error\", { error }));\n });\n\n // Send any pending messages\n for (const msg of this.pendingMessages) {\n ws.send(msg);\n }\n this.pendingMessages = [];\n\n // The socket is already open when we get it from handleUpgrade\n this.onopen?.(new Event(\"open\"));\n }\n\n /**\n * Emit an error when upgrade fails\n * Called by NodeServerAdapter\n */\n _emitError(error: Error) {\n this.readyState = 3; // CLOSED\n this.onerror?.(new ErrorEvent(\"error\", { error }));\n }\n\n send(data: string | ArrayBuffer) {\n if (this.ws && this.readyState === 1) {\n this.ws.send(data);\n } else if (this.readyState === 0) {\n // Queue the message until the socket is ready\n this.pendingMessages.push(data);\n } else {\n throw toError(createError({\n type: \"network\",\n message: \"WebSocket is not open\",\n }));\n }\n }\n\n close(code?: number, reason?: string) {\n if (this.ws) {\n this.ws.close(code, reason);\n }\n this.readyState = 2; // CLOSING\n }\n\n // WebSocket standard interface\n addEventListener(type: string, listener: EventListener) {\n switch (type) {\n case \"open\":\n this.onopen = listener as (event: Event) => void;\n break;\n case \"close\":\n this.onclose = listener as (event: CloseEvent) => void;\n break;\n case \"error\":\n this.onerror = listener as (event: Event) => void;\n break;\n case \"message\":\n this.onmessage = listener as (event: MessageEvent) => void;\n break;\n }\n }\n\n removeEventListener(_type: string, _listener: EventListener) {\n // Simplified - just null out the handler\n switch (_type) {\n case \"open\":\n this.onopen = null;\n break;\n case \"close\":\n this.onclose = null;\n break;\n case \"error\":\n this.onerror = null;\n break;\n case \"message\":\n this.onmessage = null;\n break;\n }\n }\n}\n", "import type {\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n ServeOptions,\n Server,\n} from \"../base.ts\";\nimport { NodeFileSystemAdapter } from \"./filesystem-adapter.ts\";\nimport { NodeEnvironmentAdapter } from \"./environment-adapter.ts\";\nimport { NodeServerAdapter } from \"./websocket-adapter.ts\";\nimport { createNodeServer } from \"./http-server.ts\";\n\nexport class NodeAdapter implements RuntimeAdapter {\n readonly id = \"node\" as const;\n readonly name = \"node\";\n /** @deprecated Use `id` instead */\n readonly platform = \"node\" as const;\n\n fs = new NodeFileSystemAdapter();\n env = new NodeEnvironmentAdapter();\n server = new NodeServerAdapter();\n\n readonly capabilities: RuntimeCapabilities = {\n typescript: false, // Requires compilation\n jsx: false, // Requires compilation\n http2: true,\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: false,\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: true,\n workers: true,\n jsx: false,\n typescript: false,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n return createNodeServer(handler, options);\n }\n}\n\nexport const nodeAdapter = new NodeAdapter();\n", "export { NodeAdapter, nodeAdapter } from \"./adapter.ts\";\nexport { NodeFileSystemAdapter } from \"./filesystem-adapter.ts\";\nexport { NodeEnvironmentAdapter } from \"./environment-adapter.ts\";\nexport { NodeServerAdapter, NodeWebSocket } from \"./websocket-adapter.ts\";\nexport { createNodeServer, NodeServer } from \"./http-server.ts\";\nexport type {\n NodeHttpServer,\n NodeIncomingMessage,\n NodeServerResponse,\n WSMessageData,\n WSWebSocket,\n} from \"./types.ts\";\n", "export {\n createNodeServer,\n NodeAdapter,\n nodeAdapter,\n NodeEnvironmentAdapter,\n NodeFileSystemAdapter,\n NodeServer,\n NodeServerAdapter,\n NodeWebSocket,\n} from \"./node/index.ts\";\n\nexport type {\n NodeHttpServer,\n NodeIncomingMessage,\n NodeServerResponse,\n WSMessageData,\n WSWebSocket,\n} from \"./node/index.ts\";\n", "export enum ErrorCode {\n FILE_NOT_FOUND = \"FILE_NOT_FOUND\",\n BUILD_ERROR = \"BUILD_ERROR\",\n CONFIG_ERROR = \"CONFIG_ERROR\",\n COMPILATION_ERROR = \"COMPILATION_ERROR\",\n NETWORK_ERROR = \"NETWORK_ERROR\",\n PERMISSION_ERROR = \"PERMISSION_ERROR\",\n RENDER_ERROR = \"RENDER_ERROR\",\n INITIALIZATION_ERROR = \"INITIALIZATION_ERROR\",\n AGENT_ERROR = \"AGENT_ERROR\",\n AGENT_NOT_FOUND = \"AGENT_NOT_FOUND\",\n AGENT_TIMEOUT = \"AGENT_TIMEOUT\",\n AGENT_INTENT_ERROR = \"AGENT_INTENT_ERROR\",\n ORCHESTRATION_ERROR = \"ORCHESTRATION_ERROR\",\n NOT_SUPPORTED = \"NOT_SUPPORTED\",\n}\n\nexport class VeryfrontError extends Error {\n public code: ErrorCode;\n public context?: unknown;\n\n constructor(message: string, code: ErrorCode, context?: unknown) {\n super(message);\n this.name = \"VeryfrontError\";\n this.code = code;\n this.context = context;\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class AgentError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_ERROR, context);\n this.name = \"AgentError\";\n }\n}\n\nexport class AgentNotFoundError extends VeryfrontError {\n constructor(agentId: string, context?: unknown) {\n super(`Agent with ID '${agentId}' not found`, ErrorCode.AGENT_NOT_FOUND, {\n agentId,\n ...(context as Record<string, unknown> | undefined),\n });\n this.name = \"AgentNotFoundError\";\n }\n}\n\nexport class AgentTimeoutError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_TIMEOUT, context);\n this.name = \"AgentTimeoutError\";\n }\n}\n\nexport class AgentIntentError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.AGENT_INTENT_ERROR, context);\n this.name = \"AgentIntentError\";\n }\n}\n\nexport class OrchestrationError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.ORCHESTRATION_ERROR, context);\n this.name = \"OrchestrationError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class BuildError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.BUILD_ERROR, context);\n this.name = \"BuildError\";\n }\n}\n\nexport class CompilationError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.COMPILATION_ERROR, context);\n this.name = \"CompilationError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class RuntimeError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.RENDER_ERROR, context);\n this.name = \"RuntimeError\";\n }\n}\n\nexport class RenderError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.RENDER_ERROR, context);\n this.name = \"RenderError\";\n }\n}\n", "import { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport class FileSystemError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.FILE_NOT_FOUND, context);\n this.name = \"FileSystemError\";\n }\n}\n\nexport class ConfigError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.CONFIG_ERROR, context);\n this.name = \"ConfigError\";\n }\n}\n\nexport class NetworkError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.NETWORK_ERROR, context);\n this.name = \"NetworkError\";\n }\n}\n\nexport class PermissionError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.PERMISSION_ERROR, context);\n this.name = \"PermissionError\";\n }\n}\n\nexport class NotSupportedError extends VeryfrontError {\n constructor(message: string, context?: unknown) {\n super(message, ErrorCode.NOT_SUPPORTED, context);\n this.name = \"NotSupportedError\";\n }\n}\n", "import { serverLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { ErrorCode, VeryfrontError } from \"./types.ts\";\n\n/** Default max retries for retry operations */\nconst DEFAULT_MAX_RETRIES = 3;\n\n/** Default initial delay for exponential backoff (100ms) */\nconst DEFAULT_INITIAL_DELAY_MS = 100;\n\n/** Default max delay cap for exponential backoff (5 seconds) */\nconst DEFAULT_MAX_DELAY_MS = 5000;\n\nfunction safeLog(logFn: () => void): void {\n try {\n logFn();\n } catch (error) {\n try {\n serverLogger.warn(\"[errors] Logging failed:\", error);\n } catch {\n // Silently ignore if even warning fails\n }\n }\n}\n\nexport function handleError(error: Error): void {\n safeLog(() => serverLogger.error(`Error: ${error.message}`));\n\n if (error instanceof VeryfrontError && error.context) {\n safeLog(() => serverLogger.error(\"Context:\", error.context));\n }\n\n if (error.stack) {\n safeLog(() => serverLogger.error(error.stack as string));\n }\n}\n\nexport function wrapError(\n error: unknown,\n message: string,\n context?: unknown,\n): VeryfrontError {\n const originalError = error instanceof Error ? error : new Error(String(error));\n const errorMessage = `${message}: ${originalError.message}`;\n\n const wrappedContext = {\n originalError: {\n name: originalError.name,\n message: originalError.message,\n stack: originalError.stack,\n },\n ...(context as Record<string, unknown> | undefined),\n };\n\n const errorCode = error instanceof VeryfrontError ? error.code : ErrorCode.RENDER_ERROR;\n\n return new VeryfrontError(errorMessage, errorCode, wrappedContext);\n}\n\nexport function logAndThrow(\n error: unknown,\n message?: string,\n logger: typeof serverLogger = serverLogger,\n): never {\n const errorObj = error instanceof Error ? error : new Error(String(error));\n const logMessage = message ? `${message}: ${errorObj.message}` : errorObj.message;\n\n safeLog(() => logger.error(logMessage, error));\n\n if (error instanceof Error) {\n throw error;\n }\n throw errorObj;\n}\n\nexport async function handleErrorWithFallback<T>(\n fn: () => T | Promise<T>,\n fallback: T,\n logger: typeof serverLogger = serverLogger,\n): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n safeLog(() => logger.warn(\"Operation failed, using fallback\", error));\n return fallback;\n }\n}\n\nexport function handleErrorWithFallbackSync<T>(\n fn: () => T,\n fallback: T,\n logger: typeof serverLogger = serverLogger,\n): T {\n try {\n return fn();\n } catch (error) {\n safeLog(() => logger.warn(\"Operation failed, using fallback\", error));\n return fallback;\n }\n}\n\nexport async function retryWithBackoff<T>(\n fn: () => Promise<T>,\n options: {\n maxRetries?: number;\n initialDelay?: number;\n maxDelay?: number;\n logger?: typeof serverLogger;\n } = {},\n): Promise<T> {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n initialDelay = DEFAULT_INITIAL_DELAY_MS,\n maxDelay = DEFAULT_MAX_DELAY_MS,\n logger: log = serverLogger,\n } = options;\n\n let lastError: unknown;\n let delay = initialDelay;\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n safeLog(() => log.warn(`Attempt ${attempt + 1} failed, retrying...`, error));\n\n if (attempt < maxRetries - 1) {\n await new Promise((resolve) => setTimeout(resolve, delay));\n delay = Math.min(delay * 2, maxDelay);\n }\n }\n }\n\n throw lastError;\n}\n", "export const ErrorCode = {\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\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\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\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\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\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\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\n DEV_SERVER_ERROR: \"VF700\",\n FAST_REFRESH_ERROR: \"VF701\",\n ERROR_OVERLAY_ERROR: \"VF702\",\n SOURCE_MAP_ERROR: \"VF703\",\n\n DEPLOYMENT_ERROR: \"VF800\",\n PLATFORM_ERROR: \"VF801\",\n ENV_VAR_MISSING: \"VF802\",\n PRODUCTION_BUILD_REQUIRED: \"VF803\",\n\n UNKNOWN_ERROR: \"VF900\",\n PERMISSION_DENIED: \"VF901\",\n FILE_NOT_FOUND: \"VF902\",\n INVALID_ARGUMENT: \"VF903\",\n TIMEOUT_ERROR: \"VF904\",\n} as const;\n\nexport type ErrorCodeType = typeof ErrorCode[keyof typeof ErrorCode];\n\nexport function getErrorDocsUrl(code: ErrorCodeType): string {\n return `https://veryfront.com/docs/errors/${code}`;\n}\n\nexport function inferErrorCode(error: Error): ErrorCodeType | null {\n const message = error.message.toLowerCase();\n\n if (message.includes(\"config\") && message.includes(\"not found\")) {\n return ErrorCode.CONFIG_NOT_FOUND;\n }\n if (message.includes(\"config\") && message.includes(\"invalid\")) return ErrorCode.CONFIG_INVALID;\n if (message.includes(\"cors\")) return ErrorCode.CORS_CONFIG_INVALID;\n\n if (message.includes(\"route\") && message.includes(\"conflict\")) return ErrorCode.ROUTE_CONFLICT;\n if (message.includes(\"route\") && message.includes(\"invalid\")) return ErrorCode.INVALID_ROUTE_FILE;\n\n if (message.includes(\"client\") && message.includes(\"boundary\")) {\n return ErrorCode.CLIENT_BOUNDARY_VIOLATION;\n }\n if (message.includes(\"server-only\") && message.includes(\"client\")) {\n return ErrorCode.SERVER_ONLY_IN_CLIENT;\n }\n\n if (message.includes(\"module not found\") || message.includes(\"cannot find module\")) {\n return ErrorCode.MODULE_NOT_FOUND;\n }\n if (message.includes(\"import\") || message.includes(\"resolve\")) {\n return ErrorCode.IMPORT_RESOLUTION_ERROR;\n }\n if (message.includes(\"react\") && message.includes(\"not found\")) {\n return ErrorCode.DEPENDENCY_MISSING;\n }\n\n if (message.includes(\"port\") && (message.includes(\"in use\") || message.includes(\"eaddrinuse\"))) {\n return ErrorCode.PORT_IN_USE;\n }\n if (message.includes(\"hydration\")) return ErrorCode.HYDRATION_MISMATCH;\n\n if (message.includes(\"build\") && message.includes(\"fail\")) return ErrorCode.BUILD_FAILED;\n if (message.includes(\"mdx\")) return ErrorCode.MDX_COMPILE_ERROR;\n if (message.includes(\"typescript\")) return ErrorCode.TYPESCRIPT_ERROR;\n\n return null;\n}\n", "import type { ErrorCodeType } from \"../error-codes.ts\";\nimport { getErrorDocsUrl } from \"../error-codes.ts\";\nimport type { ErrorSolution } from \"./types.ts\";\n\nexport function createErrorSolution(\n code: ErrorCodeType,\n config: Omit<ErrorSolution, \"code\" | \"docs\"> & { docs?: string },\n): ErrorSolution {\n return {\n code,\n ...config,\n docs: config.docs ?? getErrorDocsUrl(code),\n };\n}\n\nexport function createSimpleError(\n code: ErrorCodeType,\n title: string,\n message: string,\n steps: string[],\n): ErrorSolution {\n return createErrorSolution(code, { title, message, steps });\n}\n", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const CONFIG_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.CONFIG_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.CONFIG_INVALID]: createErrorSolution(ErrorCode.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\n [ErrorCode.CONFIG_PARSE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CONFIG_VALIDATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CONFIG_TYPE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.IMPORT_MAP_INVALID]: createErrorSolution(ErrorCode.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\n [ErrorCode.CORS_CONFIG_INVALID]: createErrorSolution(ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const BUILD_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.BUILD_FAILED]: createErrorSolution(ErrorCode.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\n [ErrorCode.BUNDLE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.TYPESCRIPT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.MDX_COMPILE_ERROR]: createErrorSolution(ErrorCode.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\n [ErrorCode.ASSET_OPTIMIZATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SSG_GENERATION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SOURCEMAP_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const RUNTIME_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.HYDRATION_MISMATCH]: createErrorSolution(ErrorCode.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: [ErrorCode.RENDER_ERROR],\n }),\n\n [ErrorCode.RENDER_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.COMPONENT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.LAYOUT_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.PAGE_NOT_FOUND]: createSimpleError(\n ErrorCode.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\n [ErrorCode.API_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.MIDDLEWARE_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const ROUTE_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.ROUTE_CONFLICT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_ROUTE_FILE]: createErrorSolution(ErrorCode.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\n [ErrorCode.ROUTE_HANDLER_INVALID]: createSimpleError(\n ErrorCode.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\n [ErrorCode.DYNAMIC_ROUTE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ROUTE_PARAMS_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.API_ROUTE_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const MODULE_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.MODULE_NOT_FOUND]: createErrorSolution(ErrorCode.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\n [ErrorCode.IMPORT_RESOLUTION_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CIRCULAR_DEPENDENCY]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_IMPORT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.DEPENDENCY_MISSING]: createErrorSolution(ErrorCode.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\n [ErrorCode.VERSION_MISMATCH]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const SERVER_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.PORT_IN_USE]: createErrorSolution(ErrorCode.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\n [ErrorCode.SERVER_START_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.HMR_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CACHE_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FILE_WATCH_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.REQUEST_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport const RSC_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.CLIENT_BOUNDARY_VIOLATION]: createErrorSolution(\n ErrorCode.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\n [ErrorCode.SERVER_ONLY_IN_CLIENT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.CLIENT_ONLY_IN_SERVER]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_USE_CLIENT]: createErrorSolution(ErrorCode.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\n [ErrorCode.INVALID_USE_SERVER]: createSimpleError(\n ErrorCode.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\n [ErrorCode.RSC_PAYLOAD_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const DEV_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.DEV_SERVER_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FAST_REFRESH_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ERROR_OVERLAY_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.SOURCE_MAP_ERROR]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const DEPLOYMENT_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.DEPLOYMENT_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PLATFORM_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.ENV_VAR_MISSING]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PRODUCTION_BUILD_REQUIRED]: createSimpleError(\n ErrorCode.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", "import { ErrorCode } from \"../error-codes.ts\";\nimport type { PartialErrorCatalog } from \"./types.ts\";\nimport { createSimpleError } from \"./factory.ts\";\n\nexport const GENERAL_ERROR_CATALOG: PartialErrorCatalog = {\n [ErrorCode.UNKNOWN_ERROR]: createSimpleError(\n ErrorCode.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\n [ErrorCode.PERMISSION_DENIED]: createSimpleError(\n ErrorCode.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\n [ErrorCode.FILE_NOT_FOUND]: createSimpleError(\n ErrorCode.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\n [ErrorCode.INVALID_ARGUMENT]: createSimpleError(\n ErrorCode.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\n [ErrorCode.TIMEOUT_ERROR]: createSimpleError(\n ErrorCode.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", "import type { ErrorCodeType } from \"../error-codes.ts\";\nimport type { ErrorCatalog, ErrorSolution } from \"./types.ts\";\n\nimport { CONFIG_ERROR_CATALOG } from \"./config-errors.ts\";\nimport { BUILD_ERROR_CATALOG } from \"./build-errors.ts\";\nimport { RUNTIME_ERROR_CATALOG } from \"./runtime-errors.ts\";\nimport { ROUTE_ERROR_CATALOG } from \"./route-errors.ts\";\nimport { MODULE_ERROR_CATALOG } from \"./module-errors.ts\";\nimport { SERVER_ERROR_CATALOG } from \"./server-errors.ts\";\nimport { RSC_ERROR_CATALOG } from \"./rsc-errors.ts\";\nimport { DEV_ERROR_CATALOG } from \"./dev-errors.ts\";\nimport { DEPLOYMENT_ERROR_CATALOG } from \"./deployment-errors.ts\";\nimport { GENERAL_ERROR_CATALOG } from \"./general-errors.ts\";\n\nexport const 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} as ErrorCatalog;\n\nexport function getErrorSolution(code: ErrorCodeType): ErrorSolution | null {\n return ERROR_CATALOG[code] || null;\n}\n\nexport function searchErrors(query: string): ErrorSolution[] {\n const lowerQuery = query.toLowerCase();\n return Object.values(ERROR_CATALOG).filter(\n (error) =>\n error.title.toLowerCase().includes(lowerQuery) ||\n error.message.toLowerCase().includes(lowerQuery) ||\n error.steps?.some((step) => step.toLowerCase().includes(lowerQuery)),\n );\n}\n\nexport type { ErrorCatalog, ErrorSolution, PartialErrorCatalog } from \"./types.ts\";\n\nexport { createErrorSolution, createSimpleError } from \"./factory.ts\";\n\nexport {\n BUILD_ERROR_CATALOG,\n CONFIG_ERROR_CATALOG,\n DEPLOYMENT_ERROR_CATALOG,\n DEV_ERROR_CATALOG,\n GENERAL_ERROR_CATALOG,\n MODULE_ERROR_CATALOG,\n ROUTE_ERROR_CATALOG,\n RSC_ERROR_CATALOG,\n RUNTIME_ERROR_CATALOG,\n SERVER_ERROR_CATALOG,\n};\n", "export interface ErrorSolution {\n message: string;\n steps?: string[];\n example?: string;\n docs?: string;\n}\n\nexport const ERROR_SOLUTIONS: Record<string, ErrorSolution> = {\n \"missing-config\": {\n message: \"No veryfront.config.js found in project directory\",\n steps: [\n \"Create a veryfront.config.js file in your project root\",\n \"Run 'veryfront init' to generate a default config\",\n \"Or create one manually with minimal configuration\",\n ],\n example: `export default {\n title: \"My App\",\n dev: { port: 3002 }\n};`,\n },\n\n \"invalid-config\": {\n message: \"Invalid configuration in veryfront.config.js\",\n steps: [\n \"Check that your config exports a default object\",\n \"Ensure all values are valid JavaScript\",\n \"Remove any trailing commas in objects\",\n ],\n example: `export default {\n title: \"My App\", // \u2713 Valid string\n dev: {\n port: 3002, // \u2713 Valid number\n open: true // \u2713 No trailing comma\n }\n};`,\n },\n\n \"invalid-route\": {\n message: \"Invalid route file format\",\n steps: [\n \"Route files must export handler functions (GET, POST, etc.)\",\n \"Each handler must return a Response object\",\n \"Check for syntax errors in your route file\",\n ],\n example: `// app/api/users/route.ts\nexport async function GET() {\n return Response.json({ users: [] });\n}\n\nexport async function POST(request: Request) {\n const body = await request.json();\n return Response.json({ created: true });\n}`,\n },\n\n \"client-boundary\": {\n message: \"Server-only code used in Client Component\",\n steps: [\n \"Move server-only imports to Server Components\",\n \"Use 'use server' directive for server actions\",\n \"Split component into server and client parts\",\n ],\n example: `// \u274C Wrong - database import in client component\n'use client';\nimport { db } from './database'; // Error!\n\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}`,\n docs: \"https://github.com/veryfront/veryfront/docs/rsc-boundaries\",\n },\n\n \"import-not-found\": {\n message: \"Failed to resolve import\",\n steps: [\n \"Check that the file path is correct\",\n \"Ensure the module is installed or available\",\n \"For remote imports, check network connectivity\",\n \"Add missing imports to veryfront.config.js importMap\",\n ],\n example: `// veryfront.config.js\nresolve: {\n importMap: {\n imports: {\n \"my-lib\": \"https://esm.sh/my-lib@1.0.0\",\n \"@/utils\": \"./src/utils/index.ts\"\n }\n }\n}`,\n },\n\n \"port-in-use\": {\n message: \"Port is already in use\",\n steps: [\n \"Stop any other servers running on this port\",\n \"Use a different port with --port flag\",\n \"Check for zombie processes: lsof -i :PORT\",\n ],\n example: `veryfront dev --port 3003`,\n },\n\n \"build-failed\": {\n message: \"Build failed with errors\",\n steps: [\n \"Check the error messages above for details\",\n \"Fix any TypeScript or syntax errors\",\n \"Ensure all imports can be resolved\",\n \"Run 'veryfront doctor' to check system\",\n ],\n },\n\n \"missing-deps\": {\n message: \"Required dependencies not found\",\n steps: [\n \"Check that React is in your import map\",\n \"Ensure all peer dependencies are included\",\n \"Run 'veryfront doctor' to verify setup\",\n ],\n example: `// Minimum required imports\n\"react\": \"https://esm.sh/react@19.1.1\",\n\"react-dom\": \"https://esm.sh/react-dom@19.1.1\"`,\n },\n};\n", "/**\n * Pure ANSI escape code colors for npm/Node.js builds\n *\n * This file provides a zero-dependency color implementation using ANSI codes.\n * It's used in npm builds where std/fmt/colors.ts isn't available.\n */\n\nimport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nconst ansi = (open: number, close: number): ColorFunction => (text: string) =>\n `\\x1b[${open}m${text}\\x1b[${close}m`;\n\nexport const red: ColorFunction = ansi(31, 39);\nexport const green: ColorFunction = ansi(32, 39);\nexport const yellow: ColorFunction = ansi(33, 39);\nexport const blue: ColorFunction = ansi(34, 39);\nexport const magenta: ColorFunction = ansi(35, 39);\nexport const cyan: ColorFunction = ansi(36, 39);\nexport const white: ColorFunction = ansi(37, 39);\nexport const gray: ColorFunction = ansi(90, 39);\nexport const bold: ColorFunction = ansi(1, 22);\nexport const dim: ColorFunction = ansi(2, 22);\nexport const italic: ColorFunction = ansi(3, 23);\nexport const underline: ColorFunction = ansi(4, 24);\nexport const strikethrough: ColorFunction = ansi(9, 29);\nexport const reset: ColorFunction = (text: string) => `\\x1b[0m${text}`;\n\nexport const colors: ConsoleStyler = {\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 * Deno console styling implementation using std/fmt/colors.ts\n */\n\nimport {\n blue,\n bold,\n cyan,\n dim,\n gray,\n green,\n italic,\n magenta,\n red,\n reset,\n strikethrough,\n underline,\n white,\n yellow,\n} from \"std/fmt/colors.ts\";\n\nimport type { ConsoleStyler } from \"./types.ts\";\n\nexport const colors: ConsoleStyler = {\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\nexport {\n blue,\n bold,\n cyan,\n dim,\n gray,\n green,\n italic,\n magenta,\n red,\n reset,\n strikethrough,\n underline,\n white,\n yellow,\n};\n", "/**\n * Node.js console styling implementation using picocolors\n */\n\nimport type { ConsoleStyler } from \"./types.ts\";\n\n// Lazy-loaded picocolors instance\ntype PicoColors = {\n red: (s: string) => string;\n green: (s: string) => string;\n yellow: (s: string) => string;\n blue: (s: string) => string;\n cyan: (s: string) => string;\n magenta: (s: string) => string;\n white: (s: string) => string;\n gray: (s: string) => string;\n bold: (s: string) => string;\n dim: (s: string) => string;\n italic: (s: string) => string;\n underline: (s: string) => string;\n strikethrough: (s: string) => string;\n reset: (s: string) => string;\n};\n\nlet pc: PicoColors | null = null;\n\nasync function ensurePc(): Promise<PicoColors> {\n if (pc) return pc;\n // Construct module name dynamically to prevent Deno static analyzer\n // from trying to resolve this npm package during lint/check\n const picocolorsModule = [\"npm:\", \"picocolors\"].join(\"\");\n const mod = await import(picocolorsModule);\n pc = mod.default as PicoColors;\n return pc;\n}\n\n// Lazy wrapper that falls back to identity if not loaded\nconst lazyColor = (fn: keyof PicoColors) => (s: string) => pc?.[fn]?.(s) ?? s;\n\nexport const colors: ConsoleStyler = {\n red: lazyColor(\"red\"),\n green: lazyColor(\"green\"),\n yellow: lazyColor(\"yellow\"),\n blue: lazyColor(\"blue\"),\n cyan: lazyColor(\"cyan\"),\n magenta: lazyColor(\"magenta\"),\n white: lazyColor(\"white\"),\n gray: lazyColor(\"gray\"),\n bold: lazyColor(\"bold\"),\n dim: lazyColor(\"dim\"),\n italic: lazyColor(\"italic\"),\n underline: lazyColor(\"underline\"),\n strikethrough: lazyColor(\"strikethrough\"),\n reset: lazyColor(\"reset\"),\n};\n\nexport const red = lazyColor(\"red\");\nexport const green = lazyColor(\"green\");\nexport const yellow = lazyColor(\"yellow\");\nexport const blue = lazyColor(\"blue\");\nexport const cyan = lazyColor(\"cyan\");\nexport const magenta = lazyColor(\"magenta\");\nexport const white = lazyColor(\"white\");\nexport const gray = lazyColor(\"gray\");\nexport const bold = lazyColor(\"bold\");\nexport const dim = lazyColor(\"dim\");\nexport const italic = lazyColor(\"italic\");\nexport const underline = lazyColor(\"underline\");\nexport const strikethrough = lazyColor(\"strikethrough\");\nexport const reset = lazyColor(\"reset\");\n\n// Initialize picocolors on first use\nexport async function initColors(): Promise<void> {\n await ensurePc();\n}\n", "/**\n * Cross-runtime console styling\n *\n * Provides terminal colors that work in Deno, Node.js, and Bun.\n * Falls back to no-op functions in environments without terminal support.\n */\n\nimport { isDeno } from \"../runtime.ts\";\nimport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nexport type { ColorFunction, ConsoleStyler } from \"./types.ts\";\n\nconst noOp: ColorFunction = (text: string) => text;\n\nconst fallbackColors: ConsoleStyler = {\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\nlet _colors: ConsoleStyler | null = null;\n\nasync function loadColors(): Promise<ConsoleStyler> {\n if (_colors) return _colors;\n\n try {\n if (isDeno) {\n const mod = await import(\"./deno.ts\");\n _colors = mod.colors;\n } else {\n const mod = await import(\"./node.ts\");\n _colors = mod.colors;\n }\n } catch {\n _colors = fallbackColors;\n }\n\n return _colors;\n}\n\nconst colorsPromise = loadColors();\n\nfunction getColors(): ConsoleStyler {\n return _colors ?? fallbackColors;\n}\n\nexport const red: ColorFunction = (text) => getColors().red(text);\nexport const green: ColorFunction = (text) => getColors().green(text);\nexport const yellow: ColorFunction = (text) => getColors().yellow(text);\nexport const blue: ColorFunction = (text) => getColors().blue(text);\nexport const cyan: ColorFunction = (text) => getColors().cyan(text);\nexport const magenta: ColorFunction = (text) => getColors().magenta(text);\nexport const white: ColorFunction = (text) => getColors().white(text);\nexport const gray: ColorFunction = (text) => getColors().gray(text);\nexport const bold: ColorFunction = (text) => getColors().bold(text);\nexport const dim: ColorFunction = (text) => getColors().dim(text);\nexport const italic: ColorFunction = (text) => getColors().italic(text);\nexport const underline: ColorFunction = (text) => getColors().underline(text);\nexport const strikethrough: ColorFunction = (text) => getColors().strikethrough(text);\nexport const reset: ColorFunction = (text) => getColors().reset(text);\n\nexport const 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} satisfies ConsoleStyler;\n\nexport { colorsPromise };\n", "export function identifyError(error: Error): string {\n const message = error.message.toLowerCase();\n\n if (message.includes(\"veryfront.config\") && message.includes(\"not found\")) {\n return \"missing-config\";\n }\n if (message.includes(\"config\") && (message.includes(\"invalid\") || message.includes(\"parse\"))) {\n return \"invalid-config\";\n }\n\n if (message.includes(\"route\") && (message.includes(\"invalid\") || message.includes(\"export\"))) {\n return \"invalid-route\";\n }\n\n if (message.includes(\"client\") && (message.includes(\"boundary\") || message.includes(\"server\"))) {\n return \"client-boundary\";\n }\n\n if (\n message.includes(\"import\") ||\n message.includes(\"module not found\") ||\n message.includes(\"resolve\")\n ) {\n return \"import-not-found\";\n }\n\n if (message.includes(\"port\") && (message.includes(\"in use\") || message.includes(\"eaddrinuse\"))) {\n return \"port-in-use\";\n }\n\n if (message.includes(\"build\") && message.includes(\"fail\")) {\n return \"build-failed\";\n }\n\n if (message.includes(\"react\") && message.includes(\"not found\")) {\n return \"missing-deps\";\n }\n\n return \"unknown\";\n}\n", "import { bold, cyan, dim, red, yellow } from \"@veryfront/compat/console\";\nimport { ERROR_SOLUTIONS } from \"./error-catalog.ts\";\nimport { identifyError } from \"./error-identifier.ts\";\n\nexport function formatUserError(error: Error): string {\n const output: string[] = [];\n\n output.push(\"\");\n output.push(red(bold(\"\u2716 Error: \")) + bold(error.message));\n output.push(\"\");\n\n const errorKey = identifyError(error);\n const solution = ERROR_SOLUTIONS[errorKey];\n\n if (solution) {\n if (solution.message) {\n output.push(yellow(\"Problem: \") + solution.message);\n output.push(\"\");\n }\n\n if (solution.steps && solution.steps.length > 0) {\n output.push(cyan(\"How to fix:\"));\n solution.steps.forEach((step, i) => {\n output.push(` ${dim(`${i + 1}.`)} ${step}`);\n });\n output.push(\"\");\n }\n\n if (solution.example) {\n output.push(cyan(\"Example:\"));\n output.push(\"\");\n solution.example.split(\"\\n\").forEach((line) => {\n output.push(` ${dim(line)}`);\n });\n output.push(\"\");\n }\n\n if (solution.docs) {\n output.push(dim(\"Learn more: \") + cyan(solution.docs));\n output.push(\"\");\n }\n } else {\n if (error.stack) {\n output.push(yellow(\"Stack trace:\"));\n const stackLines = error.stack.split(\"\\n\").slice(1, 4);\n stackLines.forEach((line) => {\n output.push(dim(` ${line.trim()}`));\n });\n output.push(\"\");\n }\n\n output.push(dim(\"For help, run: \") + cyan(\"veryfront doctor\"));\n output.push(\"\");\n }\n\n return output.join(\"\\n\");\n}\n", "import { red } from \"@veryfront/compat/console\";\nimport { exit } from \"@veryfront/platform/compat/process.ts\";\nimport { cliLogger } from \"@veryfront/utils/logger/logger.ts\";\nimport { formatUserError } from \"./error-formatter.ts\";\n\nexport function wrapErrorHandler<TArgs extends unknown[], TReturn>(\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn> {\n return async (...args: TArgs): Promise<TReturn> => {\n try {\n return await fn(...args);\n } catch (error) {\n if (error instanceof Error) {\n cliLogger.error(formatUserError(error));\n } else {\n cliLogger.error(red(\"\u2716 Unknown error:\"), error);\n }\n if (import.meta.main) {\n exit(1);\n }\n throw error;\n }\n };\n}\n", "export { ERROR_SOLUTIONS, type ErrorSolution } from \"./error-catalog.ts\";\nexport { formatUserError } from \"./error-formatter.ts\";\nexport { identifyError } from \"./error-identifier.ts\";\nexport { wrapErrorHandler } from \"./error-wrapper.ts\";\n", "export { ErrorCode, VeryfrontError } from \"./types.ts\";\n\nexport {\n AgentError,\n AgentIntentError,\n AgentNotFoundError,\n AgentTimeoutError,\n OrchestrationError,\n} from \"./agent-errors.ts\";\n\nexport { BuildError, CompilationError } from \"./build-errors.ts\";\n\nexport { RenderError, RuntimeError } from \"./runtime-errors.ts\";\n\nexport {\n ConfigError,\n FileSystemError,\n NetworkError,\n NotSupportedError,\n PermissionError,\n} from \"./system-errors.ts\";\n\nexport {\n handleError,\n handleErrorWithFallback,\n handleErrorWithFallbackSync,\n logAndThrow,\n retryWithBackoff,\n wrapError,\n} from \"./error-handlers.ts\";\n\nexport {\n BUILD_ERROR_CATALOG,\n CONFIG_ERROR_CATALOG,\n createErrorSolution,\n createSimpleError,\n DEPLOYMENT_ERROR_CATALOG,\n DEV_ERROR_CATALOG,\n ERROR_CATALOG,\n GENERAL_ERROR_CATALOG,\n getErrorSolution,\n MODULE_ERROR_CATALOG,\n ROUTE_ERROR_CATALOG,\n RSC_ERROR_CATALOG,\n RUNTIME_ERROR_CATALOG,\n searchErrors,\n SERVER_ERROR_CATALOG,\n} from \"./catalog/index.ts\";\n\nexport type { ErrorCatalog, ErrorSolution, PartialErrorCatalog } from \"./catalog/index.ts\";\n\nexport {\n ERROR_SOLUTIONS,\n formatUserError,\n identifyError,\n wrapErrorHandler,\n} from \"./user-friendly/index.ts\";\n\nexport type { ErrorSolution as UserFriendlyErrorSolution } from \"./user-friendly/index.ts\";\n\nexport type { ErrorCodeType } from \"./error-codes.ts\";\n", "import { FileSystemError } from \"@veryfront/errors\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\nimport type {\n DirEntry,\n FileChangeEvent,\n FileChangeKind,\n FileInfo,\n FileSystemAdapter,\n FileWatcher,\n WatchOptions,\n} from \"../base.ts\";\n\nimport { createFileWatcher, createWatcherIterator, enqueueWatchEvent } from \"../shared-watcher.ts\";\nimport type { BunFSWatcher, BunWatchEvent } from \"./types.ts\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nexport class BunFileSystemAdapter implements FileSystemAdapter {\n async readFile(path: string): Promise<string> {\n const file = Bun.file(path);\n return await file.text();\n }\n\n async readFileBytes(path: string): Promise<Uint8Array> {\n const file = Bun.file(path);\n // deno-lint-ignore no-explicit-any\n const buffer = await (file as any).arrayBuffer();\n return new Uint8Array(buffer);\n }\n\n async writeFile(path: string, content: string): Promise<void> {\n await Bun.write(path, content);\n }\n\n async exists(path: string): Promise<boolean> {\n const file = Bun.file(path);\n return await file.exists();\n }\n\n async *readDir(path: string): AsyncIterable<DirEntry> {\n const { readdir } = await import(\"node:fs/promises\");\n const entries = await readdir(path, { withFileTypes: true });\n\n for (const entry of entries) {\n yield {\n name: entry.name,\n isFile: entry.isFile(),\n isDirectory: entry.isDirectory(),\n isSymlink: entry.isSymbolicLink(),\n };\n }\n }\n\n async stat(path: string): Promise<FileInfo> {\n const file = Bun.file(path);\n const exists = await file.exists();\n if (!exists) {\n throw new FileSystemError(`File not found: ${path}`, { path });\n }\n\n const { stat } = await import(\"node:fs/promises\");\n const stats = await stat(path);\n\n return {\n size: file.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymlink: stats.isSymbolicLink(),\n mtime: stats.mtime,\n };\n }\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const { mkdir } = await import(\"node:fs/promises\");\n await mkdir(path, options);\n }\n\n async remove(path: string, options?: { recursive?: boolean }): Promise<void> {\n const { rm } = await import(\"node:fs/promises\");\n await rm(path, { recursive: options?.recursive, force: true });\n }\n\n async makeTempDir(prefix: string): Promise<string> {\n const { mkdtemp } = await import(\"node:fs/promises\");\n const { join } = await import(\"node:path\");\n const { tmpdir } = await import(\"node:os\");\n return await mkdtemp(join(tmpdir(), prefix));\n }\n\n watch(paths: string | string[], options?: WatchOptions): FileWatcher {\n const pathArray = Array.isArray(paths) ? paths : [paths];\n const recursive = options?.recursive ?? true;\n const signal = options?.signal;\n\n let closed = false;\n const watchers: Array<BunFSWatcher | import(\"node:fs\").FSWatcher> = [];\n const eventQueue: FileChangeEvent[] = [];\n let resolver: ((value: IteratorResult<FileChangeEvent>) => void) | null = null;\n\n const mapBunEventKind = (type: string): FileChangeKind => {\n switch (type) {\n case \"create\":\n return \"create\";\n case \"change\":\n return \"modify\";\n case \"delete\":\n return \"delete\";\n default:\n return \"any\";\n }\n };\n\n const setupWatcher = (path: string) => {\n try {\n if (typeof Bun !== \"undefined\" && Bun.watch) {\n const watcher = Bun.watch(path, {\n recursive,\n onChange: (event: BunWatchEvent) => {\n if (closed || signal?.aborted) return;\n\n enqueueWatchEvent(\n { kind: mapBunEventKind(event.type), paths: [event.path] },\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n );\n },\n });\n watchers.push(watcher);\n } else {\n throw toError(createError({\n type: \"not_supported\",\n message: \"Bun.watch is not available in this environment\",\n feature: \"Bun.watch\",\n }));\n }\n } catch (error) {\n serverLogger.error(`Failed to watch ${path}:`, error);\n }\n };\n\n Promise.all(pathArray.map(setupWatcher)).catch((error) => {\n serverLogger.error(\"Failed to setup Bun file watchers:\", error);\n });\n\n const iterator = createWatcherIterator(\n eventQueue,\n () => resolver,\n (r) => {\n resolver = r;\n },\n () => closed,\n () => signal?.aborted ?? false,\n );\n\n const cleanup = () => {\n closed = true;\n watchers.forEach((watcher) => {\n try {\n if (\"stop\" in watcher && typeof watcher.stop === \"function\") {\n watcher.stop();\n } else if (\"close\" in watcher && typeof watcher.close === \"function\") {\n watcher.close();\n }\n } catch (error) {\n serverLogger.debug(\"Error closing Bun file watcher during cleanup:\", error);\n }\n });\n if (resolver) {\n resolver({ done: true, value: undefined });\n resolver = null;\n }\n };\n\n if (signal) {\n signal.addEventListener(\"abort\", cleanup);\n }\n\n return createFileWatcher(iterator, cleanup);\n }\n}\n", "import type { EnvironmentAdapter } from \"../base.ts\";\n\nexport class BunEnvironmentAdapter implements EnvironmentAdapter {\n get(key: string): string | undefined {\n return Bun.env[key];\n }\n\n set(key: string, value: string): void {\n Bun.env[key] = value;\n }\n\n toObject(): Record<string, string> {\n return { ...Bun.env };\n }\n}\n", "import type { ServerAdapter, WebSocketUpgrade } from \"../base.ts\";\nimport { createError, toError } from \"../../../core/errors/veryfront-error.ts\";\n\nexport class BunServerAdapter implements ServerAdapter {\n upgradeWebSocket(request: Request): WebSocketUpgrade {\n const success = Bun.upgrade(request);\n\n if (!success) {\n throw toError(createError({\n type: \"network\",\n message: \"Failed to upgrade WebSocket connection\",\n }));\n }\n\n const socket = new BunWebSocket();\n const response = new Response(null, {\n status: 101,\n statusText: \"Switching Protocols\",\n });\n\n return { socket: socket as unknown as WebSocket, response };\n }\n}\n\nexport class BunWebSocket {\n public readyState = 1;\n\n public onopen: ((event: Event) => void) | null = null;\n public onclose: ((event: Event) => void) | null = null;\n public onerror: ((event: Event) => void) | null = null;\n public onmessage: ((event: MessageEvent) => void) | null = null;\n\n static readonly CONNECTING = 0;\n static readonly OPEN = 1;\n static readonly CLOSING = 2;\n static readonly CLOSED = 3;\n\n send(_data: string | ArrayBuffer) {\n throw toError(createError({\n type: \"network\",\n message: \"WebSocket send called on placeholder - use Bun.serve websocket handlers\",\n }));\n }\n\n close(_code?: number, _reason?: string) {\n this.readyState = 3;\n }\n}\n", "import type { ServeOptions, Server } from \"../base.ts\";\nimport type { BunServer as BunServerType } from \"./types.ts\";\nimport { DEFAULT_PORT } from \"@veryfront/config\";\nimport { serverLogger } from \"@veryfront/utils\";\n\nexport class BunServer implements Server {\n constructor(\n private server: BunServerType,\n private hostname: string,\n private port: number,\n ) {}\n\n stop(): Promise<void> {\n this.server.stop();\n return Promise.resolve();\n }\n\n get addr() {\n return { hostname: this.hostname, port: this.port };\n }\n}\n\nexport function createBunServer(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n): Promise<Server> {\n const { port = DEFAULT_PORT, hostname = \"localhost\", onListen } = options;\n\n const server = Bun.serve({\n port,\n hostname,\n async fetch(request: Request) {\n try {\n return await handler(request);\n } catch (error) {\n serverLogger.error(\"Request handler error:\", error);\n return new Response(\"Internal Server Error\", { status: 500 });\n }\n },\n });\n\n onListen?.({ hostname, port });\n\n return Promise.resolve(new BunServer(server, hostname, port));\n}\n", "import type {\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n ServeOptions,\n Server,\n} from \"../base.ts\";\nimport { BunFileSystemAdapter } from \"./filesystem-adapter.ts\";\nimport { BunEnvironmentAdapter } from \"./environment-adapter.ts\";\nimport { BunServerAdapter } from \"./websocket-adapter.ts\";\nimport { createBunServer } from \"./http-server.ts\";\n\nexport class BunAdapter implements RuntimeAdapter {\n readonly id = \"bun\" as const;\n readonly name = \"bun\";\n /** @deprecated Use `id` instead */\n readonly platform = \"bun\" as const;\n\n fs = new BunFileSystemAdapter();\n env = new BunEnvironmentAdapter();\n server = new BunServerAdapter();\n\n readonly capabilities: RuntimeCapabilities = {\n typescript: true,\n jsx: true,\n http2: false, // Bun's HTTP/2 support is experimental\n websocket: true,\n workers: true,\n fileWatching: true,\n shell: true,\n kvStore: false,\n writableFs: true,\n };\n\n /** @deprecated Use `capabilities` instead */\n readonly features: RuntimeFeatures = {\n websocket: true,\n http2: false,\n workers: true,\n jsx: true,\n typescript: true,\n };\n\n serve(\n handler: (request: Request) => Promise<Response> | Response,\n options: ServeOptions = {},\n ): Promise<Server> {\n return createBunServer(handler, options);\n }\n}\n\nexport const bunAdapter = new BunAdapter();\n", "export { BunAdapter, bunAdapter } from \"./adapter.ts\";\nexport { BunFileSystemAdapter } from \"./filesystem-adapter.ts\";\nexport { BunEnvironmentAdapter } from \"./environment-adapter.ts\";\nexport { BunServerAdapter, BunWebSocket } from \"./websocket-adapter.ts\";\nexport { BunServer, createBunServer } from \"./http-server.ts\";\nexport type {\n BunFile,\n BunFSWatcher,\n BunNamespace,\n BunServeOptions,\n BunServer as BunServerType,\n BunWatchEvent,\n BunWatchOptions,\n} from \"./types.ts\";\n", "export {\n BunAdapter,\n bunAdapter,\n BunEnvironmentAdapter,\n BunFileSystemAdapter,\n BunServer,\n BunServerAdapter,\n BunWebSocket,\n createBunServer,\n} from \"./bun/index.ts\";\n\nexport type {\n BunFile,\n BunFSWatcher,\n BunNamespace,\n BunServeOptions,\n BunServerType,\n BunWatchEvent,\n BunWatchOptions,\n} from \"./bun/index.ts\";\n", "import { createError, toError } from \"../../core/errors/veryfront-error.ts\";\nimport type { RuntimeAdapter } from \"./base.ts\";\n\nexport interface MockRuntimeAdapter extends RuntimeAdapter {\n fs: RuntimeAdapter[\"fs\"] & {\n files: Map<string, string>;\n directories: Set<string>;\n };\n}\n\n/**\n * Mock RuntimeAdapter for testing\n *\n * Provides an in-memory filesystem and environment for unit testing.\n * This adapter is useful for testing code that depends on the filesystem\n * without requiring actual file I/O.\n *\n * @example\n * ```typescript\n * const adapter = createMockAdapter();\n * adapter.fs.files.set(\"/project/pages/index.tsx\", \"export default () => <div>Home</div>\");\n * const content = await adapter.fs.readFile(\"/project/pages/index.tsx\");\n * ```\n */\n\n/**\n * Creates a mock RuntimeAdapter for testing\n *\n * The mock adapter uses in-memory Map and Set for file storage:\n * - `files`: Map<string, string> for file contents\n * - `directories`: Set<string> for tracking directories\n * - `envVars`: Map<string, string> for environment variables\n */\nexport function createMockAdapter(): MockRuntimeAdapter {\n const files = new Map<string, string>();\n const directories = new Set<string>();\n const envVars = new Map<string, string>();\n\n return {\n id: \"memory\" as const,\n name: \"mock\",\n /** @deprecated Use `id` instead */\n platform: \"memory\" as const,\n capabilities: {\n typescript: false,\n jsx: false,\n http2: false,\n websocket: false,\n workers: false,\n fileWatching: false,\n shell: false,\n kvStore: false,\n writableFs: true, // In-memory writes work\n },\n serve: (_handler, _options) => {\n return Promise.resolve({\n stop: () => Promise.resolve(),\n addr: { hostname: \"localhost\", port: 8000 },\n });\n },\n fs: {\n files,\n directories,\n readFile: (path: string) => {\n const content = files.get(path);\n if (!content) {\n throw toError(createError({\n type: \"file\",\n message: `File not found: ${path}`,\n }));\n }\n return Promise.resolve(content);\n },\n readFileBytes: (path: string) => {\n const content = files.get(path);\n if (!content) {\n throw toError(createError({\n type: \"file\",\n message: `File not found: ${path}`,\n }));\n }\n return Promise.resolve(new TextEncoder().encode(content));\n },\n writeFile: (path: string, content: string) => {\n files.set(path, content);\n return Promise.resolve();\n },\n exists: (path: string) => {\n if (files.has(path)) return Promise.resolve(true);\n if (directories.has(path)) return Promise.resolve(true);\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) return Promise.resolve(true);\n }\n return Promise.resolve(false);\n },\n readDir: async function* (path: string) {\n const entries = new Map<string, { isFile: boolean; isDirectory: boolean }>();\n\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) {\n const relativePath = filePath.slice(path.length + 1);\n const parts = relativePath.split(\"/\");\n const name = parts[0]!;\n\n if (!entries.has(name)) {\n entries.set(name, {\n isFile: parts.length === 1,\n isDirectory: parts.length > 1,\n });\n }\n }\n }\n\n for (const [name, meta] of entries.entries()) {\n yield { name, ...meta, isSymlink: false };\n }\n },\n stat: (path: string) => {\n if (files.has(path)) {\n const content = files.get(path)!;\n return Promise.resolve({\n size: content.length,\n isFile: true,\n isDirectory: false,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n\n if (directories.has(path)) {\n return Promise.resolve({\n size: 0,\n isFile: false,\n isDirectory: true,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n\n for (const filePath of files.keys()) {\n if (filePath.startsWith(path + \"/\")) {\n return Promise.resolve({\n size: 0,\n isFile: false,\n isDirectory: true,\n isSymlink: false,\n mtime: new Date(),\n });\n }\n }\n\n return Promise.reject(new Error(`Path not found: ${path}`));\n },\n mkdir: (_path: string) => Promise.resolve(),\n remove: (_path: string) => Promise.resolve(),\n makeTempDir: (prefix: string) =>\n Promise.resolve(`/tmp/${prefix}-${Math.random().toString(36).slice(2)}`),\n watch: () => ({\n async *[Symbol.asyncIterator]() {\n yield { kind: \"any\", paths: [] };\n },\n close: () => {},\n }),\n },\n env: {\n get: (key: string) => envVars.get(key),\n set: (key: string, value: string) => envVars.set(key, value),\n toObject: () => Object.fromEntries(envVars),\n },\n server: {\n upgradeWebSocket: (_request) => {\n throw new Error(\n \"WebSocket upgrade not available in mock adapter. \" +\n \"The mock adapter is designed for unit testing filesystem and environment operations. \" +\n \"For WebSocket testing, use integration tests with the actual Deno/Node/Bun adapter, \" +\n \"or mock the WebSocket behavior at a higher level in your tests.\",\n );\n },\n },\n features: {\n websocket: false,\n http2: false,\n workers: false,\n jsx: false,\n typescript: false,\n },\n };\n}\n", "/**\n * Adapter Registry - Singleton management for RuntimeAdapter\n *\n * Provides a centralized way to access and configure the runtime adapter.\n * Supports auto-detection, manual configuration, and testing overrides.\n *\n * @example\n * ```ts\n * // Auto-detect and get adapter\n * const adapter = await runtime.get();\n *\n * // Manual configuration (e.g., Cloudflare Workers)\n * await runtime.set(createCloudflareAdapter(env));\n *\n * // Testing override\n * await runtime.set(createMockAdapter());\n * ```\n */\n\nimport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\n\ntype AdapterLoader = () => Promise<RuntimeAdapter>;\n\n/**\n * Registry for managing RuntimeAdapter singleton\n */\nclass AdapterRegistry {\n private instance: RuntimeAdapter | null = null;\n private initialized = false;\n private loaders: Map<RuntimeId, AdapterLoader> = new Map();\n\n constructor() {\n // Register default loaders (lazy imports to avoid bundling unused adapters)\n this.loaders.set(\"deno\", async () => {\n const { denoAdapter } = await import(\"./deno.ts\");\n return denoAdapter;\n });\n\n this.loaders.set(\"node\", async () => {\n const { nodeAdapter } = await import(\"./node.ts\");\n return nodeAdapter;\n });\n\n this.loaders.set(\"bun\", async () => {\n const { bunAdapter } = await import(\"./bun.ts\");\n return bunAdapter;\n });\n\n // Note: Cloudflare requires manual initialization with env context\n // this.loaders.set(\"cloudflare\", ...) - not auto-detectable\n\n this.loaders.set(\"memory\", async () => {\n const { createMockAdapter } = await import(\"./mock.ts\");\n return createMockAdapter();\n });\n }\n\n /**\n * Get the current adapter, auto-detecting if needed\n */\n async get(): Promise<RuntimeAdapter> {\n if (this.instance) {\n return this.instance;\n }\n\n // Auto-detect runtime\n const runtimeId = this.detectRuntime();\n const loader = this.loaders.get(runtimeId);\n\n if (!loader) {\n throw new Error(\n `Unsupported runtime: ${runtimeId}. ` +\n `Supported runtimes: ${[...this.loaders.keys()].join(\", \")}. ` +\n `For Cloudflare Workers, use runtime.set(createCloudflareAdapter(env)).`,\n );\n }\n\n this.instance = await loader();\n await this.initialize();\n return this.instance;\n }\n\n /**\n * Manually set the adapter (for Cloudflare Workers, testing, etc.)\n */\n async set(adapter: RuntimeAdapter): Promise<void> {\n // Shutdown existing adapter if any\n if (this.instance && this.initialized) {\n await this.instance.shutdown?.();\n }\n\n this.instance = adapter;\n this.initialized = false;\n await this.initialize();\n }\n\n /**\n * Get adapter synchronously (throws if not initialized)\n */\n getSync(): RuntimeAdapter {\n if (!this.instance) {\n throw new Error(\n \"RuntimeAdapter not initialized. Call `await runtime.get()` first, \" +\n \"or use `await runtime.set(adapter)` to configure manually.\",\n );\n }\n return this.instance;\n }\n\n /**\n * Check if adapter is initialized\n */\n isInitialized(): boolean {\n return this.instance !== null && this.initialized;\n }\n\n /**\n * Reset the registry (for testing)\n */\n async reset(): Promise<void> {\n if (this.instance && this.initialized) {\n await this.instance.shutdown?.();\n }\n this.instance = null;\n this.initialized = false;\n }\n\n /**\n * Register a custom adapter loader\n */\n registerLoader(id: RuntimeId, loader: AdapterLoader): void {\n this.loaders.set(id, loader);\n }\n\n /**\n * Detect current runtime\n */\n private detectRuntime(): RuntimeId {\n // Deno\n if (typeof Deno !== \"undefined\" && typeof Deno.version === \"object\") {\n return \"deno\";\n }\n\n // Bun\n if (\"Bun\" in globalThis) {\n return \"bun\";\n }\n\n // Node.js\n if (typeof process !== \"undefined\" && process.versions?.node) {\n return \"node\";\n }\n\n // Cloudflare Workers (detected but requires manual init)\n if (\"caches\" in globalThis && \"WebSocketPair\" in globalThis) {\n throw new Error(\n \"Cloudflare Workers detected but requires manual initialization. \" +\n \"Use: await runtime.set(createCloudflareAdapter(env))\",\n );\n }\n\n throw new Error(\n \"Unsupported runtime detected. Supported runtimes: deno, node, bun. \" +\n \"For Cloudflare Workers, call runtime.set(createCloudflareAdapter(env)).\",\n );\n }\n\n /**\n * Initialize the adapter\n */\n private async initialize(): Promise<void> {\n if (!this.instance || this.initialized) {\n return;\n }\n\n await this.instance.initialize?.();\n this.initialized = true;\n }\n}\n\n/**\n * Global runtime adapter registry\n *\n * @example\n * ```ts\n * import { runtime } from \"@veryfront/platform/adapters/registry.ts\";\n *\n * // Get adapter (auto-detects runtime)\n * const adapter = await runtime.get();\n *\n * // Use filesystem\n * const content = await adapter.fs.readFile(\"./config.json\");\n * ```\n */\nexport const runtime = new AdapterRegistry();\n\n// Re-export for convenience\nexport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\n", "import { logger } from \"@veryfront/utils\";\nimport type { RuntimeAdapter, RuntimeId } from \"./base.ts\";\nimport { createError, toError } from \"../../core/errors/veryfront-error.ts\";\n\n// Re-export the registry for convenient access\nexport { runtime } from \"./registry.ts\";\n\ninterface DenoGlobal {\n Deno: {\n version: { deno: string };\n [key: string]: unknown;\n };\n}\n\ninterface BunGlobal {\n Bun: {\n version: string;\n [key: string]: unknown;\n };\n}\n\ninterface CloudflareGlobal {\n caches: unknown;\n WebSocketPair: unknown;\n}\n\nfunction isDeno(global: typeof globalThis): global is typeof globalThis & DenoGlobal {\n return \"Deno\" in global && typeof (global as DenoGlobal).Deno === \"object\";\n}\n\nfunction isBun(global: typeof globalThis): global is typeof globalThis & BunGlobal {\n return \"Bun\" in global && typeof (global as BunGlobal).Bun === \"object\";\n}\n\nfunction isCloudflare(global: typeof globalThis): global is typeof globalThis & CloudflareGlobal {\n return \"caches\" in global && \"WebSocketPair\" in global;\n}\n\n/**\n * Detect the current runtime environment\n * @returns Runtime identifier\n */\nexport function detectRuntime(): RuntimeId | \"unknown\" {\n if (isDeno(globalThis)) {\n return \"deno\";\n }\n\n if (isBun(globalThis)) {\n return \"bun\";\n }\n\n const globalProcess = (globalThis as { process?: { versions?: { node?: string } } }).process;\n if (globalProcess?.versions?.node) {\n return \"node\";\n }\n\n if (isCloudflare(globalThis)) {\n return \"cloudflare\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Get the runtime adapter for the current environment\n *\n * @deprecated Use `runtime.get()` from `./registry.ts` instead for singleton management\n *\n * @example\n * ```ts\n * // Old way (deprecated)\n * const adapter = await getAdapter();\n *\n * // New way (recommended)\n * import { runtime } from \"@veryfront/platform/adapters/registry.ts\";\n * const adapter = await runtime.get();\n * ```\n */\nexport async function getAdapter(): Promise<RuntimeAdapter> {\n const runtimeId = detectRuntime();\n\n switch (runtimeId) {\n case \"deno\": {\n const { denoAdapter } = await import(\"./deno.ts\");\n return denoAdapter;\n }\n\n case \"bun\": {\n const { bunAdapter } = await import(\"./bun.ts\");\n return bunAdapter;\n }\n\n case \"node\": {\n const { nodeAdapter } = await import(\"./node.ts\");\n return nodeAdapter;\n }\n\n case \"cloudflare\": {\n const errorMsg = \"Cloudflare adapter requires manual initialization with environment. \" +\n \"Please use createCloudflareAdapter() with your environment context.\";\n logger.error(\"[Adapter Detection]\", errorMsg);\n throw toError(createError({\n type: \"config\",\n message: errorMsg,\n }));\n }\n\n default: {\n const supportedRuntimes = [\"deno\", \"bun\", \"node\", \"cloudflare\"];\n const errorMsg = `Unsupported runtime: ${runtimeId}. Supported runtimes: ${\n supportedRuntimes.join(\", \")\n }`;\n logger.error(\"[Adapter Detection]\", errorMsg);\n throw toError(createError({\n type: \"config\",\n message: errorMsg,\n }));\n }\n }\n}\n\nexport { denoAdapter } from \"./deno.ts\";\nexport { nodeAdapter } from \"./node.ts\";\nexport { bunAdapter } from \"./bun.ts\";\n\nexport type {\n EnvironmentAdapter,\n FileSystemAdapter,\n RuntimeAdapter,\n RuntimeCapabilities,\n RuntimeFeatures,\n RuntimeId,\n} from \"./base.ts\";\n", "export { AppWrapper } from \"./AppWrapper.tsx\";\nexport type { AppWrapperProps } from \"./AppWrapper.tsx\";\n\nexport { Head } from \"./Head.tsx\";\n\nexport { LayoutComponent } from \"./LayoutComponent.tsx\";\nexport type { LayoutComponentProps } from \"./LayoutComponent.tsx\";\n\nexport { Link } from \"./Link.tsx\";\nexport type { LinkProps } from \"./Link.tsx\";\n\nexport { MDXProvider, useMDXComponents } from \"./MDXProvider.tsx\";\nexport type { MDXProviderProps } from \"./MDXProvider.tsx\";\n\nexport { ProviderComponent } from \"./ProviderComponent.tsx\";\nexport type { ProviderComponentProps } from \"./ProviderComponent.tsx\";\n\nexport * from \"./optimized-image/index.ts\";\n", "import type * as React from \"react\";\nimport type { MDXComponents, PageContext as TypedPageContext } from \"@veryfront/types\";\nimport type { MdxBundle } from \"./LayoutComponent.tsx\";\nimport { LayoutComponent } from \"./LayoutComponent.tsx\";\nimport { ProviderComponent } from \"./ProviderComponent.tsx\";\n\nexport interface AppWrapperProps {\n children: React.ReactNode;\n providers?: MdxBundle[];\n layout?: MdxBundle;\n components?: MDXComponents;\n mode?: string;\n studioEnabled?: boolean;\n pageContext?: TypedPageContext;\n}\n\nexport function AppWrapper({\n children,\n providers = [],\n layout,\n components = {},\n mode: _mode,\n studioEnabled: _studioEnabled,\n pageContext,\n}: AppWrapperProps) {\n let content = children;\n\n if (layout) {\n content = (\n <LayoutComponent mdxBundle={layout} components={components} pageContext={pageContext}>\n {content}\n </LayoutComponent>\n );\n }\n\n for (const provider of [...providers].reverse()) {\n content = (\n <ProviderComponent mdxBundle={provider} components={components}>\n {content}\n </ProviderComponent>\n );\n }\n\n return content;\n}\n", "import type React from \"react\";\nimport { useMemo, useRef } from \"react\";\nimport { mdxRenderer } from \"@veryfront/transforms/mdx/index.ts\";\nimport type { MdxBundle, MDXComponents, PageContext as TypedPageContext } from \"@veryfront/types\";\nimport { rendererLogger as logger } from \"@veryfront/utils\";\n\nexport type { MdxBundle } from \"@veryfront/types\";\n\nexport interface LayoutComponentProps {\n mdxBundle: MdxBundle;\n children: React.ReactNode;\n components?: MDXComponents;\n pageContext?: TypedPageContext;\n}\n\nfunction useStableObject<T>(obj: T): T {\n const ref = useRef(obj);\n const serialized = JSON.stringify(obj);\n const prevSerialized = useRef(serialized);\n\n if (prevSerialized.current !== serialized) {\n ref.current = obj;\n prevSerialized.current = serialized;\n }\n\n return ref.current;\n}\n\nexport function LayoutComponent({\n mdxBundle,\n children,\n components = {},\n pageContext,\n}: LayoutComponentProps) {\n const stableFrontmatter = useStableObject(mdxBundle.frontmatter);\n const stablePageContext = useStableObject(pageContext);\n\n const element = useMemo(() => {\n try {\n return mdxRenderer.render(mdxBundle.compiledCode, {\n components,\n frontmatter: { ...(stableFrontmatter || {}), pageContext: stablePageContext },\n globals: mdxBundle.globals,\n extractLayout: true,\n children,\n });\n } catch (error) {\n logger.error(\"[LayoutComponent] Render failed:\", error);\n return <>{children}</>;\n }\n }, [\n mdxBundle.compiledCode,\n stableFrontmatter,\n components,\n children,\n stablePageContext,\n mdxBundle.globals,\n ]);\n\n if (!element) return <>{children}</>;\n return element as React.ReactElement;\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { LRUCache } from \"@veryfront/utils/lru-wrapper.ts\";\nimport React from \"react\";\nimport { MDX_RENDERER_MAX_ENTRIES, MDX_RENDERER_TTL_MS } from \"@veryfront/utils/constants/cache.ts\";\nimport { type ESMLoaderContext, loadModuleESM } from \"./esm-module-loader.ts\";\nimport {\n executeModule as _executeModule,\n selectComponent as _selectComponent,\n} from \"./module-executor.ts\";\nimport { type ParsedMDX, parseMDXCode } from \"./parser.ts\";\nimport type { MDXComponents, MDXFrontmatter, MDXGlobals, MDXModule } from \"./types.ts\";\n\nexport interface MDXRenderOptions {\n components?: MDXComponents;\n frontmatter?: MDXFrontmatter;\n globals?: MDXGlobals;\n extractLayout?: boolean;\n children?: React.ReactNode;\n}\n\nexport class MDXRenderer {\n private esmCacheDir?: string;\n private moduleCache: LRUCache<string, MDXModule> = new LRUCache({\n maxEntries: MDX_RENDERER_MAX_ENTRIES,\n ttlMs: MDX_RENDERER_TTL_MS,\n });\n\n constructor() {\n }\n\n async clearCache() {\n this.moduleCache.destroy();\n\n if (this.esmCacheDir) {\n try {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n const adapter = await getAdapter();\n await adapter.fs.remove(this.esmCacheDir, { recursive: true });\n } catch (_error) {\n void _error;\n }\n this.esmCacheDir = undefined;\n }\n }\n\n async loadModuleESM(compiledProgramCode: string): Promise<MDXModule> {\n const context: ESMLoaderContext = {\n esmCacheDir: this.esmCacheDir,\n moduleCache: this.moduleCache,\n };\n const result = await loadModuleESM(compiledProgramCode, context);\n this.esmCacheDir = context.esmCacheDir;\n return result;\n }\n\n render(\n _compiledCode: string,\n _options: MDXRenderOptions = {},\n ): React.ReactElement {\n logger.error(\n \"[MDX] Synchronous render() called but string-based factories are disabled for security. \" +\n \"Please use: await mdxRenderer.loadModuleESM(compiledCode) instead.\",\n );\n\n return React.createElement(\n \"div\",\n {\n style: {\n padding: \"1rem\",\n backgroundColor: \"#fff3cd\",\n border: \"1px solid #ffc107\",\n borderRadius: \"0.375rem\",\n color: \"#856404\",\n },\n },\n React.createElement(\"strong\", {}, \"Migration Required: \"),\n \"Synchronous render() is no longer supported for security reasons. \",\n React.createElement(\"br\"),\n \"Please update to: \",\n React.createElement(\"code\", {}, \"await mdxRenderer.loadModuleESM(compiledCode)\"),\n );\n }\n\n private parseMDXCode(compiledCode: string): ParsedMDX {\n return parseMDXCode(compiledCode);\n }\n}\n\nlet _mdxRendererInstance: MDXRenderer | undefined;\n\nfunction getMDXRendererInstance(): MDXRenderer {\n if (!_mdxRendererInstance) {\n _mdxRendererInstance = new MDXRenderer();\n }\n return _mdxRendererInstance;\n}\n\nexport const mdxRenderer = new Proxy({} as MDXRenderer, {\n get(_target, prop) {\n const instance = getMDXRendererInstance();\n const value = instance[prop as keyof MDXRenderer];\n if (typeof value === \"function\") {\n return value.bind(instance);\n }\n return value;\n },\n set(_target, prop, value) {\n const instance = getMDXRendererInstance();\n (instance as any)[prop] = value;\n return true;\n },\n has(_target, prop) {\n const instance = getMDXRendererInstance();\n return prop in instance;\n },\n ownKeys(_target) {\n const instance = getMDXRendererInstance();\n return Reflect.ownKeys(instance);\n },\n getOwnPropertyDescriptor(_target, prop) {\n const instance = getMDXRendererInstance();\n return Reflect.getOwnPropertyDescriptor(instance, prop);\n },\n});\n\nexport async function clearMDXRendererCache() {\n await getMDXRendererInstance().clearCache();\n}\n\nexport {\n MDXCacheAdapter,\n type MDXCacheAdapterOptions,\n type MDXCompilationResult,\n} from \"./mdx-cache-adapter.ts\";\n", "import { LRUCacheAdapter } from \"./cache/stores/memory/lru-cache-adapter.ts\";\nimport type { LRUCacheOptions } from \"./cache/stores/memory/types.ts\";\nimport { DEFAULT_LRU_MAX_ENTRIES } from \"@veryfront/utils\";\nimport { getEnv } from \"../../platform/compat/process.ts\";\n\nexport interface LRUOptions {\n maxEntries?: number;\n ttlMs?: number;\n cleanupIntervalMs?: number;\n}\n\nexport class LRUCache<K, V> {\n private adapter: LRUCacheAdapter;\n private cleanupTimer?: ReturnType<typeof setInterval>;\n private cleanupIntervalMs: number;\n private ttlMs?: number;\n\n constructor(options: LRUOptions = {}) {\n const adapterOptions: LRUCacheOptions = {\n maxEntries: options.maxEntries ?? DEFAULT_LRU_MAX_ENTRIES,\n ttlMs: options.ttlMs,\n };\n\n this.adapter = new LRUCacheAdapter(adapterOptions);\n this.ttlMs = options.ttlMs;\n this.cleanupIntervalMs = options.cleanupIntervalMs ?? 60000;\n\n if (this.ttlMs && this.ttlMs > 0) {\n this.startPeriodicCleanup();\n }\n }\n\n private startPeriodicCleanup(): void {\n if (shouldDisableInterval()) {\n return;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n\n const timer = setInterval(() => {\n this.adapter.cleanupExpired();\n }, this.cleanupIntervalMs);\n this.cleanupTimer = timer;\n }\n\n private toStringKey(key: K): string {\n if (typeof key === \"string\") {\n return key;\n }\n return String(key);\n }\n\n get size(): number {\n return this.adapter.getStats().entries;\n }\n\n has(key: K): boolean {\n return this.adapter.get(this.toStringKey(key)) !== undefined;\n }\n\n get(key: K): V | undefined {\n return this.adapter.get<V>(this.toStringKey(key));\n }\n\n set(key: K, value: V): void {\n this.adapter.set(this.toStringKey(key), value);\n }\n\n delete(key: K): boolean {\n const stringKey = this.toStringKey(key);\n const had = this.adapter.get(stringKey) !== undefined;\n this.adapter.delete(stringKey);\n return had;\n }\n\n clear(): void {\n this.adapter.clear();\n }\n\n cleanup(): void {\n this.adapter.cleanupExpired();\n }\n\n destroy(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = undefined;\n }\n\n this.adapter.clear();\n }\n\n keys(): IterableIterator<K> {\n return this.adapter.keys() as IterableIterator<K>;\n }\n}\n\nfunction shouldDisableInterval(): boolean {\n if ((globalThis as Record<string, unknown>).__vfDisableLruInterval === true) {\n return true;\n }\n try {\n return getEnv(\"VF_DISABLE_LRU_INTERVAL\") === \"1\";\n } catch {\n return false;\n }\n}\n", "import type { CacheAdapter, LRUCacheOptions, LRUCacheStats, LRUEntry } from \"./types.ts\";\nimport { LRUNode } from \"./lru-node.ts\";\nimport { LRUListManager } from \"./lru-list-manager.ts\";\nimport { EvictionManager } from \"../../eviction/eviction-manager.ts\";\nimport { EntryManager } from \"./entry-manager.ts\";\n\nfunction defaultSizeEstimator(value: unknown): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"string\") return value.length * 2;\n if (typeof value === \"number\" || typeof value === \"bigint\") return 8;\n if (typeof value === \"boolean\") return 4;\n if (value instanceof Uint8Array || ArrayBuffer.isView(value)) return value.byteLength;\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return value.size;\n\n try {\n return JSON.stringify(value).length * 2;\n } catch {\n return 0;\n }\n}\n\nexport class LRUCacheAdapter implements CacheAdapter {\n private readonly store = new Map<string, LRUNode<unknown>>();\n private readonly tagIndex = new Map<string, Set<string>>();\n private readonly listManager = new LRUListManager<unknown>();\n private readonly evictionManager: EvictionManager<LRUEntry<unknown>>;\n private readonly entryManager: EntryManager;\n private currentSize = 0;\n private readonly maxEntries: number;\n private readonly maxSizeBytes: number;\n private readonly defaultTtlMs?: number;\n private readonly onEvict?: (key: string, value: unknown) => void;\n\n constructor(options: LRUCacheOptions = {}) {\n this.maxEntries = options.maxEntries || 1000;\n this.maxSizeBytes = options.maxSizeBytes || 50 * 1024 * 1024; // 50MB default\n this.defaultTtlMs = options.ttlMs;\n this.onEvict = options.onEvict;\n\n const estimateSizeOf = options.estimateSizeOf || defaultSizeEstimator;\n\n this.evictionManager = new EvictionManager({\n onEvict: this.onEvict,\n loggerContext: \"MemoryCache\",\n });\n this.entryManager = new EntryManager(estimateSizeOf);\n }\n\n get<T>(key: string): T | undefined {\n const node = this.store.get(key);\n if (!node) return undefined;\n\n if (this.evictionManager.isExpired(node.entry)) {\n this.delete(key);\n return undefined;\n }\n\n this.listManager.moveToFront(node);\n return node.entry.value as T;\n }\n\n set<T>(key: string, value: T, ttlMs?: number, tags?: string[]): void {\n const existingNode = this.store.get(key);\n\n if (existingNode) {\n const sizeDelta = this.entryManager.updateExistingEntry(\n existingNode,\n value,\n ttlMs,\n tags,\n this.defaultTtlMs,\n this.listManager,\n this.tagIndex,\n key,\n );\n this.currentSize += sizeDelta;\n } else {\n const [_node, size] = this.entryManager.createNewEntry(\n key,\n value,\n ttlMs,\n tags,\n this.defaultTtlMs,\n this.listManager,\n this.store,\n );\n this.currentSize += size;\n }\n\n if (tags && tags.length > 0) {\n this.entryManager.updateTagIndex(tags, key, this.tagIndex);\n }\n\n this.currentSize = this.evictionManager.enforceMemoryLimits(\n this.listManager,\n this.store,\n this.tagIndex,\n this.currentSize,\n this.maxEntries,\n this.maxSizeBytes,\n );\n }\n\n delete(key: string): void {\n const node = this.store.get(key);\n if (!node) return;\n\n this.listManager.removeNode(node);\n this.store.delete(key);\n this.currentSize -= node.entry.size;\n\n if (node.entry.tags) {\n this.entryManager.cleanupTags(node.entry.tags, key, this.tagIndex);\n }\n\n if (this.onEvict) {\n this.onEvict(key, node.entry.value);\n }\n }\n\n invalidateTag(tag: string): number {\n const set = this.tagIndex.get(tag);\n if (!set) return 0;\n\n let count = 0;\n for (const key of set) {\n this.delete(key);\n count++;\n }\n this.tagIndex.delete(tag);\n return count;\n }\n\n clear(): void {\n if (this.onEvict) {\n for (const [key, node] of this.store) {\n this.onEvict(key, node.entry.value);\n }\n }\n\n this.store.clear();\n this.tagIndex.clear();\n this.listManager.clear();\n this.currentSize = 0;\n }\n\n getStats(): LRUCacheStats {\n return {\n entries: this.store.size,\n sizeBytes: this.currentSize,\n maxEntries: this.maxEntries,\n maxSizeBytes: this.maxSizeBytes,\n tags: this.tagIndex.size,\n };\n }\n\n cleanupExpired(): number {\n const now = Date.now();\n let cleaned = 0;\n\n for (const [key, node] of this.store) {\n if (typeof node.entry.expiry === \"number\" && now > node.entry.expiry) {\n this.delete(key);\n cleaned++;\n }\n }\n\n return cleaned;\n }\n\n keys(): IterableIterator<string> {\n return this.store.keys();\n }\n\n has(key: string): boolean {\n return this.get(key) !== undefined;\n }\n}\n", "import type { LRUNode } from \"./lru-node.ts\";\n\nexport class LRUListManager<T> {\n private head: LRUNode<T> | null = null;\n private tail: LRUNode<T> | null = null;\n\n getHead(): LRUNode<T> | null {\n return this.head;\n }\n\n getTail(): LRUNode<T> | null {\n return this.tail;\n }\n\n moveToFront(node: LRUNode<T>): void {\n if (node === this.head) {\n node.entry.lastAccessed = Date.now();\n return;\n }\n\n this.removeNode(node);\n\n this.addToFront(node);\n }\n\n addToFront(node: LRUNode<T>): void {\n node.next = this.head;\n node.prev = null;\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n if (!this.tail) {\n this.tail = node;\n }\n node.entry.lastAccessed = Date.now();\n }\n\n removeNode(node: LRUNode<T>): void {\n if (node.prev) {\n node.prev.next = node.next;\n }\n if (node.next) {\n node.next.prev = node.prev;\n }\n if (node === this.head) {\n this.head = node.next;\n }\n if (node === this.tail) {\n this.tail = node.prev;\n }\n }\n\n clear(): void {\n this.head = null;\n this.tail = null;\n }\n}\n", "export interface EvictableEntry {\n size: number;\n timestamp?: number;\n expiry?: number;\n value?: unknown;\n tags?: string[];\n}\n\nexport interface LRUTrackerInterface {\n getLRU(): string | undefined;\n remove(key: string): void;\n}\n\nexport interface LRUNodeInterface<T> {\n key: string;\n entry: T;\n prev: LRUNodeInterface<T> | null;\n next: LRUNodeInterface<T> | null;\n}\n\nexport interface LRUListManagerInterface<T> {\n getTail(): LRUNodeInterface<T> | null;\n removeNode(node: LRUNodeInterface<T>): void;\n}\n\nexport interface EvictionManagerOptions {\n onEvict?: (key: string, value: unknown) => void;\n loggerContext?: string;\n}\n\nexport class EvictionManager<TEntry extends EvictableEntry> {\n private readonly onEvict?: (key: string, value: unknown) => void;\n\n constructor(options: EvictionManagerOptions = {}) {\n this.onEvict = options.onEvict;\n }\n\n evictIfNeeded(\n cache: Map<string, TEntry>,\n lruTracker: LRUTrackerInterface,\n newEntrySize: number,\n maxSize: number,\n maxMemory: number,\n ): void {\n while (cache.size >= maxSize) {\n this.evictLRU(cache, lruTracker);\n }\n\n let memoryUsed = Array.from(cache.values()).reduce((sum, entry) => sum + entry.size, 0);\n\n while (memoryUsed + newEntrySize > maxMemory && cache.size > 0) {\n const evictedSize = this.evictLRU(cache, lruTracker);\n memoryUsed -= evictedSize;\n }\n }\n\n evictLRU(cache: Map<string, TEntry>, lruTracker: LRUTrackerInterface): number {\n const keyToEvict = lruTracker.getLRU();\n\n if (!keyToEvict) {\n return 0;\n }\n\n const entry = cache.get(keyToEvict);\n const size = entry?.size || 0;\n const value = entry?.value;\n\n cache.delete(keyToEvict);\n lruTracker.remove(keyToEvict);\n\n if (this.onEvict && entry) {\n this.onEvict(keyToEvict, value);\n }\n\n return size;\n }\n\n evictLRUFromList<T extends TEntry>(\n listManager: LRUListManagerInterface<T>,\n store: Map<string, LRUNodeInterface<T>>,\n tagIndex: Map<string, Set<string>>,\n currentSize: number,\n ): number {\n const tail = listManager.getTail();\n if (!tail) return currentSize;\n\n const node = tail;\n listManager.removeNode(node);\n store.delete(node.key);\n const newSize = currentSize - node.entry.size;\n\n if (node.entry.tags) {\n this.cleanupTags(node.entry.tags, node.key, tagIndex);\n }\n\n if (this.onEvict) {\n this.onEvict(node.key, node.entry.value);\n }\n\n return newSize;\n }\n\n enforceMemoryLimits<T extends TEntry>(\n listManager: LRUListManagerInterface<T>,\n store: Map<string, LRUNodeInterface<T>>,\n tagIndex: Map<string, Set<string>>,\n currentSize: number,\n maxEntries: number,\n maxSizeBytes: number,\n ): number {\n let size = currentSize;\n while ((store.size > maxEntries || size > maxSizeBytes) && listManager.getTail()) {\n size = this.evictLRUFromList(listManager, store, tagIndex, size);\n }\n return size;\n }\n\n private cleanupTags(tags: string[], key: string, tagIndex: Map<string, Set<string>>): void {\n for (const tag of tags) {\n const set = tagIndex.get(tag);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n tagIndex.delete(tag);\n }\n }\n }\n }\n\n evictExpired(cache: Map<string, TEntry>, lruTracker: LRUTrackerInterface, ttl: number): number {\n const now = Date.now();\n let evicted = 0;\n\n for (const [key, entry] of cache.entries()) {\n if (this.isExpired(entry, ttl, now)) {\n cache.delete(key);\n lruTracker.remove(key);\n evicted++;\n }\n }\n\n return evicted;\n }\n\n isExpired(entry: TEntry, ttl?: number, now: number = Date.now()): boolean {\n if (typeof entry.expiry === \"number\") {\n return now > entry.expiry;\n }\n\n if (typeof entry.timestamp === \"number\" && typeof ttl === \"number\") {\n const age = now - entry.timestamp;\n return age > ttl;\n }\n\n return false;\n }\n}\n", "import type { LRUEntry } from \"./types.ts\";\nimport { LRUNode } from \"./lru-node.ts\";\nimport type { LRUListManager } from \"./lru-list-manager.ts\";\n\nexport class EntryManager {\n constructor(\n private readonly estimateSizeOf: (value: unknown) => number,\n ) {}\n\n updateExistingEntry<T>(\n node: LRUNode<unknown>,\n value: T,\n ttlMs: number | undefined,\n tags: string[] | undefined,\n defaultTtlMs: number | undefined,\n listManager: LRUListManager<unknown>,\n tagIndex: Map<string, Set<string>>,\n key: string,\n ): number {\n const oldSize = node.entry.size;\n const newSize = this.estimateSizeOf(value);\n const expiry = this.calculateExpiry(ttlMs, defaultTtlMs);\n\n if (node.entry.tags) {\n this.cleanupTags(node.entry.tags, key, tagIndex);\n }\n\n node.entry = {\n value,\n size: newSize,\n expiry,\n tags,\n lastAccessed: Date.now(),\n };\n\n listManager.moveToFront(node);\n\n return newSize - oldSize;\n }\n\n createNewEntry<T>(\n key: string,\n value: T,\n ttlMs: number | undefined,\n tags: string[] | undefined,\n defaultTtlMs: number | undefined,\n listManager: LRUListManager<unknown>,\n store: Map<string, LRUNode<unknown>>,\n ): [LRUNode<unknown>, number] {\n const size = this.estimateSizeOf(value);\n const expiry = this.calculateExpiry(ttlMs, defaultTtlMs);\n\n const entry: LRUEntry<unknown> = {\n value,\n size,\n expiry,\n tags,\n lastAccessed: Date.now(),\n };\n\n const node = new LRUNode(key, entry);\n store.set(key, node);\n listManager.addToFront(node);\n\n return [node, size];\n }\n\n updateTagIndex(\n tags: string[],\n key: string,\n tagIndex: Map<string, Set<string>>,\n ): void {\n for (const tag of tags) {\n if (!tagIndex.has(tag)) {\n tagIndex.set(tag, new Set());\n }\n tagIndex.get(tag)?.add(key);\n }\n }\n\n cleanupTags(\n tags: string[],\n key: string,\n tagIndex: Map<string, Set<string>>,\n ): void {\n for (const tag of tags) {\n const set = tagIndex.get(tag);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n tagIndex.delete(tag);\n }\n }\n }\n }\n\n private calculateExpiry(\n ttlMs: number | undefined,\n defaultTtlMs: number | undefined,\n ): number | undefined {\n if (typeof ttlMs === \"number\") {\n return Date.now() + ttlMs;\n }\n if (defaultTtlMs) {\n return Date.now() + defaultTtlMs;\n }\n return undefined;\n }\n}\n", "import type { LRUEntry } from \"./types.ts\";\n\nexport class LRUNode<T> {\n constructor(\n public key: string,\n public entry: LRUEntry<T>,\n public prev: LRUNode<T> | null = null,\n public next: LRUNode<T> | null = null,\n ) {}\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { LRUCache } from \"@veryfront/utils/lru-wrapper.ts\";\nimport React from \"react\";\nimport { getCacheNamespace } from \"@veryfront/utils/cache/keys/namespace.ts\";\nimport {\n getDefaultImportMap,\n transformImportsWithMap,\n} from \"@veryfront/modules/import-map/index.ts\";\nimport type { MDXFrontmatter, MDXModule } from \"./types.ts\";\nimport { join } from \"https://deno.land/std@0.220.0/path/mod.ts\";\nimport { isDeno, isNode } from \"../../../platform/compat/runtime.ts\";\nimport { cwd } from \"../../../platform/compat/process.ts\";\n\n// True Node.js runtime (not Deno with Node.js compat)\nconst IS_TRUE_NODE = isNode && !isDeno;\n\n// Constants\nconst LOG_PREFIX_MDX_LOADER = \"[mdx-loader]\";\nconst LOG_PREFIX_MDX_RENDERER = \"[mdx-renderer]\";\nconst JSX_IMPORT_PATTERN = /import\\s+([^'\"]+)\\s+from\\s+['\"]file:\\/\\/([^'\"]+\\.(jsx|tsx))['\"];?/g;\nconst REACT_IMPORT_PATTERN = /import\\s+.*React.*\\s+from\\s+['\"]react['\"]/;\nconst HTTP_IMPORT_PATTERN = /['\"]https?:\\/\\/[^'\"]+['\"]/;\nconst ESBUILD_JSX_FACTORY = \"React.createElement\";\nconst ESBUILD_JSX_FRAGMENT = \"React.Fragment\";\nconst HTTP_MODULE_FETCH_TIMEOUT_MS = 30000;\n\n// Cache for resolved react package paths (Node.js only)\nconst _resolvedPaths: Record<string, string | null> = {};\n\n/**\n * Resolve a Node.js package path using require.resolve\n * Returns null if resolution fails\n */\nasync function resolveNodePackage(packageSpec: string): Promise<string | null> {\n if (!IS_TRUE_NODE) return null;\n if (packageSpec in _resolvedPaths) return _resolvedPaths[packageSpec]!;\n\n try {\n // Use Node.js createRequire to resolve the package from THIS file's location\n // This ensures react is found from veryfront's node_modules, not the project's\n const { createRequire } = await import(\"node:module\");\n const require = createRequire(import.meta.url);\n const resolved = require.resolve(packageSpec);\n _resolvedPaths[packageSpec] = resolved;\n return resolved;\n } catch {\n _resolvedPaths[packageSpec] = null;\n return null;\n }\n}\n\n/**\n * Transform react imports to absolute file:// paths for Node.js.\n * This is needed because MDX modules are cached in arbitrary directories\n * (like temp dirs) where Node.js cannot resolve bare 'react' imports.\n */\nasync function transformReactImportsToAbsolute(code: string): Promise<string> {\n if (!IS_TRUE_NODE) return code;\n\n // Resolve the actual react package paths\n const reactPath = await resolveNodePackage(\"react\");\n const reactJsxPath = await resolveNodePackage(\"react/jsx-runtime\");\n const reactJsxDevPath = await resolveNodePackage(\"react/jsx-dev-runtime\");\n const reactDomPath = await resolveNodePackage(\"react-dom\");\n\n let result = code;\n\n // Replace bare react imports with absolute file:// paths\n if (reactJsxPath) {\n result = result.replace(\n /from\\s+['\"]react\\/jsx-runtime['\"]/g,\n `from \"file://${reactJsxPath}\"`,\n );\n }\n if (reactJsxDevPath) {\n result = result.replace(\n /from\\s+['\"]react\\/jsx-dev-runtime['\"]/g,\n `from \"file://${reactJsxDevPath}\"`,\n );\n }\n if (reactDomPath) {\n result = result.replace(\n /from\\s+['\"]react-dom['\"]/g,\n `from \"file://${reactDomPath}\"`,\n );\n }\n if (reactPath) {\n result = result.replace(\n /from\\s+['\"]react['\"]/g,\n `from \"file://${reactPath}\"`,\n );\n }\n\n return result;\n}\n\nexport interface ESMLoaderContext {\n esmCacheDir?: string;\n moduleCache: LRUCache<string, MDXModule>;\n}\n\nexport function hashString(input: string): string {\n const HASH_SEED_FNV1A = 2166136261;\n let hash = HASH_SEED_FNV1A >>> 0; // FNV-1a\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16);\n}\n\n/**\n * Creates an esbuild plugin to fetch and bundle HTTP/HTTPS imports.\n * This allows Node.js to use remote imports via esbuild bundling.\n */\nfunction createHTTPPluginForMDX(): import(\"esbuild\").Plugin {\n return {\n name: \"vf-mdx-http-fetch\",\n setup(build) {\n // Intercept HTTP/HTTPS imports\n build.onResolve({ filter: /^(http|https):\\/\\// }, (args) => ({\n path: args.path,\n namespace: \"http-url\",\n }));\n\n // Resolve relative imports within HTTP modules\n build.onResolve({ filter: /.*/, namespace: \"http-url\" }, (args) => {\n if (args.path.startsWith(\"http://\") || args.path.startsWith(\"https://\")) {\n return { path: args.path, namespace: \"http-url\" };\n }\n try {\n const resolved = new URL(args.path, args.importer).toString();\n return { path: resolved, namespace: \"http-url\" };\n } catch {\n return undefined;\n }\n });\n\n // Fetch and return HTTP module contents\n build.onLoad({ filter: /.*/, namespace: \"http-url\" }, async (args) => {\n let requestUrl = args.path;\n try {\n const u = new URL(args.path);\n // Optimize esm.sh URLs\n if (u.hostname === \"esm.sh\") {\n if (u.pathname.includes(\"/denonext/\")) {\n u.pathname = u.pathname.replace(\"/denonext/\", \"/\");\n }\n u.searchParams.set(\"target\", \"es2020\");\n u.searchParams.set(\"bundle\", \"true\");\n requestUrl = u.toString();\n }\n } catch {\n // Use original URL if parsing fails\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), HTTP_MODULE_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(requestUrl, {\n headers: { \"user-agent\": \"Mozilla/5.0 Veryfront/1.0\" },\n signal: controller.signal,\n });\n clearTimeout(timeout);\n\n if (!res.ok) {\n return {\n errors: [{ text: `Failed to fetch ${args.path}: ${res.status}` }],\n };\n }\n\n const text = await res.text();\n return { contents: text, loader: \"js\" };\n } catch (e) {\n clearTimeout(timeout);\n return {\n errors: [{\n text: `Failed to fetch ${args.path}: ${e instanceof Error ? e.message : String(e)}`,\n }],\n };\n }\n });\n },\n };\n}\n\nexport async function loadModuleESM(\n compiledProgramCode: string,\n context: ESMLoaderContext,\n): Promise<MDXModule> {\n try {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n const adapter = await getAdapter();\n\n if (!context.esmCacheDir) {\n if (IS_TRUE_NODE) {\n // On Node.js, use a cache dir inside the project so module resolution works\n // Node.js resolves bare imports relative to the file location\n const projectCacheDir = join(\n cwd(),\n \"node_modules\",\n \".cache\",\n \"veryfront-mdx\",\n );\n await adapter.fs.mkdir(projectCacheDir, { recursive: true });\n context.esmCacheDir = projectCacheDir;\n } else {\n // On Deno, system temp dir is fine\n context.esmCacheDir = await adapter.fs.makeTempDir(\"veryfront-mdx-esm-\");\n }\n }\n\n // Transform imports with import map\n let rewritten: string;\n if (IS_TRUE_NODE) {\n // On Node.js, transform react imports to absolute file:// paths\n // This is needed because MDX modules are cached in temp directories\n // where Node.js cannot resolve bare imports\n rewritten = await transformReactImportsToAbsolute(compiledProgramCode);\n } else {\n // On Deno/browser, transform to esm.sh URLs\n rewritten = transformImportsWithMap(\n compiledProgramCode,\n getDefaultImportMap(),\n undefined,\n { resolveBare: true },\n );\n }\n\n // Transform JSX/TSX imports using esbuild\n // This handles user components that use JSX syntax\n let jsxMatch;\n const jsxTransforms: Array<{ original: string; transformed: string }> = [];\n\n // Import esbuild once outside the loop for better performance\n const { transform } = await import(\"esbuild/mod.js\");\n\n while ((jsxMatch = JSX_IMPORT_PATTERN.exec(rewritten)) !== null) {\n const [fullMatch, importClause, filePath, ext] = jsxMatch;\n\n if (!filePath) {\n logger.warn(`${LOG_PREFIX_MDX_LOADER} Skipping JSX import with undefined file path`, {\n fullMatch,\n });\n continue;\n }\n\n try {\n // Read the JSX file (filePath already includes full path)\n const jsxCode = await adapter.fs.readFile(filePath);\n\n // Use esbuild to transform JSX to JavaScript\n const result = await transform(jsxCode as string, {\n loader: ext === \"tsx\" ? \"tsx\" : \"jsx\",\n jsx: \"transform\",\n jsxFactory: ESBUILD_JSX_FACTORY,\n jsxFragment: ESBUILD_JSX_FRAGMENT,\n format: \"esm\",\n });\n\n let transformed = result.code;\n\n // Add React import if not present\n if (!REACT_IMPORT_PATTERN.test(transformed)) {\n transformed = `import React from 'react';\\n${transformed}`;\n }\n\n // Write transformed code to temp file\n const transformedFileName = `jsx-${hashString(filePath)}.mjs`;\n const transformedPath = join(context.esmCacheDir!, transformedFileName);\n await adapter.fs.writeFile(transformedPath, transformed);\n\n jsxTransforms.push({\n original: fullMatch,\n transformed: `import ${importClause} from \"file://${transformedPath}\";`,\n });\n\n logger.info(\n `${LOG_PREFIX_MDX_LOADER} Transformed JSX import using esbuild: ${filePath} -> ${transformedPath}`,\n );\n } catch (error) {\n logger.warn(`${LOG_PREFIX_MDX_LOADER} Failed to transform JSX import: ${filePath}`, error);\n // Keep original import if transformation fails\n }\n }\n\n // Apply all JSX transformations\n for (const { original, transformed } of jsxTransforms) {\n rewritten = rewritten.replace(original, transformed);\n }\n\n if (/\\bconst\\s+MDXLayout\\b/.test(rewritten) && !/export\\s+\\{[^}]*MDXLayout/.test(rewritten)) {\n rewritten += \"\\nexport { MDXLayout as __vfLayout };\\n\";\n }\n\n // On Node.js, bundle HTTP imports via esbuild instead of trying to import them directly\n if (IS_TRUE_NODE && HTTP_IMPORT_PATTERN.test(rewritten)) {\n logger.info(`${LOG_PREFIX_MDX_LOADER} Bundling HTTP imports via esbuild for Node.js`);\n const { build } = await import(\"esbuild/mod.js\");\n\n // Write temp source file for esbuild to process\n const tempSourcePath = join(context.esmCacheDir!, `temp-${hashString(rewritten)}.mjs`);\n await adapter.fs.writeFile(tempSourcePath, rewritten);\n\n try {\n const result = await build({\n entryPoints: [tempSourcePath],\n bundle: true,\n format: \"esm\",\n platform: \"neutral\",\n target: \"es2020\",\n write: false,\n plugins: [createHTTPPluginForMDX()],\n // Mark npm packages as external so they're not bundled\n external: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n });\n\n const bundledCode = result.outputFiles?.[0]?.text;\n if (bundledCode) {\n rewritten = bundledCode;\n logger.info(`${LOG_PREFIX_MDX_LOADER} Successfully bundled HTTP imports`);\n }\n } catch (bundleError) {\n logger.warn(\n `${LOG_PREFIX_MDX_LOADER} Failed to bundle HTTP imports, falling back to original code`,\n bundleError,\n );\n // Keep original code if bundling fails\n } finally {\n // Clean up temp file (use unlink since rm may not exist on all adapters)\n try {\n // deno-lint-ignore no-explicit-any\n const fsAny = adapter.fs as any;\n if (typeof fsAny.rm === \"function\") {\n await fsAny.rm(tempSourcePath);\n } else if (typeof fsAny.unlink === \"function\") {\n await fsAny.unlink(tempSourcePath);\n }\n // If neither exists, just leave the temp file (it's in a cache dir anyway)\n } catch {\n // Ignore cleanup errors\n }\n }\n }\n\n const codeHash = hashString(rewritten);\n const namespace = getCacheNamespace() || \"default\";\n const compositeKey = `${namespace}:${codeHash}`;\n\n const cached = context.moduleCache.get(compositeKey);\n if (cached) return cached as MDXModule;\n\n const nsDir = join(context.esmCacheDir, namespace);\n try {\n await adapter.fs.mkdir(nsDir, { recursive: true });\n } catch (e) {\n logger.debug(\n `${LOG_PREFIX_MDX_RENDERER} mkdir nsDir failed`,\n e instanceof Error ? e : String(e),\n );\n }\n\n const filePath = join(nsDir, `${codeHash}.mjs`);\n try {\n const stat = await adapter.fs.stat(filePath);\n if (!stat?.isFile) {\n await adapter.fs.writeFile(filePath, rewritten);\n }\n } catch (error) {\n logger.debug(`${LOG_PREFIX_MDX_RENDERER} Writing temporary MDX module file:`, error);\n await adapter.fs.writeFile(filePath, rewritten);\n }\n\n logger.info(`${LOG_PREFIX_MDX_RENDERER} Loading MDX module`, {\n filePath,\n codePreview: rewritten.substring(0, 300),\n });\n const mod = await import(`file://${filePath}?v=${codeHash}`) as Record<string, unknown> & {\n __vfLayout?: React.ComponentType;\n };\n\n const result: MDXModule = {\n ...mod,\n default: mod?.default as React.ComponentType<unknown> | undefined,\n MDXContent: mod?.MDXContent as React.ComponentType<unknown> | undefined,\n frontmatter: mod?.frontmatter as MDXFrontmatter | undefined,\n headings: mod?.headings as Array<{ text: string; level: number }> | undefined,\n title: mod?.title as string | undefined,\n description: mod?.description as string | undefined,\n layout: mod?.layout as string | boolean | React.ComponentType | undefined,\n MDXLayout: (mod?.MDXLayout || mod?.__vfLayout) as React.ComponentType<unknown> | undefined,\n MainLayout: mod?.MainLayout as React.ComponentType<unknown> | undefined,\n };\n context.moduleCache.set(compositeKey, result);\n return result;\n } catch (error) {\n logger.error(`${LOG_PREFIX_MDX_RENDERER} MDX ESM load failed:`, error);\n throw error;\n }\n}\n", "import { serverLogger as logger } from \"../../logger/logger.ts\";\nimport { getEnvironmentVariable } from \"../../logger/env.ts\";\nimport type { GlobalWithVeryFrontCache } from \"@veryfront/types/global-guards.ts\";\n\nlet cacheNamespace: string | undefined =\n (globalThis as GlobalWithVeryFrontCache).__VF_CACHE_NAMESPACE__ ||\n getEnvironmentVariable(\"VF_CACHE_NAMESPACE\");\n\nexport function setCacheNamespace(namespace?: string): void {\n cacheNamespace = namespace || undefined;\n try {\n (globalThis as GlobalWithVeryFrontCache).__VF_CACHE_NAMESPACE__ = cacheNamespace;\n } catch (e) {\n logger.debug(\"[cache] setCacheNamespace failed\", e);\n }\n}\n\nexport function getCacheNamespace(): string | undefined {\n return cacheNamespace;\n}\n", "export { loadImportMap } from \"./loader.ts\";\nexport { getDefaultImportMap } from \"./default-import-map.ts\";\nexport { resolveImport } from \"./resolver.ts\";\nexport { transformImportsWithMap } from \"./transformer.ts\";\nexport { mergeImportMaps } from \"./merger.ts\";\n\nexport type { ImportMapConfig, TransformOptions } from \"./types.ts\";\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { dirname, join } from \"std/path/mod.ts\";\nimport type { RuntimeAdapter } from \"@veryfront/platform/adapters/base.ts\";\nimport { getConfig } from \"@veryfront/config\";\nimport type { ImportMapConfig } from \"./types.ts\";\nimport { getDefaultImportMap } from \"./default-import-map.ts\";\n\nexport async function loadImportMap(\n startPath: string,\n adapter?: RuntimeAdapter,\n): Promise<ImportMapConfig> {\n let runtimeAdapter = adapter;\n if (!runtimeAdapter) {\n const { getAdapter } = await import(\"@veryfront/platform/adapters/detect.ts\");\n runtimeAdapter = await getAdapter();\n }\n\n try {\n const cfg = await getConfig(startPath, runtimeAdapter!);\n if (cfg?.resolve?.importMap && typeof cfg.resolve.importMap === \"object\") {\n return {\n imports: cfg.resolve.importMap.imports ?? {},\n scopes: cfg.resolve.importMap.scopes ?? {},\n };\n }\n } catch {\n // Config not found or invalid, fall through to file-based discovery\n }\n\n let currentPath = startPath;\n\n while (currentPath !== \"/\" && currentPath !== \"\") {\n const denoJsonPath = join(currentPath, \"deno.json\");\n\n try {\n const content = await runtimeAdapter!.fs.readFile(denoJsonPath);\n const config = JSON.parse(content);\n\n if (config.imports || config.scopes) {\n logger.debug(`Loaded import map from ${denoJsonPath}`);\n return {\n imports: config.imports ?? {},\n scopes: config.scopes ?? {},\n };\n }\n } catch {\n // deno.json not found in this directory, continue searching\n }\n\n const parent = dirname(currentPath);\n if (parent === currentPath) break; // Reached root\n currentPath = parent;\n }\n\n return getDefaultImportMap();\n}\n", "import { getReactImportMap, REACT_DEFAULT_VERSION } from \"@veryfront/utils\";\nimport type { ImportMapConfig } from \"./types.ts\";\n\nexport function getDefaultImportMap(): ImportMapConfig {\n const reactVersion = REACT_DEFAULT_VERSION;\n\n const importMap = getReactImportMap(reactVersion);\n importMap[\"react/\"] = `https://esm.sh/react@${reactVersion}/`;\n\n return { imports: importMap };\n}\n", "import type { ImportMapConfig } from \"./types.ts\";\n\nexport function resolveImport(\n specifier: string,\n importMap: ImportMapConfig,\n scope?: string,\n): string {\n if (scope && importMap.scopes?.[scope]?.[specifier]) {\n return importMap.scopes[scope][specifier];\n }\n\n if (importMap.imports?.[specifier]) {\n return importMap.imports[specifier];\n }\n\n if (\n specifier.endsWith(\".js\") || specifier.endsWith(\".mjs\") ||\n specifier.endsWith(\".cjs\")\n ) {\n const base = specifier.replace(/\\.(m|c)?js$/, \"\");\n if (importMap.imports?.[base]) {\n return importMap.imports[base];\n }\n }\n\n if (importMap.imports) {\n for (const [key, value] of Object.entries(importMap.imports)) {\n if (key.endsWith(\"/\") && specifier.startsWith(key)) {\n return value + specifier.slice(key.length);\n }\n }\n }\n\n return specifier;\n}\n", "import type { ImportMapConfig, TransformOptions } from \"./types.ts\";\nimport { resolveImport } from \"./resolver.ts\";\n\nexport function transformImportsWithMap(\n code: string,\n importMap: ImportMapConfig,\n scope?: string,\n options?: TransformOptions,\n): string {\n let transformedCode = code;\n\n transformedCode = transformedCode.replace(\n /((?:import|export)\\s+(?:[\\w,{}\\s*]+\\s+from\\s+)?|export\\s+(?:\\*|\\{[^}]+\\})\\s+from\\s+)[\"']([^\"']+)[\"']/g,\n (_match, prefix, specifier) => {\n const isBare = !specifier.startsWith(\"http\") &&\n !specifier.startsWith(\"/\") &&\n !specifier.startsWith(\".\");\n if (isBare && !options?.resolveBare) {\n return `${prefix}\"${specifier}\"`;\n }\n const resolved = resolveImport(specifier, importMap, scope);\n return `${prefix}\"${resolved}\"`;\n },\n );\n\n transformedCode = transformedCode.replace(\n /from\\s+[\"']([^\"']+)[\"']/g,\n (match, specifier) => {\n const isBare = !specifier.startsWith(\"http\") &&\n !specifier.startsWith(\"/\") &&\n !specifier.startsWith(\".\");\n if (isBare && !options?.resolveBare) {\n return match;\n }\n const resolved = resolveImport(specifier, importMap, scope);\n return `from \"${resolved}\"`;\n },\n );\n\n transformedCode = transformedCode.replace(\n /import\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g,\n (_match, specifier) => {\n const resolved = resolveImport(specifier, importMap, scope);\n return `import(\"${resolved}\")`;\n },\n );\n\n return transformedCode;\n}\n", "import type { ImportMapConfig } from \"./types.ts\";\n\nexport function mergeImportMaps(...maps: ImportMapConfig[]): ImportMapConfig {\n const merged: ImportMapConfig = {\n imports: {},\n scopes: {},\n };\n\n for (const map of maps) {\n if (map.imports) {\n Object.assign(merged.imports!, map.imports);\n }\n\n if (map.scopes) {\n for (const [scope, imports] of Object.entries(map.scopes)) {\n if (!merged.scopes![scope]) {\n merged.scopes![scope] = {};\n }\n Object.assign(merged.scopes![scope], imports);\n }\n }\n }\n\n return merged;\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport type { MDXExports, MDXImportInfo, ParsedMDX } from \"./types.ts\";\nimport { extractFrontmatter, extractMetadata } from \"./module-loader/metadata-extractor.ts\";\n\nexport type { ParsedMDX };\n\nexport function parseMDXCode(compiledCode: string): ParsedMDX {\n logger.debug(\"Parsing MDX code, first 200 chars:\", compiledCode.substring(0, 200));\n const importRegex = /^\\s*import\\s+(?:{([^}]+)}|(\\w+))\\s+from\\s+['\"]([^'\"]+)['\"]\\s*;?\\s*$/gm;\n const imports = new Map<string, MDXImportInfo>();\n let match: RegExpExecArray | null;\n\n while ((match = importRegex.exec(compiledCode)) !== null) {\n if (match[1]) {\n const names = match[1].split(\",\").map((n: string) => n.trim());\n names.forEach((name: string) => {\n if (match?.[3]) {\n imports.set(name, { name, path: match[3], isDefault: false });\n }\n });\n } else if (match[2]) {\n if (match[2] && match[3]) {\n imports.set(match[2], {\n name: match[2],\n path: match[3],\n isDefault: true,\n });\n }\n }\n }\n\n const cleanedCode = compiledCode\n .replace(importRegex, \"\") // Remove top-level imports\n .replace(/^\\s*export\\s+\\{[\\s\\S]*?\\};?\\s*$/gm, \"\") // Remove named exports (including multi-line)\n .replace(/^\\s*export\\s+default\\s+function/gm, \"function\") // Convert default export function\n .replace(/^\\s*export\\s+default\\s+/gm, \"\") // Remove other default exports\n .replace(/^\\s*export\\s+const\\s+/gm, \"const \") // Convert export const to const\n .replace(/^\\s*export\\s+function\\s+/gm, \"function \") // Convert export function to function\n .replace(/^\\s*const\\s+React\\s*=.*?;?\\s*$/gm, \"\") // Remove React declarations\n .replace(/^\\s*import\\s+React\\s+from.*?;?\\s*$/gm, \"\") // Remove React imports\n .replace(/^\\s*const\\s+(Fragment|Fragment2)\\s*=.*?;?\\s*$/gm, \"\") // Remove Fragment declarations\n .replace(/^\\s*const\\s+(jsx|jsx2)\\s*=.*?;?\\s*$/gm, \"\") // Remove jsx declarations\n .replace(/^\\s*const\\s+(jsxs|jsxs2)\\s*=.*?;?\\s*$/gm, \"\"); // Remove jsxs declarations\n\n if (cleanedCode.includes(\"import React\")) {\n logger.warn(\"Import React still in cleaned code\");\n }\n if (cleanedCode.includes(\"const React\") || cleanedCode.includes(\"var React\")) {\n logger.warn(\"React declaration found in cleaned code\");\n logger.debug(\"Code snippet:\", cleanedCode.substring(0, 200));\n }\n\n const exports: MDXExports = {};\n\n const frontmatter = extractFrontmatter(cleanedCode);\n if (frontmatter) {\n exports.frontmatter = frontmatter;\n }\n\n const metadata = extractMetadata(cleanedCode);\n for (const [key, value] of Object.entries(metadata)) {\n if (value !== undefined) {\n (exports as Record<string, unknown>)[key] = value;\n }\n }\n\n return { code: cleanedCode, imports, exports };\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport type { FrontmatterMetadata, LogContext, MDXModule } from \"./types.ts\";\nimport { extractBalancedBlock, parseJsonish } from \"./string-parser.ts\";\n\nexport function extractFrontmatter(moduleCode: string): FrontmatterMetadata | undefined {\n try {\n const fmIndex = moduleCode.search(/(?:export\\s+)?const\\s+frontmatter\\s*=\\s*/);\n if (fmIndex < 0) return undefined;\n\n const braceStart = moduleCode.indexOf(\"{\", fmIndex);\n if (braceStart < 0) return undefined;\n\n const raw = extractBalancedBlock(moduleCode, braceStart, \"{\", \"}\");\n if (!raw) return undefined;\n\n const jsonish = raw\n .replace(/([^\\s\"{[:,]+)\\s*:/g, '\"$1\":')\n .replace(/'([^']*)'/g, '\"$1\"');\n\n try {\n return JSON.parse(jsonish) as FrontmatterMetadata;\n } catch (e) {\n logger.debug(\"[mdx] frontmatter JSON parse failed\", e as LogContext);\n return undefined;\n }\n } catch (e) {\n logger.debug(\"[mdx] frontmatter extraction failed\", e as LogContext);\n return undefined;\n }\n}\n\ninterface MetadataPattern {\n regex: RegExp;\n key: string;\n}\n\nconst METADATA_PATTERNS: MetadataPattern[] = [\n { regex: /(?:export\\s+)?const\\s+title\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"title\" },\n { regex: /(?:export\\s+)?const\\s+description\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"description\" },\n { regex: /(?:export\\s+)?const\\s+layout\\s*=\\s*(true|false|[\"'][^\"']+[\"'])/, key: \"layout\" },\n { regex: /(?:export\\s+)?const\\s+headings\\s*=\\s*(\\[[\\s\\S]*?\\])/, key: \"headings\" },\n { regex: /(?:export\\s+)?const\\s+nested\\s*=\\s*({[\\s\\S]*?})/, key: \"nested\" },\n { regex: /(?:export\\s+)?const\\s+tags\\s*=\\s*(\\[[\\s\\S]*?\\])/, key: \"tags\" },\n { regex: /(?:export\\s+)?const\\s+date\\s*=\\s*[\"']([^\"']+)[\"']/, key: \"date\" },\n { regex: /(?:export\\s+)?const\\s+draft\\s*=\\s*(true|false)/, key: \"draft\" },\n];\n\nexport function extractMetadata(moduleCode: string): Partial<MDXModule> {\n const exports: Partial<MDXModule> = {};\n\n METADATA_PATTERNS.forEach(({ regex, key }) => {\n const match = moduleCode.match(regex);\n if (!match) return;\n\n const value = match[1] as string;\n\n switch (key) {\n case \"title\":\n case \"description\":\n case \"date\":\n exports[key] = value;\n break;\n\n case \"layout\":\n exports[key] = value === \"true\"\n ? true\n : value === \"false\"\n ? false\n : String(value).replace(/^\"|\"$/g, \"\");\n break;\n\n case \"headings\":\n case \"tags\":\n case \"nested\":\n try {\n exports[key] = parseJsonish(value) as never;\n } catch (e) {\n logger.warn(`Failed to parse ${key}`, e);\n }\n break;\n\n case \"draft\":\n exports[key] = value === \"true\";\n break;\n }\n });\n\n return exports;\n}\n\nexport function mergeFrontmatter(result: MDXModule): void {\n result.frontmatter = result.frontmatter || {};\n\n const keys = [\"title\", \"description\", \"layout\", \"headings\", \"tags\", \"date\", \"draft\", \"nested\"];\n for (const key of keys) {\n if (result[key] !== undefined && result.frontmatter[key] === undefined) {\n result.frontmatter[key] = result[key];\n }\n }\n}\n", "export function extractBalancedBlock(\n source: string,\n startIndex: number,\n open: \"{\" | \"[\" | \"(\",\n close?: \"}\" | \"]\" | \")\",\n): string {\n const closeCh = close || (open === \"{\" ? \"}\" : open === \"[\" ? \"]\" : \")\");\n let depth = 0;\n let i = startIndex;\n\n while (i < source.length) {\n const ch = source[i] as string;\n\n if (ch === '\"' || ch === \"'\") {\n const quote = ch;\n i++;\n while (i < source.length) {\n const q = source[i] as string;\n if (q === \"\\\\\") {\n i += 2;\n continue;\n }\n if (q === quote) {\n i++;\n break;\n }\n i++;\n }\n continue;\n }\n\n if (ch === open) depth++;\n if (ch === closeCh) {\n depth--;\n if (depth === 0) {\n return source.slice(startIndex, i + 1);\n }\n }\n i++;\n }\n\n return \"\";\n}\n\nexport function cleanModuleCode(moduleCode: string): string {\n return moduleCode\n .replace(/import\\s+.*?from\\s+['\"][^'\"]+['\"];?\\s*/gm, \"\")\n .replace(/export\\s+\\{[\\s\\S]*?\\};?$/gm, \"\")\n .replace(/export\\s+default\\s+/gm, \"\")\n .replace(/export\\s+const\\s+/gm, \"const \")\n .replace(/export\\s+function\\s+/gm, \"function \");\n}\n\nexport function parseJsonish(value: string): unknown {\n const jsonish = value\n .replace(/'([^']*)'/g, '\"$1\"')\n .replace(/([{,]\\s*)([A-Za-z_$][\\w$]*)\\s*:/g, '$1\"$2\":');\n return JSON.parse(jsonish);\n}\n", "import { rendererLogger as logger } from \"@veryfront/utils\";\nimport { wrapError as _wrapError } from \"@veryfront/errors\";\nimport {\n type BundleCode,\n type BundleMetadata,\n computeCodeHash,\n computeContentHash,\n getBundleManifestStore,\n getBundleManifestTTL,\n} from \"@veryfront/utils\";\nimport type { VeryfrontConfig } from \"@veryfront/config\";\nimport type { MdxBundle } from \"@veryfront/types\";\n\nexport interface MDXCompilationResult extends MdxBundle {\n headings?: Array<{ id: string; text: string; level: number }>;\n nodeMap?: Map<number, unknown>;\n}\n\nexport interface MDXCacheAdapterOptions {\n config: VeryfrontConfig;\n mode: \"development\" | \"production\";\n}\n\nexport class MDXCacheAdapter {\n private config: VeryfrontConfig;\n private mode: \"development\" | \"production\";\n private manifestStore = getBundleManifestStore();\n\n constructor(options: MDXCacheAdapterOptions) {\n this.config = options.config;\n this.mode = options.mode;\n }\n\n private getCacheKey(contentHash: string): string {\n return `mdx:${this.mode}:${contentHash}`;\n }\n\n private getTTL(): number | undefined {\n return getBundleManifestTTL(this.config, this.mode);\n }\n\n async computeHash(content: string): Promise<string> {\n return await computeContentHash(content);\n }\n\n async getCachedBundle(\n content: string,\n frontmatter?: Record<string, unknown>,\n filePath?: string,\n ): Promise<MDXCompilationResult | undefined> {\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n\n const metadata = await this.manifestStore.getBundleMetadata(cacheKey);\n if (!metadata) {\n return undefined;\n }\n\n const bundleCode = await this.manifestStore.getBundleCode(metadata.codeHash);\n if (!bundleCode) {\n logger.debug(\"[mdx-cache] Metadata found but code missing\", {\n filePath,\n codeHash: metadata.codeHash,\n });\n return undefined;\n }\n\n logger.debug(\"[mdx-cache] Cache hit for MDX compilation\", {\n filePath,\n codeHash: metadata.codeHash,\n size: metadata.size,\n });\n\n return {\n compiledCode: bundleCode.code,\n frontmatter: (frontmatter || {}) as Record<string, string | number | boolean | string[]>,\n headings: [],\n nodeMap: new Map(),\n };\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to retrieve cached bundle\", {\n error,\n filePath,\n });\n return undefined;\n }\n }\n\n async setCachedBundle(\n content: string,\n bundle: MDXCompilationResult,\n filePath?: string,\n ): Promise<void> {\n if (!bundle.compiledCode) {\n logger.debug(\"[mdx-cache] No compiled code to cache\", { filePath });\n return;\n }\n\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n\n const bundleCode: BundleCode = {\n code: bundle.compiledCode,\n };\n\n const codeHash = await computeCodeHash(bundleCode);\n\n const encoder = new TextEncoder();\n const size = encoder.encode(bundle.compiledCode).length;\n\n const metadata: BundleMetadata = {\n hash: contentHash,\n codeHash,\n size,\n compiledAt: Date.now(),\n source: filePath || \"unknown\",\n mode: this.mode,\n meta: {\n type: \"mdx\",\n reactVersion: (await import(\"react\")).version,\n },\n };\n\n const ttl = this.getTTL();\n\n await this.manifestStore.setBundleCode(codeHash, bundleCode, ttl);\n await this.manifestStore.setBundleMetadata(cacheKey, metadata, ttl);\n\n logger.debug(\"[mdx-cache] Cached compiled MDX\", {\n filePath,\n cacheKey,\n codeHash,\n size,\n ttl,\n });\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to cache bundle\", {\n error,\n filePath,\n });\n }\n }\n\n async invalidateBundle(content: string): Promise<void> {\n try {\n const contentHash = await this.computeHash(content);\n const cacheKey = this.getCacheKey(contentHash);\n await this.manifestStore.deleteBundle(cacheKey);\n logger.debug(\"[mdx-cache] Invalidated cached bundle\", { cacheKey });\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to invalidate bundle\", { error });\n }\n }\n\n async invalidateSource(source: string): Promise<number> {\n try {\n const count = await this.manifestStore.invalidateSource(source);\n logger.debug(\"[mdx-cache] Invalidated bundles for source\", {\n source,\n count,\n });\n return count;\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to invalidate source\", {\n error,\n source,\n });\n return 0;\n }\n }\n\n async clearAll(): Promise<void> {\n try {\n await this.manifestStore.clear();\n logger.debug(\"[mdx-cache] Cleared all cached bundles\");\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to clear cache\", { error });\n }\n }\n\n async getStats(): Promise<{\n totalBundles: number;\n totalSize: number;\n oldestBundle?: number;\n newestBundle?: number;\n }> {\n try {\n return await this.manifestStore.getStats();\n } catch (error) {\n logger.debug(\"[mdx-cache] Failed to get stats\", { error });\n return {\n totalBundles: 0,\n totalSize: 0,\n };\n }\n }\n}\n", "import type * as React from \"react\";\nimport { useMemo, useRef } from \"react\";\nimport { mdxRenderer } from \"@veryfront/transforms/mdx/index.ts\";\nimport type { MDXComponents } from \"@veryfront/types\";\nimport type { MdxBundle } from \"./LayoutComponent.tsx\";\nimport { rendererLogger as logger } from \"@veryfront/utils\";\n\nexport interface ProviderComponentProps {\n mdxBundle: MdxBundle;\n children: React.ReactNode;\n components?: MDXComponents;\n}\n\nfunction useStableFrontmatter(frontmatter: MdxBundle[\"frontmatter\"]): MdxBundle[\"frontmatter\"] {\n const ref = useRef(frontmatter);\n const serialized = JSON.stringify(frontmatter);\n const prevSerialized = useRef(serialized);\n\n if (prevSerialized.current !== serialized) {\n ref.current = frontmatter;\n prevSerialized.current = serialized;\n }\n\n return ref.current;\n}\n\nexport function ProviderComponent({\n mdxBundle,\n children,\n components = {},\n}: ProviderComponentProps) {\n const stableFrontmatter = useStableFrontmatter(mdxBundle.frontmatter);\n\n const element = useMemo(() => {\n try {\n return mdxRenderer.render(mdxBundle.compiledCode, {\n components,\n frontmatter: stableFrontmatter,\n globals: mdxBundle.globals,\n extractLayout: true,\n children,\n });\n } catch (error) {\n logger.error(\"[ProviderComponent] Render failed:\", error);\n return <>{children}</>;\n }\n }, [mdxBundle.compiledCode, stableFrontmatter, components, children, mdxBundle.globals]);\n\n if (!element) return <>{children}</>;\n return element as React.ReactElement;\n}\n", "import React from \"react\";\n\nexport function Head({ children }: { children: React.ReactNode }) {\n return React.createElement(\n \"div\",\n {\n \"data-veryfront-head\": \"1\",\n style: { display: \"none\" },\n },\n children,\n );\n}\n", "import React from \"react\";\n\nexport type LinkProps = React.AnchorHTMLAttributes<HTMLAnchorElement> & {\n prefetch?: boolean;\n};\n\nexport function Link({ prefetch = true, children, ...rest }: LinkProps) {\n const props: React.AnchorHTMLAttributes<HTMLAnchorElement> = {\n ...rest,\n ...(prefetch ? { \"data-prefetch\": \"true\" } : {}),\n };\n return <a {...props}>{children}</a>;\n}\n", "import type React from \"react\";\nimport { createContext, useContext } from \"react\";\nimport type { MDXComponents } from \"@veryfront/types\";\n\nconst MDXContext = createContext<MDXComponents>({});\n\nexport interface MDXProviderProps {\n components?: MDXComponents;\n children: React.ReactNode;\n}\n\nexport function MDXProvider({\n components = {},\n children,\n}: MDXProviderProps) {\n return <MDXContext.Provider value={components}>{children}</MDXContext.Provider>;\n}\n\nexport function useMDXComponents(components?: MDXComponents): MDXComponents {\n const contextComponents = useContext(MDXContext);\n return { ...contextComponents, ...components };\n}\n", "export { OptimizedImage } from \"./OptimizedImage.tsx\";\nexport type { OptimizedImageProps } from \"./OptimizedImage.tsx\";\nexport { SimpleOptimizedImage } from \"./SimpleOptimizedImage.tsx\";\nexport { OptimizedBackgroundImage } from \"./OptimizedBackgroundImage.tsx\";\nexport { useOptimizedImage } from \"./useOptimizedImage.ts\";\nexport { generateBlurDataURL, getAspectRatioPadding, ResponsiveImageContainer } from \"./utils.tsx\";\n", "import React from \"react\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getExtension, getOptimizedPath } from \"./helpers.ts\";\n\nexport interface OptimizedImageProps {\n src: string;\n alt: string;\n width?: number;\n height?: number;\n sizes?: string;\n formats?: (\"avif\" | \"webp\" | \"jpeg\" | \"png\")[];\n quality?: number;\n loading?: \"lazy\" | \"eager\";\n priority?: boolean;\n className?: string;\n style?: React.CSSProperties;\n placeholder?: \"blur\" | \"empty\";\n blurDataURL?: string;\n onClick?: (event: React.MouseEvent<HTMLImageElement>) => void;\n onLoad?: (event: React.SyntheticEvent<HTMLImageElement>) => void;\n onError?: (event: React.SyntheticEvent<HTMLImageElement>) => void;\n}\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\nconst DEFAULT_FORMATS: (\"avif\" | \"webp\" | \"jpeg\")[] = [\"avif\", \"webp\", \"jpeg\"];\n\nexport function OptimizedImage({\n src,\n alt,\n width,\n height,\n sizes = \"100vw\",\n formats = DEFAULT_FORMATS,\n quality = 80,\n loading,\n priority = false,\n className,\n style,\n placeholder = \"empty\",\n blurDataURL,\n onClick,\n onLoad,\n onError,\n}: OptimizedImageProps) {\n const loadingStrategy = priority ? \"eager\" : loading || \"lazy\";\n\n const originalFormat = getExtension(src);\n\n const imgStyle: React.CSSProperties = {\n ...style,\n ...(placeholder === \"blur\" && blurDataURL\n ? { backgroundImage: `url(${blurDataURL})`, backgroundSize: \"cover\" }\n : {}),\n };\n\n return (\n <picture>\n {formats.map((format) => (\n <source\n key={format}\n type={`image/${format}`}\n srcSet={generateSrcSet(src, format, DEFAULT_SIZES, quality)}\n sizes={sizes}\n />\n ))}\n\n <img\n src={getOptimizedPath(src, originalFormat, width || RESPONSIVE_IMAGE_WIDTH_LG, quality)}\n alt={alt}\n width={width}\n height={height}\n loading={loadingStrategy}\n decoding=\"async\"\n className={className}\n style={imgStyle}\n onClick={onClick}\n onLoad={onLoad}\n onError={onError}\n />\n </picture>\n );\n}\n", "export function getOptimizedPath(\n src: string,\n format: string,\n size: number,\n _quality: number = 80,\n): string {\n const basePath = src.replace(/\\.[^.]+$/, \"\");\n const optimizedDir = \".veryfront/optimized-images\";\n\n return `/${optimizedDir}${basePath}-${size}w.${format}`;\n}\n\nexport function generateSrcSet(\n src: string,\n format: string,\n sizes: number[],\n quality: number,\n): string {\n return sizes\n .map((size) => {\n const path = getOptimizedPath(src, format, size, quality);\n return `${path} ${size}w`;\n })\n .join(\", \");\n}\n\nexport function getExtension(src: string): string {\n const match = src.match(/\\.([^.]+)$/);\n const extension = match?.[1];\n return extension ? extension.toLowerCase() : \"jpeg\";\n}\n", "import React from \"react\";\nimport type { OptimizedImageProps } from \"./OptimizedImage.tsx\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getOptimizedPath } from \"./helpers.ts\";\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\n\nexport function SimpleOptimizedImage({\n src,\n alt,\n width,\n height,\n format = \"webp\",\n quality = 80,\n loading = \"lazy\",\n className,\n style,\n onClick,\n onLoad,\n onError,\n}: Omit<OptimizedImageProps, \"formats\" | \"sizes\" | \"priority\" | \"placeholder\" | \"blurDataURL\"> & {\n format?: \"webp\" | \"avif\" | \"jpeg\" | \"png\";\n}) {\n const srcSet = generateSrcSet(src, format, DEFAULT_SIZES, quality);\n\n return (\n <img\n src={getOptimizedPath(src, format, width || RESPONSIVE_IMAGE_WIDTH_LG, quality)}\n srcSet={srcSet}\n alt={alt}\n width={width}\n height={height}\n loading={loading}\n decoding=\"async\"\n className={className}\n style={style as React.CSSProperties}\n onClick={onClick}\n onLoad={onLoad}\n onError={onError}\n />\n );\n}\n", "import React from \"react\";\nimport { RESPONSIVE_IMAGE_WIDTH_LG } from \"@veryfront/utils/constants/network.ts\";\nimport { getOptimizedPath } from \"./helpers.ts\";\n\nexport function OptimizedBackgroundImage({\n src,\n children,\n format = \"webp\",\n quality = 80,\n size = RESPONSIVE_IMAGE_WIDTH_LG,\n className,\n style,\n}: {\n src: string;\n children?: React.ReactNode;\n format?: \"webp\" | \"avif\" | \"jpeg\" | \"png\";\n quality?: number;\n size?: number;\n className?: string;\n style?: React.CSSProperties;\n}) {\n const optimizedSrc = getOptimizedPath(src, format, size, quality);\n\n const bgStyle: React.CSSProperties = {\n backgroundImage: `url(${optimizedSrc})`,\n backgroundSize: \"cover\",\n backgroundPosition: \"center\",\n backgroundRepeat: \"no-repeat\",\n ...style,\n };\n\n return (\n <div className={className} style={bgStyle}>\n {children}\n </div>\n );\n}\n", "import { RESPONSIVE_IMAGE_WIDTH_LG, RESPONSIVE_IMAGE_WIDTHS } from \"@veryfront/utils\";\nimport { generateSrcSet, getExtension, getOptimizedPath } from \"./helpers.ts\";\n\nconst DEFAULT_SIZES = [...RESPONSIVE_IMAGE_WIDTHS];\nconst DEFAULT_FORMATS: (\"avif\" | \"webp\" | \"jpeg\")[] = [\"avif\", \"webp\", \"jpeg\"];\n\nexport function useOptimizedImage(\n src: string,\n options: {\n formats?: (\"avif\" | \"webp\" | \"jpeg\" | \"png\")[];\n quality?: number;\n } = {},\n) {\n const formats = options.formats || DEFAULT_FORMATS;\n const quality = options.quality || 80;\n\n const sources = formats.map((format) => ({\n format,\n srcSet: generateSrcSet(src, format, DEFAULT_SIZES, quality),\n type: `image/${format}`,\n }));\n\n const fallback = getOptimizedPath(\n src,\n getExtension(src),\n RESPONSIVE_IMAGE_WIDTH_LG,\n quality,\n );\n\n return {\n sources,\n fallback,\n };\n}\n", "import React from \"react\";\n\nexport function generateBlurDataURL(\n width: number = 10,\n height: number = 10,\n color: string = \"#cccccc\",\n): string {\n const svg = `\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${width} ${height}\">\n <rect width=\"${width}\" height=\"${height}\" fill=\"${color}\"/>\n </svg>\n `;\n\n return `data:image/svg+xml;base64,${btoa(svg)}`;\n}\n\nexport function getAspectRatioPadding(width: number, height: number): string {\n return `${(height / width) * 100}%`;\n}\n\nexport function ResponsiveImageContainer({\n width,\n height,\n children,\n className,\n style,\n}: {\n width: number;\n height: number;\n children: React.ReactNode;\n className?: string;\n style?: React.CSSProperties;\n}) {\n const containerStyle = {\n position: \"relative\" as const,\n width: \"100%\",\n paddingBottom: getAspectRatioPadding(width, height),\n ...style,\n };\n\n const contentStyle = {\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n height: \"100%\",\n } as const;\n\n return (\n <div className={className} style={containerStyle}>\n <div style={contentStyle}>{children}</div>\n </div>\n );\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;AAAA;AAAA;AAMA,eAAW,OAAO,WAAW,QAAQ;AAAA,MACnC,KAAK;AAAA,QACH,IAAI,KAAiC;AACnC,iBAAO,QAAQ,IAAI,GAAG;AAAA,QACxB;AAAA,QACA,IAAI,KAAa,OAAqB;AACpC,kBAAQ,IAAI,GAAG,IAAI;AAAA,QACrB;AAAA,QACA,OAAO,KAAmB;AACxB,iBAAO,QAAQ,IAAI,GAAG;AAAA,QACxB;AAAA,QACA,IAAI,KAAsB;AACxB,iBAAO,OAAO,QAAQ;AAAA,QACxB;AAAA,QACA,WAAmC;AACjC,iBAAO,EAAE,GAAG,QAAQ,IAAI;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA;AAAA;;;ACFO,SAAS,eAAe,QAA2C;AACxE,SACE,OAAO,WAAW,YAClB,WAAW,QACX,UAAU,UACV,OAAQ,OAA0B,MAAM,KAAK,QAAQ;AAEzD;AAEO,SAAS,eAAe,QAA8C;AAC3E,SACE,OAAO,WAAW,YAClB,WAAW,QACX,aAAa,UACb,OAAQ,OAA6B,SAAS,QAAQ;AAE1D;AAEO,SAAS,cAAc,QAA0C;AACtE,SACE,OAAO,WAAW,YAClB,WAAW,QACX,SAAS,UACT,OAAQ,OAAyB,QAAQ;AAE7C;AA/CA;AAAA;AAAA;AAAA;AAAA;;;ACGO,SAAS,uBAAuB,MAAkC;AACvE,MAAI;AACF,QAAI,OAAO,SAAS,eAAe,eAAe,UAAU,GAAG;AAC7D,YAAM,QAAS,WAA8B,MAAM,IAAI,IAAI,IAAI;AAC/D,aAAO,UAAU,KAAK,SAAY;AAAA,IACpC;AACA,QAAI,eAAe,UAAU,GAAG;AAC9B,YAAM,QAAS,WAAiC,SAAS,IAAI,IAAI;AACjE,aAAO,UAAU,KAAK,SAAY;A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C,KAAK,IAAI,MAAM;AAAA,qBACrD,KAAK,aAAa,MAAM,WAAW,KAAK;AAAA;AAAA;AAI3D,SAAO,6BAA6B,KAAK,GAAG,CAAC;AAC/C;AAEO,SAAS,sBAAsB,OAAe,QAAwB;AAC3E,SAAO,GAAI,SAAS,QAAS,GAAG;AAClC;AAEO,SAAS,yBAAyB;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAMG;AACD,QAAM,iBAAiB;AAAA,IACrB,UAAU;AAAA,IACV,OAAO;AAAA,IACP,eAAe,sBAAsB,OAAO,MAAM;AAAA,IAClD,GAAG;AAAA,EACL;AAEA,QAAM,eAAe;AAAA,IACnB,UAAU;AAAA,IACV,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA,IACP,QAAQ;AAAA,EACV;AAEA,SACE,gBAAAA,KAAC,SAAI,WAAsB,OAAO,gBAChC,0BAAAA,KAAC,SAAI,OAAO,cAAe,UAAS,GACtC;AAEJ;",
6
6
  "names": ["logger", "LogLevel", "init_logger", "hasNodeProcess", "init_env", "init_env", "simpleHash", "init_logger", "init_logger", "simpleHash", "init_logger", "init_deno", "serverLogger", "join", "join", "path", "process", "serverLogger", "crypto", "init_node", "ErrorCode", "ErrorCode", "init_build_errors", "ErrorCode", "init_runtime_errors", "ErrorCode", "ErrorCode", "ErrorCode", "ErrorCode", "ErrorCode", "ErrorCode", "ErrorCode", "ErrorCode", "init_build_errors", "init_runtime_errors", "deno_exports", "init_deno", "node_exports", "blue", "bold", "colors", "cyan", "dim", "gray", "green", "italic", "magenta", "red", "reset", "strikethrough", "underline", "white", "yellow", "init_node", "init_filesystem_adapter", "join", "init_environment_adapter", "init_websocket_adapter", "init_http_server", "init_adapter", "init_filesystem_adapter", "init_environment_adapter", "init_websocket_adapter", "init_http_server", "init_adapter", "init_filesystem_adapter", "init_environment_adapter", "init_websocket_adapter", "init_http_server", "init_bun", "denoAdapter", "nodeAdapter", "bunAdapter", "createMockAdapter", "isDeno", "isBun", "isCloudflare", "denoAdapter", "bunAdapter", "nodeAdapter", "init_deno", "init_node", "init_bun", "join", "join", "HTTP_MODULE_FETCH_TIMEOUT_MS", "require", "HASH_SEED_FNV1A", "getAdapter", "filePath", "result", "getAdapter", "useMemo", "useRef", "Fragment", "jsx", "useRef", "useMemo", "jsx", "React", "jsx", "jsx", "getExtension", "jsx", "getExtension", "jsx", "DEFAULT_SIZES", "jsx", "DEFAULT_SIZES", "DEFAULT_FORMATS", "getExtension", "jsx"]
7
7
  }