@tylix/core 0.5.3 → 0.7.0

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.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +68 -17
  3. package/package.json +38 -7
  4. package/src/cache/Cache.d.ts +4 -2
  5. package/src/cache/Cache.js +46 -58
  6. package/src/channels/ChannelServer.d.ts +5 -0
  7. package/src/channels/ChannelServer.js +24 -0
  8. package/src/channels/broadcast.d.ts +3 -0
  9. package/src/channels/broadcast.js +15 -0
  10. package/src/discovery/loadCustomRoutes.d.ts +5 -1
  11. package/src/discovery/loadCustomRoutes.js +84 -3
  12. package/src/discovery/registerRouteFiles.js +6 -2
  13. package/src/http/Server.d.ts +86 -6
  14. package/src/http/Server.js +229 -26
  15. package/src/http/enhanceResponse.js +78 -34
  16. package/src/http/parseBody.d.ts +22 -1
  17. package/src/http/parseBody.js +54 -24
  18. package/src/http/rateLimit.d.ts +9 -1
  19. package/src/http/rateLimit.js +36 -8
  20. package/src/http/requireAuth.d.ts +13 -1
  21. package/src/http/requireAuth.js +8 -1
  22. package/src/index.d.ts +4 -1
  23. package/src/index.js +7 -1
  24. package/src/observability/context.js +12 -0
  25. package/src/observability/health.js +38 -0
  26. package/src/observability/index.d.ts +68 -0
  27. package/src/observability/logger.js +127 -0
  28. package/src/observability/metrics.js +127 -0
  29. package/src/router/Router.d.ts +2 -1
  30. package/src/router/Router.js +117 -46
  31. package/src/store/database.js +209 -0
  32. package/src/store/index.d.ts +31 -0
  33. package/src/store/index.js +52 -0
  34. package/src/store/memory.js +72 -0
  35. package/src/store/redis.js +77 -0
  36. package/src/http/Server.test.js +0 -99
  37. package/src/http/enhanceResponse.test.js +0 -45
  38. package/src/http/parseBody.test.js +0 -33
  39. package/src/http/parseQuery.test.js +0 -15
  40. package/src/http/requireAuth.test.js +0 -76
  41. package/src/providers/createProvider.js +0 -16
  42. package/src/router/Router.test.js +0 -128
  43. package/src/runtime/useApi.js +0 -405
  44. package/tsconfig.json +0 -13
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mbiyrukzz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,29 +1,80 @@
1
1
  # @tylix/core
2
2
 
3
- The Tylix framework runtime — HTTP server, routing, feature discovery,
4
- queues, scheduling, and channels.
3
+ The Tylix server runtime: HTTP server and router, logging, metrics and
4
+ health checks, a shared store, cache, rate limiting, queue, scheduler and
5
+ channels. `tylix dev` and `tylix start` set all of it up from your
6
+ settings; import the pieces you use in app code.
5
7
 
6
- ## What's included
8
+ ```sh
9
+ npm install @tylix/core
10
+ ```
11
+
12
+ ## Server and router
13
+
14
+ ```js
15
+ import { Router, Server } from '@tylix/core'
16
+
17
+ const router = new Router()
18
+ router.get('/api/posts/:id', (req, res) => res.json({ id: req.params.id }))
19
+ new Server(router).listen(3000)
20
+ ```
21
+
22
+ Routes are looked up by path segment, so the cost doesn't grow with the
23
+ number of routes; when two routes match, the one registered first wins.
24
+ Responses get security headers, cross-site write protection and a
25
+ Content-Security-Policy (CSP_MODE). JSON of 1 KB or more is compressed
26
+ when the client accepts it.
27
+
28
+ ## Logs, metrics and health
29
+
30
+ ```js
31
+ import { logger, metrics, addReadinessCheck, currentRequest } from '@tylix/core'
32
+
33
+ logger.info('Invoice sent', { invoiceId: 12 })
34
+ metrics.counter('invoices_sent_total', 'Invoices sent').inc()
35
+ addReadinessCheck('payments', () => paymentsApi.ping())
36
+ ```
37
+
38
+ - Every request gets an id (`X-Request-Id`), and log lines written while
39
+ it runs carry it.
40
+ - Logs are JSON lines in production and readable lines in development
41
+ (`LOG_LEVEL`, `LOG_FORMAT`). Requests slower than `SLOW_REQUEST_MS` and
42
+ queries slower than `SLOW_QUERY_MS` are logged as warnings.
43
+ - `/health` and `/ready` are always on; `/metrics` (Prometheus format) with
44
+ `METRICS=true`, guarded by `METRICS_TOKEN`.
45
+
46
+ ## Store, cache and rate limits
7
47
 
