@tylix/core 0.4.2 → 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.
- package/package.json +5 -5
- package/src/discovery/registerFeatureRoutes.d.ts +7 -2
- package/src/discovery/registerFeatureRoutes.js +27 -2
- package/src/discovery/registerRouteFiles.d.ts +1 -1
- package/src/http/Server.js +79 -5
- package/src/http/debug/buildDebugPayload.js +138 -0
- package/src/http/debug/renderDebugPage.js +688 -0
- package/src/runtime/useApi.js +366 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"tylix",
|
|
@@ -12,10 +12,10 @@
|
|
|
12
12
|
"test": "node --test src/**/*.test.js"
|
|
13
13
|
},
|
|
14
14
|
"dependencies": {
|
|
15
|
-
"@tylix/auth": "^0.
|
|
16
|
-
"@tylix/compiler": "^0.
|
|
17
|
-
"@tylix/orm": "^0.
|
|
18
|
-
"@tylix/shared": "^0.
|
|
15
|
+
"@tylix/auth": "^0.5.1",
|
|
16
|
+
"@tylix/compiler": "^0.5.1",
|
|
17
|
+
"@tylix/orm": "^0.5.1",
|
|
18
|
+
"@tylix/shared": "^0.5.1",
|
|
19
19
|
"ws": "^8.18.0"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
@@ -4,5 +4,10 @@ import type { DiscoveredFeature } from './discoverFeatures.js'
|
|
|
4
4
|
export declare function registerFeatureRoutes(
|
|
5
5
|
router: Router,
|
|
6
6
|
features: DiscoveredFeature[],
|
|
7
|
-
options?: {
|
|
8
|
-
|
|
7
|
+
options?: {
|
|
8
|
+
secret?: string
|
|
9
|
+
hydrate?: unknown
|
|
10
|
+
/** Defaults to process.cwd(). Used to look for app/routes/<table>.(js|ts). */
|
|
11
|
+
baseDir?: string
|
|
12
|
+
},
|
|
13
|
+
): string[]
|
|
@@ -1,7 +1,30 @@
|
|
|
1
|
-
import
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { requireAuth } from '../http/requireAuth.js'
|
|
4
|
+
|
|
5
|
+
// A feature "owns" its routes through app/routes/<table>.(js|ts) when that
|
|
6
|
+
// file exists (written by make:feature). registerRouteFiles mounts it, so
|
|
7
|
+
// the manifest-based mounting below must step aside to avoid duplicates.
|
|
8
|
+
function hasRouteFile(baseDir, table) {
|
|
9
|
+
return ['js', 'ts'].some((ext) =>
|
|
10
|
+
fs.existsSync(path.join(baseDir, 'app', 'routes', `${table}.${ext}`)),
|
|
11
|
+
)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Returns the tables that were skipped because a route file owns them.
|
|
15
|
+
export function registerFeatureRoutes(
|
|
16
|
+
router,
|
|
17
|
+
features,
|
|
18
|
+
{ secret, hydrate, baseDir = process.cwd() } = {},
|
|
19
|
+
) {
|
|
20
|
+
const skipped = []
|
|
2
21
|
|
|
3
|
-
export function registerFeatureRoutes(router, features, { secret, hydrate } = {}) {
|
|
4
22
|
for (const { manifest, controller } of features) {
|
|
23
|
+
if (hasRouteFile(baseDir, manifest.table)) {
|
|
24
|
+
skipped.push(manifest.table)
|
|
25
|
+
continue
|
|
26
|
+
}
|
|
27
|
+
|
|
5
28
|
const base = `/api/${manifest.table}`;
|
|
6
29
|
const wrap = (fn) => (manifest.auth ? requireAuth(fn, secret, { hydrate }) : fn);
|
|
7
30
|
|
|
@@ -11,4 +34,6 @@ export function registerFeatureRoutes(router, features, { secret, hydrate } = {}
|
|
|
11
34
|
router.put(`${base}/:id`, wrap((req, res) => controller.update(req, res)));
|
|
12
35
|
router.delete(`${base}/:id`, wrap((req, res) => controller.destroy(req, res)));
|
|
13
36
|
}
|
|
37
|
+
|
|
38
|
+
return skipped
|
|
14
39
|
}
|
package/src/http/Server.js
CHANGED
|
@@ -3,6 +3,8 @@ import { enhanceResponse } from './enhanceResponse.js'
|
|
|
3
3
|
import { readBody } from './parseBody.js'
|
|
4
4
|
import { parseQuery } from './parseQuery.js'
|
|
5
5
|
import { parseCookies } from './parseCookies.js'
|
|
6
|
+
import { buildDebugPayload } from './debug/buildDebugPayload.js'
|
|
7
|
+
import { renderDebugPage } from './debug/renderDebugPage.js'
|
|
6
8
|
|
|
7
9
|
// Forwarding headers are only believed when the app is told it sits behind
|
|
8
10
|
// a proxy it controls, because any client can send X-Forwarded-For. The LAST
|
|
@@ -29,8 +31,25 @@ function isSecure(req, trustProxy) {
|
|
|
29
31
|
return proto === 'https'
|
|
30
32
|
}
|
|
31
33
|
|
|
34
|
+
// A browser opening a page gets the HTML debug page. Everything else
|
|
35
|
+
// (fetch from useApi, curl, anything under /api/) gets JSON.
|
|
36
|
+
// Browsers send Sec-Fetch-Dest: document when you navigate (address bar,
|
|
37
|
+
// link click, reload). fetch()/useApi sends "empty", so API calls from
|
|
38
|
+
// the app keep getting JSON. Clients without the header (curl) fall
|
|
39
|
+
// back to the Accept check.
|
|
40
|
+
function wantsHtml(req) {
|
|
41
|
+
if (req.method !== 'GET') return false
|
|
42
|
+
const dest = req.headers['sec-fetch-dest']
|
|
43
|
+
if (dest) return dest === 'document'
|
|
44
|
+
const url = String(req.url).split('?')[0]
|
|
45
|
+
return (
|
|
46
|
+
!url.startsWith('/api/') &&
|
|
47
|
+
String(req.headers.accept || '').includes('text/html')
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
|
|
32
51
|
export class Server {
|
|
33
|
-
constructor(router, { notFoundHandler = null, trustProxy } = {}) {
|
|
52
|
+
constructor(router, { notFoundHandler = null, trustProxy, debug } = {}) {
|
|
34
53
|
this.router = router
|
|
35
54
|
// Optional fallback called when no route matches, before the
|
|
36
55
|
// default 404 JSON response -- e.g. tylix dev uses this to serve
|
|
@@ -42,6 +61,16 @@ export class Server {
|
|
|
42
61
|
// proxy you control (nginx). Defaults to the TRUST_PROXY=true env var.
|
|
43
62
|
this.trustProxy = trustProxy ?? process.env.TRUST_PROXY === 'true'
|
|
44
63
|
this.production = process.env.NODE_ENV === 'production'
|
|
64
|
+
// Show real error details (debug page, SQL, stack) instead of a
|
|
65
|
+
// generic 500. Defaults to the APP_DEBUG=true env var.
|
|
66
|
+
this.debug = debug ?? process.env.APP_DEBUG === 'true'
|
|
67
|
+
|
|
68
|
+
if (this.debug && this.production) {
|
|
69
|
+
console.warn(
|
|
70
|
+
'[tylix] APP_DEBUG is on while NODE_ENV=production. Error responses ' +
|
|
71
|
+
'expose SQL, request data and stack traces. Set APP_DEBUG=false.',
|
|
72
|
+
)
|
|
73
|
+
}
|
|
45
74
|
}
|
|
46
75
|
|
|
47
76
|
createHandler() {
|
|
@@ -95,14 +124,49 @@ export class Server {
|
|
|
95
124
|
await match.handler(req, res)
|
|
96
125
|
}
|
|
97
126
|
|
|
127
|
+
logFailure(req, err) {
|
|
128
|
+
// Log the path only: query strings can carry tokens.
|
|
129
|
+
const where = `${req.method} ${String(req.url).split('?')[0]}`
|
|
130
|
+
|
|
131
|
+
if (err?.name === 'DatabaseError') {
|
|
132
|
+
const lines = [
|
|
133
|
+
`[tylix] ${where} failed: ${err.title || 'Database error'}` +
|
|
134
|
+
` (${err.driver}/${err.kind})`,
|
|
135
|
+
` ${err.message}`,
|
|
136
|
+
]
|
|
137
|
+
if (err.sql) lines.push(` SQL: ${err.sql}`)
|
|
138
|
+
if (err.hint) lines.push(` Fix: ${err.hint}`)
|
|
139
|
+
console.error(lines.join('\n'))
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
console.error(`[tylix] ${where} failed:`, err)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
sendDebug(req, res, err) {
|
|
146
|
+
const payload = buildDebugPayload(err, req, { status: 500 })
|
|
147
|
+
|
|
148
|
+
if (wantsHtml(req)) {
|
|
149
|
+
res.statusCode = 500
|
|
150
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8')
|
|
151
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
152
|
+
res.end(renderDebugPage(payload))
|
|
153
|
+
return
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// `error` stays a plain string so useApi and existing frontend code
|
|
157
|
+
// keep working. The full detail travels in `debug`.
|
|
158
|
+
res.setHeader('Cache-Control', 'no-store')
|
|
159
|
+
res.status(500).json({
|
|
160
|
+
error: payload.title || payload.message,
|
|
161
|
+
debug: payload,
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
98
165
|
fail(req, res, err) {
|
|
99
166
|
// A malformed %-escape in the URL is the client's fault, not a crash.
|
|
100
167
|
const badRequest = err instanceof URIError
|
|
101
168
|
|
|
102
|
-
if (!badRequest)
|
|
103
|
-
// Log the path only: query strings can carry tokens.
|
|
104
|
-
console.error(`[tylix] ${req.method} ${String(req.url).split('?')[0]} failed:`, err)
|
|
105
|
-
}
|
|
169
|
+
if (!badRequest) this.logFailure(req, err)
|
|
106
170
|
|
|
107
171
|
if (res.headersSent) {
|
|
108
172
|
if (!res.writableEnded) res.end()
|
|
@@ -114,6 +178,16 @@ export class Server {
|
|
|
114
178
|
return
|
|
115
179
|
}
|
|
116
180
|
|
|
181
|
+
if (this.debug) {
|
|
182
|
+
try {
|
|
183
|
+
this.sendDebug(req, res, err)
|
|
184
|
+
return
|
|
185
|
+
} catch (debugErr) {
|
|
186
|
+
// The debug tooling must never be the reason a request hangs.
|
|
187
|
+
console.error('[tylix] debug page failed:', debugErr)
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
117
191
|
res.status(500).json({
|
|
118
192
|
error: this.production ? 'Internal server error' : err.message,
|
|
119
193
|
})
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
|
|
5
|
+
const SENSITIVE_KEY = /pass(word)?|secret|token|authorization|cookie|api[-_]?key|session/i
|
|
6
|
+
const MAX_BODY_CHARS = 4000
|
|
7
|
+
const MAX_LINE_CHARS = 300
|
|
8
|
+
|
|
9
|
+
function redact(value, depth = 0) {
|
|
10
|
+
if (value == null || typeof value !== 'object') return value
|
|
11
|
+
if (depth > 5) return '[too deep]'
|
|
12
|
+
if (Array.isArray(value)) return value.slice(0, 50).map((v) => redact(v, depth + 1))
|
|
13
|
+
const out = {}
|
|
14
|
+
for (const [key, val] of Object.entries(value)) {
|
|
15
|
+
out[key] = SENSITIVE_KEY.test(key) ? '[redacted]' : redact(val, depth + 1)
|
|
16
|
+
}
|
|
17
|
+
return out
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function shorten(file, cwd) {
|
|
21
|
+
const relative = path.relative(cwd, file)
|
|
22
|
+
return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
|
|
23
|
+
? relative
|
|
24
|
+
: file
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Matches both "at fn (file:1:2)" and "at file:1:2".
|
|
28
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/
|
|
29
|
+
|
|
30
|
+
export function parseStack(stack = '', cwd = process.cwd()) {
|
|
31
|
+
const frames = []
|
|
32
|
+
for (const line of String(stack).split('\n')) {
|
|
33
|
+
const match = FRAME.exec(line)
|
|
34
|
+
if (!match) continue
|
|
35
|
+
let [, fn, file, lineNo, column] = match
|
|
36
|
+
if (file.startsWith('file://')) {
|
|
37
|
+
try {
|
|
38
|
+
file = fileURLToPath(file)
|
|
39
|
+
} catch {
|
|
40
|
+
/* keep the raw value */
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const internal = file.startsWith('node:')
|
|
44
|
+
const framework =
|
|
45
|
+
!internal &&
|
|
46
|
+
(file.includes('node_modules') ||
|
|
47
|
+
/[\\/]tylix[\\/]packages[\\/]/.test(file) ||
|
|
48
|
+
file.includes('@tylix'))
|
|
49
|
+
const vendor = framework
|
|
50
|
+
frames.push({
|
|
51
|
+
fn: fn || null,
|
|
52
|
+
file,
|
|
53
|
+
short: internal ? file : shorten(file, cwd),
|
|
54
|
+
line: Number(lineNo),
|
|
55
|
+
column: Number(column),
|
|
56
|
+
kind: internal ? 'internal' : vendor ? 'vendor' : 'app',
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
return frames
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function readSource(frame) {
|
|
63
|
+
try {
|
|
64
|
+
const lines = fs.readFileSync(frame.file, 'utf8').split('\n')
|
|
65
|
+
const start = Math.max(1, frame.line - 5)
|
|
66
|
+
const end = Math.min(lines.length, frame.line + 5)
|
|
67
|
+
return {
|
|
68
|
+
file: frame.short,
|
|
69
|
+
line: frame.line,
|
|
70
|
+
column: frame.column,
|
|
71
|
+
start,
|
|
72
|
+
lines: lines.slice(start - 1, end).map((l) => l.slice(0, MAX_LINE_CHARS)),
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
return null
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function bodyToString(body) {
|
|
80
|
+
if (body == null || body === '') return null
|
|
81
|
+
let text
|
|
82
|
+
try {
|
|
83
|
+
text = typeof body === 'string' ? body : JSON.stringify(redact(body), null, 2)
|
|
84
|
+
} catch {
|
|
85
|
+
return '[unserializable body]'
|
|
86
|
+
}
|
|
87
|
+
return text.length > MAX_BODY_CHARS
|
|
88
|
+
? `${text.slice(0, MAX_BODY_CHARS)}… (${text.length} chars)`
|
|
89
|
+
: text
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function buildDebugPayload(err, req, { status = 500 } = {}) {
|
|
93
|
+
const cwd = process.cwd()
|
|
94
|
+
const isDbError = err?.name === 'DatabaseError' && typeof err.toJSON === 'function'
|
|
95
|
+
const db = isDbError ? err.toJSON() : {}
|
|
96
|
+
const frames = parseStack(err?.stack, cwd)
|
|
97
|
+
const firstApp = frames.find((f) => f.kind === 'app')
|
|
98
|
+
|
|
99
|
+
return {
|
|
100
|
+
status,
|
|
101
|
+
name: err?.name || 'Error',
|
|
102
|
+
message: err?.message ?? String(err),
|
|
103
|
+
title: db.title ?? null,
|
|
104
|
+
hint: db.hint ?? null,
|
|
105
|
+
kind: db.kind ?? null,
|
|
106
|
+
driver: db.driver ?? null,
|
|
107
|
+
code: db.code ?? err?.code ?? null,
|
|
108
|
+
detail: db.detail ?? null,
|
|
109
|
+
table: db.table ?? null,
|
|
110
|
+
column: db.column ?? null,
|
|
111
|
+
sql: db.sql ?? null,
|
|
112
|
+
params: db.params ?? [],
|
|
113
|
+
cause: err?.cause
|
|
114
|
+
? {
|
|
115
|
+
name: err.cause.name ?? 'Error',
|
|
116
|
+
message: err.cause.sqlMessage || err.cause.message || String(err.cause),
|
|
117
|
+
code: err.cause.code ?? null,
|
|
118
|
+
}
|
|
119
|
+
: null,
|
|
120
|
+
frames,
|
|
121
|
+
source: firstApp ? readSource(firstApp) : null,
|
|
122
|
+
request: {
|
|
123
|
+
method: req.method,
|
|
124
|
+
url: req.url,
|
|
125
|
+
ip: req.ip ?? null,
|
|
126
|
+
headers: redact({ ...req.headers }),
|
|
127
|
+
query: redact(req.query ?? {}),
|
|
128
|
+
params: redact(req.params ?? {}),
|
|
129
|
+
body: bodyToString(req.body),
|
|
130
|
+
},
|
|
131
|
+
env: {
|
|
132
|
+
node: process.version,
|
|
133
|
+
platform: process.platform,
|
|
134
|
+
nodeEnv: process.env.NODE_ENV || 'development',
|
|
135
|
+
cwd,
|
|
136
|
+
},
|
|
137
|
+
}
|
|
138
|
+
}
|