@devlusoft/devix 0.5.0 → 0.5.1

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.
@@ -145,7 +145,7 @@ export function handleApiRequest(url, request) {
145
145
  }
146
146
  `}function X(){return`
147
147
  export {RouterContext} from '@devlusoft/devix/runtime/context'
148
- `}import{readFileSync as $e,readdirSync as De,statSync as Ae}from"node:fs";import{join as O,relative as Ce}from"node:path";var Te=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;function Se(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function Y(e){let t=new Set;for(let r of Se(e).matchAll(Te))t.add(r[1]);return[...t]}function z(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}function K(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),n=z(r);return n==="/"?"/api":`/api/${n}`.replace("/api//","/api/")}function be(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function Z(e,t,r){return{filePath:e,urlPattern:K(e,t),identifier:be(e,t),methods:r}}function I(e,t){if(e.length===0)return`// auto-generado por devix \u2014 no editar
148
+ `}import{readFileSync as Ce,readdirSync as $e,statSync as De}from"node:fs";import{join as O,relative as Ae}from"node:path";var Te=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;function Se(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function Y(e){let t=new Set;for(let r of Se(e).matchAll(Te))t.add(r[1]);return[...t]}function z(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}function K(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),n=z(r);return n==="/"?"/api":`/api/${n}`.replace("/api//","/api/")}function be(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function Z(e,t,r){return{filePath:e,urlPattern:K(e,t),identifier:be(e,t),methods:r}}function I(e,t){if(e.length===0)return`// auto-generado por devix \u2014 no editar
149
149
  export {}
150
150
  declare module '@devlusoft/devix' {
151
151
  interface ApiRoutes {}
@@ -175,7 +175,7 @@ declare module '@devlusoft/devix' {
175
175
  ${n}
176
176
  }
177
177
  }
178
- `}function Q(e,t){let r=[];for(let n of De(e)){let o=O(e,n);Ae(o).isDirectory()?r.push(...Q(o,t)):/\.(ts|tsx)$/.test(n)&&r.push(Ce(t,o).replace(/\\/g,"/"))}return r}function L(e,t){let r=O(t,e,"api"),n;try{n=Q(r,t)}catch{return[]}return n.filter(o=>!o.endsWith("middleware.ts")&&!o.endsWith("middleware.tsx")).flatMap(o=>{try{let s=$e(O(t,o),"utf-8"),a=Y(s);return a.length===0?[]:[Z(o,`${e}/api`,a)]}catch{return[]}})}import{mkdirSync as Ie,readFileSync as Oe,writeFileSync as Le,existsSync as Me}from"node:fs";import{join as ee}from"node:path";function M(e,t){let r=ee(t,".devix"),n=ee(r,"routes.d.ts");return Ie(r,{recursive:!0}),Me(n)&&Oe(n,"utf-8")===e?!1:(Le(n,e,"utf-8"),!0)}import{parseSync as ze}from"oxc-parser";function te({routesPath:e,envPath:t,honoServerPath:r,honoServerStaticPath:n,honoPath:o}){return`
178
+ `}function Q(e,t){let r=[];for(let n of $e(e)){let o=O(e,n);De(o).isDirectory()?r.push(...Q(o,t)):/\.(ts|tsx)$/.test(n)&&r.push(Ae(t,o).replace(/\\/g,"/"))}return r}function L(e,t){let r=O(t,e,"api"),n;try{n=Q(r,t)}catch{return[]}return n.filter(o=>!o.endsWith("middleware.ts")&&!o.endsWith("middleware.tsx")).flatMap(o=>{try{let s=Ce(O(t,o),"utf-8"),a=Y(s);return a.length===0?[]:[Z(o,`${e}/api`,a)]}catch{return[]}})}import{mkdirSync as Ie,readFileSync as Oe,writeFileSync as Le,existsSync as Me}from"node:fs";import{join as ee}from"node:path";function M(e,t){let r=ee(t,".devix"),n=ee(r,"routes.d.ts");return Ie(r,{recursive:!0}),Me(n)&&Oe(n,"utf-8")===e?!1:(Le(n,e,"utf-8"),!0)}import{parseSync as ze}from"oxc-parser";function te({routesPath:e,envPath:t,honoServerPath:r,honoServerStaticPath:n,honoPath:o}){return`
179
179
  import { readFileSync } from 'node:fs'
180
180
  import { serve } from '${r}'
181
181
  import { serveStatic } from '${n}'
@@ -266,7 +266,7 @@ export type PageParams = NonNullable<Parameters<typeof loader>[0]>["params"]
266
266
  `:`// auto-generado por devix - no editar
267
267
  export type PageData = undefined
268
268
  export type PageParams = Record<string, string>