8
- - **HTTP** — `Server`, `enhanceResponse`, `parseBody`, `parseQuery`,
9
- `parseCookies`, `requireAuth`
10
- - **Routing** — `Router`
11
- - **Discovery** — `discoverFeatures`, `registerFeatureRoutes`,
12
- `loadCustomRoutes` — auto-wires generated features into routes
13
- - **Queue** — `JobRecord`, `dispatch`, run via `tylix queue:work`
14
- - **Scheduling** — `Scheduler`, run via `tylix schedule:work`
15
- - **Channels** — `ChannelServer` (WebSocket-based), run via
16
- `tylix channels:work`
17
- - **Cache** — `CacheRecord`, `Cache`
48
+ One store holds the cache, shared rate limits and channel messages, so
49
+ several workers or servers act as one. `STORE_DRIVER`:
18
50
 
19
- ## Usage
51
+ - `database` (default): the app's own database; nothing new to run
52
+ - `redis`: for heavy traffic (`REDIS_URL`; `npm install redis`)
53
+ - `memory`: one process only
20
54
 
21
55
  ```js
22
- import { Server, Router } from '@tylix/core'
56
+ import { cache, createRateLimiter } from '@tylix/core'
57
+
58
+ const stats = await cache.remember('stats:home', 60, () => computeStats())
59
+
60
+ const limit = createRateLimiter({ name: 'login', max: 5, windowMs: 60_000, store: 'shared' })
61
+ if (!(await limit(req.ip)).allowed) return res.status(429).json({ error: 'Too many attempts.' })
62
+ ```
63
+
64
+ Without `store`, a limiter counts in its own process and answers
65
+ synchronously.
66
+
67
+ ## Queue, scheduler and channels
68
+
69
+ ```js
70
+ import { dispatch, broadcast } from '@tylix/core'
71
+
72
+ await dispatch('SendInvoice', { invoiceId: 12 }) // run by tylix queue:work
73
+ await broadcast('chat', { text: 'Deploy finished' }) // to clients of tylix channels:work
23
74
  ```
24
75
 
25
- Most of this runs implicitly under `tylix dev` / `tylix build` rather
26
- than being wired up by hand.
76
+ Queue workers claim each job atomically, so several workers never run the
77
+ same job.
27
78
 
28
79
  ## License
29
80
 
package/package.json CHANGED
@@ -1,21 +1,52 @@
1
1
  {
2
2
  "name": "@tylix/core",
3
- "version": "0.5.3",
3
+ "version": "0.7.0",
4
+ "description": "The Tylix server core: HTTP server and router, logging, metrics and health checks, a shared store (memory, database, Redis), cache, rate limiting, queue, scheduler and channels.",
5
+ "license": "MIT",
6
+ "author": "Mbiyrukzz",
4
7
  "type": "module",
5
8
  "keywords": [
6
9
  "tylix",
7
- "core"
10
+ "core",
11
+ "http",
12
+ "server",
13
+ "router",
14
+ "observability",
15
+ "cache",
16
+ "queue",
17
+ "websocket"
8
18
  ],
19
+ "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/core#readme",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Mbiyrukzz/tylix.git",
23
+ "directory": "packages/core"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/Mbiyrukzz/tylix/issues"
27
+ },
28
+ "engines": {
29
+ "node": ">=22.13"
30
+ },
9
31
  "main": "./src/index.js",
10
32
  "types": "./src/index.d.ts",
