@devlusoft/devix 0.4.0 → 0.4.1-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/build.js +88 -9
- package/dist/cli/build.js.map +4 -4
- package/dist/cli/dev-server.d.ts +1 -0
- package/dist/cli/dev-server.js +234 -0
- package/dist/cli/dev-server.js.map +7 -0
- package/dist/cli/dev.js +1 -154
- package/dist/cli/dev.js.map +4 -4
- package/dist/cli/devix-dev-server.js +155 -0
- package/dist/cli/devix-dev-server.js.map +7 -0
- package/dist/cli/generate.js +88 -9
- package/dist/cli/generate.js.map +4 -4
- package/dist/cli/index.js +89 -12
- package/dist/cli/index.js.map +4 -4
- package/dist/cli/start.js +1 -1
- package/dist/cli/start.js.map +3 -3
- package/dist/runtime/head.js +1 -1
- package/dist/runtime/head.js.map +3 -3
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/index.js.map +3 -3
- package/dist/runtime/link.js +1 -1
- package/dist/runtime/link.js.map +2 -2
- package/dist/runtime/router-provider.js +1 -1
- package/dist/runtime/router-provider.js.map +3 -3
- package/dist/runtime/server-app.js +1 -1
- package/dist/runtime/server-app.js.map +3 -3
- package/dist/server/collect-css.js +1 -1
- package/dist/server/collect-css.js.map +2 -2
- package/dist/server/render.js +1 -1
- package/dist/server/render.js.map +3 -3
- package/dist/src/cli/build.d.ts +1 -0
- package/dist/src/cli/dev-server.d.ts +1 -0
- package/dist/src/cli/dev.d.ts +1 -0
- package/dist/src/cli/devix-dev-server.d.ts +1 -0
- package/dist/src/cli/generate.d.ts +1 -0
- package/dist/src/cli/index.d.ts +2 -0
- package/dist/src/cli/start.d.ts +1 -0
- package/dist/src/config.d.ts +22 -0
- package/dist/src/runtime/api-context.d.ts +24 -0
- package/dist/src/runtime/client-router.d.ts +13 -0
- package/dist/src/runtime/context.d.ts +32 -0
- package/dist/src/runtime/create-handler.d.ts +10 -0
- package/dist/src/runtime/error-boundary.d.ts +19 -0
- package/dist/src/runtime/fetch.d.ts +39 -0
- package/dist/src/runtime/head.d.ts +7 -0
- package/dist/src/runtime/index.d.ts +14 -0
- package/dist/src/runtime/link.d.ts +8 -0
- package/dist/src/runtime/metadata.d.ts +10 -0
- package/dist/src/runtime/router-provider.d.ts +25 -0
- package/dist/src/runtime/server-app.d.ts +15 -0
- package/dist/src/server/api-router.d.ts +22 -0
- package/dist/src/server/api.d.ts +2 -0
- package/dist/src/server/collect-css.d.ts +2 -0
- package/dist/src/server/handler-store.d.ts +10 -0
- package/dist/src/server/index.d.ts +6 -0
- package/dist/src/server/pages-router.d.ts +21 -0
- package/dist/src/server/public-index.d.ts +1 -0
- package/dist/src/server/render.d.ts +62 -0
- package/dist/src/server/routes.d.ts +11 -0
- package/dist/src/server/types.d.ts +52 -0
- package/dist/src/types.d.ts +42 -0
- package/dist/src/utils/async.d.ts +1 -0
- package/dist/src/utils/banner.d.ts +1 -0
- package/dist/src/utils/cookies.d.ts +12 -0
- package/dist/src/utils/duration.d.ts +1 -0
- package/dist/src/utils/env.d.ts +1 -0
- package/dist/src/utils/html.d.ts +2 -0
- package/dist/src/utils/patterns.d.ts +1 -0
- package/dist/src/utils/response.d.ts +19 -0
- package/dist/src/vite/codegen/api.d.ts +6 -0
- package/dist/src/vite/codegen/client-routes.d.ts +6 -0
- package/dist/src/vite/codegen/context.d.ts +1 -0
- package/dist/src/vite/codegen/entry-client.d.ts +5 -0
- package/dist/src/vite/codegen/extract-methods.d.ts +4 -0
- package/dist/src/vite/codegen/render.d.ts +6 -0
- package/dist/src/vite/codegen/routes-dts.d.ts +10 -0
- package/dist/src/vite/codegen/scan-api.d.ts +2 -0
- package/dist/src/vite/codegen/write-routes-dts.d.ts +1 -0
- package/dist/src/vite/index.d.ts +3 -0
- package/dist/types.d.ts +7 -0
- package/dist/utils/banner.js +1 -1
- package/dist/utils/banner.js.map +1 -1
- package/dist/utils/load-config.d.ts +2 -0
- package/dist/utils/load-config.js +2 -0
- package/dist/utils/load-config.js.map +7 -0
- package/dist/vite/codegen/entry-client.js +11 -3
- package/dist/vite/codegen/entry-client.js.map +2 -2
- package/dist/vite/codegen/server-entry.d.ts +6 -0
- package/dist/vite/codegen/server-entry.js +73 -0
- package/dist/vite/codegen/server-entry.js.map +7 -0
- package/dist/vite/index.js +90 -11
- package/dist/vite/index.js.map +4 -4
- package/package.json +3 -2
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import{createServer as Oe}from"node:http";import{createServer as Ue}from"vite";import{getRequestListener as je}from"@hono/node-server";import{Hono as Fe}from"hono";import{mergeConfig as Ee}from"vite";import Pe from"@vitejs/plugin-react";import{fileURLToPath as Te}from"node:url";import{dirname as $e,resolve as p}from"node:path";function H({cssUrls:e}){return`
|
|
2
|
+
${e.map(r=>`import '${r}'`).join(`
|
|
3
|
+
`)}
|
|
4
|
+
import "@vitejs/plugin-react/preamble"
|
|
5
|
+
import React from "react"
|
|
6
|
+
import {hydrateRoot, createRoot} from 'react-dom/client'
|
|
7
|
+
import {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'
|
|
8
|
+
import {RouterProvider} from '@devlusoft/devix'
|
|
9
|
+
|
|
10
|
+
const root = document.getElementById('devix-root')
|
|
11
|
+
|
|
12
|
+
if (!window.__DEVIX__) {
|
|
13
|
+
const ErrorPage = getDefaultErrorPage()
|
|
14
|
+
createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))
|
|
15
|
+
} else {
|
|
16
|
+
const {metadata, viewport, clientEntry} = window.__DEVIX__
|
|
17
|
+
const loaderData = window.__LOADER_DATA__
|
|
18
|
+
const layoutsData = window.__LAYOUTS_DATA__ ?? []
|
|
19
|
+
|
|
20
|
+
const matched = matchClientRoute(window.location.pathname)
|
|
21
|
+
|
|
22
|
+
if (matched) {
|
|
23
|
+
const [pageMod, ...layoutMods] = await Promise.all([
|
|
24
|
+
matched.load(),
|
|
25
|
+
...matched.loadLayouts.map(l => l()),
|
|
26
|
+
])
|
|
27
|
+
hydrateRoot(
|
|
28
|
+
root,
|
|
29
|
+
React.createElement(RouterProvider, {
|
|
30
|
+
clientEntry,
|
|
31
|
+
initialData: loaderData,
|
|
32
|
+
initialParams: matched.params,
|
|
33
|
+
initialPage: pageMod.default,
|
|
34
|
+
initialLayouts: layoutMods.map(m => m.default),
|
|
35
|
+
initialLayoutsData: layoutsData,
|
|
36
|
+
initialMeta: metadata,
|
|
37
|
+
initialViewport: viewport,
|
|
38
|
+
})
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if (window.location.hash) {
|
|
42
|
+
const id = window.location.hash.slice(1)
|
|
43
|
+
const scrollBehavior = getComputedStyle(document.documentElement).scrollBehavior
|
|
44
|
+
requestAnimationFrame(() => {
|
|
45
|
+
document.getElementById(id)?.scrollIntoView({ behavior: scrollBehavior })
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
} else {
|
|
49
|
+
const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()
|
|
50
|
+
createRoot(root).render(
|
|
51
|
+
React.createElement(RouterProvider, {
|
|
52
|
+
clientEntry,
|
|
53
|
+
initialData: null,
|
|
54
|
+
initialParams: {},
|
|
55
|
+
initialPage: () => null,
|
|
56
|
+
initialLayouts: [],
|
|
57
|
+
initialLayoutsData: [],
|
|
58
|
+
initialMeta: null,
|
|
59
|
+
initialError: {statusCode: 404, message: 'Not found'},
|
|
60
|
+
initialErrorPage: ErrorPage,
|
|
61
|
+
})
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
`}function q({pagesDir:e,matcherPath:t}){return`
|
|
66
|
+
import React from 'react'
|
|
67
|
+
import { createMatcher } from '${t}'
|
|
68
|
+
const pageFiles = import.meta.glob(['/${e}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])
|
|
69
|
+
const layoutFiles = import.meta.glob('/${e}/**/layout.tsx')
|
|
70
|
+
const errorFiles = import.meta.glob('/${e}/**/error.tsx')
|
|
71
|
+
|
|
72
|
+
export const matchClientRoute = createMatcher(pageFiles, layoutFiles)
|
|
73
|
+
|
|
74
|
+
export async function loadErrorPage() {
|
|
75
|
+
const key = Object.keys(errorFiles)[0]
|
|
76
|
+
if (!key) return null
|
|
77
|
+
const mod = await errorFiles[key]()
|
|
78
|
+
return mod?.default ?? null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function getDefaultErrorPage() {
|
|
82
|
+
return function DefaultError({ statusCode, message }) {
|
|
83
|
+
return React.createElement('main', {
|
|
84
|
+
style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column',
|
|
85
|
+
alignItems: 'center', justifyContent: 'center', gap: '8px',
|
|
86
|
+
fontFamily: 'system-ui, sans-serif' }
|
|
87
|
+
},
|
|
88
|
+
React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),
|
|
89
|
+
React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
`}function N({pagesDir:e,renderPath:t}){return`
|
|
94
|
+
import { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${t}'
|
|
95
|
+
|
|
96
|
+
const _pages = import.meta.glob(['/${e}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])
|
|
97
|
+
const _layouts = import.meta.glob('/${e}/**/layout.tsx')
|
|
98
|
+
|
|
99
|
+
const _glob = {
|
|
100
|
+
pages: _pages,
|
|
101
|
+
layouts: _layouts,
|
|
102
|
+
pagesDir: '/${e}',
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function render(url, request, options) {
|
|
106
|
+
return _render(url, request, _glob, options)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function runLoader(url, request, options) {
|
|
110
|
+
return _runLoader(url, request, _glob, options)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function getStaticRoutes() {
|
|
114
|
+
return _getStaticRoutes(_glob)
|
|
115
|
+
}
|
|
116
|
+
`}function V({apiPath:e,appDir:t}){return`
|
|
117
|
+
import { handleApiRequest as _handleApiRequest } from '${e}'
|
|
118
|
+
|
|
119
|
+
const _routes = import.meta.glob(['/${t}/api/**/*.ts', '!**/middleware.ts'])
|
|
120
|
+
const _middlewares = import.meta.glob('/${t}/api/**/middleware.ts')
|
|
121
|
+
|
|
122
|
+
const _glob = {
|
|
123
|
+
routes: _routes,
|
|
124
|
+
middlewares: _middlewares,
|
|
125
|
+
apiDir: '/${t}/api',
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function handleApiRequest(url, request) {
|
|
129
|
+
return _handleApiRequest(url, request, _glob)
|
|
130
|
+
}
|
|
131
|
+
`}function $(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}var ue=null;function S(){ue=null}function W(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),i=$(r);return i==="/"?"/api":`/api/${i}`.replace("/api//","/api/")}var pe=null;function D(){pe=null}function B(){return`
|
|
132
|
+
export {RouterContext} from '@devlusoft/devix/runtime/context'
|
|
133
|
+
`}import{readFileSync as ge,readdirSync as he,statSync as ye}from"node:fs";import{join as A,relative as xe}from"node:path";var de=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;function me(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function J(e){let t=new Set;for(let r of me(e).matchAll(de))t.add(r[1]);return[...t]}function fe(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function X(e,t,r){return{filePath:e,urlPattern:W(e,t),identifier:fe(e,t),methods:r}}function C(e,t){if(e.length===0)return`// auto-generado por devix \u2014 no editar
|
|
134
|
+
declare module '@devlusoft/devix' {
|
|
135
|
+
interface ApiRoutes {}
|
|
136
|
+
}
|
|
137
|
+
`;let r=e.map(o=>{let s="../"+o.filePath.replace(/\.(ts|tsx)$/,"");return`import type * as ${o.identifier} from '${s}'`}).join(`
|
|
138
|
+
`),i=e.flatMap(o=>o.methods.map(s=>` '${s} ${o.urlPattern}': InferRoute<(typeof ${o.identifier})['${s}']>`)).join(`
|
|
139
|
+
`);return`// auto-generado por devix \u2014 no editar
|
|
140
|
+
${r}
|
|
141
|
+
|
|
142
|
+
type JsonResponse<T> = Response & { readonly __body: T }
|
|
143
|
+
type UnwrapJson<T> = T extends JsonResponse<infer U> ? U : never
|
|
144
|
+
type InferFnReturn<T> = T extends (...args: any[]) => any
|
|
145
|
+
? UnwrapJson<Awaited<ReturnType<T>>> | Exclude<Awaited<ReturnType<T>>, JsonResponse<any> | null | void | undefined>
|
|
146
|
+
: never
|
|
147
|
+
type InferRoute<T> =
|
|
148
|
+
T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }
|
|
149
|
+
? {
|
|
150
|
+
__body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>
|
|
151
|
+
__response: InferFnReturn<() => TReturn>
|
|
152
|
+
}
|
|
153
|
+
: InferFnReturn<T>
|
|
154
|
+
|
|
155
|
+
declare module '@devlusoft/devix' {
|
|
156
|
+
interface ApiRoutes {
|
|
157
|
+
${i}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
`}function G(e,t){let r=[];for(let i of he(e)){let o=A(e,i);ye(o).isDirectory()?r.push(...G(o,t)):/\.(ts|tsx)$/.test(i)&&r.push(xe(t,o).replace(/\\/g,"/"))}return r}function b(e,t){let r=A(t,e,"api"),i;try{i=G(r,t)}catch{return[]}return i.filter(o=>!o.endsWith("middleware.ts")&&!o.endsWith("middleware.tsx")).flatMap(o=>{try{let s=ge(A(t,o),"utf-8"),m=J(s);return m.length===0?[]:[X(o,`${e}/api`,m)]}catch{return[]}})}import{mkdirSync as ve,readFileSync as Re,writeFileSync as _e,existsSync as we}from"node:fs";import{join as Y}from"node:path";function M(e,t){let r=Y(t,".devix"),i=Y(r,"routes.d.ts");return ve(r,{recursive:!0}),we(i)&&Re(i,"utf-8")===e?!1:(_e(i,e,"utf-8"),!0)}import{parseSync as Se}from"oxc-parser";function z({routesPath:e,envPath:t}){return`
|
|
161
|
+
import { readFileSync } from 'node:fs'
|
|
162
|
+
import { serve } from '@hono/node-server'
|
|
163
|
+
import { serveStatic } from '@hono/node-server/serve-static'
|
|
164
|
+
import { Hono } from 'hono'
|
|
165
|
+
import { resolve, join, dirname } from 'node:path'
|
|
166
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
167
|
+
import { registerApiRoutes, registerSsrRoute } from '${e}'
|
|
168
|
+
import { loadDotenv } from '${t}'
|
|
169
|
+
|
|
170
|
+
loadDotenv('production')
|
|
171
|
+
|
|
172
|
+
const __dir = dirname(fileURLToPath(import.meta.url))
|
|
173
|
+
|
|
174
|
+
let renderModule, apiModule, manifest, runtimeConfig
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
runtimeConfig = JSON.parse(readFileSync(resolve(__dir, '../devix.config.json'), 'utf-8'))
|
|
178
|
+
if (runtimeConfig.output !== 'static') {
|
|
179
|
+
renderModule = await import(pathToFileURL(resolve(__dir, 'render.js')).href)
|
|
180
|
+
apiModule = await import(pathToFileURL(resolve(__dir, 'api.js')).href)
|
|
181
|
+
}
|
|
182
|
+
manifest = JSON.parse(readFileSync(resolve(__dir, '../client/.vite/manifest.json'), 'utf-8'))
|
|
183
|
+
} catch {
|
|
184
|
+
console.error('[devix] Build not found. Run "devix build" first.')
|
|
185
|
+
process.exit(1)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const port = Number(process.env.PORT) || runtimeConfig.port || 3000
|
|
189
|
+
const host = typeof runtimeConfig.host === 'string'
|
|
190
|
+
? runtimeConfig.host
|
|
191
|
+
: runtimeConfig.host ? '0.0.0.0' : (process.env.HOST || '0.0.0.0')
|
|
192
|
+
|
|
193
|
+
const clientRoot = resolve(__dir, '../client')
|
|
194
|
+
const app = new Hono()
|
|
195
|
+
|
|
196
|
+
if (runtimeConfig.output === 'static') {
|
|
197
|
+
app.get('/_data/*', (c) => {
|
|
198
|
+
const pathname = c.req.path.replace(/^\\\\/_data/, '') || '/'
|
|
199
|
+
const filePath = pathname === '/'
|
|
200
|
+
? join(clientRoot, '_data/index.json')
|
|
201
|
+
: join(clientRoot, '_data', pathname + '.json')
|
|
202
|
+
try {
|
|
203
|
+
return c.json(JSON.parse(readFileSync(filePath, 'utf-8')))
|
|
204
|
+
} catch {
|
|
205
|
+
return c.json({ error: 'not found' }, 404)
|
|
206
|
+
}
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
app.use('/*', serveStatic({
|
|
211
|
+
root: clientRoot,
|
|
212
|
+
onFound: (_path, c) => {
|
|
213
|
+
c.header('Cache-Control', _path.includes('/assets/')
|
|
214
|
+
? 'public, immutable, max-age=31536000'
|
|
215
|
+
: 'no-cache')
|
|
216
|
+
}
|
|
217
|
+
}))
|
|
218
|
+
|
|
219
|
+
if (runtimeConfig.output === 'static') {
|
|
220
|
+
console.log('[devix] Static mode \u2014 serving pre-generated files from dist/client')
|
|
221
|
+
} else {
|
|
222
|
+
registerApiRoutes(app, { renderModule, apiModule, manifest })
|
|
223
|
+
registerSsrRoute(app, { renderModule, apiModule, manifest, loaderTimeout: runtimeConfig.loaderTimeout })
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const server = serve({ fetch: app.fetch, port, hostname: host }, (info) =>
|
|
227
|
+
console.log(\`http://\${info.address}:\${info.port}\`))
|
|
228
|
+
|
|
229
|
+
process.on('SIGTERM', () => server.close())
|
|
230
|
+
process.on('SIGINT', () => server.close())
|
|
231
|
+
`}var _=$e(Te(import.meta.url)),I="virtual:devix/entry-client",L="virtual:devix/client-routes",O="virtual:devix/render",U="virtual:devix/api",j="virtual:devix/context",F="virtual:devix/server-entry",Z=new Set(["loader","guard","generateStaticParams","headers"]);function K(e){let t=e.appDir??"app",r=`${t}/pages`,i=(e.css??[]).map(n=>n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`),o=p(_,"../server/render.js").replace(/\\/g,"/"),s=p(_,"../server/api.js").replace(/\\/g,"/"),m=p(_,"../runtime/client-router.js").replace(/\\/g,"/"),y=p(_,"../server/routes.js").replace(/\\/g,"/"),f=p(_,"../utils/env.js").replace(/\\/g,"/"),x={name:"devix",enforce:"pre",resolveId(n){if(n===I)return`\0${I}`;if(n===L)return`\0${L}`;if(n===O)return`\0${O}`;if(n===U)return`\0${U}`;if(n===j)return`\0${j}`;if(n===F)return`\0${F}`},load(n){if(n===`\0${I}`)return H({cssUrls:i});if(n===`\0${L}`)return q({pagesDir:r,matcherPath:m});if(n===`\0${O}`)return N({pagesDir:r,renderPath:o});if(n===`\0${U}`)return V({apiPath:s,appDir:t});if(n===`\0${j}`)return B();if(n===`\0${F}`)return z({routesPath:y,envPath:f})},transform(n,u,v){if(v?.ssr)return;let a=p(process.cwd(),r);if(!u.startsWith(a))return;let le=Se(u,n,{sourceType:"module"}),R=[];for(let c of le.program.body){if(c.type!=="ExportNamedDeclaration"||!c.declaration)continue;let d=c.declaration;if(d.type==="FunctionDeclaration"&&d.id&&Z.has(d.id.name)&&R.push({start:c.start,end:c.end,name:d.id.name}),d.type==="VariableDeclaration"){let E=new Set;for(let T of d.declarations)T.id.type==="Identifier"&&Z.has(T.id.name)&&(E.has(c.start)||(E.add(c.start),R.push({start:c.start,end:c.end,name:T.id.name})))}}if(R.length===0)return;R.sort((c,d)=>d.start-c.start);let w=n;for(let{start:c,end:d,name:E}of R)w=w.slice(0,c)+`export const ${E} = undefined`+w.slice(d);return{code:w,map:null}},buildStart(){let n=process.cwd(),u=b(t,n);M(C(u,`${t}/api`),n)},configureServer(n){let u=process.cwd(),v=()=>{let a=b(t,u);M(C(a,`${t}/api`),u)};n.watcher.add(p(u,"devix.config.ts")),n.watcher.on("change",a=>{a===p(u,"devix.config.ts")&&(console.log("[devix] Config changed, restarting..."),process.exit(75))}),n.watcher.on("add",a=>{a.startsWith(p(u,r))&&S(),a.includes(`${t}/api`)&&(D(),v())}),n.watcher.on("unlink",a=>{a.startsWith(p(u,r))&&S(),a.includes(`${t}/api`)&&(D(),v())}),n.watcher.on("change",a=>{a.includes(`${t}/api`)&&!a.endsWith("middleware.ts")&&v()})}},P={plugins:[Pe(),x],publicDir:p(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return Ee(P,e.vite??{})}function Q(e,{apiModule:t,renderModule:r,loaderTimeout:i}){e.all("/api/*",async o=>{try{return await t.handleApiRequest(o.req.url,o.req.raw)}catch(s){return console.error(s),o.json({error:"internal error"},500)}}),e.get("/_data/*",async o=>{try{let{pathname:s,search:m}=new URL(o.req.url,"http://localhost"),y=s.replace(/^\/_data/,"")+m,f=await r.runLoader(y,o.req.raw,{loaderTimeout:i});return f.error?o.json({error:"internal error"},500):o.json(f)}catch(s){return console.error(s),o.json({error:"internal error"},500)}})}import l from"picocolors";import{networkInterfaces as De}from"node:os";function Ce(e){let t=De();for(let r of Object.values(t))for(let i of r??[])if(i.family==="IPv4"&&!i.internal)return`http://${i.address}:${e}/`;return null}function ee(e){let t="0.4.1-beta.10",r=Ce(e);console.log(),console.log(` ${l.bold(l.yellow("devix"))} ${l.dim(`v${t}`)}`),console.log(),console.log(` ${l.green("\u279C")} ${l.bold("Local:")} ${l.cyan(`http://localhost:${e}/`)}`),console.log(r?` ${l.green("\u279C")} ${l.bold("Network:")} ${l.cyan(r)}`:` ${l.green("\u279C")} ${l.bold("Network:")} ${l.dim("use --host to expose")}`),console.log()}async function te(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 re(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 Ae}from"vite";function oe(e){let t=Ae(e,process.cwd(),"");for(let[r,i]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=i)}import{build as be}from"esbuild";import{join as ne}from"node:path";import{unlinkSync as Me,writeFileSync as Ie}from"node:fs";import{pathToFileURL as Le}from"node:url";async function ie(e){let t=await be({entryPoints:[ne(e,"devix.config.ts")],bundle:!0,write:!1,format:"esm",platform:"node",packages:"external"}),r=ne(e,`.devix-config-${Date.now()}.mjs`);Ie(r,t.outputFiles[0].text);try{return(await import(Le(r).href)).default}finally{Me(r)}}oe("development");var se="virtual:devix/render",ke="virtual:devix/api",h=await ie(process.cwd()),ae=Number(process.env.PORT)||h.port||3e3,He=typeof h.host=="string"?h.host:h.host?"0.0.0.0":"localhost",g=await Ue({...K(h),configFile:!1,appType:"custom",server:{middlewareMode:!0}}),ce={render:async(...e)=>(await g.ssrLoadModule(se)).render(...e),runLoader:async(...e)=>(await g.ssrLoadModule(se)).runLoader(...e)},qe={handleApiRequest:async(...e)=>(await g.ssrLoadModule(ke)).handleApiRequest(...e)},k=new Fe;Q(k,{renderModule:ce,apiModule:qe});k.get("*",async e=>{try{let{html:t,statusCode:r,headers:i}=await ce.render(e.req.url,e.req.raw,{loaderTimeout:re(h.loaderTimeout??1e4)}),s=(await te(g)).map(x=>`<link rel="stylesheet" href="${x}">`).join(`
|
|
232
|
+
`),m=s?t.replace("</head>",`${s}
|
|
233
|
+
</head>`):t,y=await g.transformIndexHtml(e.req.url,`<!DOCTYPE html>${m}`),f=e.html(y,r);for(let[x,P]of Object.entries(i))f.headers.set(x,P);return f}catch(t){return g.ssrFixStacktrace(t),console.error(t),e.text("Internal Server Error",500)}});var Ne=je(k.fetch);Oe(async(e,t)=>{await new Promise(r=>g.middlewares(e,t,r)),t.writableEnded||await Ne(e,t)}).listen(ae,He,()=>{ee(ae)});
|
|
234
|
+
//# sourceMappingURL=dev-server.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 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/utils/patterns.ts", "../../src/server/pages-router.ts", "../../src/server/api-router.ts", "../../src/vite/codegen/context.ts", "../../src/vite/codegen/scan-api.ts", "../../src/vite/codegen/extract-methods.ts", "../../src/vite/codegen/routes-dts.ts", "../../src/vite/codegen/write-routes-dts.ts", "../../src/vite/codegen/server-entry.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 })\n\napp.get('*', async (c) => {\n try {\n const { html, statusCode, headers } = await renderModule.render(c.req.url, c.req.raw, {\n loaderTimeout:\n parseDuration(config.loaderTimeout ?? 10_000)\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, resolve } from 'node:path'\nimport { generateEntryClient } from './codegen/entry-client'\nimport { generateClientRoutes } from './codegen/client-routes'\nimport { generateRender } from './codegen/render'\nimport { generateApi } from './codegen/api'\nimport { invalidatePagesCache } from \"../server/pages-router\";\nimport { invalidateApiCache } from \"../server/api-router\";\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\";\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 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 })\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 },\n\n configureServer(server) {\n const root = process.cwd()\n\n const regenerateDts = () => {\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\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 server.watcher.on('add', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('change', (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\n const matched = matchClientRoute(window.location.pathname)\n\n 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 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 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 Page {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface Layout {\n dir: string\n key: string\n}\n\nexport interface PagesResult {\n pages: Page[]\n layouts: Layout[]\n}\n\nfunction keyToRoutePattern(key: string, pagesDir: string): string {\n const rel = key.slice(pagesDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === \"/\" ? \"/\" : `/${pattern}`\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nlet cache: PagesResult | null = null\n\nexport function invalidatePagesCache() {\n cache = null\n}\n\nexport function buildPages(pageKeys: string[], layoutKeys: string[], pagesDir: string): PagesResult {\n if (cache) return cache\n\n const pages: Page[] = []\n const layouts: Layout[] = []\n\n for (const key of layoutKeys) {\n layouts.push({dir: keyToDir(key), key})\n }\n\n for (const key of pageKeys) {\n const pattern = keyToRoutePattern(key, pagesDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n pages.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n\n pages.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 cache = {pages, layouts}\n return cache\n}\n\nexport function collectLayoutChain(pageKey: string, layouts: Layout[]): Layout[] {\n const pageDir = keyToDir(pageKey)\n\n return layouts\n .filter(layout => pageDir.startsWith(layout.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchPage(pathname: string, pages: Page[]): {\n page: Page\n params: Record<string, string>\n} | null {\n for (const page of pages) {\n const match = pathname.match(page.regex)\n if (match) {\n const params: Record<string, string> = {}\n page.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {page, params}\n }\n }\n return null\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\nlet cache: ApiResult | null = null\n\nexport function invalidateApiCache() {\n cache = null\n}\n\nexport function buildRoutes(routeKeys: string[], middlewareKeys: string[], apiDir: string): ApiResult {\n if (cache) return cache\n\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 cache = {routes, middlewares}\n return cache\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", "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", "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\\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> = Response & { readonly __body: T }\ntype UnwrapJson<T> = T extends JsonResponse<infer U> ? U : never\ntype InferFnReturn<T> = T extends (...args: any[]) => any\n ? UnwrapJson<Awaited<ReturnType<T>>> | Exclude<Awaited<ReturnType<T>>, JsonResponse<any> | null | void | undefined>\n : 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: InferFnReturn<() => TReturn>\n }\n : InferFnReturn<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}\n\nexport function generateServerEntry({ routesPath, envPath }: ServerEntryOptions): string {\n return `\nimport { readFileSync } from 'node:fs'\n import { serve } from '@hono/node-server' \n import { serveStatic } from '@hono/node-server/serve-static'\n import { Hono } from 'hono' \n import { resolve, join, dirname } from 'node:path' \n import { fileURLToPath, pathToFileURL } from 'node:url'\n import { registerApiRoutes, registerSsrRoute } from '${routesPath}' \n import { loadDotenv } from '${envPath}'\n \n loadDotenv('production')\n \n const __dir = dirname(fileURLToPath(import.meta.url))\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 registerApiRoutes(app, { renderModule, apiModule, manifest })\n registerSsrRoute(app, { renderModule, apiModule, manifest, loaderTimeout: runtimeConfig.loaderTimeout })\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 type {Hono} from 'hono'\nimport type {Manifest} from 'vite'\n\ninterface ServerOptions {\n renderModule: any\n apiModule: any\n manifest?: Manifest\n loaderTimeout?: number\n}\n\nexport function registerApiRoutes(app: Hono, {apiModule, renderModule, loaderTimeout}: ServerOptions) {\n app.all('/api/*', async (c) => {\n try {\n return await apiModule.handleApiRequest(c.req.url, c.req.raw)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal 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})\n if (data.error) return c.json({error: 'internal error'}, 500)\n return c.json(data)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal error'}, 500)\n }\n })\n}\n\nexport function registerSsrRoute(app: Hono, {renderModule, manifest, loaderTimeout}: ServerOptions) {\n app.get('*', async (c) => {\n try {\n const {html, statusCode, headers} = await renderModule.render(c.req.url, c.req.raw, {manifest, loaderTimeout})\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,OAA6B,eAAAC,OAAmB,OAEhD,OAAOC,OAAW,uBAClB,OAAS,iBAAAC,OAAqB,WAC9B,OAAS,WAAAC,GAAS,WAAAC,MAAe,YCA1B,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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CA+DZ,CClEO,SAASC,EAAqB,CAAC,SAAAC,EAAU,YAAAC,CAAW,EAAwB,CAC/E,MAAO;AAAA;AAAA,iCAEsBA,CA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,EAAI,CACrB,CAAC",
|
|
6
|
+
"names": ["createServer", "createViteServer", "getRequestListener", "Hono", "mergeConfig", "react", "fileURLToPath", "dirname", "resolve", "generateEntryClient", "cssUrls", "u", "generateClientRoutes", "pagesDir", "matcherPath", "generateRender", "pagesDir", "renderPath", "generateApi", "apiPath", "appDir", "routePattern", "rel", "cache", "invalidatePagesCache", "keyToRoutePattern", "key", "apiDir", "rel", "pattern", "routePattern", "cache", "invalidateApiCache", "generateContext", "readFileSync", "readdirSync", "statSync", "join", "relative", "METHOD_EXPORT_RE", "stripComments", "content", "extractHttpMethods", "found", "match", "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", "__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", "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", "server", "regenerateDts", "file", "invalidatePagesCache", "invalidateApiCache", "base", "react", "mergeConfig", "registerApiRoutes", "app", "apiModule", "renderModule", "loaderTimeout", "c", "e", "pathname", "search", "url", "data", "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
|
+
}
|
package/dist/cli/dev.js
CHANGED
|
@@ -1,155 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
${e.map(r=>`import '${r}'`).join(`
|
|
3
|
-
`)}
|
|
4
|
-
import "@vitejs/plugin-react/preamble"
|
|
5
|
-
import React from "react"
|
|
6
|
-
import {hydrateRoot, createRoot} from 'react-dom/client'
|
|
7
|
-
import {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'
|
|
8
|
-
import {RouterProvider} from '@devlusoft/devix'
|
|
9
|
-
|
|
10
|
-
const root = document.getElementById('devix-root')
|
|
11
|
-
|
|
12
|
-
if (!window.__DEVIX__) {
|
|
13
|
-
const ErrorPage = getDefaultErrorPage()
|
|
14
|
-
createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))
|
|
15
|
-
} else {
|
|
16
|
-
const {metadata, viewport, clientEntry} = window.__DEVIX__
|
|
17
|
-
const loaderData = window.__LOADER_DATA__
|
|
18
|
-
const layoutsData = window.__LAYOUTS_DATA__ ?? []
|
|
19
|
-
|
|
20
|
-
const matched = matchClientRoute(window.location.pathname)
|
|
21
|
-
|
|
22
|
-
if (matched) {
|
|
23
|
-
const [pageMod, ...layoutMods] = await Promise.all([
|
|
24
|
-
matched.load(),
|
|
25
|
-
...matched.loadLayouts.map(l => l()),
|
|
26
|
-
])
|
|
27
|
-
hydrateRoot(
|
|
28
|
-
root,
|
|
29
|
-
React.createElement(RouterProvider, {
|
|
30
|
-
clientEntry,
|
|
31
|
-
initialData: loaderData,
|
|
32
|
-
initialParams: matched.params,
|
|
33
|
-
initialPage: pageMod.default,
|
|
34
|
-
initialLayouts: layoutMods.map(m => m.default),
|
|
35
|
-
initialLayoutsData: layoutsData,
|
|
36
|
-
initialMeta: metadata,
|
|
37
|
-
initialViewport: viewport,
|
|
38
|
-
})
|
|
39
|
-
)
|
|
40
|
-
} else {
|
|
41
|
-
const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()
|
|
42
|
-
createRoot(root).render(
|
|
43
|
-
React.createElement(RouterProvider, {
|
|
44
|
-
clientEntry,
|
|
45
|
-
initialData: null,
|
|
46
|
-
initialParams: {},
|
|
47
|
-
initialPage: () => null,
|
|
48
|
-
initialLayouts: [],
|
|
49
|
-
initialLayoutsData: [],
|
|
50
|
-
initialMeta: null,
|
|
51
|
-
initialError: {statusCode: 404, message: 'Not found'},
|
|
52
|
-
initialErrorPage: ErrorPage,
|
|
53
|
-
})
|
|
54
|
-
)
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
`}function I({pagesDir:e,matcherPath:t}){return`
|
|
58
|
-
import React from 'react'
|
|
59
|
-
import { createMatcher } from '${t}'
|
|
60
|
-
const pageFiles = import.meta.glob(['/${e}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])
|
|
61
|
-
const layoutFiles = import.meta.glob('/${e}/**/layout.tsx')
|
|
62
|
-
const errorFiles = import.meta.glob('/${e}/**/error.tsx')
|
|
63
|
-
|
|
64
|
-
export const matchClientRoute = createMatcher(pageFiles, layoutFiles)
|
|
65
|
-
|
|
66
|
-
export async function loadErrorPage() {
|
|
67
|
-
const key = Object.keys(errorFiles)[0]
|
|
68
|
-
if (!key) return null
|
|
69
|
-
const mod = await errorFiles[key]()
|
|
70
|
-
return mod?.default ?? null
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function getDefaultErrorPage() {
|
|
74
|
-
return function DefaultError({ statusCode, message }) {
|
|
75
|
-
return React.createElement('main', {
|
|
76
|
-
style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column',
|
|
77
|
-
alignItems: 'center', justifyContent: 'center', gap: '8px',
|
|
78
|
-
fontFamily: 'system-ui, sans-serif' }
|
|
79
|
-
},
|
|
80
|
-
React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),
|
|
81
|
-
React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),
|
|
82
|
-
)
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
`}function L({pagesDir:e,renderPath:t}){return`
|
|
86
|
-
import { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${t}'
|
|
87
|
-
|
|
88
|
-
const _pages = import.meta.glob(['/${e}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])
|
|
89
|
-
const _layouts = import.meta.glob('/${e}/**/layout.tsx')
|
|
90
|
-
|
|
91
|
-
const _glob = {
|
|
92
|
-
pages: _pages,
|
|
93
|
-
layouts: _layouts,
|
|
94
|
-
pagesDir: '/${e}',
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export function render(url, request, options) {
|
|
98
|
-
return _render(url, request, _glob, options)
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export function runLoader(url, request, options) {
|
|
102
|
-
return _runLoader(url, request, _glob, options)
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export function getStaticRoutes() {
|
|
106
|
-
return _getStaticRoutes(_glob)
|
|
107
|
-
}
|
|
108
|
-
`}function M({apiPath:e,appDir:t}){return`
|
|
109
|
-
import { handleApiRequest as _handleApiRequest } from '${e}'
|
|
110
|
-
|
|
111
|
-
const _routes = import.meta.glob(['/${t}/api/**/*.ts', '!**/middleware.ts'])
|
|
112
|
-
const _middlewares = import.meta.glob('/${t}/api/**/middleware.ts')
|
|
113
|
-
|
|
114
|
-
const _glob = {
|
|
115
|
-
routes: _routes,
|
|
116
|
-
middlewares: _middlewares,
|
|
117
|
-
apiDir: '/${t}/api',
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export function handleApiRequest(url, request) {
|
|
121
|
-
return _handleApiRequest(url, request, _glob)
|
|
122
|
-
}
|
|
123
|
-
`}function y(e){return e.replace(/\.(tsx|ts|jsx|js)$/,"").replace(/\(.*?\)\//g,"").replace(/^index$|\/index$/,"").replace(/\[([^\]]+)]/g,":$1")||"/"}var z=null;function x(){z=null}function O(e,t){let r=e.slice(t.length+1).replace(/\\/g,"/"),o=y(r);return o==="/"?"/api":`/api/${o}`.replace("/api//","/api/")}var Z=null;function R(){Z=null}function k(){return`
|
|
124
|
-
export {RouterContext} from '@devlusoft/devix/runtime/context'
|
|
125
|
-
`}import{readFileSync as te,readdirSync as re,statSync as ne}from"node:fs";import{join as _,relative as oe}from"node:path";var K=/export\s+(?:const|async\s+function|function)\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;function Q(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"")}function U(e){let t=new Set;for(let r of Q(e).matchAll(K))t.add(r[1]);return[...t]}function ee(e,t){return"_api_"+e.slice(`${t}/`.length).replace(/\.(ts|tsx)$/,"").replace(/[^a-zA-Z0-9]/g,"_")}function H(e,t,r){return{filePath:e,urlPattern:O(e,t),identifier:ee(e,t),methods:r}}function v(e,t){if(e.length===0)return`// auto-generado por devix \u2014 no editar
|
|
126
|
-
declare module '@devlusoft/devix' {
|
|
127
|
-
interface ApiRoutes {}
|
|
128
|
-
}
|
|
129
|
-
`;let r=e.map(n=>{let s="../"+n.filePath.replace(/\.(ts|tsx)$/,"");return`import type * as ${n.identifier} from '${s}'`}).join(`
|
|
130
|
-
`),o=e.flatMap(n=>n.methods.map(s=>` '${s} ${n.urlPattern}': InferRoute<(typeof ${n.identifier})['${s}']>`)).join(`
|
|
131
|
-
`);return`// auto-generado por devix \u2014 no editar
|
|
132
|
-
${r}
|
|
133
|
-
|
|
134
|
-
type JsonResponse<T> = Response & { readonly __body: T }
|
|
135
|
-
type UnwrapJson<T> = T extends JsonResponse<infer U> ? U : never
|
|
136
|
-
type InferFnReturn<T> = T extends (...args: any[]) => any
|
|
137
|
-
? UnwrapJson<Awaited<ReturnType<T>>> | Exclude<Awaited<ReturnType<T>>, JsonResponse<any> | null | void | undefined>
|
|
138
|
-
: never
|
|
139
|
-
type InferRoute<T> =
|
|
140
|
-
T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }
|
|
141
|
-
? {
|
|
142
|
-
__body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>
|
|
143
|
-
__response: InferFnReturn<() => TReturn>
|
|
144
|
-
}
|
|
145
|
-
: InferFnReturn<T>
|
|
146
|
-
|
|
147
|
-
declare module '@devlusoft/devix' {
|
|
148
|
-
interface ApiRoutes {
|
|
149
|
-
${o}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
`}function q(e,t){let r=[];for(let o of re(e)){let n=_(e,o);ne(n).isDirectory()?r.push(...q(n,t)):/\.(ts|tsx)$/.test(o)&&r.push(oe(t,n).replace(/\\/g,"/"))}return r}function w(e,t){let r=_(t,e,"api"),o;try{o=q(r,t)}catch{return[]}return o.filter(n=>!n.endsWith("middleware.ts")&&!n.endsWith("middleware.tsx")).flatMap(n=>{try{let s=te(_(t,n),"utf-8"),l=U(s);return l.length===0?[]:[H(n,`${e}/api`,l)]}catch{return[]}})}import{mkdirSync as ie,readFileSync as se,writeFileSync as ae,existsSync as ce}from"node:fs";import{join as j}from"node:path";function E(e,t){let r=j(t,".devix"),o=j(r,"routes.d.ts");return ie(r,{recursive:!0}),ce(o)&&se(o,"utf-8")===e?!1:(ae(o,e,"utf-8"),!0)}var $=de(pe(import.meta.url)),P="virtual:devix/entry-client",T="virtual:devix/client-routes",D="virtual:devix/render",A="virtual:devix/api",C="virtual:devix/context";function F(e){let t=e.appDir??"app",r=`${t}/pages`,o=(e.css??[]).map(i=>i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`),n=m($,"../server/render.js").replace(/\\/g,"/"),s=m($,"../server/api.js").replace(/\\/g,"/"),l=m($,"../runtime/client-router.js").replace(/\\/g,"/"),g={name:"devix",enforce:"pre",resolveId(i){if(i===P)return`\0${P}`;if(i===T)return`\0${T}`;if(i===D)return`\0${D}`;if(i===A)return`\0${A}`;if(i===C)return`\0${C}`},load(i){if(i===`\0${P}`)return S({cssUrls:o});if(i===`\0${T}`)return I({pagesDir:r,matcherPath:l});if(i===`\0${D}`)return L({pagesDir:r,renderPath:n});if(i===`\0${A}`)return M({apiPath:s,appDir:t});if(i===`\0${C}`)return k()},buildStart(){let i=process.cwd(),u=w(t,i);E(v(u,`${t}/api`),i)},configureServer(i){let u=process.cwd(),h=()=>{let c=w(t,u);E(v(c,`${t}/api`),u)};i.watcher.on("add",c=>{c.startsWith(m(u,r))&&x(),c.includes(`${t}/api`)&&(R(),h())}),i.watcher.on("unlink",c=>{c.startsWith(m(u,r))&&x(),c.includes(`${t}/api`)&&(R(),h())}),i.watcher.on("change",c=>{c.includes(`${t}/api`)&&!c.endsWith("middleware.ts")&&h()})}},p={plugins:[ue(),g],publicDir:m(process.cwd(),e.publicDir??"public"),ssr:{noExternal:["@devlusoft/devix"]},...e.envPrefix?{envPrefix:e.envPrefix}:{}};return le(p,e.vite??{})}function V(e,{apiModule:t,renderModule:r,loaderTimeout:o}){e.all("/api/*",async n=>{try{return await t.handleApiRequest(n.req.url,n.req.raw)}catch(s){return console.error(s),n.json({error:"internal error"},500)}}),e.get("/_data/*",async n=>{try{let{pathname:s,search:l}=new URL(n.req.url,"http://localhost"),g=s.replace(/^\/_data/,"")+l,p=await r.runLoader(g,n.req.raw,{loaderTimeout:o});return p.error?n.json({error:"internal error"},500):n.json(p)}catch(s){return console.error(s),n.json({error:"internal error"},500)}})}import a from"picocolors";import{networkInterfaces as me}from"node:os";function fe(e){let t=me();for(let r of Object.values(t))for(let o of r??[])if(o.family==="IPv4"&&!o.internal)return`http://${o.address}:${e}/`;return null}function N(e){let t="0.4.0",r=fe(e);console.log(),console.log(` ${a.bold(a.yellow("devix"))} ${a.dim(`v${t}`)}`),console.log(),console.log(` ${a.green("\u279C")} ${a.bold("Local:")} ${a.cyan(`http://localhost:${e}/`)}`),console.log(r?` ${a.green("\u279C")} ${a.bold("Network:")} ${a.cyan(r)}`:` ${a.green("\u279C")} ${a.bold("Network:")} ${a.dim("use --host to expose")}`),console.log()}async function W(e){let t=new Set;for(let[,r]of e.moduleGraph.idToModuleMap)r.id&&(r.id.endsWith(".css")||r.id.includes(".css?"))&&t.add(r.url);return[...t]}function B(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 ge}from"vite";function X(e){let t=ge(e,process.cwd(),"");for(let[r,o]of Object.entries(t))process.env[r]===void 0&&(process.env[r]=o)}X("development");var J="virtual:devix/render",ve="virtual:devix/api",f=(await import(`${process.cwd()}/devix.config.ts`)).default,Y=Number(process.env.PORT)||f.port||3e3,_e=typeof f.host=="string"?f.host:f.host?"0.0.0.0":"localhost",d=await ye({...F(f),configFile:!1,appType:"custom",server:{middlewareMode:!0}}),G={render:async(...e)=>(await d.ssrLoadModule(J)).render(...e),runLoader:async(...e)=>(await d.ssrLoadModule(J)).runLoader(...e)},we={handleApiRequest:async(...e)=>(await d.ssrLoadModule(ve)).handleApiRequest(...e)},b=new Re;V(b,{renderModule:G,apiModule:we});b.get("*",async e=>{try{let{html:t,statusCode:r,headers:o}=await G.render(e.req.url,e.req.raw,{loaderTimeout:B(f.loaderTimeout??1e4)}),s=(await W(d)).map(i=>`<link rel="stylesheet" href="${i}">`).join(`
|
|
153
|
-
`),l=s?t.replace("</head>",`${s}
|
|
154
|
-
</head>`):t,g=await d.transformIndexHtml(e.req.url,`<!DOCTYPE html>${l}`),p=e.html(g,r);for(let[i,u]of Object.entries(o))p.headers.set(i,u);return p}catch(t){return d.ssrFixStacktrace(t),console.error(t),e.text("Internal Server Error",500)}});var Ee=xe(b.fetch);he(async(e,t)=>{await new Promise(r=>d.middlewares(e,t,r)),t.writableEnded||await Ee(e,t)}).listen(Y,_e,()=>{N(Y)});
|
|
1
|
+
import{spawnSync as e}from"node:child_process";import{fileURLToPath as r}from"node:url";import{dirname as t,resolve as o}from"node:path";var s=t(r(import.meta.url));for(;e(process.execPath,[o(s,"dev-server.js")],{stdio:"inherit",env:process.env}).status===75;);
|
|
155
2
|
//# sourceMappingURL=dev.js.map
|