@devlusoft/devix 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/build.js +15 -6
- package/dist/cli/build.js.map +2 -2
- package/dist/cli/dev-server.js +19 -10
- package/dist/cli/dev-server.js.map +2 -2
- package/dist/cli/generate.js +10 -1
- package/dist/cli/generate.js.map +2 -2
- package/dist/cli/index.js +12 -3
- package/dist/cli/index.js.map +2 -2
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/index.js.map +3 -3
- package/dist/runtime/router-provider.d.ts +12 -3
- package/dist/runtime/router-provider.js +1 -1
- package/dist/runtime/router-provider.js.map +3 -3
- package/dist/utils/banner.js +1 -1
- package/dist/vite/codegen/entry-client.js +12 -3
- package/dist/vite/codegen/entry-client.js.map +2 -2
- package/dist/vite/index.js +14 -5
- package/dist/vite/index.js.map +2 -2
- package/package.json +6 -1
package/dist/cli/generate.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/load-config.ts", "../../src/vite/codegen/entry-client.ts", "../../src/vite/codegen/client-routes.ts", "../../src/vite/codegen/render.ts", "../../src/vite/codegen/api.ts", "../../src/vite/codegen/context.ts", "../../src/vite/codegen/extract-methods.ts", "../../src/utils/patterns.ts", "../../src/server/api-router.ts", "../../src/vite/codegen/routes-dts.ts", "../../src/vite/codegen/scan-api.ts", "../../src/vite/codegen/write-routes-dts.ts", "../../src/vite/codegen/server-entry.ts", "../../src/vite/codegen/page-types.ts", "../../src/vite/index.ts", "../../src/utils/duration.ts", "../../src/cli/build.ts", "../../src/cli/generate.ts"],
|
|
4
|
-
"sourcesContent": ["import {build} from 'esbuild'\nimport type {DevixConfig} from \"../config\"\nimport {join} from \"node:path\"\nimport {unlinkSync, writeFileSync} from \"node:fs\";\nimport {pathToFileURL} from \"node:url\";\n\nexport async function loadConfig(cwd: string): Promise<DevixConfig> {\n const result = await build({\n entryPoints: [join(cwd, 'devix.config.ts')],\n bundle: true,\n write: false,\n format: 'esm',\n platform: 'node',\n packages: 'external',\n })\n\n const tmpFile = join(cwd, `.devix-config-${Date.now()}.mjs`)\n writeFileSync(tmpFile, result.outputFiles[0].text)\n\n try {\n const mod = await import(pathToFileURL(tmpFile).href)\n return mod.default\n } finally {\n unlinkSync(tmpFile)\n }\n}", "interface EntryClientOptions {\n cssUrls: string[]\n}\n\nexport function generateEntryClient({ cssUrls }: EntryClientOptions): string {\n const cssImports = cssUrls.map(u => `import '${u}'`).join('\\n')\n\n return `\n${cssImports}\nimport \"@vitejs/plugin-react/preamble\"\nimport React from \"react\"\nimport {hydrateRoot, createRoot} from 'react-dom/client'\nimport {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'\nimport {RouterProvider} from '@devlusoft/devix'\n\nconst root = document.getElementById('devix-root')\n\nif (!window.__DEVIX__) {\n const ErrorPage = getDefaultErrorPage()\n createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))\n} else {\n const {metadata, viewport, clientEntry} = window.__DEVIX__\n const loaderData = window.__LOADER_DATA__\n const layoutsData = window.__LAYOUTS_DATA__ ?? []\n const guardData = window.__GUARD_DATA__ ?? null\n\n const matched = matchClientRoute(window.location.pathname)\n\n if (window.__LOADER_ERROR__) {\n const {statusCode, message, code, data} = window.__LOADER_ERROR__\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialError: {statusCode, message, code, data},\n initialErrorPage: ErrorPage,\n })\n )\n } else if (matched) {\n const [pageMod, ...layoutMods] = await Promise.all([\n matched.load(),\n ...matched.loadLayouts.map(l => l()),\n ])\n hydrateRoot(\n root,\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: loaderData,\n initialParams: matched.params,\n initialPage: pageMod.default,\n initialLayouts: layoutMods.map(m => m.default),\n initialLayoutsData: layoutsData,\n initialGuardData: guardData,\n initialMeta: metadata,\n initialViewport: viewport,\n })\n )\n\n if (window.location.hash) { \n const id = window.location.hash.slice(1) \n const scrollBehavior = getComputedStyle(document.documentElement).scrollBehavior \n requestAnimationFrame(() => { \n document.getElementById(id)?.scrollIntoView({ behavior: scrollBehavior }) \n }) \n } \n } else {\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialLayouts: [],\n initialLayoutsData: [],\n initialMeta: null,\n initialError: {statusCode: 404, message: 'Not found'},\n initialErrorPage: ErrorPage,\n })\n )\n }\n}\n`\n}", "interface ClientRoutesOptions {\n pagesDir: string\n matcherPath: string\n}\n\nexport function generateClientRoutes({pagesDir, matcherPath}: ClientRoutesOptions) {\n return `\nimport React from 'react'\nimport { createMatcher } from '${matcherPath}'\nconst pageFiles = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst layoutFiles = import.meta.glob('/${pagesDir}/**/layout.tsx')\nconst errorFiles = import.meta.glob('/${pagesDir}/**/error.tsx')\n\nexport const matchClientRoute = createMatcher(pageFiles, layoutFiles)\n\nexport async function loadErrorPage() {\n const key = Object.keys(errorFiles)[0]\n if (!key) return null\n const mod = await errorFiles[key]()\n return mod?.default ?? null\n}\n\nexport function getDefaultErrorPage() {\n return function DefaultError({ statusCode, message }) {\n return React.createElement('main', {\n style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column', \n alignItems: 'center', justifyContent: 'center', gap: '8px',\n fontFamily: 'system-ui, sans-serif' }\n },\n React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),\n React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),\n )\n }\n}\n`\n}", "interface RenderOptions {\n pagesDir: string\n renderPath: string\n}\n\nexport function generateRender({pagesDir, renderPath}: RenderOptions): string {\n return `\nimport { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${renderPath}'\n\nconst _pages = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst _layouts = import.meta.glob('/${pagesDir}/**/layout.tsx')\n\nconst _glob = {\n pages: _pages,\n layouts: _layouts,\n pagesDir: '/${pagesDir}',\n}\n\nexport function render(url, request, options) {\n return _render(url, request, _glob, options)\n}\n\nexport function runLoader(url, request, options) {\n return _runLoader(url, request, _glob, options)\n}\n\nexport function getStaticRoutes() {\n return _getStaticRoutes(_glob)\n}\n`\n}\n", "interface ApiOptions {\n apiPath: string\n appDir: string\n}\n\nexport function generateApi({apiPath, appDir}: ApiOptions): string {\n return `\nimport { handleApiRequest as _handleApiRequest } from '${apiPath}'\n\nconst _routes = import.meta.glob(['/${appDir}/api/**/*.ts', '!**/middleware.ts'])\nconst _middlewares = import.meta.glob('/${appDir}/api/**/middleware.ts')\n\nconst _glob = {\n routes: _routes,\n middlewares: _middlewares,\n apiDir: '/${appDir}/api',\n}\n\nexport function handleApiRequest(url, request) {\n return _handleApiRequest(url, request, _glob)\n}\n`\n}\n", "export function generateContext(): string {\n return `\nexport {RouterContext} from '@devlusoft/devix/runtime/context'\n`\n}", "const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nconst METHOD_EXPORT_RE = /export\\s+(?:const|async\\s+function|function)\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/g\n\nfunction stripComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/.*$/gm, '')\n}\n\nexport function extractHttpMethods(content: string): HttpMethod[] {\n const found = new Set<HttpMethod>()\n for (const match of stripComments(content).matchAll(METHOD_EXPORT_RE)) {\n found.add(match[1] as HttpMethod)\n }\n return [...found]\n}\n", "export function routePattern(rel: string): string {\n return rel\n .replace(/\\.(tsx|ts|jsx|js)$/, '')\n .replace(/\\(.*?\\)\\//g, '')\n .replace(/^index$|\\/index$/, '')\n .replace(/\\[([^\\]]+)]/g, ':$1')\n || '/'\n}", "import {routePattern} from \"../utils/patterns\";\n\nexport interface ApiRoute {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface ApiMiddleware {\n dir: string\n key: string\n}\n\nexport interface ApiResult {\n routes: ApiRoute[]\n middlewares: ApiMiddleware[]\n}\n\nexport function keyToRoutePattern(key: string, apiDir: string): string {\n const rel = key.slice(apiDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === '/' ? '/api' : `/api/${pattern}`.replace('/api//', '/api/')\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nexport function buildRoutes(routeKeys: string[], middlewareKeys: string[], apiDir: string): ApiResult {\n const routes: ApiRoute[] = []\n const middlewares: ApiMiddleware[] = []\n\n for (const key of middlewareKeys) {\n middlewares.push({dir: keyToDir(key), key})\n }\n\n for (const key of routeKeys) {\n const pattern = keyToRoutePattern(key, apiDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n routes.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n routes.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n return {routes, middlewares}\n}\n\nexport function collectMiddlewareChain(routeKey: string, middlewares: ApiMiddleware[]): ApiMiddleware[] {\n const routeDir = keyToDir(routeKey)\n\n return middlewares\n .filter(mw => routeDir.startsWith(mw.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchRoute(\n pathname: string,\n routes: ApiRoute[]\n): { route: ApiRoute; params: Record<string, string> } | null {\n for (const route of routes) {\n const match = pathname.match(route.regex)\n if (match) {\n const params: Record<string, string> = {}\n route.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {route, params}\n }\n }\n return null\n}\n", "import { keyToRoutePattern } from '../../server/api-router'\nimport type { HttpMethod } from './extract-methods'\n\nexport interface RouteEntry {\n filePath: string\n urlPattern: string\n identifier: string\n methods: HttpMethod[]\n}\n\nexport function filePathToIdentifier(filePath: string, apiDir: string): string {\n return '_api_' + filePath\n .slice(`${apiDir}/`.length)\n .replace(/\\.(ts|tsx)$/, '')\n .replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nexport function buildRouteEntry(filePath: string, apiDir: string, methods: HttpMethod[]): RouteEntry {\n return {\n filePath,\n urlPattern: keyToRoutePattern(filePath, apiDir),\n identifier: filePathToIdentifier(filePath, apiDir),\n methods,\n }\n}\n\nexport function generateRoutesDts(entries: RouteEntry[], apiDir: string): string {\n if (entries.length === 0) {\n return `// auto-generado por devix \u2014 no editar\\nexport {}\\ndeclare module '@devlusoft/devix' {\\n interface ApiRoutes {}\\n}\\n`\n }\n\n const imports = entries\n .map(e => {\n const importPath = '../' + e.filePath.replace(/\\.(ts|tsx)$/, '')\n return `import type * as ${e.identifier} from '${importPath}'`\n })\n .join('\\n')\n\n const routeLines = entries.flatMap(e =>\n e.methods.map(m =>\n ` '${m} ${e.urlPattern}': InferRoute<(typeof ${e.identifier})['${m}']>`\n )\n ).join('\\n')\n\n return `// auto-generado por devix \u2014 no editar\n${imports}\n\ntype JsonResponse<T, S extends number = number> = Response & { readonly __body: T; readonly __status: S }\ntype Is2xx<S extends number> = [number] extends [S] ? boolean : S extends 200 | 201 | 202 | 203 | 204 | 205 | 206 ? true : false\ntype UnwrapSuccessJson<T> = T extends JsonResponse<infer U, infer S> ? Is2xx<S> extends false ? never : U : never\ntype UnwrapErrorJson<T> = T extends JsonResponse<infer U, infer S> ? Is2xx<S> extends true ? never : U : never\ntype InferFnSuccess<T> = T extends (...args: any[]) => any ? UnwrapSuccessJson<Awaited<ReturnType<T>>> : never\ntype InferFnErrors<T> = T extends (...args: any[]) => any ? UnwrapErrorJson<Awaited<ReturnType<T>>> : never\ntype InferRoute<T> =\n T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }\n ? {\n __body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>\n __response: InferFnSuccess<() => TReturn>\n __errors: InferFnErrors<() => TReturn>\n }\n : InferFnSuccess<T>\n\ndeclare module '@devlusoft/devix' {\n interface ApiRoutes {\n${routeLines}\n }\n}\n`\n}\n", "import {readFileSync, readdirSync, statSync} from 'node:fs'\nimport {join, relative} from 'node:path'\nimport {extractHttpMethods} from './extract-methods'\nimport {buildRouteEntry} from './routes-dts'\nimport type {RouteEntry} from './routes-dts'\n\nfunction walkDir(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkDir(full, root))\n } else if (/\\.(ts|tsx)$/.test(name)) {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport function scanApiFiles(appDir: string, projectRoot: string): RouteEntry[] {\n const apiDir = join(projectRoot, appDir, 'api')\n\n let files: string[]\n try {\n files = walkDir(apiDir, projectRoot)\n } catch {\n return []\n }\n\n return files\n .filter(f => !f.endsWith('middleware.ts') && !f.endsWith('middleware.tsx'))\n .flatMap(filePath => {\n try {\n const content = readFileSync(join(projectRoot, filePath), 'utf-8')\n const methods = extractHttpMethods(content)\n if (methods.length === 0) return []\n return [buildRouteEntry(filePath, `${appDir}/api`, methods)]\n } catch {\n return []\n }\n })\n}\n", "import {mkdirSync, readFileSync, writeFileSync, existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nexport function writeRoutesDts(content: string, projectRoot: string): boolean {\n const devixDir = join(projectRoot, '.devix')\n const outPath = join(devixDir, 'routes.d.ts')\n\n mkdirSync(devixDir, {recursive: true})\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) {\n return false\n }\n\n writeFileSync(outPath, content, 'utf-8')\n return true\n}\n", "interface ServerEntryOptions {\n routesPath: string\n envPath: string\n honoServerPath: string\n honoServerStaticPath: string\n honoPath: string\n}\n\nexport function generateServerEntry({ routesPath, envPath, honoServerPath, honoServerStaticPath, honoPath }: ServerEntryOptions): string {\n return `\nimport { readFileSync } from 'node:fs'\n import { serve } from '${honoServerPath}'\n import { serveStatic } from '${honoServerStaticPath}'\n import { Hono } from '${honoPath}'\n import { resolve, join, dirname } from 'node:path'\n import { pathToFileURL } from 'node:url'\n import { registerApiRoutes, registerSsrRoute } from '${routesPath}' \n import { loadDotenv } from '${envPath}'\n \n loadDotenv('production')\n \n const __dir = dirname(process.argv[1])\n\n let renderModule, apiModule, manifest, runtimeConfig \n \n try { \n runtimeConfig = JSON.parse(readFileSync(resolve(__dir, '../devix.config.json'), 'utf-8'))\n if (runtimeConfig.output !== 'static') { \n renderModule = await import(pathToFileURL(resolve(__dir, 'render.js')).href)\n apiModule = await import(pathToFileURL(resolve(__dir, 'api.js')).href) \n } \n manifest = JSON.parse(readFileSync(resolve(__dir, '../client/.vite/manifest.json'), 'utf-8')) \n } catch { \n console.error('[devix] Build not found. Run \"devix build\" first.')\n process.exit(1) \n } \n \n const port = Number(process.env.PORT) || runtimeConfig.port || 3000 \n const host = typeof runtimeConfig.host === 'string'\n ? runtimeConfig.host \n : runtimeConfig.host ? '0.0.0.0' : (process.env.HOST || '0.0.0.0') \n \n const clientRoot = resolve(__dir, '../client') \n const app = new Hono()\n \n if (runtimeConfig.output === 'static') {\n app.get('/_data/*', (c) => {\n const pathname = c.req.path.replace(/^\\\\/_data/, '') || '/' \n const filePath = pathname === '/' \n ? join(clientRoot, '_data/index.json') \n : join(clientRoot, '_data', pathname + '.json') \n try { \n return c.json(JSON.parse(readFileSync(filePath, 'utf-8')))\n } catch { \n return c.json({ error: 'not found' }, 404)\n } \n }) \n }\n\n app.use('/*', serveStatic({ \n root: clientRoot,\n onFound: (_path, c) => { \n c.header('Cache-Control', _path.includes('/assets/') \n ? 'public, immutable, max-age=31536000'\n : 'no-cache') \n } \n })) \n \n if (runtimeConfig.output === 'static') {\n console.log('[devix] Static mode \u2014 serving pre-generated files from dist/client')\n } else {\n let userServerConfig\n try {\n const userConfigMod = await import(pathToFileURL(resolve(process.cwd(), 'devix.config.ts')).href).catch(() =>\n import(pathToFileURL(resolve(process.cwd(), 'devix.config.js')).href))\n userServerConfig = userConfigMod?.default?.server\n } catch {\n /* config sin server \u2014 sigue normal */\n }\n registerApiRoutes(app, { renderModule, apiModule, manifest, server: userServerConfig })\n registerSsrRoute(app, { renderModule, apiModule, manifest, loaderTimeout: runtimeConfig.loaderTimeout, server: userServerConfig })\n } \n \n const server = serve({ fetch: app.fetch, port, hostname: host }, (info) => \n console.log(\\`http://\\${info.address}:\\${info.port}\\`))\n\nprocess.on('SIGTERM', () => server.close())\nprocess.on('SIGINT', () => server.close())\n`\n}", "import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync} from \"node:fs\";\nimport {join, relative} from \"node:path\";\nimport {parseSync} from \"oxc-parser\";\n\nfunction walkPages(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkPages(full, root))\n } else if (/\\.(ts|tsx)$/.test(name) && name !== 'layout.tsx' && name !== 'error.tsx') {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport interface LoaderExportInfo {\n exists: boolean\n isAsync: boolean\n isReExport: boolean\n}\n\nexport function inspectLoaderExport(code: string, filePath: string): LoaderExportInfo {\n const ast = parseSync(filePath, code, {sourceType: 'module'})\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration') continue\n const decl = node.declaration\n if (decl?.type === 'FunctionDeclaration' && decl.id?.name === 'loader') {\n return {exists: true, isAsync: decl.async, isReExport: false}\n }\n if (decl?.type === 'VariableDeclaration') {\n for (const d of decl.declarations) {\n if (d.id.type === 'Identifier' && d.id.name === 'loader') {\n const init = d.init\n const isAsync =\n (init?.type === 'ArrowFunctionExpression' && init.async) ||\n (init?.type === 'FunctionExpression' && init.async)\n return {exists: true, isAsync, isReExport: false}\n }\n }\n }\n for (const spec of (node.specifiers ?? [])) {\n if (spec.exported.type === 'Identifier' && spec.exported.name === 'loader') {\n return {exists: true, isAsync: false, isReExport: true}\n }\n }\n }\n return {exists: false, isAsync: false, isReExport: false}\n}\n\nexport function hasLoaderExport(code: string, filePath: string): boolean {\n return inspectLoaderExport(code, filePath).exists\n}\n\nexport function generatePageTypesDts(importPath: string, withLoader: boolean): string {\n if (!withLoader) {\n return '// auto-generado por devix - no editar\\nexport type PageData = undefined\\nexport type PageParams = Record<string, string>\\n'\n }\n return `// auto-generado por devix \u2014 no editar\\nimport type { loader } from \"${importPath}\"\\nimport type { Redirect } from \"@devlusoft/devix\"\\n\\nexport type PageData = Exclude<\\n Awaited<ReturnType<NonNullable<typeof loader>>>,\\n Redirect | void | undefined\\n>\\nexport type PageParams = NonNullable<Parameters<typeof loader>[0]>[\"params\"]\\n`\n}\n\nexport interface WritePageTypesResult {\n warnings: string[]\n}\n\nexport function writePageTypes(pageRelPath: string, root: string): WritePageTypesResult {\n const fullPath = join(root, pageRelPath)\n const code = readFileSync(fullPath, 'utf-8')\n const loaderInfo = inspectLoaderExport(code, fullPath)\n const warnings: string[] = []\n\n if (loaderInfo.exists && !loaderInfo.isAsync && !loaderInfo.isReExport) {\n warnings.push(\n `[devix] ${pageRelPath}: 'loader' must be async. ` +\n `Use 'export async function loader' or 'export const loader = async (...) => ...'.`\n )\n }\n\n const typesDir = join(root, '.devix', 'pages', pageRelPath.replace(/\\.(tsx?|jsx?)$/, ''))\n const outPath = join(typesDir, '$types.d.ts')\n\n const pageAbsNoExt = fullPath.replace(/\\.(tsx?|jsx?)$/, '')\n const importPath = relative(typesDir, pageAbsNoExt).replace(/\\\\/g, '/')\n\n const content = generatePageTypesDts(importPath, loaderInfo.exists)\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) return {warnings}\n\n mkdirSync(typesDir, {recursive: true})\n writeFileSync(outPath, content, 'utf-8')\n return {warnings}\n}\n\nexport function deletePageTypes(pageRelPath: string, root: string): void {\n const typesDir = join(root, '.devix', 'pages', pageRelPath.replace(/\\.(tsx?|jsx?)$/, ''))\n const outPath = join(typesDir, '$types.d.ts')\n if (existsSync(outPath)) rmSync(outPath)\n}\n\nexport function scanAndWritePageTypes(appDir: string, root: string): WritePageTypesResult {\n const pagesDir = join(root, appDir, 'pages')\n const warnings: string[] = []\n let files: string[]\n try {\n files = walkPages(pagesDir, root)\n } catch {\n return {warnings}\n }\n for (const file of files) {\n try {\n const result = writePageTypes(file, root)\n warnings.push(...result.warnings)\n } catch {\n /* ignorar archivos no procesables */\n }\n }\n return {warnings}\n}", "import {UserConfig, Plugin, mergeConfig} from 'vite'\nimport type {DevixConfig} from '../config'\nimport react from '@vitejs/plugin-react'\nimport {fileURLToPath} from 'node:url'\nimport {dirname, relative, resolve} from 'node:path'\nimport {createRequire} from 'node:module'\nimport {generateEntryClient} from './codegen/entry-client'\nimport {generateClientRoutes} from './codegen/client-routes'\nimport {generateRender} from './codegen/render'\nimport {generateApi} from './codegen/api'\nimport {generateContext} from \"./codegen/context\";\nimport {scanApiFiles} from \"./codegen/scan-api\";\nimport {generateRoutesDts} from \"./codegen/routes-dts\";\nimport {writeRoutesDts} from \"./codegen/write-routes-dts\";\nimport {parseSync} from 'oxc-parser'\nimport {generateServerEntry} from \"./codegen/server-entry\";\nimport {deletePageTypes, scanAndWritePageTypes, writePageTypes} from \"./codegen/page-types\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst VIRTUAL_ENTRY_CLIENT = 'virtual:devix/entry-client'\nconst VIRTUAL_CLIENT_ROUTES = 'virtual:devix/client-routes'\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\nconst VIRTUAL_CONTEXT = 'virtual:devix/context'\nconst VIRTUAL_SERVER_ENTRY = 'virtual:devix/server-entry'\n\nconst SERVER_EXPORTS = new Set(['loader', 'guard', 'generateStaticParams', 'headers'])\n\nexport function devix(config: DevixConfig): UserConfig {\n const appDir = config.appDir ?? 'app'\n const pagesDir = `${appDir}/pages`\n const cssUrls = (config.css ?? []).map(u => u.startsWith('/') ? u : `/${u.replace(/^\\.\\//, '')}`)\n\n const renderPath = resolve(__dirname, '../server/render.js').replace(/\\\\/g, '/')\n const apiPath = resolve(__dirname, '../server/api.js').replace(/\\\\/g, '/')\n const matcherPath = resolve(__dirname, '../runtime/client-router.js').replace(/\\\\/g, '/')\n const routesPath = resolve(__dirname, '../server/routes.js').replace(/\\\\/g, '/')\n const envPath = resolve(__dirname, '../utils/env.js').replace(/\\\\/g, '/')\n\n const _require = createRequire(import.meta.url)\n const honoServerPath = _require.resolve('@hono/node-server').replace(/\\\\/g, '/')\n const honoServerStaticPath = _require.resolve('@hono/node-server/serve-static').replace(/\\\\/g, '/')\n const honoPath = _require.resolve('hono').replace(/\\\\/g, '/')\n\n const virtualPlugin: Plugin = {\n name: 'devix',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ENTRY_CLIENT) return `\\0${VIRTUAL_ENTRY_CLIENT}`\n if (id === VIRTUAL_CLIENT_ROUTES) return `\\0${VIRTUAL_CLIENT_ROUTES}`\n if (id === VIRTUAL_RENDER) return `\\0${VIRTUAL_RENDER}`\n if (id === VIRTUAL_API) return `\\0${VIRTUAL_API}`\n if (id === VIRTUAL_CONTEXT) return `\\0${VIRTUAL_CONTEXT}`\n if (id === VIRTUAL_SERVER_ENTRY) return `\\0${VIRTUAL_SERVER_ENTRY}`\n },\n\n load(id) {\n if (id === `\\0${VIRTUAL_ENTRY_CLIENT}`)\n return generateEntryClient({cssUrls})\n if (id === `\\0${VIRTUAL_CLIENT_ROUTES}`)\n return generateClientRoutes({pagesDir, matcherPath})\n if (id === `\\0${VIRTUAL_RENDER}`)\n return generateRender({pagesDir, renderPath})\n if (id === `\\0${VIRTUAL_API}`)\n return generateApi({apiPath, appDir})\n if (id === `\\0${VIRTUAL_CONTEXT}`)\n return generateContext()\n if (id === `\\0${VIRTUAL_SERVER_ENTRY}`)\n return generateServerEntry({routesPath, envPath, honoServerPath, honoServerStaticPath, honoPath})\n },\n\n\n transform(code, id, options) {\n if (options?.ssr) return\n\n const resolvedPagesDir = resolve(process.cwd(), pagesDir)\n if (!id.startsWith(resolvedPagesDir)) return\n\n const ast = parseSync(id, code, {sourceType: 'module'})\n\n const replacements: { start: number; end: number; name: string }[] = []\n\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration' || !node.declaration) continue\n\n const decl = node.declaration\n\n if (decl.type === 'FunctionDeclaration' && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n replacements.push({start: node.start, end: node.end, name: decl.id.name})\n }\n\n if (decl.type === 'VariableDeclaration') {\n const seen = new Set<number>()\n for (const declarator of decl.declarations) {\n if (declarator.id.type === 'Identifier' && SERVER_EXPORTS.has(declarator.id.name)) {\n if (!seen.has(node.start)) {\n seen.add(node.start)\n replacements.push({start: node.start, end: node.end, name: declarator.id.name})\n }\n }\n }\n }\n }\n\n if (replacements.length === 0) return\n\n replacements.sort((a, b) => b.start - a.start)\n\n let result = code\n for (const {start, end, name} of replacements) {\n result = result.slice(0, start) + `export const ${name} = undefined` + result.slice(end)\n }\n\n return {code: result, map: null}\n },\n\n buildStart() {\n const root = process.cwd()\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n const {warnings} = scanAndWritePageTypes(appDir, root)\n for (const w of warnings) console.warn(w)\n },\n\n configureServer(server) {\n const root = process.cwd()\n\n const initial = scanAndWritePageTypes(appDir, root)\n for (const w of initial.warnings) console.warn(w)\n\n const regenerateDts = () => {\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n }\n\n const isPageFile = (file: string) => file.startsWith(resolve(root, pagesDir)) && !file.endsWith('layout.tsx') && !file.endsWith('error.tsx')\n\n const pageRelPath = (file: string) => relative(root, file).replace(/\\\\/g, '/')\n\n const invalidateVirtualModule = (id: string) => {\n const mod = server.moduleGraph.getModuleById(`\\0${id}`)\n if (mod) server.moduleGraph.invalidateModule(mod)\n }\n\n server.watcher.add(resolve(root, 'devix.config.ts'))\n server.watcher.on('change', (file) => {\n if (file === resolve(root, 'devix.config.ts')) {\n console.log('[devix] Config changed, restarting...')\n process.exit(75)\n }\n })\n\n const writePageTypesAndLog = (file: string) => {\n try {\n const {warnings} = writePageTypes(pageRelPath(file), root)\n for (const w of warnings) console.warn(w)\n } catch {\n /* ignorar archivos no procesables */\n }\n }\n\n server.watcher.on('add', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidateVirtualModule(VIRTUAL_RENDER)\n if (isPageFile(file)) writePageTypesAndLog(file)\n if (file.includes(`${appDir}/api`)) {\n invalidateVirtualModule(VIRTUAL_API)\n regenerateDts()\n }\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidateVirtualModule(VIRTUAL_RENDER)\n if (isPageFile(file)) deletePageTypes(pageRelPath(file), root)\n if (file.includes(`${appDir}/api`)) {\n invalidateVirtualModule(VIRTUAL_API)\n regenerateDts()\n }\n })\n server.watcher.on('change', (file) => {\n if (isPageFile(file)) writePageTypesAndLog(file)\n if (file.includes(`${appDir}/api`) && !file.endsWith('middleware.ts')) {\n regenerateDts()\n }\n })\n },\n }\n\n const base: UserConfig = {\n plugins: [react(), virtualPlugin],\n publicDir: resolve(process.cwd(), config.publicDir ?? 'public'),\n ssr: {noExternal: ['@devlusoft/devix']},\n ...(config.envPrefix ? {envPrefix: config.envPrefix} : {}),\n }\n\n return mergeConfig(base, config.vite ?? {})\n}", "export function parseDuration(value: number | string): number {\n if (typeof value === 'number') return value\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/)\n if (!match) throw new Error(`[devix] Invalid duration: \"${value}\". Use a number (ms) or a string like \"5s\", \"2m\", \"500ms\".`)\n const n = parseFloat(match[1])\n switch (match[2]) {\n case 'h': return n * 3_600_000\n case 'm': return n * 60_000\n case 's': return n * 1_000\n case 'ms':\n default: return n\n }\n}\n", "import {writeFileSync} from 'node:fs'\nimport {resolve} from 'node:path'\nimport {build} from 'vite'\nimport {devix} from '../vite'\nimport {parseDuration} from '../utils/duration'\nimport {loadConfig} from \"../utils/load-config\";\n\nconst config = await loadConfig(process.cwd())\nconst baseConfig = devix(config)\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n outDir: 'dist/client',\n manifest: true,\n rolldownOptions: {\n input: 'virtual:devix/entry-client',\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n copyPublicDir: false,\n rolldownOptions: {\n input: {\n render: 'virtual:devix/render',\n api: 'virtual:devix/api',\n },\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n emptyOutDir: false,\n copyPublicDir: false,\n rolldownOptions: {\n input: { index: 'virtual:devix/server-entry' },\n },\n },\n})\n\nconst runtimeConfig = {\n port: config.port ?? 3000,\n host: config.host ?? false,\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n output: config.output ?? 'server',\n}\n\nwriteFileSync(\n resolve(process.cwd(), 'dist/devix.config.json'),\n JSON.stringify(runtimeConfig, null, 2),\n 'utf-8'\n)\n\n\nexport {}", "import {readFileSync, mkdirSync, writeFileSync, rmSync} from 'node:fs'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport { pathToFileURL } from \"node:url\"\nimport {loadConfig} from \"../utils/load-config\";\n\nconst userConfig = await loadConfig(process.cwd())\nif (userConfig.output !== 'static') {\n console.warn('[devix] Tip: set output: \"static\" in devix.config.ts to skip the SSR server at runtime.')\n}\n\nawait import('./build.js')\n\nconst t = Date.now()\nconst renderModule = await import(pathToFileURL(resolve(process.cwd(), 'dist/server/render.js')).href + `?t=${t}`)\n\nconst manifest: Manifest = JSON.parse(\n readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8')\n)\n\nconst urls: string[] = await renderModule.getStaticRoutes()\n\nconsole.log(`[devix] Generating ${urls.length} static page${urls.length === 1 ? '' : 's'}...`)\n\nfor (const url of urls) {\n const fullUrl = `http://localhost${url}`\n const {html, statusCode} = await renderModule.render(fullUrl, new Request(fullUrl), {manifest})\n\n if (statusCode !== 200) {\n console.warn(`[devix] Skipping ${url} \u2014 status ${statusCode}`)\n continue\n }\n\n const outPath = url === '/'\n ? join(process.cwd(), 'dist/client/index.html')\n : join(process.cwd(), 'dist/client', url, 'index.html')\n\n mkdirSync(join(outPath, '..'), {recursive: true})\n writeFileSync(outPath, `<!DOCTYPE html>${html}`, 'utf-8')\n\n const data = await renderModule.runLoader(fullUrl, new Request(fullUrl), {manifest})\n const dataPath = url === '/'\n ? join(process.cwd(), 'dist/client/_data/index.json')\n : join(process.cwd(), 'dist/client/_data', `${url}.json`)\n \n mkdirSync(join(dataPath, '..'), {recursive: true})\n writeFileSync(dataPath, JSON.stringify(data), 'utf-8')\n\n console.log(` \u2713 ${url}`)\n}\n\nconsole.log('[devix] Generation complete.')\n\nif (userConfig.output === 'static') {\n rmSync(resolve(process.cwd(), 'dist/server'), { recursive: true, force: true })\n console.log('[devix] Removed dist/server (not needed in static mode)')\n}\n\nexport {}\n"],
|
|
5
|
-
"mappings": "mCAAA,OAAQ,SAAAA,OAAY,UAEpB,OAAQ,QAAAC,MAAW,YACnB,OAAQ,cAAAC,GAAY,iBAAAC,OAAoB,UACxC,OAAQ,iBAAAC,OAAoB,WAE5B,eAAsBC,EAAWC,EAAmC,CAChE,IAAMC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AI,CAAC,EACjDjB,GAAciB,EAAU,KAAK,UAAUD,CAAI,EAAG,OAAO,EAErD,QAAQ,IAAI,YAAOL,CAAG,EAAE,CAC5B,CAEA,QAAQ,IAAI,8BAA8B,EAEtCN,GAAW,SAAW,WACtBJ,GAAOC,EAAQ,QAAQ,IAAI,EAAG,aAAa,EAAG,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAC9E,QAAQ,IAAI,yDAAyD",
|
|
4
|
+
"sourcesContent": ["import {build} from 'esbuild'\nimport type {DevixConfig} from \"../config\"\nimport {join} from \"node:path\"\nimport {unlinkSync, writeFileSync} from \"node:fs\";\nimport {pathToFileURL} from \"node:url\";\n\nexport async function loadConfig(cwd: string): Promise<DevixConfig> {\n const result = await build({\n entryPoints: [join(cwd, 'devix.config.ts')],\n bundle: true,\n write: false,\n format: 'esm',\n platform: 'node',\n packages: 'external',\n })\n\n const tmpFile = join(cwd, `.devix-config-${Date.now()}.mjs`)\n writeFileSync(tmpFile, result.outputFiles[0].text)\n\n try {\n const mod = await import(pathToFileURL(tmpFile).href)\n return mod.default\n } finally {\n unlinkSync(tmpFile)\n }\n}", "interface EntryClientOptions {\n cssUrls: string[]\n}\n\nexport function generateEntryClient({ cssUrls }: EntryClientOptions): string {\n const cssImports = cssUrls.map(u => `import '${u}'`).join('\\n')\n\n return `\n${cssImports}\nimport \"@vitejs/plugin-react/preamble\"\nimport React from \"react\"\nimport {hydrateRoot, createRoot} from 'react-dom/client'\nimport {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'\nimport {RouterProvider} from '@devlusoft/devix'\n\nconst root = document.getElementById('devix-root')\n\nif (!window.__DEVIX__) {\n const ErrorPage = getDefaultErrorPage()\n createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))\n} else {\n const {metadata, viewport, clientEntry} = window.__DEVIX__\n const loaderData = window.__LOADER_DATA__\n const layoutsData = window.__LAYOUTS_DATA__ ?? []\n const guardData = window.__GUARD_DATA__ ?? null\n\n const matched = matchClientRoute(window.location.pathname)\n\n if (window.__LOADER_ERROR__) {\n const {statusCode, message, code, data} = window.__LOADER_ERROR__\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n matchClientRoute,\n loadErrorPage,\n getDefaultErrorPage,\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialError: {statusCode, message, code, data},\n initialErrorPage: ErrorPage,\n })\n )\n } else if (matched) {\n const [pageMod, ...layoutMods] = await Promise.all([\n matched.load(),\n ...matched.loadLayouts.map(l => l()),\n ])\n hydrateRoot(\n root,\n React.createElement(RouterProvider, {\n matchClientRoute,\n loadErrorPage,\n getDefaultErrorPage,\n clientEntry,\n initialData: loaderData,\n initialParams: matched.params,\n initialPage: pageMod.default,\n initialLayouts: layoutMods.map(m => m.default),\n initialLayoutsData: layoutsData,\n initialGuardData: guardData,\n initialMeta: metadata,\n initialViewport: viewport,\n })\n )\n\n if (window.location.hash) { \n const id = window.location.hash.slice(1) \n const scrollBehavior = getComputedStyle(document.documentElement).scrollBehavior \n requestAnimationFrame(() => { \n document.getElementById(id)?.scrollIntoView({ behavior: scrollBehavior }) \n }) \n } \n } else {\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n matchClientRoute,\n loadErrorPage,\n getDefaultErrorPage,\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialLayouts: [],\n initialLayoutsData: [],\n initialMeta: null,\n initialError: {statusCode: 404, message: 'Not found'},\n initialErrorPage: ErrorPage,\n })\n )\n }\n}\n`\n}", "interface ClientRoutesOptions {\n pagesDir: string\n matcherPath: string\n}\n\nexport function generateClientRoutes({pagesDir, matcherPath}: ClientRoutesOptions) {\n return `\nimport React from 'react'\nimport { createMatcher } from '${matcherPath}'\nconst pageFiles = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst layoutFiles = import.meta.glob('/${pagesDir}/**/layout.tsx')\nconst errorFiles = import.meta.glob('/${pagesDir}/**/error.tsx')\n\nexport const matchClientRoute = createMatcher(pageFiles, layoutFiles)\n\nexport async function loadErrorPage() {\n const key = Object.keys(errorFiles)[0]\n if (!key) return null\n const mod = await errorFiles[key]()\n return mod?.default ?? null\n}\n\nexport function getDefaultErrorPage() {\n return function DefaultError({ statusCode, message }) {\n return React.createElement('main', {\n style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column', \n alignItems: 'center', justifyContent: 'center', gap: '8px',\n fontFamily: 'system-ui, sans-serif' }\n },\n React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),\n React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),\n )\n }\n}\n`\n}", "interface RenderOptions {\n pagesDir: string\n renderPath: string\n}\n\nexport function generateRender({pagesDir, renderPath}: RenderOptions): string {\n return `\nimport { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${renderPath}'\n\nconst _pages = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst _layouts = import.meta.glob('/${pagesDir}/**/layout.tsx')\n\nconst _glob = {\n pages: _pages,\n layouts: _layouts,\n pagesDir: '/${pagesDir}',\n}\n\nexport function render(url, request, options) {\n return _render(url, request, _glob, options)\n}\n\nexport function runLoader(url, request, options) {\n return _runLoader(url, request, _glob, options)\n}\n\nexport function getStaticRoutes() {\n return _getStaticRoutes(_glob)\n}\n`\n}\n", "interface ApiOptions {\n apiPath: string\n appDir: string\n}\n\nexport function generateApi({apiPath, appDir}: ApiOptions): string {\n return `\nimport { handleApiRequest as _handleApiRequest } from '${apiPath}'\n\nconst _routes = import.meta.glob(['/${appDir}/api/**/*.ts', '!**/middleware.ts'])\nconst _middlewares = import.meta.glob('/${appDir}/api/**/middleware.ts')\n\nconst _glob = {\n routes: _routes,\n middlewares: _middlewares,\n apiDir: '/${appDir}/api',\n}\n\nexport function handleApiRequest(url, request) {\n return _handleApiRequest(url, request, _glob)\n}\n`\n}\n", "export function generateContext(): string {\n return `\nexport {RouterContext} from '@devlusoft/devix/runtime/context'\n`\n}", "const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nconst METHOD_EXPORT_RE = /export\\s+(?:const|async\\s+function|function)\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/g\n\nfunction stripComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/.*$/gm, '')\n}\n\nexport function extractHttpMethods(content: string): HttpMethod[] {\n const found = new Set<HttpMethod>()\n for (const match of stripComments(content).matchAll(METHOD_EXPORT_RE)) {\n found.add(match[1] as HttpMethod)\n }\n return [...found]\n}\n", "export function routePattern(rel: string): string {\n return rel\n .replace(/\\.(tsx|ts|jsx|js)$/, '')\n .replace(/\\(.*?\\)\\//g, '')\n .replace(/^index$|\\/index$/, '')\n .replace(/\\[([^\\]]+)]/g, ':$1')\n || '/'\n}", "import {routePattern} from \"../utils/patterns\";\n\nexport interface ApiRoute {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface ApiMiddleware {\n dir: string\n key: string\n}\n\nexport interface ApiResult {\n routes: ApiRoute[]\n middlewares: ApiMiddleware[]\n}\n\nexport function keyToRoutePattern(key: string, apiDir: string): string {\n const rel = key.slice(apiDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === '/' ? '/api' : `/api/${pattern}`.replace('/api//', '/api/')\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nexport function buildRoutes(routeKeys: string[], middlewareKeys: string[], apiDir: string): ApiResult {\n const routes: ApiRoute[] = []\n const middlewares: ApiMiddleware[] = []\n\n for (const key of middlewareKeys) {\n middlewares.push({dir: keyToDir(key), key})\n }\n\n for (const key of routeKeys) {\n const pattern = keyToRoutePattern(key, apiDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n routes.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n routes.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n return {routes, middlewares}\n}\n\nexport function collectMiddlewareChain(routeKey: string, middlewares: ApiMiddleware[]): ApiMiddleware[] {\n const routeDir = keyToDir(routeKey)\n\n return middlewares\n .filter(mw => routeDir.startsWith(mw.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchRoute(\n pathname: string,\n routes: ApiRoute[]\n): { route: ApiRoute; params: Record<string, string> } | null {\n for (const route of routes) {\n const match = pathname.match(route.regex)\n if (match) {\n const params: Record<string, string> = {}\n route.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {route, params}\n }\n }\n return null\n}\n", "import { keyToRoutePattern } from '../../server/api-router'\nimport type { HttpMethod } from './extract-methods'\n\nexport interface RouteEntry {\n filePath: string\n urlPattern: string\n identifier: string\n methods: HttpMethod[]\n}\n\nexport function filePathToIdentifier(filePath: string, apiDir: string): string {\n return '_api_' + filePath\n .slice(`${apiDir}/`.length)\n .replace(/\\.(ts|tsx)$/, '')\n .replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nexport function buildRouteEntry(filePath: string, apiDir: string, methods: HttpMethod[]): RouteEntry {\n return {\n filePath,\n urlPattern: keyToRoutePattern(filePath, apiDir),\n identifier: filePathToIdentifier(filePath, apiDir),\n methods,\n }\n}\n\nexport function generateRoutesDts(entries: RouteEntry[], apiDir: string): string {\n if (entries.length === 0) {\n return `// auto-generado por devix \u2014 no editar\\nexport {}\\ndeclare module '@devlusoft/devix' {\\n interface ApiRoutes {}\\n}\\n`\n }\n\n const imports = entries\n .map(e => {\n const importPath = '../' + e.filePath.replace(/\\.(ts|tsx)$/, '')\n return `import type * as ${e.identifier} from '${importPath}'`\n })\n .join('\\n')\n\n const routeLines = entries.flatMap(e =>\n e.methods.map(m =>\n ` '${m} ${e.urlPattern}': InferRoute<(typeof ${e.identifier})['${m}']>`\n )\n ).join('\\n')\n\n return `// auto-generado por devix \u2014 no editar\n${imports}\n\ntype JsonResponse<T, S extends number = number> = Response & { readonly __body: T; readonly __status: S }\ntype Is2xx<S extends number> = [number] extends [S] ? boolean : S extends 200 | 201 | 202 | 203 | 204 | 205 | 206 ? true : false\ntype UnwrapSuccessJson<T> = T extends JsonResponse<infer U, infer S> ? Is2xx<S> extends false ? never : U : never\ntype UnwrapErrorJson<T> = T extends JsonResponse<infer U, infer S> ? Is2xx<S> extends true ? never : U : never\ntype InferFnSuccess<T> = T extends (...args: any[]) => any ? UnwrapSuccessJson<Awaited<ReturnType<T>>> : never\ntype InferFnErrors<T> = T extends (...args: any[]) => any ? UnwrapErrorJson<Awaited<ReturnType<T>>> : never\ntype InferRoute<T> =\n T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }\n ? {\n __body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>\n __response: InferFnSuccess<() => TReturn>\n __errors: InferFnErrors<() => TReturn>\n }\n : InferFnSuccess<T>\n\ndeclare module '@devlusoft/devix' {\n interface ApiRoutes {\n${routeLines}\n }\n}\n`\n}\n", "import {readFileSync, readdirSync, statSync} from 'node:fs'\nimport {join, relative} from 'node:path'\nimport {extractHttpMethods} from './extract-methods'\nimport {buildRouteEntry} from './routes-dts'\nimport type {RouteEntry} from './routes-dts'\n\nfunction walkDir(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkDir(full, root))\n } else if (/\\.(ts|tsx)$/.test(name)) {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport function scanApiFiles(appDir: string, projectRoot: string): RouteEntry[] {\n const apiDir = join(projectRoot, appDir, 'api')\n\n let files: string[]\n try {\n files = walkDir(apiDir, projectRoot)\n } catch {\n return []\n }\n\n return files\n .filter(f => !f.endsWith('middleware.ts') && !f.endsWith('middleware.tsx'))\n .flatMap(filePath => {\n try {\n const content = readFileSync(join(projectRoot, filePath), 'utf-8')\n const methods = extractHttpMethods(content)\n if (methods.length === 0) return []\n return [buildRouteEntry(filePath, `${appDir}/api`, methods)]\n } catch {\n return []\n }\n })\n}\n", "import {mkdirSync, readFileSync, writeFileSync, existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nexport function writeRoutesDts(content: string, projectRoot: string): boolean {\n const devixDir = join(projectRoot, '.devix')\n const outPath = join(devixDir, 'routes.d.ts')\n\n mkdirSync(devixDir, {recursive: true})\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) {\n return false\n }\n\n writeFileSync(outPath, content, 'utf-8')\n return true\n}\n", "interface ServerEntryOptions {\n routesPath: string\n envPath: string\n honoServerPath: string\n honoServerStaticPath: string\n honoPath: string\n}\n\nexport function generateServerEntry({ routesPath, envPath, honoServerPath, honoServerStaticPath, honoPath }: ServerEntryOptions): string {\n return `\nimport { readFileSync } from 'node:fs'\n import { serve } from '${honoServerPath}'\n import { serveStatic } from '${honoServerStaticPath}'\n import { Hono } from '${honoPath}'\n import { resolve, join, dirname } from 'node:path'\n import { pathToFileURL } from 'node:url'\n import { registerApiRoutes, registerSsrRoute } from '${routesPath}' \n import { loadDotenv } from '${envPath}'\n \n loadDotenv('production')\n \n const __dir = dirname(process.argv[1])\n\n let renderModule, apiModule, manifest, runtimeConfig \n \n try { \n runtimeConfig = JSON.parse(readFileSync(resolve(__dir, '../devix.config.json'), 'utf-8'))\n if (runtimeConfig.output !== 'static') { \n renderModule = await import(pathToFileURL(resolve(__dir, 'render.js')).href)\n apiModule = await import(pathToFileURL(resolve(__dir, 'api.js')).href) \n } \n manifest = JSON.parse(readFileSync(resolve(__dir, '../client/.vite/manifest.json'), 'utf-8')) \n } catch { \n console.error('[devix] Build not found. Run \"devix build\" first.')\n process.exit(1) \n } \n \n const port = Number(process.env.PORT) || runtimeConfig.port || 3000 \n const host = typeof runtimeConfig.host === 'string'\n ? runtimeConfig.host \n : runtimeConfig.host ? '0.0.0.0' : (process.env.HOST || '0.0.0.0') \n \n const clientRoot = resolve(__dir, '../client') \n const app = new Hono()\n \n if (runtimeConfig.output === 'static') {\n app.get('/_data/*', (c) => {\n const pathname = c.req.path.replace(/^\\\\/_data/, '') || '/' \n const filePath = pathname === '/' \n ? join(clientRoot, '_data/index.json') \n : join(clientRoot, '_data', pathname + '.json') \n try { \n return c.json(JSON.parse(readFileSync(filePath, 'utf-8')))\n } catch { \n return c.json({ error: 'not found' }, 404)\n } \n }) \n }\n\n app.use('/*', serveStatic({ \n root: clientRoot,\n onFound: (_path, c) => { \n c.header('Cache-Control', _path.includes('/assets/') \n ? 'public, immutable, max-age=31536000'\n : 'no-cache') \n } \n })) \n \n if (runtimeConfig.output === 'static') {\n console.log('[devix] Static mode \u2014 serving pre-generated files from dist/client')\n } else {\n let userServerConfig\n try {\n const userConfigMod = await import(pathToFileURL(resolve(process.cwd(), 'devix.config.ts')).href).catch(() =>\n import(pathToFileURL(resolve(process.cwd(), 'devix.config.js')).href))\n userServerConfig = userConfigMod?.default?.server\n } catch {\n /* config sin server \u2014 sigue normal */\n }\n registerApiRoutes(app, { renderModule, apiModule, manifest, server: userServerConfig })\n registerSsrRoute(app, { renderModule, apiModule, manifest, loaderTimeout: runtimeConfig.loaderTimeout, server: userServerConfig })\n } \n \n const server = serve({ fetch: app.fetch, port, hostname: host }, (info) => \n console.log(\\`http://\\${info.address}:\\${info.port}\\`))\n\nprocess.on('SIGTERM', () => server.close())\nprocess.on('SIGINT', () => server.close())\n`\n}", "import {existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync} from \"node:fs\";\nimport {join, relative} from \"node:path\";\nimport {parseSync} from \"oxc-parser\";\n\nfunction walkPages(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkPages(full, root))\n } else if (/\\.(ts|tsx)$/.test(name) && name !== 'layout.tsx' && name !== 'error.tsx') {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport interface LoaderExportInfo {\n exists: boolean\n isAsync: boolean\n isReExport: boolean\n}\n\nexport function inspectLoaderExport(code: string, filePath: string): LoaderExportInfo {\n const ast = parseSync(filePath, code, {sourceType: 'module'})\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration') continue\n const decl = node.declaration\n if (decl?.type === 'FunctionDeclaration' && decl.id?.name === 'loader') {\n return {exists: true, isAsync: decl.async, isReExport: false}\n }\n if (decl?.type === 'VariableDeclaration') {\n for (const d of decl.declarations) {\n if (d.id.type === 'Identifier' && d.id.name === 'loader') {\n const init = d.init\n const isAsync =\n (init?.type === 'ArrowFunctionExpression' && init.async) ||\n (init?.type === 'FunctionExpression' && init.async)\n return {exists: true, isAsync, isReExport: false}\n }\n }\n }\n for (const spec of (node.specifiers ?? [])) {\n if (spec.exported.type === 'Identifier' && spec.exported.name === 'loader') {\n return {exists: true, isAsync: false, isReExport: true}\n }\n }\n }\n return {exists: false, isAsync: false, isReExport: false}\n}\n\nexport function hasLoaderExport(code: string, filePath: string): boolean {\n return inspectLoaderExport(code, filePath).exists\n}\n\nexport function generatePageTypesDts(importPath: string, withLoader: boolean): string {\n if (!withLoader) {\n return '// auto-generado por devix - no editar\\nexport type PageData = undefined\\nexport type PageParams = Record<string, string>\\n'\n }\n return `// auto-generado por devix \u2014 no editar\\nimport type { loader } from \"${importPath}\"\\nimport type { Redirect } from \"@devlusoft/devix\"\\n\\nexport type PageData = Exclude<\\n Awaited<ReturnType<NonNullable<typeof loader>>>,\\n Redirect | void | undefined\\n>\\nexport type PageParams = NonNullable<Parameters<typeof loader>[0]>[\"params\"]\\n`\n}\n\nexport interface WritePageTypesResult {\n warnings: string[]\n}\n\nexport function writePageTypes(pageRelPath: string, root: string): WritePageTypesResult {\n const fullPath = join(root, pageRelPath)\n const code = readFileSync(fullPath, 'utf-8')\n const loaderInfo = inspectLoaderExport(code, fullPath)\n const warnings: string[] = []\n\n if (loaderInfo.exists && !loaderInfo.isAsync && !loaderInfo.isReExport) {\n warnings.push(\n `[devix] ${pageRelPath}: 'loader' must be async. ` +\n `Use 'export async function loader' or 'export const loader = async (...) => ...'.`\n )\n }\n\n const typesDir = join(root, '.devix', 'pages', pageRelPath.replace(/\\.(tsx?|jsx?)$/, ''))\n const outPath = join(typesDir, '$types.d.ts')\n\n const pageAbsNoExt = fullPath.replace(/\\.(tsx?|jsx?)$/, '')\n const importPath = relative(typesDir, pageAbsNoExt).replace(/\\\\/g, '/')\n\n const content = generatePageTypesDts(importPath, loaderInfo.exists)\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) return {warnings}\n\n mkdirSync(typesDir, {recursive: true})\n writeFileSync(outPath, content, 'utf-8')\n return {warnings}\n}\n\nexport function deletePageTypes(pageRelPath: string, root: string): void {\n const typesDir = join(root, '.devix', 'pages', pageRelPath.replace(/\\.(tsx?|jsx?)$/, ''))\n const outPath = join(typesDir, '$types.d.ts')\n if (existsSync(outPath)) rmSync(outPath)\n}\n\nexport function scanAndWritePageTypes(appDir: string, root: string): WritePageTypesResult {\n const pagesDir = join(root, appDir, 'pages')\n const warnings: string[] = []\n let files: string[]\n try {\n files = walkPages(pagesDir, root)\n } catch {\n return {warnings}\n }\n for (const file of files) {\n try {\n const result = writePageTypes(file, root)\n warnings.push(...result.warnings)\n } catch {\n /* ignorar archivos no procesables */\n }\n }\n return {warnings}\n}", "import {UserConfig, Plugin, mergeConfig} from 'vite'\nimport type {DevixConfig} from '../config'\nimport react from '@vitejs/plugin-react'\nimport {fileURLToPath} from 'node:url'\nimport {dirname, relative, resolve} from 'node:path'\nimport {createRequire} from 'node:module'\nimport {generateEntryClient} from './codegen/entry-client'\nimport {generateClientRoutes} from './codegen/client-routes'\nimport {generateRender} from './codegen/render'\nimport {generateApi} from './codegen/api'\nimport {generateContext} from \"./codegen/context\";\nimport {scanApiFiles} from \"./codegen/scan-api\";\nimport {generateRoutesDts} from \"./codegen/routes-dts\";\nimport {writeRoutesDts} from \"./codegen/write-routes-dts\";\nimport {parseSync} from 'oxc-parser'\nimport {generateServerEntry} from \"./codegen/server-entry\";\nimport {deletePageTypes, scanAndWritePageTypes, writePageTypes} from \"./codegen/page-types\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst VIRTUAL_ENTRY_CLIENT = 'virtual:devix/entry-client'\nconst VIRTUAL_CLIENT_ROUTES = 'virtual:devix/client-routes'\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\nconst VIRTUAL_CONTEXT = 'virtual:devix/context'\nconst VIRTUAL_SERVER_ENTRY = 'virtual:devix/server-entry'\n\nconst SERVER_EXPORTS = new Set(['loader', 'guard', 'generateStaticParams', 'headers'])\n\nexport function devix(config: DevixConfig): UserConfig {\n const appDir = config.appDir ?? 'app'\n const pagesDir = `${appDir}/pages`\n const cssUrls = (config.css ?? []).map(u => u.startsWith('/') ? u : `/${u.replace(/^\\.\\//, '')}`)\n\n const renderPath = resolve(__dirname, '../server/render.js').replace(/\\\\/g, '/')\n const apiPath = resolve(__dirname, '../server/api.js').replace(/\\\\/g, '/')\n const matcherPath = resolve(__dirname, '../runtime/client-router.js').replace(/\\\\/g, '/')\n const routesPath = resolve(__dirname, '../server/routes.js').replace(/\\\\/g, '/')\n const envPath = resolve(__dirname, '../utils/env.js').replace(/\\\\/g, '/')\n\n const _require = createRequire(import.meta.url)\n const honoServerPath = _require.resolve('@hono/node-server').replace(/\\\\/g, '/')\n const honoServerStaticPath = _require.resolve('@hono/node-server/serve-static').replace(/\\\\/g, '/')\n const honoPath = _require.resolve('hono').replace(/\\\\/g, '/')\n\n const virtualPlugin: Plugin = {\n name: 'devix',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ENTRY_CLIENT) return `\\0${VIRTUAL_ENTRY_CLIENT}`\n if (id === VIRTUAL_CLIENT_ROUTES) return `\\0${VIRTUAL_CLIENT_ROUTES}`\n if (id === VIRTUAL_RENDER) return `\\0${VIRTUAL_RENDER}`\n if (id === VIRTUAL_API) return `\\0${VIRTUAL_API}`\n if (id === VIRTUAL_CONTEXT) return `\\0${VIRTUAL_CONTEXT}`\n if (id === VIRTUAL_SERVER_ENTRY) return `\\0${VIRTUAL_SERVER_ENTRY}`\n },\n\n load(id) {\n if (id === `\\0${VIRTUAL_ENTRY_CLIENT}`)\n return generateEntryClient({cssUrls})\n if (id === `\\0${VIRTUAL_CLIENT_ROUTES}`)\n return generateClientRoutes({pagesDir, matcherPath})\n if (id === `\\0${VIRTUAL_RENDER}`)\n return generateRender({pagesDir, renderPath})\n if (id === `\\0${VIRTUAL_API}`)\n return generateApi({apiPath, appDir})\n if (id === `\\0${VIRTUAL_CONTEXT}`)\n return generateContext()\n if (id === `\\0${VIRTUAL_SERVER_ENTRY}`)\n return generateServerEntry({routesPath, envPath, honoServerPath, honoServerStaticPath, honoPath})\n },\n\n\n transform(code, id, options) {\n if (options?.ssr) return\n\n const resolvedPagesDir = resolve(process.cwd(), pagesDir)\n if (!id.startsWith(resolvedPagesDir)) return\n\n const ast = parseSync(id, code, {sourceType: 'module'})\n\n const replacements: { start: number; end: number; name: string }[] = []\n\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration' || !node.declaration) continue\n\n const decl = node.declaration\n\n if (decl.type === 'FunctionDeclaration' && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n replacements.push({start: node.start, end: node.end, name: decl.id.name})\n }\n\n if (decl.type === 'VariableDeclaration') {\n const seen = new Set<number>()\n for (const declarator of decl.declarations) {\n if (declarator.id.type === 'Identifier' && SERVER_EXPORTS.has(declarator.id.name)) {\n if (!seen.has(node.start)) {\n seen.add(node.start)\n replacements.push({start: node.start, end: node.end, name: declarator.id.name})\n }\n }\n }\n }\n }\n\n if (replacements.length === 0) return\n\n replacements.sort((a, b) => b.start - a.start)\n\n let result = code\n for (const {start, end, name} of replacements) {\n result = result.slice(0, start) + `export const ${name} = undefined` + result.slice(end)\n }\n\n return {code: result, map: null}\n },\n\n buildStart() {\n const root = process.cwd()\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n const {warnings} = scanAndWritePageTypes(appDir, root)\n for (const w of warnings) console.warn(w)\n },\n\n configureServer(server) {\n const root = process.cwd()\n\n const initial = scanAndWritePageTypes(appDir, root)\n for (const w of initial.warnings) console.warn(w)\n\n const regenerateDts = () => {\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n }\n\n const isPageFile = (file: string) => file.startsWith(resolve(root, pagesDir)) && !file.endsWith('layout.tsx') && !file.endsWith('error.tsx')\n\n const pageRelPath = (file: string) => relative(root, file).replace(/\\\\/g, '/')\n\n const invalidateVirtualModule = (id: string) => {\n const mod = server.moduleGraph.getModuleById(`\\0${id}`)\n if (mod) server.moduleGraph.invalidateModule(mod)\n }\n\n server.watcher.add(resolve(root, 'devix.config.ts'))\n server.watcher.on('change', (file) => {\n if (file === resolve(root, 'devix.config.ts')) {\n console.log('[devix] Config changed, restarting...')\n process.exit(75)\n }\n })\n\n const writePageTypesAndLog = (file: string) => {\n try {\n const {warnings} = writePageTypes(pageRelPath(file), root)\n for (const w of warnings) console.warn(w)\n } catch {\n /* ignorar archivos no procesables */\n }\n }\n\n server.watcher.on('add', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidateVirtualModule(VIRTUAL_RENDER)\n if (isPageFile(file)) writePageTypesAndLog(file)\n if (file.includes(`${appDir}/api`)) {\n invalidateVirtualModule(VIRTUAL_API)\n regenerateDts()\n }\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidateVirtualModule(VIRTUAL_RENDER)\n if (isPageFile(file)) deletePageTypes(pageRelPath(file), root)\n if (file.includes(`${appDir}/api`)) {\n invalidateVirtualModule(VIRTUAL_API)\n regenerateDts()\n }\n })\n server.watcher.on('change', (file) => {\n if (isPageFile(file)) writePageTypesAndLog(file)\n if (file.includes(`${appDir}/api`) && !file.endsWith('middleware.ts')) {\n regenerateDts()\n }\n })\n },\n }\n\n const base: UserConfig = {\n plugins: [react(), virtualPlugin],\n publicDir: resolve(process.cwd(), config.publicDir ?? 'public'),\n ssr: {noExternal: ['@devlusoft/devix']},\n ...(config.envPrefix ? {envPrefix: config.envPrefix} : {}),\n }\n\n return mergeConfig(base, config.vite ?? {})\n}", "export function parseDuration(value: number | string): number {\n if (typeof value === 'number') return value\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/)\n if (!match) throw new Error(`[devix] Invalid duration: \"${value}\". Use a number (ms) or a string like \"5s\", \"2m\", \"500ms\".`)\n const n = parseFloat(match[1])\n switch (match[2]) {\n case 'h': return n * 3_600_000\n case 'm': return n * 60_000\n case 's': return n * 1_000\n case 'ms':\n default: return n\n }\n}\n", "import {writeFileSync} from 'node:fs'\nimport {resolve} from 'node:path'\nimport {build} from 'vite'\nimport {devix} from '../vite'\nimport {parseDuration} from '../utils/duration'\nimport {loadConfig} from \"../utils/load-config\";\n\nconst config = await loadConfig(process.cwd())\nconst baseConfig = devix(config)\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n outDir: 'dist/client',\n manifest: true,\n rolldownOptions: {\n input: 'virtual:devix/entry-client',\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n copyPublicDir: false,\n rolldownOptions: {\n input: {\n render: 'virtual:devix/render',\n api: 'virtual:devix/api',\n },\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n emptyOutDir: false,\n copyPublicDir: false,\n rolldownOptions: {\n input: { index: 'virtual:devix/server-entry' },\n },\n },\n})\n\nconst runtimeConfig = {\n port: config.port ?? 3000,\n host: config.host ?? false,\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n output: config.output ?? 'server',\n}\n\nwriteFileSync(\n resolve(process.cwd(), 'dist/devix.config.json'),\n JSON.stringify(runtimeConfig, null, 2),\n 'utf-8'\n)\n\n\nexport {}", "import {readFileSync, mkdirSync, writeFileSync, rmSync} from 'node:fs'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport { pathToFileURL } from \"node:url\"\nimport {loadConfig} from \"../utils/load-config\";\n\nconst userConfig = await loadConfig(process.cwd())\nif (userConfig.output !== 'static') {\n console.warn('[devix] Tip: set output: \"static\" in devix.config.ts to skip the SSR server at runtime.')\n}\n\nawait import('./build.js')\n\nconst t = Date.now()\nconst renderModule = await import(pathToFileURL(resolve(process.cwd(), 'dist/server/render.js')).href + `?t=${t}`)\n\nconst manifest: Manifest = JSON.parse(\n readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8')\n)\n\nconst urls: string[] = await renderModule.getStaticRoutes()\n\nconsole.log(`[devix] Generating ${urls.length} static page${urls.length === 1 ? '' : 's'}...`)\n\nfor (const url of urls) {\n const fullUrl = `http://localhost${url}`\n const {html, statusCode} = await renderModule.render(fullUrl, new Request(fullUrl), {manifest})\n\n if (statusCode !== 200) {\n console.warn(`[devix] Skipping ${url} \u2014 status ${statusCode}`)\n continue\n }\n\n const outPath = url === '/'\n ? join(process.cwd(), 'dist/client/index.html')\n : join(process.cwd(), 'dist/client', url, 'index.html')\n\n mkdirSync(join(outPath, '..'), {recursive: true})\n writeFileSync(outPath, `<!DOCTYPE html>${html}`, 'utf-8')\n\n const data = await renderModule.runLoader(fullUrl, new Request(fullUrl), {manifest})\n const dataPath = url === '/'\n ? join(process.cwd(), 'dist/client/_data/index.json')\n : join(process.cwd(), 'dist/client/_data', `${url}.json`)\n \n mkdirSync(join(dataPath, '..'), {recursive: true})\n writeFileSync(dataPath, JSON.stringify(data), 'utf-8')\n\n console.log(` \u2713 ${url}`)\n}\n\nconsole.log('[devix] Generation complete.')\n\nif (userConfig.output === 'static') {\n rmSync(resolve(process.cwd(), 'dist/server'), { recursive: true, force: true })\n console.log('[devix] Removed dist/server (not needed in static mode)')\n}\n\nexport {}\n"],
|
|
5
|
+
"mappings": "mCAAA,OAAQ,SAAAA,OAAY,UAEpB,OAAQ,QAAAC,MAAW,YACnB,OAAQ,cAAAC,GAAY,iBAAAC,OAAoB,UACxC,OAAQ,iBAAAC,OAAoB,WAE5B,eAAsBC,EAAWC,EAAmC,CAChE,IAAMC,EAAS,MAAMP,GAAM,CACvB,YAAa,CAACC,EAAKK,EAAK,iBAAiB,CAAC,EAC1C,OAAQ,GACR,MAAO,GACP,OAAQ,MACR,SAAU,OACV,SAAU,UACd,CAAC,EAEKE,EAAUP,EAAKK,EAAK,iBAAiB,KAAK,IAAI,CAAC,MAAM,EAC3DH,GAAcK,EAASD,EAAO,YAAY,CAAC,EAAE,IAAI,EAEjD,GAAI,CAEA,OADY,MAAM,OAAOH,GAAcI,CAAO,EAAE,OACrC,OACf,QAAE,CACEN,GAAWM,CAAO,CACtB,CACJ,CAzBA,IAAAC,EAAAC,EAAA,oBCIO,SAASC,EAAoB,CAAE,QAAAC,CAAQ,EAA+B,CAGzE,MAAO;AAAA,EAFYA,EAAQ,IAAIC,GAAK,WAAWA,CAAC,GAAG,EAAE,KAAK;AAAA,CAAI,CAGtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAC,EAE9F,GAAIK,IAAe,IAAK,CACpB,QAAQ,KAAK,oBAAoBH,CAAG,kBAAaG,CAAU,EAAE,EAC7D,QACJ,CAEA,IAAMC,EAAUJ,IAAQ,IAClBR,EAAK,QAAQ,IAAI,EAAG,wBAAwB,EAC5CA,EAAK,QAAQ,IAAI,EAAG,cAAeQ,EAAK,YAAY,EAE1DZ,GAAUI,EAAKY,EAAS,IAAI,EAAG,CAAC,UAAW,EAAI,CAAC,EAChDf,GAAce,EAAS,kBAAkBF,CAAI,GAAI,OAAO,EAExD,IAAMG,EAAO,MAAMR,EAAa,UAAUI,EAAS,IAAI,QAAQA,CAAO,EAAG,CAAC,SAAAH,EAAQ,CAAC,EAC7EQ,EAAWN,IAAQ,IACnBR,EAAK,QAAQ,IAAI,EAAG,8BAA8B,EAClDA,EAAK,QAAQ,IAAI,EAAG,oBAAqB,GAAGQ,CAAG,OAAO,EAE5DZ,GAAUI,EAAKc,EAAU,IAAI,EAAG,CAAC,UAAW,EAAI,CAAC,EACjDjB,GAAciB,EAAU,KAAK,UAAUD,CAAI,EAAG,OAAO,EAErD,QAAQ,IAAI,YAAOL,CAAG,EAAE,CAC5B,CAEA,QAAQ,IAAI,8BAA8B,EAEtCN,GAAW,SAAW,WACtBJ,GAAOC,EAAQ,QAAQ,IAAI,EAAG,aAAa,EAAG,CAAE,UAAW,GAAM,MAAO,EAAK,CAAC,EAC9E,QAAQ,IAAI,yDAAyD",
|
|
6
6
|
"names": ["build", "join", "unlinkSync", "writeFileSync", "pathToFileURL", "loadConfig", "cwd", "result", "tmpFile", "init_load_config", "__esmMin", "generateEntryClient", "cssUrls", "u", "init_entry_client", "__esmMin", "generateClientRoutes", "pagesDir", "matcherPath", "init_client_routes", "__esmMin", "generateRender", "pagesDir", "renderPath", "init_render", "__esmMin", "generateApi", "apiPath", "appDir", "init_api", "__esmMin", "generateContext", "init_context", "__esmMin", "stripComments", "content", "extractHttpMethods", "found", "match", "METHOD_EXPORT_RE", "init_extract_methods", "__esmMin", "routePattern", "rel", "init_patterns", "__esmMin", "keyToRoutePattern", "key", "apiDir", "rel", "pattern", "routePattern", "init_api_router", "__esmMin", "init_patterns", "filePathToIdentifier", "filePath", "apiDir", "buildRouteEntry", "methods", "keyToRoutePattern", "generateRoutesDts", "entries", "imports", "e", "importPath", "routeLines", "m", "init_routes_dts", "__esmMin", "init_api_router", "readFileSync", "readdirSync", "statSync", "join", "relative", "walkDir", "dir", "root", "entries", "name", "full", "scanApiFiles", "appDir", "projectRoot", "apiDir", "files", "f", "filePath", "content", "methods", "extractHttpMethods", "buildRouteEntry", "init_scan_api", "__esmMin", "init_extract_methods", "init_routes_dts", "mkdirSync", "readFileSync", "writeFileSync", "existsSync", "join", "writeRoutesDts", "content", "projectRoot", "devixDir", "outPath", "init_write_routes_dts", "__esmMin", "generateServerEntry", "routesPath", "envPath", "honoServerPath", "honoServerStaticPath", "honoPath", "init_server_entry", "__esmMin", "existsSync", "mkdirSync", "readdirSync", "readFileSync", "rmSync", "statSync", "writeFileSync", "join", "relative", "parseSync", "walkPages", "dir", "root", "entries", "name", "full", "inspectLoaderExport", "code", "filePath", "ast", "node", "decl", "d", "init", "spec", "generatePageTypesDts", "importPath", "withLoader", "writePageTypes", "pageRelPath", "fullPath", "loaderInfo", "warnings", "typesDir", "outPath", "pageAbsNoExt", "content", "deletePageTypes", "scanAndWritePageTypes", "appDir", "pagesDir", "files", "file", "result", "init_page_types", "__esmMin", "mergeConfig", "react", "fileURLToPath", "dirname", "relative", "resolve", "createRequire", "parseSync", "devix", "config", "appDir", "pagesDir", "cssUrls", "u", "renderPath", "__dirname", "apiPath", "matcherPath", "routesPath", "envPath", "_require", "honoServerPath", "honoServerStaticPath", "honoPath", "virtualPlugin", "id", "VIRTUAL_ENTRY_CLIENT", "VIRTUAL_CLIENT_ROUTES", "VIRTUAL_RENDER", "VIRTUAL_API", "VIRTUAL_CONTEXT", "VIRTUAL_SERVER_ENTRY", "generateEntryClient", "generateClientRoutes", "generateRender", "generateApi", "generateContext", "generateServerEntry", "code", "options", "resolvedPagesDir", "ast", "replacements", "node", "decl", "SERVER_EXPORTS", "seen", "declarator", "a", "b", "result", "start", "end", "name", "root", "entries", "scanApiFiles", "writeRoutesDts", "generateRoutesDts", "warnings", "scanAndWritePageTypes", "w", "server", "initial", "regenerateDts", "isPageFile", "file", "pageRelPath", "invalidateVirtualModule", "mod", "writePageTypesAndLog", "writePageTypes", "deletePageTypes", "base", "init_vite", "__esmMin", "init_entry_client", "init_client_routes", "init_render", "init_api", "init_context", "init_scan_api", "init_routes_dts", "init_write_routes_dts", "init_server_entry", "init_page_types", "parseDuration", "value", "match", "n", "init_duration", "__esmMin", "build_exports", "writeFileSync", "resolve", "build", "config", "baseConfig", "runtimeConfig", "init_build", "__esmMin", "init_vite", "init_duration", "init_load_config", "loadConfig", "devix", "parseDuration", "init_load_config", "readFileSync", "mkdirSync", "writeFileSync", "rmSync", "resolve", "join", "pathToFileURL", "userConfig", "loadConfig", "t", "renderModule", "manifest", "urls", "url", "fullUrl", "html", "statusCode", "outPath", "data", "dataPath"]
|
|
7
7
|
}
|
package/dist/cli/index.js
CHANGED
|
@@ -26,6 +26,9 @@ if (!window.__DEVIX__) {
|
|
|
26
26
|
const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()
|
|
27
27
|
createRoot(root).render(
|
|
28
28
|
React.createElement(RouterProvider, {
|
|
29
|
+
matchClientRoute,
|
|
30
|
+
loadErrorPage,
|
|
31
|
+
getDefaultErrorPage,
|
|
29
32
|
clientEntry,
|
|
30
33
|
initialData: null,
|
|
31
34
|
initialParams: {},
|
|
@@ -42,6 +45,9 @@ if (!window.__DEVIX__) {
|
|
|
42
45
|
hydrateRoot(
|
|
43
46
|
root,
|
|
44
47
|
React.createElement(RouterProvider, {
|
|
48
|
+
matchClientRoute,
|
|
49
|
+
loadErrorPage,
|
|
50
|
+
getDefaultErrorPage,
|
|
45
51
|
clientEntry,
|
|
46
52
|
initialData: loaderData,
|
|
47
53
|
initialParams: matched.params,
|
|
@@ -65,6 +71,9 @@ if (!window.__DEVIX__) {
|
|
|
65
71
|
const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()
|
|
66
72
|
createRoot(root).render(
|
|
67
73
|
React.createElement(RouterProvider, {
|
|
74
|
+
matchClientRoute,
|
|
75
|
+
loadErrorPage,
|
|
76
|
+
getDefaultErrorPage,
|
|
68
77
|
clientEntry,
|
|
69
78
|
initialData: null,
|
|
70
79
|
initialParams: {},
|
|
@@ -146,7 +155,7 @@ export function handleApiRequest(url, request) {
|
|
|
146
155
|
}
|
|
147
156
|
`}var he=d(()=>{"use strict"});function xe(){return`
|
|
148
157
|
export {RouterContext} from '@devlusoft/devix/runtime/context'
|
|
149
|
-
`}var ye=d(()=>{"use strict"});function vt(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function ve(e){let t=new Set;for(let r of vt(e).matchAll(yt))t.add(r[1]);return[...t]}var yt,Re=d(()=>{"use strict";yt=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g});function we(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}var Ee=d(()=>{"use strict"});function _e(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),o=we(r);return o==="/"?"/api":`/api/${o}`.replace("/api//","/api/")}var Se=d(()=>{"use strict";Ee()});function Rt(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function
|
|
158
|
+
`}var ye=d(()=>{"use strict"});function vt(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function ve(e){let t=new Set;for(let r of vt(e).matchAll(yt))t.add(r[1]);return[...t]}var yt,Re=d(()=>{"use strict";yt=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g});function we(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}var Ee=d(()=>{"use strict"});function _e(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),o=we(r);return o==="/"?"/api":`/api/${o}`.replace("/api//","/api/")}var Se=d(()=>{"use strict";Ee()});function Rt(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function Pe(e,t,r){return{filePath:e,urlPattern:_e(e,t),identifier:Rt(e,t),methods:r}}function U(e,t){if(e.length===0)return`// auto-generado por devix \u2014 no editar
|
|
150
159
|
export {}
|
|
151
160
|
declare module '@devlusoft/devix' {
|
|
152
161
|
interface ApiRoutes {}
|
|
@@ -176,7 +185,7 @@ declare module '@devlusoft/devix' {
|
|
|
176
185
|
${o}
|
|
177
186
|
}
|
|
178
187
|
}
|
|
179
|
-
`}var k=d(()=>{"use strict";Se()});import{readFileSync as wt,readdirSync as Et,statSync as _t}from"node:fs";import{join as N,relative as St}from"node:path";function
|
|
188
|
+
`}var k=d(()=>{"use strict";Se()});import{readFileSync as wt,readdirSync as Et,statSync as _t}from"node:fs";import{join as N,relative as St}from"node:path";function Te(e,t){let r=[];for(let o of Et(e)){let n=N(e,o);_t(n).isDirectory()?r.push(...Te(n,t)):/\.(ts|tsx)$/.test(o)&&r.push(St(t,n).replace(/\\/g,"/"))}return r}function H(e,t){let r=N(t,e,"api"),o;try{o=Te(r,t)}catch{return[]}return o.filter(n=>!n.endsWith("middleware.ts")&&!n.endsWith("middleware.tsx")).flatMap(n=>{try{let s=wt(N(t,n),"utf-8"),a=ve(s);return a.length===0?[]:[Pe(n,`${e}/api`,a)]}catch{return[]}})}var be=d(()=>{"use strict";Re();k()});import{mkdirSync as Pt,readFileSync as Tt,writeFileSync as bt,existsSync as Ct}from"node:fs";import{join as Ce}from"node:path";function B(e,t){let r=Ce(t,".devix"),o=Ce(r,"routes.d.ts");return Pt(r,{recursive:!0}),Ct(o)&&Tt(o,"utf-8")===e?!1:(bt(o,e,"utf-8"),!0)}var De=d(()=>{"use strict"});function $e({routesPath:e,envPath:t,honoServerPath:r,honoServerStaticPath:o,honoPath:n}){return`
|
|
180
189
|
import { readFileSync } from 'node:fs'
|
|
181
190
|
import { serve } from '${r}'
|
|
182
191
|
import { serveStatic } from '${o}'
|
|
@@ -267,7 +276,7 @@ export type PageParams = NonNullable<Parameters<typeof loader>[0]>["params"]
|
|
|
267
276
|
`:`// auto-generado por devix - no editar
|
|
268
277
|
export type PageData = undefined
|
|
269
278
|
export type PageParams = Record<string, string>
|
|
270
|
-
`}function J(e,t){let r=E(t,e),o=Oe(r,"utf-8"),n=Ft(o,r),s=[];n.exists&&!n.isAsync&&!n.isReExport&&s.push(`[devix] ${e}: 'loader' must be async. Use 'export async function loader' or 'export const loader = async (...) => ...'.`);let a=E(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),m=E(a,"$types.d.ts"),g=r.replace(/\.(tsx?|jsx?)$/,""),l=Ie(a,g).replace(/\\/g,"/"),f=Mt(l,n.exists);return je(m)&&Oe(m,"utf-8")===f?{warnings:s}:(Dt(a,{recursive:!0}),jt(m,f,"utf-8"),{warnings:s})}function Me(e,t){let r=E(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),o=E(r,"$types.d.ts");je(o)&&At(o)}function q(e,t){let r=E(t,e,"pages"),o=[],n;try{n=Fe(r,t)}catch{return{warnings:o}}for(let s of n)try{let a=J(s,t);o.push(...a.warnings)}catch{}return{warnings:o}}var Le=d(()=>{"use strict"});import{mergeConfig as Lt}from"vite";import Ut from"@vitejs/plugin-react";import{fileURLToPath as kt}from"node:url";import{dirname as Nt,relative as Ht,resolve as h}from"node:path";import{createRequire as Bt}from"node:module";import{parseSync as Jt}from"oxc-parser";function ke(e){let t=e.appDir??"app",r=`${t}/pages`,o=(e.css??[]).map(c=>c.startsWith("/")?c:`/${c.replace(/^\.\//,"")}`),n=h(D,"../server/render.js").replace(/\\/g,"/"),s=h(D,"../server/api.js").replace(/\\/g,"/"),a=h(D,"../runtime/client-router.js").replace(/\\/g,"/"),m=h(D,"../server/routes.js").replace(/\\/g,"/"),g=h(D,"../utils/env.js").replace(/\\/g,"/"),l=Bt(import.meta.url),f=l.resolve("@hono/node-server").replace(/\\/g,"/"),L=l.resolve("@hono/node-server/serve-static").replace(/\\/g,"/"),lt=l.resolve("hono").replace(/\\/g,"/"),dt={name:"devix",enforce:"pre",resolveId(c){if(c===V)return`\0${V}`;if(c===W)return`\0${W}`;if(c===$)return`\0${$}`;if(c===A)return`\0${A}`;if(c===G)return`\0${G}`;if(c===X)return`\0${X}`},load(c){if(c===`\0${V}`)return le({cssUrls:o});if(c===`\0${W}`)return ue({pagesDir:r,matcherPath:a});if(c===`\0${$}`)return fe({pagesDir:r,renderPath:n});if(c===`\0${A}`)return ge({apiPath:s,appDir:t});if(c===`\0${G}`)return xe();if(c===`\0${X}`)return $e({routesPath:m,envPath:g,honoServerPath:f,honoServerStaticPath:L,honoPath:lt})},transform(c,u,P){if(P?.ssr)return;let w=h(process.cwd(),r);if(!u.startsWith(w))return;let b=Jt(u,c,{sourceType:"module"}),R=[];for(let p of b.program.body){if(p.type!=="ExportNamedDeclaration"||!p.declaration)continue;let i=p.declaration;if(i.type==="FunctionDeclaration"&&i.id&&Ue.has(i.id.name)&&R.push({start:p.start,end:p.end,name:i.id.name}),i.type==="VariableDeclaration"){let y=new Set;for(let C of i.declarations)C.id.type==="Identifier"&&Ue.has(C.id.name)&&(y.has(p.start)||(y.add(p.start),R.push({start:p.start,end:p.end,name:C.id.name})))}}if(R.length===0)return;R.sort((p,i)=>i.start-p.start);let x=c;for(let{start:p,end:i,name:y}of R)x=x.slice(0,p)+`export const ${y} = undefined`+x.slice(i);return{code:x,map:null}},buildStart(){let c=process.cwd(),u=H(t,c);B(U(u,`${t}/api`),c);let{warnings:P}=q(t,c);for(let w of P)console.warn(w)},configureServer(c){let u=process.cwd(),P=q(t,u);for(let i of P.warnings)console.warn(i);let w=()=>{let i=H(t,u);B(U(i,`${t}/api`),u)},b=i=>i.startsWith(h(u,r))&&!i.endsWith("layout.tsx")&&!i.endsWith("error.tsx"),R=i=>Ht(u,i).replace(/\\/g,"/"),x=i=>{let y=c.moduleGraph.getModuleById(`\0${i}`);y&&c.moduleGraph.invalidateModule(y)};c.watcher.add(h(u,"devix.config.ts")),c.watcher.on("change",i=>{i===h(u,"devix.config.ts")&&(console.log("[devix] Config changed, restarting..."),process.exit(75))});let p=i=>{try{let{warnings:y}=J(R(i),u);for(let C of y)console.warn(C)}catch{}};c.watcher.on("add",i=>{i.startsWith(h(u,r))&&x($),b(i)&&p(i),i.includes(`${t}/api`)&&(x(A),w())}),c.watcher.on("unlink",i=>{i.startsWith(h(u,r))&&x($),b(i)&&Me(R(i),u),i.includes(`${t}/api`)&&(x(A),w())}),c.watcher.on("change",i=>{b(i)&&p(i),i.includes(`${t}/api`)&&!i.endsWith("middleware.ts")&&w()})}},ut={plugins:[Ut(),dt],publicDir:h(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return Lt(ut,e.vite??{})}var D,V,W,$,A,G,X,Ue,Ne=d(()=>{"use strict";de();pe();me();he();ye();be();k();De();Ae();Le();D=Nt(kt(import.meta.url)),V="virtual:devix/entry-client",W="virtual:devix/client-routes",$="virtual:devix/render",A="virtual:devix/api",G="virtual:devix/context",X="virtual:devix/server-entry",Ue=new Set(["loader","guard","generateStaticParams","headers"])});function He(e){if(typeof e=="number")return e;let t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/);if(!t)throw new Error(`[devix] Invalid duration: "${e}". Use a number (ms) or a string like "5s", "2m", "500ms".`);let r=parseFloat(t[1]);switch(t[2]){case"h":return r*36e5;case"m":return r*6e4;case"s":return r*1e3;default:return r}}var Be=d(()=>{"use strict"});import{build as qt}from"esbuild";import{join as Je}from"node:path";import{unlinkSync as Vt,writeFileSync as Wt}from"node:fs";import{pathToFileURL as Gt}from"node:url";async function _(e){let t=await qt({entryPoints:[Je(e,"devix.config.ts")],bundle:!0,write:!1,format:"esm",platform:"node",packages:"external"}),r=Je(e,`.devix-config-${Date.now()}.mjs`);Wt(r,t.outputFiles[0].text);try{return(await import(Gt(r).href)).default}finally{Vt(r)}}var F=d(()=>{"use strict"});var qe={};import{writeFileSync as Xt}from"node:fs";import{resolve as Yt}from"node:path";import{build as Y}from"vite";var O,z,zt,K=d(async()=>{"use strict";Ne();Be();F();O=await _(process.cwd()),z=ke(O);await Y({...z,configFile:!1,build:{outDir:"dist/client",manifest:!0,rolldownOptions:{input:"virtual:devix/entry-client"}}});await Y({...z,configFile:!1,build:{ssr:!0,outDir:"dist/server",copyPublicDir:!1,rolldownOptions:{input:{render:"virtual:devix/render",api:"virtual:devix/api"}}}});await Y({...z,configFile:!1,build:{ssr:!0,outDir:"dist/server",emptyOutDir:!1,copyPublicDir:!1,rolldownOptions:{input:{index:"virtual:devix/server-entry"}}}});zt={port:O.port??3e3,host:O.host??!1,loaderTimeout:He(O.loaderTimeout??1e4),output:O.output??"server"};Xt(Yt(process.cwd(),"dist/devix.config.json"),JSON.stringify(zt,null,2),"utf-8")});var tr={};import{readFileSync as Kt,mkdirSync as Ve,writeFileSync as We,rmSync as Zt}from"node:fs";import{resolve as ee,join as S}from"node:path";import{pathToFileURL as Qt}from"node:url";var Xe,er,Z,Ge,Q,Ye=d(async()=>{"use strict";F();Xe=await _(process.cwd());Xe.output!=="static"&&console.warn('[devix] Tip: set output: "static" in devix.config.ts to skip the SSR server at runtime.');await K().then(()=>qe);er=Date.now(),Z=await import(Qt(ee(process.cwd(),"dist/server/render.js")).href+`?t=${er}`),Ge=JSON.parse(Kt(ee(process.cwd(),"dist/client/.vite/manifest.json"),"utf-8")),Q=await Z.getStaticRoutes();console.log(`[devix] Generating ${Q.length} static page${Q.length===1?"":"s"}...`);for(let e of Q){let t=`http://localhost${e}`,{html:r,statusCode:o}=await Z.render(t,new Request(t),{manifest:Ge});if(o!==200){console.warn(`[devix] Skipping ${e} \u2014 status ${o}`);continue}let n=e==="/"?S(process.cwd(),"dist/client/index.html"):S(process.cwd(),"dist/client",e,"index.html");Ve(S(n,".."),{recursive:!0}),We(n,`<!DOCTYPE html>${r}`,"utf-8");let s=await Z.runLoader(t,new Request(t),{manifest:Ge}),a=e==="/"?S(process.cwd(),"dist/client/_data/index.json"):S(process.cwd(),"dist/client/_data",`${e}.json`);Ve(S(a,".."),{recursive:!0}),We(a,JSON.stringify(s),"utf-8"),console.log(` \u2713 ${e}`)}console.log("[devix] Generation complete.");Xe.output==="static"&&(Zt(ee(process.cwd(),"dist/server"),{recursive:!0,force:!0}),console.log("[devix] Removed dist/server (not needed in static mode)"))});function M(e){let t={statusCode:e.statusCode,message:e.message};return e.code!==void 0&&(t.code=e.code),e.data!==void 0&&(t.data=e.data),t}var te=d(()=>{"use strict"});function rr(e,t){return or(t).test(e)}function re(e,t){if(!t||t.length===0)return!1;for(let r of t)if(rr(e,r))return!0;return!1}function or(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="*"&&e[r+1]==="*")t+=".*",r+=2;else if(o==="*")t+="[^/]*",r+=1;else if(o===":"){for(r+=1;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r+=1;t+="[^/]+"}else".+?^$()|[]{}\\".includes(o)?(t+="\\"+o,r+=1):(t+=o,r+=1)}return new RegExp(`^${t}$`)}var ze=d(()=>{"use strict"});function T(e,t,r){let o=M({statusCode:e,message:t,code:r});return new Response(JSON.stringify(o),{status:e,headers:{"Content-Type":"application/json"}})}function nr(e){if(!e.startsWith(Ke+"/"))return null;let t=e.slice(Ke.length+1),r=t.indexOf("/");return r===-1?{namespace:t,path:"/"}:{namespace:t.slice(0,r),path:t.slice(r)}}async function Ze(e,t){let r=new URL(e.url),o=nr(r.pathname);if(!o)return T(404,"Not found","PROXY_NOT_FOUND");let n=t?.[o.namespace];if(!n)return T(404,`Backend "${o.namespace}" not configured`,"BACKEND_NOT_FOUND");if(!re(o.path,n.allowedPaths))return T(403,"Path not allowed","PATH_NOT_ALLOWED");if(re(o.path,n.deniedPaths))return T(403,"Path denied","PATH_DENIED");let s=new URL(o.path+r.search,n.url),a=new Headers;if(n.prepare){let l={request:e,headers:a,url:s};try{let f=await n.prepare(l);if(f instanceof Response)return f}catch(f){return console.error(`[devix] server.${o.namespace}.prepare error:`,f),T(500,"Proxy prepare failed","PREPARE_ERROR")}}if(!a.has("Accept")){let l=e.headers.get("Accept");l&&a.set("Accept",l)}let m=e.headers.get("Content-Type");m&&!a.has("Content-Type")&&a.set("Content-Type",m);let g=null;e.method!=="GET"&&e.method!=="HEAD"&&(g=await e.arrayBuffer(),g.byteLength===0&&(g=null));try{let l=await fetch(s,{method:e.method,headers:a,body:g,redirect:"manual"});return new Response(l.body,{status:l.status,statusText:l.statusText,headers:ir(l.headers)})}catch(l){return console.error(`[devix] server.${o.namespace} fetch error:`,l),T(502,"Bad Gateway","BACKEND_UNREACHABLE")}}function ir(e){let t=new Headers;return e.forEach((r,o)=>{sr.has(o.toLowerCase())||t.set(o,r)}),t}var Ke,sr,Qe=d(()=>{"use strict";ze();te();Ke="/_devix/server";sr=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"])});function et(e,{apiModule:t,renderModule:r,loaderTimeout:o,server:n}){n&&e.all("/_devix/server/*",async s=>{try{return await Ze(s.req.raw,n)}catch(a){return console.error("[devix] proxy fatal error:",a),s.json({statusCode:500,message:"Internal Server Error"},500)}}),e.all("/api/*",async s=>{try{return await t.handleApiRequest(s.req.url,s.req.raw,n)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}}),e.get("/_data/*",async s=>{try{let{pathname:a,search:m}=new URL(s.req.url,"http://localhost"),g=a.replace(/^\/_data/,"")+m,l=await r.runLoader(g,s.req.raw,{loaderTimeout:o,server:n});if(l.error)return s.json({statusCode:500,message:"Internal Server Error"},500);if("loaderError"in l){let f=M(l.loaderError);return s.json(f,f.statusCode)}return s.json(l)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}})}function tt(e,{renderModule:t,manifest:r,loaderTimeout:o,server:n}){e.get("*",async s=>{try{let{html:a,statusCode:m,headers:g}=await t.render(s.req.url,s.req.raw,{manifest:r,loaderTimeout:o,server:n}),l=s.html(`<!DOCTYPE html>${a}`,m);for(let[f,L]of Object.entries(g))l.headers.set(f,L);return l}catch(a){return console.error(a),s.text("Internal Server Error",500)}})}var rt=d(()=>{"use strict";te();Qe()});import{loadEnv as ar}from"vite";function ot(e){let t=ar(e,process.cwd(),"");for(let[r,o]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=o)}var nt=d(()=>{"use strict"});var fr={};import{readFileSync as oe}from"node:fs";import{serve as cr}from"@hono/node-server";import{serveStatic as lr}from"@hono/node-server/serve-static";import{Hono as dr}from"hono";import{resolve as st,join as j}from"node:path";import{pathToFileURL as it}from"node:url";var ne,se,ie,v,ur,pr,I,ae,at=d(async()=>{"use strict";rt();nt();F();ot("production");try{v=JSON.parse(oe(j(process.cwd(),"dist/devix.config.json"),"utf-8")),v.output!=="static"&&(ne=await import(it(st(process.cwd(),"dist/server/render.js")).href),se=await import(it(st(process.cwd(),"dist/server/api.js")).href)),ie=JSON.parse(oe(j(process.cwd(),"dist/client/.vite/manifest.json"),"utf-8"))}catch{console.error('[devix] Build not found. Run "devix build" first.'),process.exit(1)}ur=Number(process.env.PORT)||v.port||3e3,pr=typeof v.host=="string"?v.host:v.host?"0.0.0.0":process.env.HOST||"0.0.0.0",I=new dr,ae=j(process.cwd(),"dist/client");v.output==="static"&&I.get("/_data/*",e=>{let t=e.req.path.replace(/^\/_data/,"")||"/",r=t==="/"?j(ae,"_data/index.json"):j(ae,"_data",`${t}.json`);try{let o=oe(r,"utf-8");return e.json(JSON.parse(o))}catch{return e.json({error:"not found"},404)}});I.use("/*",lr({root:ae,onFound:(e,t)=>{t.header("Cache-Control",e.includes("/assets/")?"public, immutable, max-age=31536000":"no-cache")}}));if(v.output==="static")console.log("[devix] Static mode \u2014 serving pre-generated files from dist/client");else{let e=await _(process.cwd()).catch(()=>null);et(I,{renderModule:ne,apiModule:se,manifest:ie,server:e?.server}),tt(I,{renderModule:ne,apiModule:se,manifest:ie,loaderTimeout:v.loaderTimeout})}cr({fetch:I.fetch,port:ur,hostname:pr},e=>console.log(`http://${e.address}:${e.port}`))});var ct=process.argv[2];switch(ct){case"dev":await Promise.resolve().then(()=>(ce(),xt));break;case"build":await K().then(()=>qe);break;case"generate":await Ye().then(()=>tr);break;case"start":await at().then(()=>fr);break;case"--version":case"-v":{console.log("0.5.3");break}case"--help":case"-h":console.log(`
|
|
279
|
+
`}function J(e,t){let r=E(t,e),o=Oe(r,"utf-8"),n=Ft(o,r),s=[];n.exists&&!n.isAsync&&!n.isReExport&&s.push(`[devix] ${e}: 'loader' must be async. Use 'export async function loader' or 'export const loader = async (...) => ...'.`);let a=E(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),m=E(a,"$types.d.ts"),g=r.replace(/\.(tsx?|jsx?)$/,""),l=Ie(a,g).replace(/\\/g,"/"),f=Mt(l,n.exists);return je(m)&&Oe(m,"utf-8")===f?{warnings:s}:(Dt(a,{recursive:!0}),jt(m,f,"utf-8"),{warnings:s})}function Me(e,t){let r=E(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),o=E(r,"$types.d.ts");je(o)&&At(o)}function q(e,t){let r=E(t,e,"pages"),o=[],n;try{n=Fe(r,t)}catch{return{warnings:o}}for(let s of n)try{let a=J(s,t);o.push(...a.warnings)}catch{}return{warnings:o}}var Le=d(()=>{"use strict"});import{mergeConfig as Lt}from"vite";import Ut from"@vitejs/plugin-react";import{fileURLToPath as kt}from"node:url";import{dirname as Nt,relative as Ht,resolve as h}from"node:path";import{createRequire as Bt}from"node:module";import{parseSync as Jt}from"oxc-parser";function ke(e){let t=e.appDir??"app",r=`${t}/pages`,o=(e.css??[]).map(c=>c.startsWith("/")?c:`/${c.replace(/^\.\//,"")}`),n=h(D,"../server/render.js").replace(/\\/g,"/"),s=h(D,"../server/api.js").replace(/\\/g,"/"),a=h(D,"../runtime/client-router.js").replace(/\\/g,"/"),m=h(D,"../server/routes.js").replace(/\\/g,"/"),g=h(D,"../utils/env.js").replace(/\\/g,"/"),l=Bt(import.meta.url),f=l.resolve("@hono/node-server").replace(/\\/g,"/"),L=l.resolve("@hono/node-server/serve-static").replace(/\\/g,"/"),lt=l.resolve("hono").replace(/\\/g,"/"),dt={name:"devix",enforce:"pre",resolveId(c){if(c===V)return`\0${V}`;if(c===W)return`\0${W}`;if(c===$)return`\0${$}`;if(c===A)return`\0${A}`;if(c===G)return`\0${G}`;if(c===X)return`\0${X}`},load(c){if(c===`\0${V}`)return le({cssUrls:o});if(c===`\0${W}`)return ue({pagesDir:r,matcherPath:a});if(c===`\0${$}`)return fe({pagesDir:r,renderPath:n});if(c===`\0${A}`)return ge({apiPath:s,appDir:t});if(c===`\0${G}`)return xe();if(c===`\0${X}`)return $e({routesPath:m,envPath:g,honoServerPath:f,honoServerStaticPath:L,honoPath:lt})},transform(c,u,T){if(T?.ssr)return;let w=h(process.cwd(),r);if(!u.startsWith(w))return;let b=Jt(u,c,{sourceType:"module"}),R=[];for(let p of b.program.body){if(p.type!=="ExportNamedDeclaration"||!p.declaration)continue;let i=p.declaration;if(i.type==="FunctionDeclaration"&&i.id&&Ue.has(i.id.name)&&R.push({start:p.start,end:p.end,name:i.id.name}),i.type==="VariableDeclaration"){let y=new Set;for(let C of i.declarations)C.id.type==="Identifier"&&Ue.has(C.id.name)&&(y.has(p.start)||(y.add(p.start),R.push({start:p.start,end:p.end,name:C.id.name})))}}if(R.length===0)return;R.sort((p,i)=>i.start-p.start);let x=c;for(let{start:p,end:i,name:y}of R)x=x.slice(0,p)+`export const ${y} = undefined`+x.slice(i);return{code:x,map:null}},buildStart(){let c=process.cwd(),u=H(t,c);B(U(u,`${t}/api`),c);let{warnings:T}=q(t,c);for(let w of T)console.warn(w)},configureServer(c){let u=process.cwd(),T=q(t,u);for(let i of T.warnings)console.warn(i);let w=()=>{let i=H(t,u);B(U(i,`${t}/api`),u)},b=i=>i.startsWith(h(u,r))&&!i.endsWith("layout.tsx")&&!i.endsWith("error.tsx"),R=i=>Ht(u,i).replace(/\\/g,"/"),x=i=>{let y=c.moduleGraph.getModuleById(`\0${i}`);y&&c.moduleGraph.invalidateModule(y)};c.watcher.add(h(u,"devix.config.ts")),c.watcher.on("change",i=>{i===h(u,"devix.config.ts")&&(console.log("[devix] Config changed, restarting..."),process.exit(75))});let p=i=>{try{let{warnings:y}=J(R(i),u);for(let C of y)console.warn(C)}catch{}};c.watcher.on("add",i=>{i.startsWith(h(u,r))&&x($),b(i)&&p(i),i.includes(`${t}/api`)&&(x(A),w())}),c.watcher.on("unlink",i=>{i.startsWith(h(u,r))&&x($),b(i)&&Me(R(i),u),i.includes(`${t}/api`)&&(x(A),w())}),c.watcher.on("change",i=>{b(i)&&p(i),i.includes(`${t}/api`)&&!i.endsWith("middleware.ts")&&w()})}},ut={plugins:[Ut(),dt],publicDir:h(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return Lt(ut,e.vite??{})}var D,V,W,$,A,G,X,Ue,Ne=d(()=>{"use strict";de();pe();me();he();ye();be();k();De();Ae();Le();D=Nt(kt(import.meta.url)),V="virtual:devix/entry-client",W="virtual:devix/client-routes",$="virtual:devix/render",A="virtual:devix/api",G="virtual:devix/context",X="virtual:devix/server-entry",Ue=new Set(["loader","guard","generateStaticParams","headers"])});function He(e){if(typeof e=="number")return e;let t=e.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/);if(!t)throw new Error(`[devix] Invalid duration: "${e}". Use a number (ms) or a string like "5s", "2m", "500ms".`);let r=parseFloat(t[1]);switch(t[2]){case"h":return r*36e5;case"m":return r*6e4;case"s":return r*1e3;default:return r}}var Be=d(()=>{"use strict"});import{build as qt}from"esbuild";import{join as Je}from"node:path";import{unlinkSync as Vt,writeFileSync as Wt}from"node:fs";import{pathToFileURL as Gt}from"node:url";async function _(e){let t=await qt({entryPoints:[Je(e,"devix.config.ts")],bundle:!0,write:!1,format:"esm",platform:"node",packages:"external"}),r=Je(e,`.devix-config-${Date.now()}.mjs`);Wt(r,t.outputFiles[0].text);try{return(await import(Gt(r).href)).default}finally{Vt(r)}}var F=d(()=>{"use strict"});var qe={};import{writeFileSync as Xt}from"node:fs";import{resolve as Yt}from"node:path";import{build as Y}from"vite";var O,z,zt,K=d(async()=>{"use strict";Ne();Be();F();O=await _(process.cwd()),z=ke(O);await Y({...z,configFile:!1,build:{outDir:"dist/client",manifest:!0,rolldownOptions:{input:"virtual:devix/entry-client"}}});await Y({...z,configFile:!1,build:{ssr:!0,outDir:"dist/server",copyPublicDir:!1,rolldownOptions:{input:{render:"virtual:devix/render",api:"virtual:devix/api"}}}});await Y({...z,configFile:!1,build:{ssr:!0,outDir:"dist/server",emptyOutDir:!1,copyPublicDir:!1,rolldownOptions:{input:{index:"virtual:devix/server-entry"}}}});zt={port:O.port??3e3,host:O.host??!1,loaderTimeout:He(O.loaderTimeout??1e4),output:O.output??"server"};Xt(Yt(process.cwd(),"dist/devix.config.json"),JSON.stringify(zt,null,2),"utf-8")});var tr={};import{readFileSync as Kt,mkdirSync as Ve,writeFileSync as We,rmSync as Zt}from"node:fs";import{resolve as ee,join as S}from"node:path";import{pathToFileURL as Qt}from"node:url";var Xe,er,Z,Ge,Q,Ye=d(async()=>{"use strict";F();Xe=await _(process.cwd());Xe.output!=="static"&&console.warn('[devix] Tip: set output: "static" in devix.config.ts to skip the SSR server at runtime.');await K().then(()=>qe);er=Date.now(),Z=await import(Qt(ee(process.cwd(),"dist/server/render.js")).href+`?t=${er}`),Ge=JSON.parse(Kt(ee(process.cwd(),"dist/client/.vite/manifest.json"),"utf-8")),Q=await Z.getStaticRoutes();console.log(`[devix] Generating ${Q.length} static page${Q.length===1?"":"s"}...`);for(let e of Q){let t=`http://localhost${e}`,{html:r,statusCode:o}=await Z.render(t,new Request(t),{manifest:Ge});if(o!==200){console.warn(`[devix] Skipping ${e} \u2014 status ${o}`);continue}let n=e==="/"?S(process.cwd(),"dist/client/index.html"):S(process.cwd(),"dist/client",e,"index.html");Ve(S(n,".."),{recursive:!0}),We(n,`<!DOCTYPE html>${r}`,"utf-8");let s=await Z.runLoader(t,new Request(t),{manifest:Ge}),a=e==="/"?S(process.cwd(),"dist/client/_data/index.json"):S(process.cwd(),"dist/client/_data",`${e}.json`);Ve(S(a,".."),{recursive:!0}),We(a,JSON.stringify(s),"utf-8"),console.log(` \u2713 ${e}`)}console.log("[devix] Generation complete.");Xe.output==="static"&&(Zt(ee(process.cwd(),"dist/server"),{recursive:!0,force:!0}),console.log("[devix] Removed dist/server (not needed in static mode)"))});function M(e){let t={statusCode:e.statusCode,message:e.message};return e.code!==void 0&&(t.code=e.code),e.data!==void 0&&(t.data=e.data),t}var te=d(()=>{"use strict"});function rr(e,t){return or(t).test(e)}function re(e,t){if(!t||t.length===0)return!1;for(let r of t)if(rr(e,r))return!0;return!1}function or(e){let t="",r=0;for(;r<e.length;){let o=e[r];if(o==="*"&&e[r+1]==="*")t+=".*",r+=2;else if(o==="*")t+="[^/]*",r+=1;else if(o===":"){for(r+=1;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r+=1;t+="[^/]+"}else".+?^$()|[]{}\\".includes(o)?(t+="\\"+o,r+=1):(t+=o,r+=1)}return new RegExp(`^${t}$`)}var ze=d(()=>{"use strict"});function P(e,t,r){let o=M({statusCode:e,message:t,code:r});return new Response(JSON.stringify(o),{status:e,headers:{"Content-Type":"application/json"}})}function nr(e){if(!e.startsWith(Ke+"/"))return null;let t=e.slice(Ke.length+1),r=t.indexOf("/");return r===-1?{namespace:t,path:"/"}:{namespace:t.slice(0,r),path:t.slice(r)}}async function Ze(e,t){let r=new URL(e.url),o=nr(r.pathname);if(!o)return P(404,"Not found","PROXY_NOT_FOUND");let n=t?.[o.namespace];if(!n)return P(404,`Backend "${o.namespace}" not configured`,"BACKEND_NOT_FOUND");if(!re(o.path,n.allowedPaths))return P(403,"Path not allowed","PATH_NOT_ALLOWED");if(re(o.path,n.deniedPaths))return P(403,"Path denied","PATH_DENIED");let s=new URL(o.path+r.search,n.url),a=new Headers;if(n.prepare){let l={request:e,headers:a,url:s};try{let f=await n.prepare(l);if(f instanceof Response)return f}catch(f){return console.error(`[devix] server.${o.namespace}.prepare error:`,f),P(500,"Proxy prepare failed","PREPARE_ERROR")}}if(!a.has("Accept")){let l=e.headers.get("Accept");l&&a.set("Accept",l)}let m=e.headers.get("Content-Type");m&&!a.has("Content-Type")&&a.set("Content-Type",m);let g=null;e.method!=="GET"&&e.method!=="HEAD"&&(g=await e.arrayBuffer(),g.byteLength===0&&(g=null));try{let l=await fetch(s,{method:e.method,headers:a,body:g,redirect:"manual"});return new Response(l.body,{status:l.status,statusText:l.statusText,headers:ir(l.headers)})}catch(l){return console.error(`[devix] server.${o.namespace} fetch error:`,l),P(502,"Bad Gateway","BACKEND_UNREACHABLE")}}function ir(e){let t=new Headers;return e.forEach((r,o)=>{sr.has(o.toLowerCase())||t.set(o,r)}),t}var Ke,sr,Qe=d(()=>{"use strict";ze();te();Ke="/_devix/server";sr=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"])});function et(e,{apiModule:t,renderModule:r,loaderTimeout:o,server:n}){n&&e.all("/_devix/server/*",async s=>{try{return await Ze(s.req.raw,n)}catch(a){return console.error("[devix] proxy fatal error:",a),s.json({statusCode:500,message:"Internal Server Error"},500)}}),e.all("/api/*",async s=>{try{return await t.handleApiRequest(s.req.url,s.req.raw,n)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}}),e.get("/_data/*",async s=>{try{let{pathname:a,search:m}=new URL(s.req.url,"http://localhost"),g=a.replace(/^\/_data/,"")+m,l=await r.runLoader(g,s.req.raw,{loaderTimeout:o,server:n});if(l.error)return s.json({statusCode:500,message:"Internal Server Error"},500);if("loaderError"in l){let f=M(l.loaderError);return s.json(f,f.statusCode)}return s.json(l)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}})}function tt(e,{renderModule:t,manifest:r,loaderTimeout:o,server:n}){e.get("*",async s=>{try{let{html:a,statusCode:m,headers:g}=await t.render(s.req.url,s.req.raw,{manifest:r,loaderTimeout:o,server:n}),l=s.html(`<!DOCTYPE html>${a}`,m);for(let[f,L]of Object.entries(g))l.headers.set(f,L);return l}catch(a){return console.error(a),s.text("Internal Server Error",500)}})}var rt=d(()=>{"use strict";te();Qe()});import{loadEnv as ar}from"vite";function ot(e){let t=ar(e,process.cwd(),"");for(let[r,o]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=o)}var nt=d(()=>{"use strict"});var fr={};import{readFileSync as oe}from"node:fs";import{serve as cr}from"@hono/node-server";import{serveStatic as lr}from"@hono/node-server/serve-static";import{Hono as dr}from"hono";import{resolve as st,join as j}from"node:path";import{pathToFileURL as it}from"node:url";var ne,se,ie,v,ur,pr,I,ae,at=d(async()=>{"use strict";rt();nt();F();ot("production");try{v=JSON.parse(oe(j(process.cwd(),"dist/devix.config.json"),"utf-8")),v.output!=="static"&&(ne=await import(it(st(process.cwd(),"dist/server/render.js")).href),se=await import(it(st(process.cwd(),"dist/server/api.js")).href)),ie=JSON.parse(oe(j(process.cwd(),"dist/client/.vite/manifest.json"),"utf-8"))}catch{console.error('[devix] Build not found. Run "devix build" first.'),process.exit(1)}ur=Number(process.env.PORT)||v.port||3e3,pr=typeof v.host=="string"?v.host:v.host?"0.0.0.0":process.env.HOST||"0.0.0.0",I=new dr,ae=j(process.cwd(),"dist/client");v.output==="static"&&I.get("/_data/*",e=>{let t=e.req.path.replace(/^\/_data/,"")||"/",r=t==="/"?j(ae,"_data/index.json"):j(ae,"_data",`${t}.json`);try{let o=oe(r,"utf-8");return e.json(JSON.parse(o))}catch{return e.json({error:"not found"},404)}});I.use("/*",lr({root:ae,onFound:(e,t)=>{t.header("Cache-Control",e.includes("/assets/")?"public, immutable, max-age=31536000":"no-cache")}}));if(v.output==="static")console.log("[devix] Static mode \u2014 serving pre-generated files from dist/client");else{let e=await _(process.cwd()).catch(()=>null);et(I,{renderModule:ne,apiModule:se,manifest:ie,server:e?.server}),tt(I,{renderModule:ne,apiModule:se,manifest:ie,loaderTimeout:v.loaderTimeout})}cr({fetch:I.fetch,port:ur,hostname:pr},e=>console.log(`http://${e.address}:${e.port}`))});var ct=process.argv[2];switch(ct){case"dev":await Promise.resolve().then(()=>(ce(),xt));break;case"build":await K().then(()=>qe);break;case"generate":await Ye().then(()=>tr);break;case"start":await at().then(()=>fr);break;case"--version":case"-v":{console.log("0.5.4");break}case"--help":case"-h":console.log(`
|
|
271
280
|
devix \u2014 a lightweight SSR framework
|
|
272
281
|
|
|
273
282
|
Usage:
|