33
+ "files": [
34
+ "src",
35
+ "!**/*.test.js",
36
+ "!**/*.test.mjs",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
11
43
  "scripts": {
12
- "test": "node --test src/**/*.test.js"
44
+ "test": "node --test 'src/**/*.test.js'"
13
45
  },
14
46
  "dependencies": {
15
- "@tylix/auth": "^0.5.1",
16
- "@tylix/compiler": "^0.5.1",
17
- "@tylix/orm": "^0.5.1",
18
- "@tylix/shared": "^0.5.1",
47
+ "@tylix/auth": "^0.7.0",
48
+ "@tylix/orm": "^0.7.0",
49
+ "@tylix/shared": "^0.7.0",
19
50
  "ws": "^8.18.0"
20
51
  },
21
52
  "devDependencies": {
@@ -1,7 +1,9 @@
1
1
  export declare const cache: {
2
- set(key: string, value: unknown, ttlSeconds?: number | null): Promise<unknown>
2
+ set<T>(key: string, value: T, ttlSeconds?: number | null): Promise<T>
3
3
  get<T = unknown>(key: string): Promise<T | null>
4
4
  has(key: string): Promise<boolean>
5
5
  forget(key: string): Promise<boolean>
6
6
  clear(prefix?: string | null): Promise<number>
7
- }
7
+ /** The cached value, or compute() it, cache it for ttlSeconds and return it. */
8
+ remember<T>(key: string, ttlSeconds: number | null, compute: () => T | Promise<T>): Promise<T>
9
+ }
@@ -1,75 +1,63 @@
1
- import { CacheRecord } from './CacheRecord.js'
1
+ import { getStore } from '../store/index.js'
2
2
 
3
- function isExpired(row) {
4
- if (!row.expires_at) return false
5
- return new Date(row.expires_at).getTime() <= Date.now()
6
- }
3
+ // The app cache, kept in the app's store (STORE_DRIVER), so every worker
4
+ // and server shares it.
5
+ //
6
+ // const stats = await cache.remember('stats:home', 60, () => computeStats())
7
+ // await cache.forget('stats:home')
8
+ // await cache.clear('user:') // every key starting with user:
9
+ //
10
+ // Values are stored as JSON. null means "not cached", so caching null
11
+ // has no effect.
7
12
 
8
- export const cache = {
9
- // ttlSeconds omitted or null = never expires
10
- async set(key, value, ttlSeconds = null) {
11
- const serialized = JSON.stringify(value)
12
- const expiresAt =
13
- ttlSeconds !== null
14
- ? new Date(Date.now() + ttlSeconds * 1000).toISOString()
15
- : null
13
+ const key = (name) => `cache:${name}`
14
+ const ttl = (seconds) => (seconds ? { ttlMs: seconds * 1000 } : {})
16
15
 
17
- const existing = await CacheRecord.query().where('key', key).first()
16
+ // remember() calls already computing a key in this process; the others
17
+ // wait for that result instead of computing it again.
18
+ const computing = new Map()
18
19
 
19
- if (existing) {
20
- return CacheRecord.update(existing.id, {
21
- value: serialized,
22
- expires_at: expiresAt,
23
- })
24
- }
25
- return CacheRecord.create({ key, value: serialized, expires_at: expiresAt })
20
+ export const cache = {
21
+ // ttlSeconds omitted or null = never expires
22
+ async set(name, value, ttlSeconds = null) {
23
+ await getStore().set(key(name), value, ttl(ttlSeconds))
24
+ return value
26
25
  },
27
26
 
28
- async get(key) {
29
- const row = await CacheRecord.query().where('key', key).first()
30
- if (!row) return null
31
-
32
- if (isExpired(row)) {
33
- await CacheRecord.delete(row.id)
34
- return null
35
- }
27
+ async get(name) {
28
+ return getStore().get(key(name))
29
+ },
36
30
 
37
- return JSON.parse(row.value)
31
+ async has(name) {
32
+ return (await getStore().get(key(name))) !== null
38
33
  },
39
34
 
40
- async has(key) {
41
- const row = await CacheRecord.query().where('key', key).first()
42
- if (!row) return false
43
- if (isExpired(row)) {
44
- await CacheRecord.delete(row.id)
45
- return false
46
- }
35
+ async forget(name) {
36
+ await getStore().delete(key(name))
47
37
  return true
48
38
  },
49
39
 
50
- async forget(key) {
51
- const row = await CacheRecord.query().where('key', key).first()
52
- if (row) await CacheRecord.delete(row.id)
53
- return true
40
+ // Clears everything, or -- if a prefix is given -- only keys starting
41
+ // with it (cache.clear('user:') drops every per-user entry).
42
+ async clear(prefix = '') {
43
+ return getStore().deletePrefix(key(prefix ?? ''))
54
44
  },
55
45
 
56
- // Clears everything, or -- if a prefix is given -- only keys
57
- // starting with it (e.g. cache.clear('user:') to drop all
58
- // per-user cache entries without wiping the whole table).
59
- async clear(prefix = null) {
60
- if (prefix === null) {
61
- const all = await CacheRecord.all()
62
- for (const row of all) {
63
- await CacheRecord.delete(row.id)
46
+ // The cached value, or compute() it, cache it and return it.
47
+ async remember(name, ttlSeconds, compute) {
48
+ const hit = await cache.get(name)
49
+ if (hit !== null) return hit
50
+ if (computing.has(name)) return computing.get(name)
51
+ const pending = (async () => {
52
+ try {
53
+ const value = await compute()
54
+ if (value !== null && value !== undefined) await cache.set(name, value, ttlSeconds)
55
+ return value
56
+ } finally {
57
+ computing.delete(name)
64
58
  }
65
- return all.length
66
- }
67
-
68
- const all = await CacheRecord.all()
69
- const matching = all.filter((row) => row.key.startsWith(prefix))
70
- for (const row of matching) {
71
- await CacheRecord.delete(row.id)
72
- }
73
- return matching.length
59
+ })()
60
+ computing.set(name, pending)
61
+ return pending
74
62
  },
75
63
  }
@@ -10,6 +10,11 @@ export declare class ChannelServer {
10
10
  channels: Map<string, { handlers: ChannelHandlers; clients: Set<WebSocket> }>
11
11
  wss: WebSocketServer | null
12
12
  channel(name: string, handlers: ChannelHandlers): this
13
+ /** Sends to this server's clients, and through the store to other channel servers. */
13
14
  broadcast(name: string, data: unknown): void
15
+ /** Sends to this server's clients only. */
16
+ deliver(name: string, data: unknown): void
17
+ /** Relays broadcast() calls from the app and other channel servers to this server's clients. */
18
+ connectStore(store: import('../store/index.js').Store): Promise<this>
14
19
  listen(port: number): WebSocketServer
15
20
  }
@@ -1,9 +1,13 @@
1
1
  import { WebSocketServer } from 'ws'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { CHANNEL_TOPIC } from './broadcast.js'
2
4
 
3
5
  export class ChannelServer {
4
6
  constructor() {
5
7
  this.channels = new Map()
6
8
  this.wss = null
9
+ // Marks this server's own relayed messages, which it has delivered already.
10
+ this.id = randomUUID()
7
11
  }
8
12
 
9
13
  channel(name, handlers) {
@@ -11,7 +15,16 @@ export class ChannelServer {
11
15
  return this
12
16
  }
13
17
 
18
+ // Sends to this server's clients on `name`, and through the store (when
19
+ // connected) to the clients of every other channel server.
14
20
  broadcast(name, data) {
21
+ this.deliver(name, data)
22
+ this.store?.publish(CHANNEL_TOPIC, { channel: name, data, from: this.id }).catch((err) => {
23
+ console.error('[tylix] Could not relay a channel message:', err.message)
24
+ })
25
+ }
26
+
27
+ deliver(name, data) {
15
28
  const channel = this.channels.get(name)
16
29
  if (!channel) return
17
30
  const message = JSON.stringify(data)
@@ -20,6 +33,17 @@ export class ChannelServer {
20
33
  }
21
34
  }
22
35
 
36
+ // Receives broadcast() calls from the app and from other channel
37
+ // servers through the store, and relays them to this server's clients.
38
+ async connectStore(store) {
39
+ this.store = store
40
+ this.unsubscribe = await store.subscribe(CHANNEL_TOPIC, (message) => {
41
+ if (message?.from === this.id || typeof message?.channel !== 'string') return
42
+ this.deliver(message.channel, message.data)
43
+ })
44
+ return this
45
+ }
46
+
23
47
  listen(port) {
24
48
  this.wss = new WebSocketServer({ port })
25
49
 
@@ -0,0 +1,3 @@
1
+ /** Sends data to everyone on a channel, from any process of the app (through the store). */
2
+ export declare function broadcast(channel: string, data: unknown): Promise<void>
3
+ export declare const CHANNEL_TOPIC: string
@@ -0,0 +1,15 @@
1
+ import { getStore } from '../store/index.js'
2
+
3
+ // Sends data to everyone on a channel, from anywhere in the app (an API
4
+ // handler, a job, an observer), whichever process runs the channel
5
+ // server. The message travels through the app's store, so it needs a
6
+ // shared driver (database or redis) when "tylix channels:work" runs as a
7
+ // separate process, which it does.
8
+ //
9
+ // await broadcast('chat', { text: 'Deploy finished' })
10
+
11
+ export const CHANNEL_TOPIC = 'channels'
12
+
13
+ export async function broadcast(channel, data) {
14
+ await getStore().publish(CHANNEL_TOPIC, { channel, data, from: 'app' })
15
+ }
@@ -1,3 +1,7 @@
1
1
  import type { Router } from '../router/Router.js'
2
2
 
3
- export declare function loadCustomRoutes(router: Router, baseDir: string): Promise<boolean>
3
+ export declare function loadCustomRoutes(
4
+ router: Router,
5
+ baseDir: string,
6
+ options?: { secret?: string; hydrate?: unknown },
7
+ ): Promise<boolean>
@@ -2,8 +2,56 @@ import fs from 'node:fs/promises'
2
2
  import path from 'node:path'
3
3
  import { pathToFileURL } from 'node:url'
4
4
  import { detectLanguage } from '@tylix/shared'
5
+ import { requireAuth } from '../http/requireAuth.js'
5
6
 
6
- export async function loadCustomRoutes(router, baseDir) {
7
+ const VERBS = new Set(['get', 'post', 'put', 'patch', 'delete'])
8
+
9
+ // Same symbol requireAuth sets on its handlers. authGuard below is not a
10
+ // requireAuth result, so it is marked here by hand.
11
+ const AUTH_MARK = Symbol.for('tylix.requireAuth')
12
+
13
+ // A view of the router where every route registered through it gets the
14
+ // `guards` middleware placed ahead of its own middleware and handler.
15
+ // Every method returns the scoped view, so chaining stays guarded.
16
+ function scopedRouter(router, guards) {
17
+ const register = (method, pattern, ...handlers) => {
18
+ if (handlers.length === 0) {
19
+ throw new Error(
20
+ `Router.${method.toLowerCase()}("${pattern}") needs a handler`,
21
+ )
22
+ }
23
+ router.register(method, pattern, ...guards, ...handlers)
24
+ return scoped
25
+ }
26
+
27
+ const scoped = new Proxy(router, {
28
+ get(target, prop) {
29
+ if (prop === 'register') return register
30
+ if (typeof prop === 'string' && VERBS.has(prop)) {
31
+ return (pattern, ...handlers) =>
32
+ register(prop.toUpperCase(), pattern, ...handlers)
33
+ }
34
+ if (prop === 'use') {
35
+ return () => {
36
+ throw new Error(
37
+ 'router.use() is global middleware and cannot be called inside protectedRoutes(); call it in publicRoutes() or a plain routes() export instead.',
38
+ )
39
+ }
40
+ }
41
+ const value = Reflect.get(target, prop, target)
42
+ return typeof value === 'function' ? value.bind(target) : value
43
+ },
44
+ })
45
+
46
+ return scoped
47
+ }
48
+
49
+ // Loads app/routes/web.{ts,js}. It may export:
50
+ // publicRoutes(router) reachable by anyone
51
+ // protectedRoutes(router) every route requires a logged-in user
52
+ // routes(router, { auth }) legacy: you wrap handlers yourself
53
+ // Returns true when the web file exists.
54
+ export async function loadCustomRoutes(router, baseDir, { secret, hydrate } = {}) {
7
55
  const language = await detectLanguage(baseDir)
8
56
  const ext = language === 'typescript' ? 'ts' : 'js'
9
57
  const routesPath = path.join(baseDir, 'app', 'routes', `web.${ext}`)
@@ -15,8 +63,41 @@ export async function loadCustomRoutes(router, baseDir) {
15
63
  if (!exists) return false
16
64
 
17
65
  const mod = await import(pathToFileURL(routesPath).href)
66
+ const auth = (handler) => requireAuth(handler, secret, { hydrate })
67
+
68
+ // Middleware form of requireAuth: runs first, and only calls next()
69
+ // when the token is valid (requireAuth answers 401/500 itself otherwise).
70
+ const authGuard = (req, res, next) =>
71
+ requireAuth(() => next(), secret, { hydrate })(req, res)
72
+ authGuard[AUTH_MARK] = true
73
+
74
+ let loaded = false
75
+
76
+ if (typeof mod.publicRoutes === 'function') {
77
+ await mod.publicRoutes(router)
78
+ loaded = true
79
+ }
80
+
81
+ if (typeof mod.protectedRoutes === 'function') {
82
+ if (!secret) {
83
+ throw new Error(
84
+ 'protectedRoutes() needs auth.secret, but none is configured. Set AUTH_SECRET.',
85
+ )
86
+ }
87
+ await mod.protectedRoutes(scopedRouter(router, [authGuard]))
88
+ loaded = true
89
+ }
90
+
18
91
  if (typeof mod.routes === 'function') {
19
- await mod.routes(router)
92
+ await mod.routes(router, { auth })
93
+ loaded = true
20
94
  }
95
+
96
+ if (!loaded) {
97
+ console.warn(
98
+ `⚠ app/routes/web.${ext} exports none of publicRoutes, protectedRoutes or routes, skipped`,
99
+ )
100
+ }
101
+
21
102
  return true
22
- }
103
+ }
@@ -6,6 +6,8 @@ import { requireAuth } from '../http/requireAuth.js'
6
6
  const ROUTE_FILE = /\.(js|ts)$/
7
7
  // .d.ts files, _private files, dotfiles, and web.* (already loaded by loadCustomRoutes)
8
8
  const SKIP = /(\.d\.ts$|^_|^\.|^web\.(js|ts)$)/
9
+ // Handler files written by make:api. web.* imports them; they export no routes().
10
+ const SKIP_DIRS = new Set(['handlers'])
9
11
 
10
12
  async function collect(dir) {
11
13
  const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])
@@ -14,8 +16,10 @@ async function collect(dir) {
14
16
  for (const entry of entries) {
15
17
  if (SKIP.test(entry.name)) continue
16
18
  const full = path.join(dir, entry.name)
17
- if (entry.isDirectory()) files.push(...(await collect(full)))
18
- else if (entry.isFile() && ROUTE_FILE.test(entry.name)) files.push(full)
19
+ if (entry.isDirectory()) {
20
+ if (SKIP_DIRS.has(entry.name)) continue
21
+ files.push(...(await collect(full)))
22
+ } else if (entry.isFile() && ROUTE_FILE.test(entry.name)) files.push(full)
19
23
  }
20
24
 
21
25
  return files.sort()
@@ -1,20 +1,100 @@
1
1
  import type { Router } from '../router/Router.js'
2
+ import type { Server as HttpServer } from 'node:http'
2
3
 
3
- export type NotFoundHandler = (req: any, res: any) => boolean | void | Promise<boolean | void>
4
+ export type NotFoundHandler = (
5
+ req: any,
6
+ res: any,
7
+ ) => boolean | void | Promise<boolean | void>
4
8
 
5
9
  export interface ServerOptions {
10
+ /**
11
+ * Called when no route matches, before the default 404 JSON response.
12
+ * `tylix dev` uses it to serve static files from public/. Return true
13
+ * if it handled the request; false/undefined falls through to the 404.
14
+ */
6
15
  notFoundHandler?: NotFoundHandler | null
16
+
7
17
  /**
8
- * Believe X-Forwarded-For and X-Forwarded-Proto. Enable only behind a
9
- * proxy you control (nginx). Defaults to the TRUST_PROXY=true env var.
18
+ * Believe X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto.
19
+ * Enable only behind a proxy you control (nginx).
20
+ * Defaults to the TRUST_PROXY=true env var.
10
21
  */
11
22
  trustProxy?: boolean
23
+
24
+ /** Where request, error and slow-request logs go. Default: the app's logger. */
25
+ logger?: import('../observability/index.js').Logger
26
+ /** One log line per request: true, false or "api" (only /api/). Default: true in production, "api" otherwise. */
27
+ accessLog?: boolean | 'api'
28
+ /** Requests slower than this are logged as warnings; 0 turns it off. Default 1000. */
29
+ slowRequestMs?: number
30
+ /** Record HTTP and process metrics: true for the app's registry, or a registry. Default off. */
31
+ metrics?: boolean | import('../observability/index.js').MetricsRegistry
32
+ /** Compress JSON responses of at least minBytes (default 1024) with Brotli or gzip; false turns it off. */
33
+ compression?: false | { minBytes?: number }
34
+
35
+ /** Other origins allowed to send browser writes. Defaults to TRUSTED_ORIGINS. */
36
+ trustedOrigins?: string[]
37
+ /** The app's public URL, always a trusted origin. Defaults to APP_URL. */
38
+ appUrl?: string
39
+ /** off | report-only | enforce. Defaults to CSP_MODE. */
40
+ cspMode?: 'off' | 'report-only' | 'enforce'
41
+ /** The Content-Security-Policy. Defaults to CSP_POLICY, then a built-in policy. */
42
+ csp?: string
43
+
44
+ /**
45
+ * Show real error details (debug page, SQL, stack) instead of a generic
46
+ * 500. Defaults to the APP_DEBUG=true env var.
47
+ */
48
+ debug?: boolean
49
+
50
+ /**
51
+ * Largest request body accepted, in bytes. Bigger bodies get a 413.
52
+ * Defaults to the MAX_BODY_BYTES env var, then 1 MB.
53
+ */
54
+ maxBodyBytes?: number
55
+
56
+ /**
57
+ * When the port is already in use, try the next one instead of failing.
58
+ * Defaults to the AUTO_PORT env var, otherwise on outside production
59
+ * and off in production.
60
+ */
61
+ autoPort?: boolean
62
+
63
+ /**
64
+ * How many following ports to try. Defaults to the PORT_ATTEMPTS env
65
+ * var, then 10.
66
+ */
67
+ maxPortAttempts?: number
12
68
  }
13
69
 
14
70
  export declare class Server {
71
+ router: Router
72
+ notFoundHandler: NotFoundHandler | null
73
+ trustProxy: boolean
74
+ production: boolean
75
+ debug: boolean
76
+ maxBodyBytes: number
77
+ /** When the port is in use, try the next one instead of failing. */
78
+ autoPort: boolean
79
+ /** How many following ports to try. */
80
+ maxPortAttempts: number
81
+ /** Origins allowed to make cross-site browser writes (TRUSTED_ORIGINS + APP_URL). */
82
+ trustedOrigins: Set<string>
83
+ /** CSP_MODE: 'off' | 'report-only' | 'enforce' (lowercased, not validated). */
84
+ cspMode: string
85
+ csp: string
86
+
15
87
  constructor(router: Router, options?: ServerOptions)
88
+
16
89
  createHandler(): (req: any, res: any) => Promise<void>
17
- listen(port: number, callback?: () => void): import('node:http').Server
18
- }
19
90
 
20
- export declare function readBody(req: any): Promise<{ raw: string; body: any }>
91
+ /** `callback` receives the port actually bound. */
92
+ listen(port: number, callback?: (port: number) => void): HttpServer
93
+
94
+ applySecurityHeaders(req: any, res: any): void
95
+ isCrossSiteWrite(req: any): boolean
96
+ handle(req: any, res: any): Promise<void>
97
+ logFailure(req: any, err: any): void
98
+ sendDebug(req: any, res: any, err: any): void
99
+ fail(req: any, res: any, err: any): void
100
+ }