269
- `}function j(e,t){let r=w(t,e),n=re(r,"utf-8"),o=Be(n,r),s=[];o.exists&&!o.isAsync&&!o.isReExport&&s.push(`[devix] ${e}: 'loader' must be async. Use 'export async function loader' or 'export const loader = async (...) => ...'.`);let a=w(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),f=w(a,"$types.d.ts"),m=r.replace(/\.(tsx?|jsx?)$/,""),l=oe(a,m).replace(/\\/g,"/"),p=Ve(l,o.exists);return ne(f)&&re(f,"utf-8")===p?{warnings:s}:(je(a,{recursive:!0}),ke(f,p,"utf-8"),{warnings:s})}function ie(e,t){let r=w(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),n=w(r,"$types.d.ts");ne(n)&&Fe(n)}function U(e,t){let r=w(t,e,"pages"),n=[],o;try{o=se(r,t)}catch{return{warnings:n}}for(let s of o)try{let a=j(s,t);n.push(...a.warnings)}catch{}return{warnings:n}}var $=Ge(Je(import.meta.url)),F="virtual:devix/entry-client",N="virtual:devix/client-routes",D="virtual:devix/render",A="virtual:devix/api",k="virtual:devix/context",H="virtual:devix/server-entry",ae=new Set(["loader","guard","generateStaticParams","headers"]);function ce(e){let t=e.appDir??"app",r=`${t}/pages`,n=(e.css??[]).map(c=>c.startsWith("/")?c:`/${c.replace(/^\.\//,"")}`),o=g($,"../server/render.js").replace(/\\/g,"/"),s=g($,"../server/api.js").replace(/\\/g,"/"),a=g($,"../runtime/client-router.js").replace(/\\/g,"/"),f=g($,"../server/routes.js").replace(/\\/g,"/"),m=g($,"../utils/env.js").replace(/\\/g,"/"),l=Ye(import.meta.url),p=l.resolve("@hono/node-server").replace(/\\/g,"/"),Ee=l.resolve("@hono/node-server/serve-static").replace(/\\/g,"/"),we=l.resolve("hono").replace(/\\/g,"/"),_e={name:"devix",enforce:"pre",resolveId(c){if(c===F)return`\0${F}`;if(c===N)return`\0${N}`;if(c===D)return`\0${D}`;if(c===A)return`\0${A}`;if(c===k)return`\0${k}`;if(c===H)return`\0${H}`},load(c){if(c===`\0${F}`)return q({cssUrls:n});if(c===`\0${N}`)return W({pagesDir:r,matcherPath:a});if(c===`\0${D}`)return J({pagesDir:r,renderPath:o});if(c===`\0${A}`)return G({apiPath:s,appDir:t});if(c===`\0${k}`)return X();if(c===`\0${H}`)return te({routesPath:f,envPath:m,honoServerPath:p,honoServerStaticPath:Ee,honoPath:we})},transform(c,u,T){if(T?.ssr)return;let E=g(process.cwd(),r);if(!u.startsWith(E))return;let S=ze(u,c,{sourceType:"module"}),R=[];for(let d of S.program.body){if(d.type!=="ExportNamedDeclaration"||!d.declaration)continue;let i=d.declaration;if(i.type==="FunctionDeclaration"&&i.id&&ae.has(i.id.name)&&R.push({start:d.start,end:d.end,name:i.id.name}),i.type==="VariableDeclaration"){let x=new Set;for(let b of i.declarations)b.id.type==="Identifier"&&ae.has(b.id.name)&&(x.has(d.start)||(x.add(d.start),R.push({start:d.start,end:d.end,name:b.id.name})))}}if(R.length===0)return;R.sort((d,i)=>i.start-d.start);let h=c;for(let{start:d,end:i,name:x}of R)h=h.slice(0,d)+`export const ${x} = undefined`+h.slice(i);return{code:h,map:null}},buildStart(){let c=process.cwd(),u=L(t,c);M(I(u,`${t}/api`),c);let{warnings:T}=U(t,c);for(let E of T)console.warn(E)},configureServer(c){let u=process.cwd(),T=U(t,u);for(let i of T.warnings)console.warn(i);let E=()=>{let i=L(t,u);M(I(i,`${t}/api`),u)},S=i=>i.startsWith(g(u,r))&&!i.endsWith("layout.tsx")&&!i.endsWith("error.tsx"),R=i=>Xe(u,i).replace(/\\/g,"/"),h=i=>{let x=c.moduleGraph.getModuleById(`\0${i}`);x&&c.moduleGraph.invalidateModule(x)};c.watcher.add(g(u,"devix.config.ts")),c.watcher.on("change",i=>{i===g(u,"devix.config.ts")&&(console.log("[devix] Config changed, restarting..."),process.exit(75))});let d=i=>{try{let{warnings:x}=j(R(i),u);for(let b of x)console.warn(b)}catch{}};c.watcher.on("add",i=>{i.startsWith(g(u,r))&&h(D),S(i)&&d(i),i.includes(`${t}/api`)&&(h(A),E())}),c.watcher.on("unlink",i=>{i.startsWith(g(u,r))&&h(D),S(i)&&ie(R(i),u),i.includes(`${t}/api`)&&(h(A),E())}),c.watcher.on("change",i=>{S(i)&&d(i),i.includes(`${t}/api`)&&!i.endsWith("middleware.ts")&&E()})}},Pe={plugins:[We(),_e],publicDir:g(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return qe(Pe,e.vite??{})}function C(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}function Ke(e,t){return Ze(t).test(e)}function B(e,t){if(!t||t.length===0)return!1;for(let r of t)if(Ke(e,r))return!0;return!1}function Ze(e){let t="",r=0;for(;r<e.length;){let n=e[r];if(n==="*"&&e[r+1]==="*")t+=".*",r+=2;else if(n==="*")t+="[^/]*",r+=1;else if(n===":"){for(r+=1;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r+=1;t+="[^/]+"}else".+?^$()|[]{}\\".includes(n)?(t+="\\"+n,r+=1):(t+=n,r+=1)}return new RegExp(`^${t}$`)}var le="/_devix/server";function P(e,t,r){let n=C({statusCode:e,message:t,code:r});return new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":"application/json"}})}function Qe(e){if(!e.startsWith(le+"/"))return null;let t=e.slice(le.length+1),r=t.indexOf("/");return r===-1?{namespace:t,path:"/"}:{namespace:t.slice(0,r),path:t.slice(r)}}async function ue(e,t){let r=new URL(e.url),n=Qe(r.pathname);if(!n)return P(404,"Not found","PROXY_NOT_FOUND");let o=t?.[n.namespace];if(!o)return P(404,`Backend "${n.namespace}" not configured`,"BACKEND_NOT_FOUND");if(!B(n.path,o.allowedPaths))return P(403,"Path not allowed","PATH_NOT_ALLOWED");if(B(n.path,o.deniedPaths))return P(403,"Path denied","PATH_DENIED");let s=new URL(n.path+r.search,o.url),a=new Headers;if(o.prepare){let l={request:e,headers:a,url:s};try{let p=await o.prepare(l);if(p instanceof Response)return p}catch(p){return console.error(`[devix] server.${n.namespace}.prepare error:`,p),P(500,"Proxy prepare failed","PREPARE_ERROR")}}if(!a.has("Accept")){let l=e.headers.get("Accept");l&&a.set("Accept",l)}let f=e.headers.get("Content-Type");f&&!a.has("Content-Type")&&a.set("Content-Type",f);let m=null;e.method!=="GET"&&e.method!=="HEAD"&&(m=await e.arrayBuffer(),m.byteLength===0&&(m=null));try{let l=await fetch(s,{method:e.method,headers:a,body:m,redirect:"manual"});return new Response(l.body,{status:l.status,statusText:l.statusText,headers:tt(l.headers)})}catch(l){return console.error(`[devix] server.${n.namespace} fetch error:`,l),P(502,"Bad Gateway","BACKEND_UNREACHABLE")}}var et=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"]);function tt(e){let t=new Headers;return e.forEach((r,n)=>{et.has(n.toLowerCase())||t.set(n,r)}),t}function de(e,{apiModule:t,renderModule:r,loaderTimeout:n,server:o}){o&&e.all("/_devix/server/*",async s=>{try{return await ue(s.req.raw,o)}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,o)}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:f}=new URL(s.req.url,"http://localhost"),m=a.replace(/^\/_data/,"")+f,l=await r.runLoader(m,s.req.raw,{loaderTimeout:n,server:o});if(l.error)return s.json({statusCode:500,message:"Internal Server Error"},500);if("loaderError"in l){let p=C(l.loaderError);return s.json(p,p.statusCode)}return s.json(l)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}})}import y from"picocolors";import{networkInterfaces as rt}from"node:os";function nt(e){let t=rt();for(let r of Object.values(t))for(let n of r??[])if(n.family==="IPv4"&&!n.internal)return`http://${n.address}:${e}/`;return null}function pe(e){let t="0.5.0",r=nt(e);console.log(),console.log(` ${y.bold(y.yellow("devix"))} ${y.dim(`v${t}`)}`),console.log(),console.log(` ${y.green("\u279C")} ${y.bold("Local:")} ${y.cyan(`http://localhost:${e}/`)}`),console.log(r?` ${y.green("\u279C")} ${y.bold("Network:")} ${y.cyan(r)}`:` ${y.green("\u279C")} ${y.bold("Network:")} ${y.dim("use --host to expose")}`),console.log()}async function fe(e){let t=new Set;for(let[,r]of e.moduleGraph.idToModuleMap)r.id&&(r.id.endsWith(".css")||r.id.includes(".css?"))&&r.url.startsWith("/")&&t.add(r.url);return[...t]}function me(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}}import{loadEnv as ot}from"vite";function ge(e){let t=ot(e,process.cwd(),"");for(let[r,n]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=n)}import{build as st}from"esbuild";import{join as ye}from"node:path";import{unlinkSync as it,writeFileSync as at}from"node:fs";import{pathToFileURL as ct}from"node:url";async function he(e){let t=await st({entryPoints:[ye(e,"devix.config.ts")],bundle:!0,write:!1,format:"esm",platform:"node",packages:"external"}),r=ye(e,`.devix-config-${Date.now()}.mjs`);at(r,t.outputFiles[0].text);try{return(await import(ct(r).href)).default}finally{it(r)}}ge("development");var xe="virtual:devix/render",ft="virtual:devix/api",v=await he(process.cwd()),Re=Number(process.env.PORT)||v.port||3e3,mt=typeof v.host=="string"?v.host:v.host?"0.0.0.0":"localhost",_=await ut({...ce(v),configFile:!1,appType:"custom",server:{middlewareMode:!0}}),ve={render:async(...e)=>(await _.ssrLoadModule(xe)).render(...e),runLoader:async(...e)=>(await _.ssrLoadModule(xe)).runLoader(...e)},gt={handleApiRequest:async(...e)=>(await _.ssrLoadModule(ft)).handleApiRequest(...e)},V=new pt;de(V,{renderModule:ve,apiModule:gt,server:v.server});V.get("*",async e=>{try{let{html:t,statusCode:r,headers:n}=await ve.render(e.req.url,e.req.raw,{loaderTimeout:me(v.loaderTimeout??1e4),server:v.server}),s=(await fe(_)).map(l=>`<link rel="stylesheet" href="${l}">`).join(`
269
+ `}function j(e,t){let r=w(t,e),n=re(r,"utf-8"),o=Be(n,r),s=[];o.exists&&!o.isAsync&&!o.isReExport&&s.push(`[devix] ${e}: 'loader' must be async. Use 'export async function loader' or 'export const loader = async (...) => ...'.`);let a=w(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),f=w(a,"$types.d.ts"),m=r.replace(/\.(tsx?|jsx?)$/,""),l=oe(a,m).replace(/\\/g,"/"),p=Ve(l,o.exists);return ne(f)&&re(f,"utf-8")===p?{warnings:s}:(je(a,{recursive:!0}),ke(f,p,"utf-8"),{warnings:s})}function ie(e,t){let r=w(t,".devix","pages",e.replace(/\.(tsx?|jsx?)$/,"")),n=w(r,"$types.d.ts");ne(n)&&Fe(n)}function U(e,t){let r=w(t,e,"pages"),n=[],o;try{o=se(r,t)}catch{return{warnings:n}}for(let s of o)try{let a=j(s,t);n.push(...a.warnings)}catch{}return{warnings:n}}var C=Ge(Je(import.meta.url)),F="virtual:devix/entry-client",N="virtual:devix/client-routes",$="virtual:devix/render",D="virtual:devix/api",k="virtual:devix/context",H="virtual:devix/server-entry",ae=new Set(["loader","guard","generateStaticParams","headers"]);function ce(e){let t=e.appDir??"app",r=`${t}/pages`,n=(e.css??[]).map(c=>c.startsWith("/")?c:`/${c.replace(/^\.\//,"")}`),o=g(C,"../server/render.js").replace(/\\/g,"/"),s=g(C,"../server/api.js").replace(/\\/g,"/"),a=g(C,"../runtime/client-router.js").replace(/\\/g,"/"),f=g(C,"../server/routes.js").replace(/\\/g,"/"),m=g(C,"../utils/env.js").replace(/\\/g,"/"),l=Ye(import.meta.url),p=l.resolve("@hono/node-server").replace(/\\/g,"/"),Ee=l.resolve("@hono/node-server/serve-static").replace(/\\/g,"/"),we=l.resolve("hono").replace(/\\/g,"/"),_e={name:"devix",enforce:"pre",resolveId(c){if(c===F)return`\0${F}`;if(c===N)return`\0${N}`;if(c===$)return`\0${$}`;if(c===D)return`\0${D}`;if(c===k)return`\0${k}`;if(c===H)return`\0${H}`},load(c){if(c===`\0${F}`)return q({cssUrls:n});if(c===`\0${N}`)return W({pagesDir:r,matcherPath:a});if(c===`\0${$}`)return J({pagesDir:r,renderPath:o});if(c===`\0${D}`)return G({apiPath:s,appDir:t});if(c===`\0${k}`)return X();if(c===`\0${H}`)return te({routesPath:f,envPath:m,honoServerPath:p,honoServerStaticPath:Ee,honoPath:we})},transform(c,u,T){if(T?.ssr)return;let E=g(process.cwd(),r);if(!u.startsWith(E))return;let S=ze(u,c,{sourceType:"module"}),R=[];for(let d of S.program.body){if(d.type!=="ExportNamedDeclaration"||!d.declaration)continue;let i=d.declaration;if(i.type==="FunctionDeclaration"&&i.id&&ae.has(i.id.name)&&R.push({start:d.start,end:d.end,name:i.id.name}),i.type==="VariableDeclaration"){let x=new Set;for(let b of i.declarations)b.id.type==="Identifier"&&ae.has(b.id.name)&&(x.has(d.start)||(x.add(d.start),R.push({start:d.start,end:d.end,name:b.id.name})))}}if(R.length===0)return;R.sort((d,i)=>i.start-d.start);let h=c;for(let{start:d,end:i,name:x}of R)h=h.slice(0,d)+`export const ${x} = undefined`+h.slice(i);return{code:h,map:null}},buildStart(){let c=process.cwd(),u=L(t,c);M(I(u,`${t}/api`),c);let{warnings:T}=U(t,c);for(let E of T)console.warn(E)},configureServer(c){let u=process.cwd(),T=U(t,u);for(let i of T.warnings)console.warn(i);let E=()=>{let i=L(t,u);M(I(i,`${t}/api`),u)},S=i=>i.startsWith(g(u,r))&&!i.endsWith("layout.tsx")&&!i.endsWith("error.tsx"),R=i=>Xe(u,i).replace(/\\/g,"/"),h=i=>{let x=c.moduleGraph.getModuleById(`\0${i}`);x&&c.moduleGraph.invalidateModule(x)};c.watcher.add(g(u,"devix.config.ts")),c.watcher.on("change",i=>{i===g(u,"devix.config.ts")&&(console.log("[devix] Config changed, restarting..."),process.exit(75))});let d=i=>{try{let{warnings:x}=j(R(i),u);for(let b of x)console.warn(b)}catch{}};c.watcher.on("add",i=>{i.startsWith(g(u,r))&&h($),S(i)&&d(i),i.includes(`${t}/api`)&&(h(D),E())}),c.watcher.on("unlink",i=>{i.startsWith(g(u,r))&&h($),S(i)&&ie(R(i),u),i.includes(`${t}/api`)&&(h(D),E())}),c.watcher.on("change",i=>{S(i)&&d(i),i.includes(`${t}/api`)&&!i.endsWith("middleware.ts")&&E()})}},Pe={plugins:[We(),_e],publicDir:g(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return qe(Pe,e.vite??{})}function A(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}function Ke(e,t){return Ze(t).test(e)}function B(e,t){if(!t||t.length===0)return!1;for(let r of t)if(Ke(e,r))return!0;return!1}function Ze(e){let t="",r=0;for(;r<e.length;){let n=e[r];if(n==="*"&&e[r+1]==="*")t+=".*",r+=2;else if(n==="*")t+="[^/]*",r+=1;else if(n===":"){for(r+=1;r<e.length&&/[a-zA-Z0-9_]/.test(e[r]);)r+=1;t+="[^/]+"}else".+?^$()|[]{}\\".includes(n)?(t+="\\"+n,r+=1):(t+=n,r+=1)}return new RegExp(`^${t}$`)}var le="/_devix/server";function P(e,t,r){let n=A({statusCode:e,message:t,code:r});return new Response(JSON.stringify(n),{status:e,headers:{"Content-Type":"application/json"}})}function Qe(e){if(!e.startsWith(le+"/"))return null;let t=e.slice(le.length+1),r=t.indexOf("/");return r===-1?{namespace:t,path:"/"}:{namespace:t.slice(0,r),path:t.slice(r)}}async function ue(e,t){let r=new URL(e.url),n=Qe(r.pathname);if(!n)return P(404,"Not found","PROXY_NOT_FOUND");let o=t?.[n.namespace];if(!o)return P(404,`Backend "${n.namespace}" not configured`,"BACKEND_NOT_FOUND");if(!B(n.path,o.allowedPaths))return P(403,"Path not allowed","PATH_NOT_ALLOWED");if(B(n.path,o.deniedPaths))return P(403,"Path denied","PATH_DENIED");let s=new URL(n.path+r.search,o.url),a=new Headers;if(o.prepare){let l={request:e,headers:a,url:s};try{let p=await o.prepare(l);if(p instanceof Response)return p}catch(p){return console.error(`[devix] server.${n.namespace}.prepare error:`,p),P(500,"Proxy prepare failed","PREPARE_ERROR")}}if(!a.has("Accept")){let l=e.headers.get("Accept");l&&a.set("Accept",l)}let f=e.headers.get("Content-Type");f&&!a.has("Content-Type")&&a.set("Content-Type",f);let m=null;e.method!=="GET"&&e.method!=="HEAD"&&(m=await e.arrayBuffer(),m.byteLength===0&&(m=null));try{let l=await fetch(s,{method:e.method,headers:a,body:m,redirect:"manual"});return new Response(l.body,{status:l.status,statusText:l.statusText,headers:tt(l.headers)})}catch(l){return console.error(`[devix] server.${n.namespace} fetch error:`,l),P(502,"Bad Gateway","BACKEND_UNREACHABLE")}}var et=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailers","transfer-encoding","upgrade"]);function tt(e){let t=new Headers;return e.forEach((r,n)=>{et.has(n.toLowerCase())||t.set(n,r)}),t}function de(e,{apiModule:t,renderModule:r,loaderTimeout:n,server:o}){o&&e.all("/_devix/server/*",async s=>{try{return await ue(s.req.raw,o)}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,o)}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:f}=new URL(s.req.url,"http://localhost"),m=a.replace(/^\/_data/,"")+f,l=await r.runLoader(m,s.req.raw,{loaderTimeout:n,server:o});if(l.error)return s.json({statusCode:500,message:"Internal Server Error"},500);if("loaderError"in l){let p=A(l.loaderError);return s.json(p,p.statusCode)}return s.json(l)}catch(a){return console.error(a),s.json({statusCode:500,message:"Internal Server Error"},500)}})}import y from"picocolors";import{networkInterfaces as rt}from"node:os";function nt(e){let t=rt();for(let r of Object.values(t))for(let n of r??[])if(n.family==="IPv4"&&!n.internal)return`http://${n.address}:${e}/`;return null}function pe(e){let t="0.5.1",r=nt(e);console.log(),console.log(` ${y.bold(y.yellow("devix"))} ${y.dim(`v${t}`)}`),console.log(),console.log(` ${y.green("\u279C")} ${y.bold("Local:")} ${y.cyan(`http://localhost:${e}/`)}`),console.log(r?` ${y.green("\u279C")} ${y.bold("Network:")} ${y.cyan(r)}`:` ${y.green("\u279C")} ${y.bold("Network:")} ${y.dim("use --host to expose")}`),console.log()}async function fe(e){let t=new Set;for(let[,r]of e.moduleGraph.idToModuleMap)r.id&&(r.id.endsWith(".css")||r.id.includes(".css?"))&&r.url.startsWith("/")&&t.add(r.url);return[...t]}function me(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}}import{loadEnv as ot}from"vite";function ge(e){let t=ot(e,process.cwd(),"");for(let[r,n]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=n)}import{build as st}from"esbuild";import{join as ye}from"node:path";import{unlinkSync as it,writeFileSync as at}from"node:fs";import{pathToFileURL as ct}from"node:url";async function he(e){let t=await st({entryPoints:[ye(e,"devix.config.ts")],bundle:!0,write:!1,format:"esm",platform:"node",packages:"external"}),r=ye(e,`.devix-config-${Date.now()}.mjs`);at(r,t.outputFiles[0].text);try{return(await import(ct(r).href)).default}finally{it(r)}}ge("development");var xe="virtual:devix/render",ft="virtual:devix/api",v=await he(process.cwd()),Re=Number(process.env.PORT)||v.port||3e3,mt=typeof v.host=="string"?v.host:v.host?"0.0.0.0":"localhost",_=await ut({...ce(v),configFile:!1,appType:"custom",server:{middlewareMode:!0}}),ve={render:async(...e)=>(await _.ssrLoadModule(xe)).render(...e),runLoader:async(...e)=>(await _.ssrLoadModule(xe)).runLoader(...e)},gt={handleApiRequest:async(...e)=>(await _.ssrLoadModule(ft)).handleApiRequest(...e)},V=new pt;de(V,{renderModule:ve,apiModule:gt,server:v.server});V.get("*",async e=>{try{let{html:t,statusCode:r,headers:n}=await ve.render(e.req.url,e.req.raw,{loaderTimeout:me(v.loaderTimeout??1e4),server:v.server}),s=(await fe(_)).map(l=>`<link rel="stylesheet" href="${l}">`).join(`
270
270
  `),a=s?t.replace("</head>",`${s}
271
271
  </head>`):t,f=await _.transformIndexHtml(e.req.url,`<!DOCTYPE html>${a}`),m=e.html(f,r);for(let[l,p]of Object.entries(n))m.headers.set(l,p);return m}catch(t){return _.ssrFixStacktrace(t),console.error(t),e.text("Internal Server Error",500)}});var yt=dt(V.fetch);lt(async(e,t)=>{await new Promise(r=>_.middlewares(e,t,r)),t.writableEnded||await yt(e,t)}).listen(Re,mt,()=>{pe(Re)});
272
272
  //# sourceMappingURL=dev-server.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/cli/dev-server.ts", "../../src/vite/index.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/scan-api.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/write-routes-dts.ts", "../../src/vite/codegen/server-entry.ts", "../../src/vite/codegen/page-types.ts", "../../src/utils/response.ts", "../../src/utils/glob.ts", "../../src/server/server-proxy.ts", "../../src/server/routes.ts", "../../src/utils/banner.ts", "../../src/server/collect-css.ts", "../../src/utils/duration.ts", "../../src/utils/env.ts", "../../src/utils/load-config.ts"],
4
- "sourcesContent": ["import { createServer } from 'node:http'\nimport { createServer as createViteServer } from 'vite'\nimport { getRequestListener } from '@hono/node-server'\nimport { Hono } from 'hono'\nimport { devix } from '../vite'\nimport { registerApiRoutes } from '../server/routes'\nimport { printDevBanner } from \"../utils/banner\"\nimport { collectCss } from \"../server/collect-css\"\nimport { parseDuration } from \"../utils/duration\"\nimport { loadDotenv } from \"../utils/env\"\nimport {loadConfig} from \"../utils/load-config\";\n\nloadDotenv('development')\n\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\n\nconst config = await loadConfig(process.cwd())\nconst port = Number(process.env.PORT) || config.port || 3000\nconst host = typeof config.host === 'string' ? config.host : config.host ? '0.0.0.0' : 'localhost'\n\nconst vite = await createViteServer({\n ...devix(config),\n configFile: false,\n appType: 'custom',\n server: { middlewareMode: true },\n})\n\nconst renderModule = {\n render: async (...args: any[]) => (await vite.ssrLoadModule(VIRTUAL_RENDER)).render(...args),\n runLoader: async (...args: any[]) => (await vite.ssrLoadModule(VIRTUAL_RENDER)).runLoader(...args),\n}\nconst apiModule = {\n handleApiRequest: async (...args: any[]) => (await\n vite.ssrLoadModule(VIRTUAL_API)).handleApiRequest(...args),\n}\n\nconst app = new Hono()\nregisterApiRoutes(app, { renderModule, apiModule, server: config.server })\n\napp.get('*', async (c) => {\n try {\n const { html, statusCode, headers } = await renderModule.render(c.req.url, c.req.raw, {\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n server: config.server,\n })\n const cssUrls = await collectCss(vite)\n const cssLinks = cssUrls.map(url => `<link rel=\"stylesheet\" href=\"${url}\">`).join('\\n')\n const htmlWithCss = cssLinks ? html.replace('</head>', `${cssLinks}\\n</head>`) : html\n const transformed = await vite.transformIndexHtml(c.req.url, `<!DOCTYPE html>${htmlWithCss}`)\n const res = c.html(transformed, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n vite.ssrFixStacktrace(e as Error)\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n})\n\nconst honoHandler = getRequestListener(app.fetch)\ncreateServer(async (req, res) => {\n await new Promise<void>(resolve => vite.middlewares(req, res, resolve))\n if (!res.writableEnded) await honoHandler(req, res)\n}).listen(port, host, () => {\n printDevBanner(port)\n})\n\nexport { } ", "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}", "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}", "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", "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 {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}", "export type JsonResponse<T = unknown, S extends number = number> = Response & {\n readonly __body: T\n readonly __status: S\n}\n\nexport function json<const T>(data: T): JsonResponse<T, 200>\nexport function json<const T, const S extends number>(data: T, status: S): JsonResponse<T, S>\nexport function json<const T>(data: T, status: number = 200): JsonResponse<T, any> {\n return new Response(JSON.stringify(data), {\n status,\n headers: {'Content-Type': 'application/json'},\n }) as JsonResponse<T, any>\n}\n\nexport const text = (body: string, status = 200): Response =>\n new Response(body, {status, headers: {'Content-Type': 'text/plain; charset=utf-8'}})\n\nconst REDIRECT_BRAND = Symbol.for('devix.redirect')\n\nexport interface RedirectOptions {\n status?: number\n replace?: boolean\n}\n\nexport interface Redirect {\n readonly [REDIRECT_BRAND]: true\n readonly url: string\n readonly status: number\n readonly replace: boolean\n}\n\nexport function redirect(url: string, statusOrOptions?: number | RedirectOptions): Redirect {\n const status = typeof statusOrOptions === 'number' ? statusOrOptions : (statusOrOptions?.status ?? 302)\n const replace = typeof statusOrOptions === 'object' ? (statusOrOptions?.replace ?? false) : false\n return {[REDIRECT_BRAND]: true, url, status, replace} as Redirect\n}\n\nexport function isRedirect(value: unknown): value is Redirect {\n return typeof value === 'object' && value !== null && REDIRECT_BRAND in value\n}\n\nconst ERROR_BRAND = Symbol.for('devix.loaderError')\n\nexport interface RouteError {\n readonly [ERROR_BRAND]: true\n readonly statusCode: number\n readonly message: string\n readonly code?: string\n readonly data?: unknown\n}\n\nexport interface ErrorOptions {\n code?: string\n data?: unknown\n}\n\n/**\n * Crea un error tipado que funciona en loaders, guards y handlers API.\n *\n * En loaders/guards: ret\u00F3rnalo (no lo lances) y el sistema renderiza `error.tsx`.\n * En handlers API: ret\u00F3rnalo y el sistema serializa el shape `ErrorBody` como JSON\n * con el statusCode correcto.\n *\n * ```ts\n * return error(404, 'Post no encontrado', { code: 'POST_NOT_FOUND' })\n * ```\n */\nexport function error(statusCode: number, message: string, options?: ErrorOptions): RouteError {\n return {\n [ERROR_BRAND]: true,\n statusCode,\n message,\n code: options?.code,\n data: options?.data,\n } as RouteError\n}\n\nexport function isLoaderError(value: unknown): value is RouteError {\n return typeof value === 'object' && value !== null && ERROR_BRAND in value\n}\n\n/**\n * Shape p\u00FAblico del body de un error API. Todos los errores emitidos por `error()`\n * o `DevixError` se serializan a este shape. `FetchError.body` del cliente lo recibe.\n */\nexport interface ErrorBody {\n statusCode: number\n message: string\n code?: string\n data?: unknown\n}\n\nexport function errorToBody(err: { statusCode: number; message: string; code?: string; data?: unknown }): ErrorBody {\n const body: ErrorBody = { statusCode: err.statusCode, message: err.message }\n if (err.code !== undefined) body.code = err.code\n if (err.data !== undefined) body.data = err.data\n return body\n}\n", "/**\n * Match simple de path contra un glob estilo `'/v1/**'`, `'/v1/users/*'`, `'/v1/users/:id'`.\n *\n * Reglas:\n * - `**` matchea cualquier subpath (incluye `/`).\n * - `*` matchea un \u00FAnico segmento (sin `/`).\n * - `:param` matchea un \u00FAnico segmento.\n * - Cualquier otro caracter es literal.\n */\nexport function matchPathGlob(path: string, pattern: string): boolean {\n const regex = globToRegex(pattern)\n return regex.test(path)\n}\n\nexport function matchesAnyGlob(path: string, patterns: readonly string[] | undefined): boolean {\n if (!patterns || patterns.length === 0) return false\n for (const pattern of patterns) {\n if (matchPathGlob(path, pattern)) return true\n }\n return false\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let regex = ''\n let i = 0\n while (i < pattern.length) {\n const c = pattern[i]\n if (c === '*' && pattern[i + 1] === '*') {\n regex += '.*'\n i += 2\n } else if (c === '*') {\n regex += '[^/]*'\n i += 1\n } else if (c === ':') {\n i += 1\n while (i < pattern.length && /[a-zA-Z0-9_]/.test(pattern[i])) i += 1\n regex += '[^/]+'\n } else if ('.+?^$()|[]{}\\\\'.includes(c)) {\n regex += '\\\\' + c\n i += 1\n } else {\n regex += c\n i += 1\n }\n }\n return new RegExp(`^${regex}$`)\n}\n", "import type {ServerBackendConfig, PrepareContext} from '../config'\nimport {matchesAnyGlob} from '../utils/glob'\nimport {errorToBody} from '../utils/response'\n\nconst PROXY_PREFIX = '/_devix/server'\n\nfunction jsonError(statusCode: number, message: string, code?: string): Response {\n const body = errorToBody({statusCode, message, code})\n return new Response(JSON.stringify(body), {\n status: statusCode,\n headers: {'Content-Type': 'application/json'},\n })\n}\n\n/**\n * Parsea `/_devix/server/<namespace>/<path>` \u2192 `{namespace, path}`.\n * Retorna null si el path no es un request al proxy.\n */\nexport function parseProxyPath(pathname: string): {namespace: string; path: string} | null {\n if (!pathname.startsWith(PROXY_PREFIX + '/')) return null\n const rest = pathname.slice(PROXY_PREFIX.length + 1)\n const slash = rest.indexOf('/')\n if (slash === -1) {\n return {namespace: rest, path: '/'}\n }\n return {namespace: rest.slice(0, slash), path: rest.slice(slash)}\n}\n\n/**\n * Maneja un request entrante al proxy interno. Aplica allowlist/denylist,\n * ejecuta `prepare`, y reenv\u00EDa al backend configurado.\n */\nexport async function handleProxyRequest(\n request: Request,\n config: Record<string, ServerBackendConfig> | undefined,\n): Promise<Response> {\n const url = new URL(request.url)\n const parsed = parseProxyPath(url.pathname)\n if (!parsed) {\n return jsonError(404, 'Not found', 'PROXY_NOT_FOUND')\n }\n\n const backend = config?.[parsed.namespace]\n if (!backend) {\n return jsonError(404, `Backend \"${parsed.namespace}\" not configured`, 'BACKEND_NOT_FOUND')\n }\n\n if (!matchesAnyGlob(parsed.path, backend.allowedPaths)) {\n return jsonError(403, 'Path not allowed', 'PATH_NOT_ALLOWED')\n }\n if (matchesAnyGlob(parsed.path, backend.deniedPaths)) {\n return jsonError(403, 'Path denied', 'PATH_DENIED')\n }\n\n const targetUrl = new URL(parsed.path + url.search, backend.url)\n const headers = new Headers()\n\n if (backend.prepare) {\n const ctx: PrepareContext = {request, headers, url: targetUrl}\n try {\n const result = await backend.prepare(ctx)\n if (result instanceof Response) return result\n } catch (err) {\n console.error(`[devix] server.${parsed.namespace}.prepare error:`, err)\n return jsonError(500, 'Proxy prepare failed', 'PREPARE_ERROR')\n }\n }\n\n if (!headers.has('Accept')) {\n const accept = request.headers.get('Accept')\n if (accept) headers.set('Accept', accept)\n }\n const ct = request.headers.get('Content-Type')\n if (ct && !headers.has('Content-Type')) headers.set('Content-Type', ct)\n\n let body: BodyInit | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n body = await request.arrayBuffer()\n if ((body as ArrayBuffer).byteLength === 0) body = null\n }\n\n try {\n const backendRes = await fetch(targetUrl, {\n method: request.method,\n headers,\n body,\n redirect: 'manual',\n })\n return new Response(backendRes.body, {\n status: backendRes.status,\n statusText: backendRes.statusText,\n headers: filterHopByHop(backendRes.headers),\n })\n } catch (err) {\n console.error(`[devix] server.${parsed.namespace} fetch error:`, err)\n return jsonError(502, 'Bad Gateway', 'BACKEND_UNREACHABLE')\n }\n}\n\nconst HOP_BY_HOP = new Set([\n 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',\n 'te', 'trailers', 'transfer-encoding', 'upgrade',\n])\n\nfunction filterHopByHop(src: Headers): Headers {\n const dst = new Headers()\n src.forEach((value, key) => {\n if (!HOP_BY_HOP.has(key.toLowerCase())) dst.set(key, value)\n })\n return dst\n}\n\nexport const PROXY_PATH_PREFIX = PROXY_PREFIX\n", "import type {Hono} from 'hono'\nimport type {ContentfulStatusCode} from 'hono/utils/http-status'\nimport type {Manifest} from 'vite'\nimport {errorToBody} from \"../utils/response\"\nimport type {ServerBackendConfig} from \"../config\"\nimport {handleProxyRequest} from \"./server-proxy\"\n\ninterface ServerOptions {\n renderModule: any\n apiModule: any\n manifest?: Manifest\n loaderTimeout?: number\n server?: Record<string, ServerBackendConfig>\n}\n\nexport function registerApiRoutes(app: Hono, {apiModule, renderModule, loaderTimeout, server}: ServerOptions) {\n if (server) {\n app.all('/_devix/server/*', async (c) => {\n try {\n return await handleProxyRequest(c.req.raw, server)\n } catch (e) {\n console.error('[devix] proxy fatal error:', e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n }\n\n app.all('/api/*', async (c) => {\n try {\n return await apiModule.handleApiRequest(c.req.url, c.req.raw, server)\n } catch (e) {\n console.error(e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n\n app.get('/_data/*', async (c) => {\n try {\n const {pathname, search} = new URL(c.req.url, 'http://localhost')\n const url = pathname.replace(/^\\/_data/, '') + search\n\n const data = await renderModule.runLoader(url, c.req.raw, {loaderTimeout, server})\n if (data.error) return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n if ('loaderError' in data) {\n const body = errorToBody(data.loaderError)\n return c.json(body, body.statusCode as ContentfulStatusCode)\n }\n return c.json(data)\n } catch (e) {\n console.error(e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n}\n\nexport function registerSsrRoute(app: Hono, {renderModule, manifest, loaderTimeout, server}: ServerOptions) {\n app.get('*', async (c) => {\n try {\n const {html, statusCode, headers} = await renderModule.render(c.req.url, c.req.raw, {manifest, loaderTimeout, server})\n const res = c.html(`<!DOCTYPE html>${html}`, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n })\n}", "import pc from 'picocolors'\nimport {networkInterfaces} from 'node:os'\n\ndeclare const __DEVIX_VERSION__: string\n\nfunction getNetworkUrl(port: number): string | null {\n const nets = networkInterfaces()\n for (const interfaces of Object.values(nets)) {\n for (const net of interfaces ?? []) {\n if (net.family === 'IPv4' && !net.internal) {\n return `http://${net.address}:${port}/`\n }\n }\n }\n return null\n}\n\nexport function printDevBanner(port: number) {\n const version = __DEVIX_VERSION__\n const networkUrl = getNetworkUrl(port)\n\n console.log()\n console.log(` ${pc.bold(pc.yellow('devix'))} ${pc.dim(`v${version}`)}`)\n console.log()\n console.log(` ${pc.green('\u279C')} ${pc.bold('Local:')} ${pc.cyan(`http://localhost:${port}/`)}`)\n if (networkUrl) {\n console.log(` ${pc.green('\u279C')} ${pc.bold('Network:')} ${pc.cyan(networkUrl)}`)\n } else {\n console.log(` ${pc.green('\u279C')} ${pc.bold('Network:')} ${pc.dim('use --host to expose')}`)\n }\n console.log()\n}", "import type {ViteDevServer} from 'vite'\n\nexport async function collectCss(vite: ViteDevServer): Promise<string[]> {\n const cssUrls = new Set<string>()\n\n for (const [, mod] of vite.moduleGraph.idToModuleMap) {\n if (!mod.id) continue\n if ((mod.id.endsWith('.css') || mod.id.includes('.css?')) && mod.url.startsWith('/')) {\n cssUrls.add(mod.url)\n }\n }\n\n return [...cssUrls]\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 {loadEnv} from 'vite'\n\nexport function loadDotenv(mode: string) {\n const env = loadEnv(mode, process.cwd(), '')\n for (const [key, value] of Object.entries(env)) {\n if (process.env[key] === undefined) {\n process.env[key] = value\n }\n }\n}\n", "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}"],
5
- "mappings": "AAAA,OAAS,gBAAAA,OAAoB,YAC7B,OAAS,gBAAgBC,OAAwB,OACjD,OAAS,sBAAAC,OAA0B,oBACnC,OAAS,QAAAC,OAAY,OCHrB,OAA4B,eAAAC,OAAkB,OAE9C,OAAOC,OAAW,uBAClB,OAAQ,iBAAAC,OAAoB,WAC5B,OAAQ,WAAAC,GAAS,YAAAC,GAAU,WAAAC,MAAc,YACzC,OAAQ,iBAAAC,OAAoB,cCDrB,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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AO,eAAiB,GAAM,EAC3D,OAAQA,EAAO,MACjB,CAAC,EAEKkB,GADU,MAAMC,GAAWf,CAAI,GACZ,IAAIgB,GAAO,gCAAgCA,CAAG,IAAI,EAAE,KAAK;AAAA,CAAI,EAChFC,EAAcH,EAAWJ,EAAK,QAAQ,UAAW,GAAGI,CAAQ;AAAA,QAAW,EAAIJ,EAC3EQ,EAAc,MAAMlB,EAAK,mBAAmBS,EAAE,IAAI,IAAK,kBAAkBQ,CAAW,EAAE,EACtFE,EAAMV,EAAE,KAAKS,EAAaP,CAAU,EAC1C,OAAW,CAACS,EAAKC,CAAK,IAAK,OAAO,QAAQT,CAAiC,EACzEO,EAAI,QAAQ,IAAIC,EAAKC,CAAK,EAE5B,OAAOF,CACT,OAASG,EAAG,CACV,OAAAtB,EAAK,iBAAiBsB,CAAU,EAChC,QAAQ,MAAMA,CAAC,EACRb,EAAE,KAAK,wBAAyB,GAAG,CAC5C,CACF,CAAC,EAED,IAAMc,GAAcC,GAAmBlB,EAAI,KAAK,EAChDmB,GAAa,MAAOC,EAAKP,IAAQ,CAC/B,MAAM,IAAI,QAAcQ,GAAW3B,EAAK,YAAY0B,EAAKP,EAAKQ,CAAO,CAAC,EACjER,EAAI,eAAe,MAAMI,GAAYG,EAAKP,CAAG,CACpD,CAAC,EAAE,OAAOrB,GAAMC,GAAM,IAAM,CAC1B6B,GAAe9B,EAAI,CACrB,CAAC",
4
+ "sourcesContent": ["import { createServer } from 'node:http'\nimport { createServer as createViteServer } from 'vite'\nimport { getRequestListener } from '@hono/node-server'\nimport { Hono, type Context } from 'hono'\nimport { devix } from '../vite'\nimport { registerApiRoutes } from '../server/routes'\nimport { printDevBanner } from \"../utils/banner\"\nimport { collectCss } from \"../server/collect-css\"\nimport { parseDuration } from \"../utils/duration\"\nimport { loadDotenv } from \"../utils/env\"\nimport {loadConfig} from \"../utils/load-config\";\n\nloadDotenv('development')\n\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\n\nconst config = await loadConfig(process.cwd())\nconst port = Number(process.env.PORT) || config.port || 3000\nconst host = typeof config.host === 'string' ? config.host : config.host ? '0.0.0.0' : 'localhost'\n\nconst vite = await createViteServer({\n ...devix(config),\n configFile: false,\n appType: 'custom',\n server: { middlewareMode: true },\n})\n\nconst renderModule = {\n render: async (...args: any[]) => (await vite.ssrLoadModule(VIRTUAL_RENDER)).render(...args),\n runLoader: async (...args: any[]) => (await vite.ssrLoadModule(VIRTUAL_RENDER)).runLoader(...args),\n}\nconst apiModule = {\n handleApiRequest: async (...args: any[]) => (await\n vite.ssrLoadModule(VIRTUAL_API)).handleApiRequest(...args),\n}\n\nconst app = new Hono()\nregisterApiRoutes(app, { renderModule, apiModule, server: config.server })\n\napp.get('*', async (c: Context) => {\n try {\n const { html, statusCode, headers } = await renderModule.render(c.req.url, c.req.raw, {\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n server: config.server,\n })\n const cssUrls = await collectCss(vite)\n const cssLinks = cssUrls.map(url => `<link rel=\"stylesheet\" href=\"${url}\">`).join('\\n')\n const htmlWithCss = cssLinks ? html.replace('</head>', `${cssLinks}\\n</head>`) : html\n const transformed = await vite.transformIndexHtml(c.req.url, `<!DOCTYPE html>${htmlWithCss}`)\n const res = c.html(transformed, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n vite.ssrFixStacktrace(e as Error)\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n})\n\nconst honoHandler = getRequestListener(app.fetch)\ncreateServer(async (req, res) => {\n await new Promise<void>(resolve => vite.middlewares(req, res, resolve))\n if (!res.writableEnded) await honoHandler(req, res)\n}).listen(port, host, () => {\n printDevBanner(port)\n})\n\nexport { } ", "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}", "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}", "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", "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 {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}", "export type JsonResponse<T = unknown, S extends number = number> = Response & {\n readonly __body: T\n readonly __status: S\n}\n\nexport function json<const T>(data: T): JsonResponse<T, 200>\nexport function json<const T, const S extends number>(data: T, status: S): JsonResponse<T, S>\nexport function json<const T>(data: T, status: number = 200): JsonResponse<T, any> {\n return new Response(JSON.stringify(data), {\n status,\n headers: {'Content-Type': 'application/json'},\n }) as JsonResponse<T, any>\n}\n\nexport const text = (body: string, status = 200): Response =>\n new Response(body, {status, headers: {'Content-Type': 'text/plain; charset=utf-8'}})\n\nconst REDIRECT_BRAND = Symbol.for('devix.redirect')\n\nexport interface RedirectOptions {\n status?: number\n replace?: boolean\n}\n\nexport interface Redirect {\n readonly [REDIRECT_BRAND]: true\n readonly url: string\n readonly status: number\n readonly replace: boolean\n}\n\nexport function redirect(url: string, statusOrOptions?: number | RedirectOptions): Redirect {\n const status = typeof statusOrOptions === 'number' ? statusOrOptions : (statusOrOptions?.status ?? 302)\n const replace = typeof statusOrOptions === 'object' ? (statusOrOptions?.replace ?? false) : false\n return {[REDIRECT_BRAND]: true, url, status, replace} as Redirect\n}\n\nexport function isRedirect(value: unknown): value is Redirect {\n return typeof value === 'object' && value !== null && REDIRECT_BRAND in value\n}\n\nconst ERROR_BRAND = Symbol.for('devix.loaderError')\n\nexport interface RouteError {\n readonly [ERROR_BRAND]: true\n readonly statusCode: number\n readonly message: string\n readonly code?: string\n readonly data?: unknown\n}\n\nexport interface ErrorOptions {\n code?: string\n data?: unknown\n}\n\n/**\n * Crea un error tipado que funciona en loaders, guards y handlers API.\n *\n * En loaders/guards: ret\u00F3rnalo (no lo lances) y el sistema renderiza `error.tsx`.\n * En handlers API: ret\u00F3rnalo y el sistema serializa el shape `ErrorBody` como JSON\n * con el statusCode correcto.\n *\n * ```ts\n * return error(404, 'Post no encontrado', { code: 'POST_NOT_FOUND' })\n * ```\n */\nexport function error(statusCode: number, message: string, options?: ErrorOptions): RouteError {\n return {\n [ERROR_BRAND]: true,\n statusCode,\n message,\n code: options?.code,\n data: options?.data,\n } as RouteError\n}\n\nexport function isLoaderError(value: unknown): value is RouteError {\n return typeof value === 'object' && value !== null && ERROR_BRAND in value\n}\n\n/**\n * Shape p\u00FAblico del body de un error API. Todos los errores emitidos por `error()`\n * o `DevixError` se serializan a este shape. `FetchError.body` del cliente lo recibe.\n */\nexport interface ErrorBody {\n statusCode: number\n message: string\n code?: string\n data?: unknown\n}\n\nexport function errorToBody(err: { statusCode: number; message: string; code?: string; data?: unknown }): ErrorBody {\n const body: ErrorBody = { statusCode: err.statusCode, message: err.message }\n if (err.code !== undefined) body.code = err.code\n if (err.data !== undefined) body.data = err.data\n return body\n}\n", "/**\n * Match simple de path contra un glob estilo `'/v1/**'`, `'/v1/users/*'`, `'/v1/users/:id'`.\n *\n * Reglas:\n * - `**` matchea cualquier subpath (incluye `/`).\n * - `*` matchea un \u00FAnico segmento (sin `/`).\n * - `:param` matchea un \u00FAnico segmento.\n * - Cualquier otro caracter es literal.\n */\nexport function matchPathGlob(path: string, pattern: string): boolean {\n const regex = globToRegex(pattern)\n return regex.test(path)\n}\n\nexport function matchesAnyGlob(path: string, patterns: readonly string[] | undefined): boolean {\n if (!patterns || patterns.length === 0) return false\n for (const pattern of patterns) {\n if (matchPathGlob(path, pattern)) return true\n }\n return false\n}\n\nfunction globToRegex(pattern: string): RegExp {\n let regex = ''\n let i = 0\n while (i < pattern.length) {\n const c = pattern[i]\n if (c === '*' && pattern[i + 1] === '*') {\n regex += '.*'\n i += 2\n } else if (c === '*') {\n regex += '[^/]*'\n i += 1\n } else if (c === ':') {\n i += 1\n while (i < pattern.length && /[a-zA-Z0-9_]/.test(pattern[i])) i += 1\n regex += '[^/]+'\n } else if ('.+?^$()|[]{}\\\\'.includes(c)) {\n regex += '\\\\' + c\n i += 1\n } else {\n regex += c\n i += 1\n }\n }\n return new RegExp(`^${regex}$`)\n}\n", "import type {ServerBackendConfig, PrepareContext} from '../config'\nimport {matchesAnyGlob} from '../utils/glob'\nimport {errorToBody} from '../utils/response'\n\nconst PROXY_PREFIX = '/_devix/server'\n\nfunction jsonError(statusCode: number, message: string, code?: string): Response {\n const body = errorToBody({statusCode, message, code})\n return new Response(JSON.stringify(body), {\n status: statusCode,\n headers: {'Content-Type': 'application/json'},\n })\n}\n\n/**\n * Parsea `/_devix/server/<namespace>/<path>` \u2192 `{namespace, path}`.\n * Retorna null si el path no es un request al proxy.\n */\nexport function parseProxyPath(pathname: string): {namespace: string; path: string} | null {\n if (!pathname.startsWith(PROXY_PREFIX + '/')) return null\n const rest = pathname.slice(PROXY_PREFIX.length + 1)\n const slash = rest.indexOf('/')\n if (slash === -1) {\n return {namespace: rest, path: '/'}\n }\n return {namespace: rest.slice(0, slash), path: rest.slice(slash)}\n}\n\n/**\n * Maneja un request entrante al proxy interno. Aplica allowlist/denylist,\n * ejecuta `prepare`, y reenv\u00EDa al backend configurado.\n */\nexport async function handleProxyRequest(\n request: Request,\n config: Record<string, ServerBackendConfig> | undefined,\n): Promise<Response> {\n const url = new URL(request.url)\n const parsed = parseProxyPath(url.pathname)\n if (!parsed) {\n return jsonError(404, 'Not found', 'PROXY_NOT_FOUND')\n }\n\n const backend = config?.[parsed.namespace]\n if (!backend) {\n return jsonError(404, `Backend \"${parsed.namespace}\" not configured`, 'BACKEND_NOT_FOUND')\n }\n\n if (!matchesAnyGlob(parsed.path, backend.allowedPaths)) {\n return jsonError(403, 'Path not allowed', 'PATH_NOT_ALLOWED')\n }\n if (matchesAnyGlob(parsed.path, backend.deniedPaths)) {\n return jsonError(403, 'Path denied', 'PATH_DENIED')\n }\n\n const targetUrl = new URL(parsed.path + url.search, backend.url)\n const headers = new Headers()\n\n if (backend.prepare) {\n const ctx: PrepareContext = {request, headers, url: targetUrl}\n try {\n const result = await backend.prepare(ctx)\n if (result instanceof Response) return result\n } catch (err) {\n console.error(`[devix] server.${parsed.namespace}.prepare error:`, err)\n return jsonError(500, 'Proxy prepare failed', 'PREPARE_ERROR')\n }\n }\n\n if (!headers.has('Accept')) {\n const accept = request.headers.get('Accept')\n if (accept) headers.set('Accept', accept)\n }\n const ct = request.headers.get('Content-Type')\n if (ct && !headers.has('Content-Type')) headers.set('Content-Type', ct)\n\n let body: BodyInit | null = null\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n body = await request.arrayBuffer()\n if ((body as ArrayBuffer).byteLength === 0) body = null\n }\n\n try {\n const backendRes = await fetch(targetUrl, {\n method: request.method,\n headers,\n body,\n redirect: 'manual',\n })\n return new Response(backendRes.body, {\n status: backendRes.status,\n statusText: backendRes.statusText,\n headers: filterHopByHop(backendRes.headers),\n })\n } catch (err) {\n console.error(`[devix] server.${parsed.namespace} fetch error:`, err)\n return jsonError(502, 'Bad Gateway', 'BACKEND_UNREACHABLE')\n }\n}\n\nconst HOP_BY_HOP = new Set([\n 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',\n 'te', 'trailers', 'transfer-encoding', 'upgrade',\n])\n\nfunction filterHopByHop(src: Headers): Headers {\n const dst = new Headers()\n src.forEach((value, key) => {\n if (!HOP_BY_HOP.has(key.toLowerCase())) dst.set(key, value)\n })\n return dst\n}\n\nexport const PROXY_PATH_PREFIX = PROXY_PREFIX\n", "import type {Context, Hono} from 'hono'\nimport type {ContentfulStatusCode} from 'hono/utils/http-status'\nimport type {Manifest} from 'vite'\nimport {errorToBody} from \"../utils/response\"\nimport type {ServerBackendConfig} from \"../config\"\nimport {handleProxyRequest} from \"./server-proxy\"\n\ninterface ServerOptions {\n renderModule: any\n apiModule: any\n manifest?: Manifest\n loaderTimeout?: number\n server?: Record<string, ServerBackendConfig>\n}\n\nexport function registerApiRoutes(app: Hono, {apiModule, renderModule, loaderTimeout, server}: ServerOptions) {\n if (server) {\n app.all('/_devix/server/*', async (c: Context) => {\n try {\n return await handleProxyRequest(c.req.raw, server)\n } catch (e) {\n console.error('[devix] proxy fatal error:', e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n }\n\n app.all('/api/*', async (c: Context) => {\n try {\n return await apiModule.handleApiRequest(c.req.url, c.req.raw, server)\n } catch (e) {\n console.error(e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n\n app.get('/_data/*', async (c: Context) => {\n try {\n const {pathname, search} = new URL(c.req.url, 'http://localhost')\n const url = pathname.replace(/^\\/_data/, '') + search\n\n const data = await renderModule.runLoader(url, c.req.raw, {loaderTimeout, server})\n if (data.error) return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n if ('loaderError' in data) {\n const body = errorToBody(data.loaderError)\n return c.json(body, body.statusCode as ContentfulStatusCode)\n }\n return c.json(data)\n } catch (e) {\n console.error(e)\n return c.json({statusCode: 500, message: 'Internal Server Error'}, 500)\n }\n })\n}\n\nexport function registerSsrRoute(app: Hono, {renderModule, manifest, loaderTimeout, server}: ServerOptions) {\n app.get('*', async (c: Context) => {\n try {\n const {html, statusCode, headers} = await renderModule.render(c.req.url, c.req.raw, {manifest, loaderTimeout, server})\n const res = c.html(`<!DOCTYPE html>${html}`, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n })\n}", "import pc from 'picocolors'\nimport {networkInterfaces} from 'node:os'\n\ndeclare const __DEVIX_VERSION__: string\n\nfunction getNetworkUrl(port: number): string | null {\n const nets = networkInterfaces()\n for (const interfaces of Object.values(nets)) {\n for (const net of interfaces ?? []) {\n if (net.family === 'IPv4' && !net.internal) {\n return `http://${net.address}:${port}/`\n }\n }\n }\n return null\n}\n\nexport function printDevBanner(port: number) {\n const version = __DEVIX_VERSION__\n const networkUrl = getNetworkUrl(port)\n\n console.log()\n console.log(` ${pc.bold(pc.yellow('devix'))} ${pc.dim(`v${version}`)}`)\n console.log()\n console.log(` ${pc.green('\u279C')} ${pc.bold('Local:')} ${pc.cyan(`http://localhost:${port}/`)}`)\n if (networkUrl) {\n console.log(` ${pc.green('\u279C')} ${pc.bold('Network:')} ${pc.cyan(networkUrl)}`)\n } else {\n console.log(` ${pc.green('\u279C')} ${pc.bold('Network:')} ${pc.dim('use --host to expose')}`)\n }\n console.log()\n}", "import type {ViteDevServer} from 'vite'\n\nexport async function collectCss(vite: ViteDevServer): Promise<string[]> {\n const cssUrls = new Set<string>()\n\n for (const [, mod] of vite.moduleGraph.idToModuleMap) {\n if (!mod.id) continue\n if ((mod.id.endsWith('.css') || mod.id.includes('.css?')) && mod.url.startsWith('/')) {\n cssUrls.add(mod.url)\n }\n }\n\n return [...cssUrls]\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 {loadEnv} from 'vite'\n\nexport function loadDotenv(mode: string) {\n const env = loadEnv(mode, process.cwd(), '')\n for (const [key, value] of Object.entries(env)) {\n if (process.env[key] === undefined) {\n process.env[key] = value\n }\n }\n}\n", "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}"],
5
+ "mappings": "AAAA,OAAS,gBAAAA,OAAoB,YAC7B,OAAS,gBAAgBC,OAAwB,OACjD,OAAS,sBAAAC,OAA0B,oBACnC,OAAS,QAAAC,OAA0B,OCHnC,OAA4B,eAAAC,OAAkB,OAE9C,OAAOC,OAAW,uBAClB,OAAQ,iBAAAC,OAAoB,WAC5B,OAAQ,WAAAC,GAAS,YAAAC,GAAU,WAAAC,MAAc,YACzC,OAAQ,iBAAAC,OAAoB,cCDrB,SAASC,EAAoB,CAAE,QAAAC,CAAQ,EAA+B,CAGzE,MAAO;AAAA,EAFYA,EAAQ,IAAIC,GAAK,WAAWA,CAAC,GAAG,EAAE,KAAK;AAAA,CAAI,CAGtD;AAAA;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"Hono", "mergeConfig", "react", "fileURLToPath", "dirname", "relative", "resolve", "createRequire", "generateEntryClient", "cssUrls", "u", "generateClientRoutes", "pagesDir", "matcherPath", "generateRender", "pagesDir", "renderPath", "generateApi", "apiPath", "appDir", "generateContext", "readFileSync", "readdirSync", "statSync", "join", "relative", "METHOD_EXPORT_RE", "stripComments", "content", "extractHttpMethods", "found", "match", "routePattern", "rel", "keyToRoutePattern", "key", "apiDir", "rel", "pattern", "routePattern", "filePathToIdentifier", "filePath", "apiDir", "buildRouteEntry", "methods", "keyToRoutePattern", "generateRoutesDts", "entries", "imports", "e", "importPath", "routeLines", "m", "walkDir", "dir", "root", "entries", "name", "readdirSync", "full", "join", "statSync", "relative", "scanApiFiles", "appDir", "projectRoot", "apiDir", "files", "f", "filePath", "content", "readFileSync", "methods", "extractHttpMethods", "buildRouteEntry", "mkdirSync", "readFileSync", "writeFileSync", "existsSync", "join", "writeRoutesDts", "content", "projectRoot", "devixDir", "outPath", "parseSync", "generateServerEntry", "routesPath", "envPath", "honoServerPath", "honoServerStaticPath", "honoPath", "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", "root", "fullPath", "join", "code", "readFileSync", "loaderInfo", "inspectLoaderExport", "warnings", "typesDir", "outPath", "pageAbsNoExt", "relative", "content", "existsSync", "mkdirSync", "writeFileSync", "deletePageTypes", "rmSync", "scanAndWritePageTypes", "appDir", "pagesDir", "files", "walkPages", "file", "result", "__dirname", "dirname", "fileURLToPath", "VIRTUAL_ENTRY_CLIENT", "VIRTUAL_CLIENT_ROUTES", "VIRTUAL_RENDER", "VIRTUAL_API", "VIRTUAL_CONTEXT", "VIRTUAL_SERVER_ENTRY", "SERVER_EXPORTS", "devix", "config", "appDir", "pagesDir", "cssUrls", "u", "renderPath", "resolve", "apiPath", "matcherPath", "routesPath", "envPath", "_require", "createRequire", "honoServerPath", "honoServerStaticPath", "honoPath", "virtualPlugin", "id", "generateEntryClient", "generateClientRoutes", "generateRender", "generateApi", "generateContext", "generateServerEntry", "code", "options", "resolvedPagesDir", "ast", "parseSync", "replacements", "node", "decl", "seen", "declarator", "a", "b", "result", "start", "end", "name", "root", "entries", "scanApiFiles", "writeRoutesDts", "generateRoutesDts", "warnings", "scanAndWritePageTypes", "w", "server", "initial", "regenerateDts", "isPageFile", "file", "pageRelPath", "relative", "invalidateVirtualModule", "mod", "writePageTypesAndLog", "writePageTypes", "deletePageTypes", "base", "react", "mergeConfig", "errorToBody", "err", "body", "matchPathGlob", "path", "pattern", "globToRegex", "matchesAnyGlob", "patterns", "regex", "i", "c", "PROXY_PREFIX", "jsonError", "statusCode", "message", "code", "body", "errorToBody", "parseProxyPath", "pathname", "rest", "slash", "handleProxyRequest", "request", "config", "url", "parsed", "backend", "matchesAnyGlob", "targetUrl", "headers", "ctx", "result", "err", "accept", "ct", "backendRes", "filterHopByHop", "HOP_BY_HOP", "src", "dst", "value", "key", "registerApiRoutes", "app", "apiModule", "renderModule", "loaderTimeout", "server", "c", "handleProxyRequest", "e", "pathname", "search", "url", "data", "body", "errorToBody", "pc", "networkInterfaces", "getNetworkUrl", "port", "nets", "interfaces", "net", "printDevBanner", "version", "networkUrl", "collectCss", "vite", "cssUrls", "mod", "parseDuration", "value", "match", "n", "loadEnv", "loadDotenv", "mode", "env", "key", "value", "build", "join", "unlinkSync", "writeFileSync", "pathToFileURL", "loadConfig", "cwd", "result", "tmpFile", "loadDotenv", "VIRTUAL_RENDER", "VIRTUAL_API", "config", "loadConfig", "port", "host", "vite", "createViteServer", "devix", "renderModule", "args", "apiModule", "app", "Hono", "registerApiRoutes", "c", "html", "statusCode", "headers", "parseDuration", "cssLinks", "collectCss", "url", "htmlWithCss", "transformed", "res", "key", "value", "e", "honoHandler", "getRequestListener", "createServer", "req", "resolve", "printDevBanner"]
7
7
  }
package/dist/cli/index.js CHANGED
@@ -267,7 +267,7 @@ export type PageParams = NonNullable<Parameters<typeof loader>[0]>["params"]
267
267
  `:`// auto-generado por devix - no editar
268
268
  export type PageData = undefined
269
269
  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.0");break}case"--help":case"-h":console.log(`
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.1");break}case"--help":case"-h":console.log(`
271
271
  devix \u2014 a lightweight SSR framework
272
272
 
273
273
  Usage: