@tylix/core 0.6.0 → 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.
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.6.0",
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.6.0",
16
- "@tylix/compiler": "^0.6.0",
17
- "@tylix/orm": "^0.6.0",
18
- "@tylix/shared": "^0.6.0",
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
+ }
@@ -21,6 +21,26 @@ export interface ServerOptions {
21
21
  */
22
22
  trustProxy?: boolean
23
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
+
24
44
  /**
25
45
  * Show real error details (debug page, SQL, stack) instead of a generic
26
46
  * 500. Defaults to the APP_DEBUG=true env var.
@@ -32,6 +52,19 @@ export interface ServerOptions {
32
52
  * Defaults to the MAX_BODY_BYTES env var, then 1 MB.
33
53
  */
34
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
35
68
  }
36
69
 
37
70
  export declare class Server {
@@ -41,6 +74,10 @@ export declare class Server {
41
74
  production: boolean
42
75
  debug: boolean
43
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
44
81
  /** Origins allowed to make cross-site browser writes (TRUSTED_ORIGINS + APP_URL). */
45
82
  trustedOrigins: Set<string>
46
83
  /** CSP_MODE: 'off' | 'report-only' | 'enforce' (lowercased, not validated). */
@@ -50,7 +87,9 @@ export declare class Server {
50
87
  constructor(router: Router, options?: ServerOptions)
51
88
 
52
89
  createHandler(): (req: any, res: any) => Promise<void>
53
- listen(port: number, callback?: () => void): HttpServer
90
+
91
+ /** `callback` receives the port actually bound. */
92
+ listen(port: number, callback?: (port: number) => void): HttpServer
54
93
 
55
94
  applySecurityHeaders(req: any, res: any): void
56
95
  isCrossSiteWrite(req: any): boolean