@tylix/core 0.1.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/package.json ADDED
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "@tylix/core",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./src/index.js",
6
+ "scripts": {
7
+ "test": "node --test src/**/*.test.js"
8
+ },
9
+ "dependencies": {
10
+ "@tylix/auth": "^0.1.0",
11
+ "@tylix/orm": "^0.1.0",
12
+ "@tylix/shared": "^0.1.0"
13
+ }
14
+ }
@@ -0,0 +1,75 @@
1
+ import { CacheRecord } from './CacheRecord.js'
2
+
3
+ function isExpired(row) {
4
+ if (!row.expires_at) return false
5
+ return new Date(row.expires_at).getTime() <= Date.now()
6
+ }
7
+
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
16
+
17
+ const existing = await CacheRecord.query().where('key', key).first()
18
+
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 })
26
+ },
27
+
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
+ }
36
+
37
+ return JSON.parse(row.value)
38
+ },
39
+
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
+ }
47
+ return true
48
+ },
49
+
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
54
+ },
55
+
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)
64
+ }
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
74
+ },
75
+ }
@@ -0,0 +1,7 @@
1
+ import { Model } from '@tylix/orm'
2
+
3
+ export class CacheRecord extends Model {
4
+ static table = 'cache'
5
+ static fillable = ['key', 'value', 'expires_at']
6
+ static timestamps = true
7
+ }
@@ -0,0 +1,57 @@
1
+ import { WebSocketServer } from 'ws'
2
+
3
+ export class ChannelServer {
4
+ constructor() {
5
+ this.channels = new Map()
6
+ this.wss = null
7
+ }
8
+
9
+ channel(name, handlers) {
10
+ this.channels.set(name, { handlers, clients: new Set() })
11
+ return this
12
+ }
13
+
14
+ broadcast(name, data) {
15
+ const channel = this.channels.get(name)
16
+ if (!channel) return
17
+ const message = JSON.stringify(data)
18
+ for (const client of channel.clients) {
19
+ if (client.readyState === client.OPEN) client.send(message)
20
+ }
21
+ }
22
+
23
+ listen(port) {
24
+ this.wss = new WebSocketServer({ port })
25
+
26
+ this.wss.on('connection', (ws, req) => {
27
+ const url = new URL(req.url, `http://${req.headers.host}`)
28
+ const channelName = url.pathname.slice(1)
29
+ const channel = this.channels.get(channelName)
30
+
31
+ if (!channel) {
32
+ ws.close(1008, `Unknown channel "${channelName}"`)
33
+ return
34
+ }
35
+
36
+ channel.clients.add(ws)
37
+ channel.handlers.onConnect?.(ws)
38
+
39
+ ws.on('message', (raw) => {
40
+ let data
41
+ try {
42
+ data = JSON.parse(raw.toString())
43
+ } catch {
44
+ return // malformed message, ignore rather than crash the connection
45
+ }
46
+ channel.handlers.onMessage?.(ws, data)
47
+ })
48
+
49
+ ws.on('close', () => {
50
+ channel.clients.delete(ws)
51
+ channel.handlers.onDisconnect?.(ws)
52
+ })
53
+ })
54
+
55
+ return this.wss
56
+ }
57
+ }
@@ -0,0 +1,30 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+
5
+ export async function discoverFeatures(baseDir) {
6
+ const featuresDir = path.join(baseDir, "app", "Features");
7
+ const exists = await fs.access(featuresDir).then(() => true).catch(() => false);
8
+ if (!exists) return [];
9
+
10
+ const entries = await fs.readdir(featuresDir, { withFileTypes: true });
11
+ const features = [];
12
+
13
+ for (const entry of entries) {
14
+ if (!entry.isDirectory()) continue;
15
+
16
+ const manifestPath = path.join(featuresDir, entry.name, "feature.json");
17
+ const manifestExists = await fs.access(manifestPath).then(() => true).catch(() => false);
18
+ if (!manifestExists) continue;
19
+
20
+ const manifest = JSON.parse(await fs.readFile(manifestPath, "utf-8"));
21
+
22
+ const controllerPath = path.join(baseDir, "app", "controllers", `${manifest.controller}.js`);
23
+ const controllerModule = await import(pathToFileURL(controllerPath).href);
24
+ const ControllerClass = controllerModule[manifest.controller];
25
+
26
+ features.push({ manifest, controller: new ControllerClass() });
27
+ }
28
+
29
+ return features;
30
+ }
@@ -0,0 +1,18 @@
1
+ import fs from 'node:fs/promises'
2
+ import path from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+
5
+ export async function loadCustomRoutes(router, baseDir) {
6
+ const routesPath = path.join(baseDir, 'app', 'routes', 'web.js')
7
+ const exists = await fs
8
+ .access(routesPath)
9
+ .then(() => true)
10
+ .catch(() => false)
11
+ if (!exists) return false
12
+
13
+ const mod = await import(pathToFileURL(routesPath).href)
14
+ if (typeof mod.routes === 'function') {
15
+ await mod.routes(router)
16
+ }
17
+ return true
18
+ }
@@ -0,0 +1,14 @@
1
+ import { requireAuth } from "../http/requireAuth.js";
2
+
3
+ export function registerFeatureRoutes(router, features, { secret } = {}) {
4
+ for (const { manifest, controller } of features) {
5
+ const base = `/api/${manifest.table}`;
6
+ const wrap = (fn) => (manifest.auth ? requireAuth(fn, secret) : fn);
7
+
8
+ router.get(base, wrap((req, res) => controller.index(req, res)));
9
+ router.get(`${base}/:id`, wrap((req, res) => controller.show(req, res)));
10
+ router.post(base, wrap((req, res) => controller.store(req, res)));
11
+ router.put(`${base}/:id`, wrap((req, res) => controller.update(req, res)));
12
+ router.delete(`${base}/:id`, wrap((req, res) => controller.destroy(req, res)));
13
+ }
14
+ }
@@ -0,0 +1,55 @@
1
+ import http from 'node:http'
2
+ import { enhanceResponse } from './enhanceResponse.js'
3
+ import { parseBody } from './parseBody.js'
4
+ import { parseQuery } from './parseQuery.js'
5
+ import { parseCookies } from './parseCookies.js'
6
+
7
+ export class Server {
8
+ constructor(router, { notFoundHandler = null } = {}) {
9
+ this.router = router
10
+ // Optional fallback called when no route matches, before the
11
+ // default 404 JSON response -- e.g. tylix dev uses this to serve
12
+ // static files from public/. Return true if it handled the
13
+ // request (already wrote a response); false/undefined falls
14
+ // through to the default 404.
15
+ this.notFoundHandler = notFoundHandler
16
+ }
17
+
18
+ createHandler() {
19
+ return async (req, res) => {
20
+ enhanceResponse(res)
21
+
22
+ const match = this.router.match(req.method, req.url)
23
+ if (!match) {
24
+ if (this.notFoundHandler) {
25
+ const handled = await this.notFoundHandler(req, res)
26
+ if (handled) return
27
+ }
28
+ res.status(404).json({ error: 'Not found' })
29
+ return
30
+ }
31
+
32
+ req.params = match.params
33
+ req.query = parseQuery(req.url)
34
+ req.cookies = parseCookies(req)
35
+
36
+ try {
37
+ req.body = await parseBody(req)
38
+ } catch (err) {
39
+ res.status(400).json({ error: err.message })
40
+ return
41
+ }
42
+
43
+ try {
44
+ await match.handler(req, res)
45
+ } catch (err) {
46
+ res.status(500).json({ error: err.message })
47
+ }
48
+ }
49
+ }
50
+
51
+ listen(port, callback) {
52
+ const server = http.createServer(this.createHandler())
53
+ return server.listen(port, callback)
54
+ }
55
+ }
@@ -0,0 +1,99 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { Router } from "../router/Router.js";
4
+ import { Server } from "./Server.js";
5
+
6
+ test("handles a matched GET route", async () => {
7
+ const router = new Router();
8
+ router.get("/api/ping", (req, res) => res.json({ pong: true }));
9
+
10
+ const server = new Server(router);
11
+ const httpServer = server.listen(0);
12
+ const { port } = httpServer.address();
13
+
14
+ const response = await fetch(`http://localhost:${port}/api/ping`);
15
+ const body = await response.json();
16
+
17
+ assert.equal(response.status, 200);
18
+ assert.deepEqual(body, { pong: true });
19
+
20
+ httpServer.close();
21
+ });
22
+
23
+ test("returns 404 for unmatched routes", async () => {
24
+ const router = new Router();
25
+ const server = new Server(router);
26
+ const httpServer = server.listen(0);
27
+ const { port } = httpServer.address();
28
+
29
+ const response = await fetch(`http://localhost:${port}/nonexistent`);
30
+ assert.equal(response.status, 404);
31
+
32
+ httpServer.close();
33
+ });
34
+
35
+ test("parses JSON body and passes params to handler", async () => {
36
+ const router = new Router();
37
+ router.post("/api/echo/:id", (req, res) => {
38
+ res.json({ id: req.params.id, body: req.body });
39
+ });
40
+
41
+ const server = new Server(router);
42
+ const httpServer = server.listen(0);
43
+ const { port } = httpServer.address();
44
+
45
+ const response = await fetch(`http://localhost:${port}/api/echo/42`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/json" },
48
+ body: JSON.stringify({ title: "Hello" }),
49
+ });
50
+ const body = await response.json();
51
+
52
+ assert.deepEqual(body, { id: "42", body: { title: "Hello" } });
53
+
54
+ httpServer.close();
55
+ });
56
+
57
+ test("parses query string into req.query", async () => {
58
+ const router = new Router();
59
+ router.get("/api/comments/:id", (req, res) => {
60
+ res.json({ id: req.params.id, include: req.query.include ?? null });
61
+ });
62
+
63
+ const server = new Server(router);
64
+ const httpServer = server.listen(0);
65
+ const { port } = httpServer.address();
66
+
67
+ const response = await fetch(`http://localhost:${port}/api/comments/1?include=post`);
68
+ const body = await response.json();
69
+
70
+ assert.deepEqual(body, { id: "1", include: "post" });
71
+
72
+ httpServer.close();
73
+ });
74
+
75
+ test("calls notFoundHandler when no route matches, and skips 404 if it handles the request", async () => {
76
+ const router = new Router();
77
+ const server = new Server(router, {
78
+ notFoundHandler: async (req, res) => {
79
+ if (req.url === "/static-file.txt") {
80
+ res.setHeader("Content-Type", "text/plain");
81
+ res.end("served by fallback");
82
+ return true;
83
+ }
84
+ return false;
85
+ },
86
+ });
87
+
88
+ const httpServer = server.listen(0);
89
+ const { port } = httpServer.address();
90
+
91
+ const handled = await fetch(`http://localhost:${port}/static-file.txt`);
92
+ const handledBody = await handled.text();
93
+ assert.equal(handledBody, "served by fallback");
94
+
95
+ const unhandled = await fetch(`http://localhost:${port}/nonexistent`);
96
+ assert.equal(unhandled.status, 404);
97
+
98
+ httpServer.close();
99
+ });
@@ -0,0 +1,67 @@
1
+ function serializeCookie(name, value, options = {}) {
2
+ const parts = [`${name}=${encodeURIComponent(value)}`]
3
+
4
+ if (options.maxAge != null) {
5
+ parts.push(`Max-Age=${Math.floor(options.maxAge)}`)
6
+ }
7
+ if (options.expires) {
8
+ parts.push(`Expires=${options.expires.toUTCString()}`)
9
+ }
10
+ parts.push(`Path=${options.path || '/'}`)
11
+ if (options.domain) {
12
+ parts.push(`Domain=${options.domain}`)
13
+ }
14
+ if (options.httpOnly !== false) {
15
+ parts.push('HttpOnly')
16
+ }
17
+ if (options.secure) {
18
+ parts.push('Secure')
19
+ }
20
+ parts.push(`SameSite=${options.sameSite || 'Lax'}`)
21
+
22
+ return parts.join('; ')
23
+ }
24
+
25
+ export function enhanceResponse(res) {
26
+ res.status = function (code) {
27
+ res.statusCode = code
28
+ return res
29
+ }
30
+
31
+ res.json = function (data) {
32
+ res.setHeader('Content-Type', 'application/json')
33
+ res.end(JSON.stringify(data))
34
+ return res
35
+ }
36
+
37
+ res.send = function (data) {
38
+ if (data === undefined) {
39
+ res.end()
40
+ return res
41
+ }
42
+ res.end(typeof data === 'string' ? data : JSON.stringify(data))
43
+ return res
44
+ }
45
+
46
+ // Set-Cookie can legitimately appear more than once (access + refresh
47
+ // tokens in the same response), so this appends rather than overwrites.
48
+ res.cookie = function (name, value, options = {}) {
49
+ const serialized = serializeCookie(name, value, options)
50
+ const existing = res.getHeader('Set-Cookie')
51
+ const cookies = existing
52
+ ? Array.isArray(existing)
53
+ ? existing.slice()
54
+ : [existing]
55
+ : []
56
+ cookies.push(serialized)
57
+ res.setHeader('Set-Cookie', cookies)
58
+ return res
59
+ }
60
+
61
+ res.clearCookie = function (name, options = {}) {
62
+ res.cookie(name, '', { ...options, maxAge: 0, expires: new Date(0) })
63
+ return res
64
+ }
65
+
66
+ return res
67
+ }
@@ -0,0 +1,45 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { enhanceResponse } from "./enhanceResponse.js";
4
+
5
+ function createMockResponse() {
6
+ return {
7
+ statusCode: 200,
8
+ headers: {},
9
+ body: null,
10
+ setHeader(key, value) {
11
+ this.headers[key] = value;
12
+ },
13
+ end(data) {
14
+ this.body = data;
15
+ },
16
+ };
17
+ }
18
+
19
+ test("status() sets statusCode and returns res for chaining", () => {
20
+ const res = enhanceResponse(createMockResponse());
21
+ const result = res.status(404);
22
+ assert.equal(res.statusCode, 404);
23
+ assert.equal(result, res);
24
+ });
25
+
26
+ test("json() sets content-type and serializes body", () => {
27
+ const res = enhanceResponse(createMockResponse());
28
+ res.json({ hello: "world" });
29
+ assert.equal(res.headers["Content-Type"], "application/json");
30
+ assert.equal(res.body, JSON.stringify({ hello: "world" }));
31
+ });
32
+
33
+ test("status().json() chains correctly", () => {
34
+ const res = enhanceResponse(createMockResponse());
35
+ res.status(201).json({ id: 1 });
36
+ assert.equal(res.statusCode, 201);
37
+ assert.equal(res.body, JSON.stringify({ id: 1 }));
38
+ });
39
+
40
+ test("send() with no args ends the response with no body", () => {
41
+ const res = enhanceResponse(createMockResponse());
42
+ res.status(204).send();
43
+ assert.equal(res.statusCode, 204);
44
+ assert.equal(res.body, undefined);
45
+ });
@@ -0,0 +1,30 @@
1
+ export function parseBody(req) {
2
+ return new Promise((resolve, reject) => {
3
+ let chunks = "";
4
+
5
+ req.on("data", (chunk) => {
6
+ chunks += chunk;
7
+ });
8
+
9
+ req.on("end", () => {
10
+ if (!chunks) {
11
+ resolve({});
12
+ return;
13
+ }
14
+
15
+ const contentType = req.headers["content-type"] || "";
16
+ if (!contentType.includes("application/json")) {
17
+ resolve({});
18
+ return;
19
+ }
20
+
21
+ try {
22
+ resolve(JSON.parse(chunks));
23
+ } catch (err) {
24
+ reject(new Error("Invalid JSON body"));
25
+ }
26
+ });
27
+
28
+ req.on("error", reject);
29
+ });
30
+ }
@@ -0,0 +1,33 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { Readable } from "node:stream";
4
+ import { parseBody } from "./parseBody.js";
5
+
6
+ function createMockRequest(bodyString, contentType = "application/json") {
7
+ const req = Readable.from([bodyString]);
8
+ req.headers = { "content-type": contentType };
9
+ return req;
10
+ }
11
+
12
+ test("parses a valid JSON body", async () => {
13
+ const req = createMockRequest(JSON.stringify({ title: "Hello" }));
14
+ const body = await parseBody(req);
15
+ assert.deepEqual(body, { title: "Hello" });
16
+ });
17
+
18
+ test("returns empty object for empty body", async () => {
19
+ const req = createMockRequest("");
20
+ const body = await parseBody(req);
21
+ assert.deepEqual(body, {});
22
+ });
23
+
24
+ test("returns empty object when content-type is not JSON", async () => {
25
+ const req = createMockRequest("plain text", "text/plain");
26
+ const body = await parseBody(req);
27
+ assert.deepEqual(body, {});
28
+ });
29
+
30
+ test("rejects on malformed JSON", async () => {
31
+ const req = createMockRequest("{not valid json");
32
+ await assert.rejects(() => parseBody(req), /Invalid JSON body/);
33
+ });
@@ -0,0 +1,21 @@
1
+ // No cookie-parser here — Tylix's HTTP layer is hand-rolled on top of
2
+ // node:http, so cookies need to be parsed off the raw `Cookie` header
3
+ // the same way parseQuery.js handles the URL's query string.
4
+ export function parseCookies(req) {
5
+ const header = req.headers?.cookie;
6
+ if (!header) return {};
7
+
8
+ const cookies = {};
9
+ for (const pair of header.split(";")) {
10
+ const separatorIndex = pair.indexOf("=");
11
+ if (separatorIndex === -1) continue;
12
+
13
+ const key = pair.slice(0, separatorIndex).trim();
14
+ const value = pair.slice(separatorIndex + 1).trim();
15
+ if (!key) continue;
16
+
17
+ cookies[key] = decodeURIComponent(value);
18
+ }
19
+
20
+ return cookies;
21
+ }
@@ -0,0 +1,7 @@
1
+ export function parseQuery(url) {
2
+ const queryStart = url.indexOf("?");
3
+ if (queryStart === -1) return {};
4
+
5
+ const params = new URLSearchParams(url.slice(queryStart + 1));
6
+ return Object.fromEntries(params.entries());
7
+ }
@@ -0,0 +1,15 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { parseQuery } from "./parseQuery.js";
4
+
5
+ test("returns empty object when there is no query string", () => {
6
+ assert.deepEqual(parseQuery("/api/posts"), {});
7
+ });
8
+
9
+ test("parses a single query param", () => {
10
+ assert.deepEqual(parseQuery("/api/comments/1?include=post"), { include: "post" });
11
+ });
12
+
13
+ test("parses multiple query params", () => {
14
+ assert.deepEqual(parseQuery("/api/posts?page=2&limit=10"), { page: "2", limit: "10" });
15
+ });
@@ -0,0 +1,34 @@
1
+ import { verifyToken, ACCESS_TOKEN_COOKIE } from "@tylix/auth";
2
+
3
+ /**
4
+ * Wraps a route handler so it only runs if the request carries a valid
5
+ * session. Checks the httpOnly access-token cookie first (what the
6
+ * browser app now uses), then falls back to an
7
+ * "Authorization: Bearer <token>" header (for non-browser API clients
8
+ * that can't rely on cookies). On success, req.user is set to the
9
+ * token's payload (e.g. { userId }); on failure, responds 401 and
10
+ * never calls the wrapped handler.
11
+ */
12
+ export function requireAuth(handler, secret) {
13
+ return async (req, res) => {
14
+ const cookieToken = req.cookies?.[ACCESS_TOKEN_COOKIE];
15
+
16
+ const authHeader = req.headers?.authorization || "";
17
+ const [scheme, headerToken] = authHeader.split(" ");
18
+ const bearerToken = scheme === "Bearer" ? headerToken : null;
19
+
20
+ const token = cookieToken || bearerToken;
21
+
22
+ if (!token) {
23
+ return res.status(401).json({ error: "Not authenticated." });
24
+ }
25
+
26
+ const result = verifyToken(token, secret);
27
+ if (!result.valid) {
28
+ return res.status(401).json({ error: result.error || "Invalid token." });
29
+ }
30
+
31
+ req.user = result.payload;
32
+ return handler(req, res);
33
+ };
34
+ }
@@ -0,0 +1,76 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { signToken } from "@tylix/auth";
4
+ import { requireAuth } from "./requireAuth.js";
5
+
6
+ function createMockRes() {
7
+ return {
8
+ statusCode: 200,
9
+ body: null,
10
+ status(code) {
11
+ this.statusCode = code;
12
+ return this;
13
+ },
14
+ json(data) {
15
+ this.body = data;
16
+ return this;
17
+ },
18
+ };
19
+ }
20
+
21
+ test("calls the handler and sets req.user when the token is valid", async () => {
22
+ const token = signToken({ userId: 7 }, "test-secret");
23
+ const req = { headers: { authorization: `Bearer ${token}` } };
24
+ const res = createMockRes();
25
+
26
+ let calledWith = null;
27
+ const handler = requireAuth((req, res) => {
28
+ calledWith = req.user;
29
+ res.json({ ok: true });
30
+ }, "test-secret");
31
+
32
+ await handler(req, res);
33
+
34
+ assert.deepEqual(calledWith, { userId: 7 });
35
+ assert.deepEqual(res.body, { ok: true });
36
+ });
37
+
38
+ test("responds 401 when Authorization header is missing", async () => {
39
+ const req = { headers: {} };
40
+ const res = createMockRes();
41
+
42
+ const handler = requireAuth(() => {
43
+ throw new Error("should not be called");
44
+ }, "test-secret");
45
+
46
+ await handler(req, res);
47
+
48
+ assert.equal(res.statusCode, 401);
49
+ });
50
+
51
+ test("responds 401 when the token is signed with a different secret", async () => {
52
+ const token = signToken({ userId: 1 }, "wrong-secret");
53
+ const req = { headers: { authorization: `Bearer ${token}` } };
54
+ const res = createMockRes();
55
+
56
+ const handler = requireAuth(() => {
57
+ throw new Error("should not be called");
58
+ }, "test-secret");
59
+
60
+ await handler(req, res);
61
+
62
+ assert.equal(res.statusCode, 401);
63
+ });
64
+
65
+ test("responds 401 when the Authorization header has no Bearer scheme", async () => {
66
+ const req = { headers: { authorization: "Basic abc123" } };
67
+ const res = createMockRes();
68
+
69
+ const handler = requireAuth(() => {
70
+ throw new Error("should not be called");
71
+ }, "test-secret");
72
+
73
+ await handler(req, res);
74
+
75
+ assert.equal(res.statusCode, 401);
76
+ });
package/src/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export * from './router/Router.js'
2
+ export * from './http/Server.js'
3
+ export * from './http/enhanceResponse.js'
4
+ export * from './http/parseBody.js'
5
+ export * from './http/parseQuery.js'
6
+ export * from './http/parseCookies.js'
7
+ export * from './http/requireAuth.js'
8
+ export * from './discovery/discoverFeatures.js'
9
+ export * from './discovery/registerFeatureRoutes.js'
10
+ export * from './discovery/loadCustomRoutes.js'
11
+ export * from './queue/JobRecord.js'
12
+ export * from './queue/dispatch.js'
13
+ export * from './scheduling/Scheduler.js'
14
+ export * from './channels/ChannelServer.js'
15
+ export * from './cache/CacheRecord.js'
16
+ export * from './cache/Cache.js'
@@ -0,0 +1,16 @@
1
+ import { reactive } from '@tylix/compiler'
2
+
3
+ export function createProvider(setup) {
4
+ const state = reactive(setup.state ? setup.state() : {})
5
+ let inflight = null
6
+
7
+ async function load(...args) {
8
+ if (inflight) return inflight
9
+ inflight = setup.fetch(state, ...args).finally(() => {
10
+ inflight = null
11
+ })
12
+ return inflight
13
+ }
14
+
15
+ return { state, load, ...(setup.actions ? setup.actions(state) : {}) }
16
+ }
@@ -0,0 +1,7 @@
1
+ import { Model } from '@tylix/orm'
2
+
3
+ export class JobRecord extends Model {
4
+ static table = 'jobs'
5
+ static fillable = ['job', 'payload', 'status', 'attempts', 'error']
6
+ static timestamps = true
7
+ }
@@ -0,0 +1,10 @@
1
+ import { JobRecord } from './JobRecord.js'
2
+
3
+ export async function dispatch(jobName, payload = {}) {
4
+ return JobRecord.create({
5
+ job: jobName,
6
+ payload: JSON.stringify(payload),
7
+ status: 'pending',
8
+ attempts: 0,
9
+ })
10
+ }
@@ -0,0 +1,103 @@
1
+ function compose(fns) {
2
+ return async function (req, res) {
3
+ let index = -1
4
+ async function dispatch(i) {
5
+ if (i <= index) {
6
+ throw new Error('next() called multiple times in one middleware chain')
7
+ }
8
+ index = i
9
+ const fn = fns[i]
10
+ if (!fn) return
11
+ await fn(req, res, () => dispatch(i + 1))
12
+ }
13
+ return dispatch(0)
14
+ }
15
+ }
16
+
17
+ export class Router {
18
+ constructor() {
19
+ this.routes = []
20
+ this.middlewares = []
21
+ }
22
+
23
+ // Global middleware, run before every route match, in registration
24
+ // order. e.g. router.use(loggerMiddleware).
25
+ use(fn) {
26
+ this.middlewares.push(fn)
27
+ return this
28
+ }
29
+
30
+ register(method, pattern, ...handlers) {
31
+ if (handlers.length === 0) {
32
+ throw new Error(
33
+ `Router.${method.toLowerCase()}("${pattern}") needs a handler`,
34
+ )
35
+ }
36
+ const finalHandler = handlers[handlers.length - 1]
37
+ const routeMiddleware = handlers.slice(0, -1)
38
+
39
+ const keys = []
40
+ const regexPattern = pattern
41
+ .split('/')
42
+ .map((segment) => {
43
+ if (segment.startsWith(':')) {
44
+ keys.push(segment.slice(1))
45
+ return '([^/]+)'
46
+ }
47
+ return segment
48
+ })
49
+ .join('/')
50
+
51
+ const regex = new RegExp(`^${regexPattern}$`)
52
+ this.routes.push({
53
+ method: method.toUpperCase(),
54
+ pattern,
55
+ regex,
56
+ keys,
57
+ routeMiddleware,
58
+ finalHandler,
59
+ })
60
+ return this
61
+ }
62
+
63
+ get(pattern, ...handlers) {
64
+ return this.register('GET', pattern, ...handlers)
65
+ }
66
+
67
+ post(pattern, ...handlers) {
68
+ return this.register('POST', pattern, ...handlers)
69
+ }
70
+
71
+ put(pattern, ...handlers) {
72
+ return this.register('PUT', pattern, ...handlers)
73
+ }
74
+
75
+ delete(pattern, ...handlers) {
76
+ return this.register('DELETE', pattern, ...handlers)
77
+ }
78
+
79
+ match(method, url) {
80
+ const pathname = url.split('?')[0]
81
+
82
+ for (const route of this.routes) {
83
+ if (route.method !== method.toUpperCase()) continue
84
+
85
+ const result = route.regex.exec(pathname)
86
+ if (!result) continue
87
+
88
+ const params = {}
89
+ route.keys.forEach((key, i) => {
90
+ params[key] = result[i + 1]
91
+ })
92
+
93
+ const chain = compose([
94
+ ...this.middlewares,
95
+ ...route.routeMiddleware,
96
+ route.finalHandler,
97
+ ])
98
+ return { handler: chain, params }
99
+ }
100
+
101
+ return null
102
+ }
103
+ }
@@ -0,0 +1,49 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { Router } from "./Router.js";
4
+
5
+ test("matches an exact static route", () => {
6
+ const router = new Router();
7
+ const handler = () => {};
8
+ router.get("/api/posts", handler);
9
+
10
+ const match = router.match("GET", "/api/posts");
11
+ assert.equal(match.handler, handler);
12
+ assert.deepEqual(match.params, {});
13
+ });
14
+
15
+ test("matches a dynamic route and extracts params", () => {
16
+ const router = new Router();
17
+ const handler = () => {};
18
+ router.get("/api/posts/:id", handler);
19
+
20
+ const match = router.match("GET", "/api/posts/42");
21
+ assert.equal(match.handler, handler);
22
+ assert.deepEqual(match.params, { id: "42" });
23
+ });
24
+
25
+ test("differentiates by HTTP method", () => {
26
+ const router = new Router();
27
+ const getHandler = () => {};
28
+ const postHandler = () => {};
29
+ router.get("/api/posts", getHandler);
30
+ router.post("/api/posts", postHandler);
31
+
32
+ assert.equal(router.match("GET", "/api/posts").handler, getHandler);
33
+ assert.equal(router.match("POST", "/api/posts").handler, postHandler);
34
+ });
35
+
36
+ test("returns null when no route matches", () => {
37
+ const router = new Router();
38
+ router.get("/api/posts", () => {});
39
+ assert.equal(router.match("GET", "/api/nonexistent"), null);
40
+ });
41
+
42
+ test("ignores query string when matching", () => {
43
+ const router = new Router();
44
+ const handler = () => {};
45
+ router.get("/api/posts", handler);
46
+
47
+ const match = router.match("GET", "/api/posts?page=2");
48
+ assert.equal(match.handler, handler);
49
+ });
@@ -0,0 +1,42 @@
1
+ export async function useApi(url, options = {}) {
2
+ const {
3
+ method = 'GET',
4
+ body,
5
+ headers = {},
6
+ credentials = 'include',
7
+ } = options
8
+
9
+ const finalHeaders = { ...headers }
10
+ let finalBody = body
11
+ if (body && typeof body === 'object' && !(body instanceof FormData)) {
12
+ finalHeaders['Content-Type'] =
13
+ finalHeaders['Content-Type'] || 'application/json'
14
+ finalBody = JSON.stringify(body)
15
+ }
16
+
17
+ try {
18
+ const response = await fetch(url, {
19
+ method,
20
+ headers: finalHeaders,
21
+ body: finalBody,
22
+ credentials,
23
+ })
24
+ let data = null
25
+ try {
26
+ data = await response.json()
27
+ } catch {
28
+ /* empty body */
29
+ }
30
+ if (!response.ok) {
31
+ return {
32
+ ok: false,
33
+ status: response.status,
34
+ data,
35
+ error: (data && (data.error || data.message)) || 'Request failed',
36
+ }
37
+ }
38
+ return { ok: true, status: response.status, data, error: null }
39
+ } catch (err) {
40
+ return { ok: false, status: 0, data: null, error: err.message }
41
+ }
42
+ }
@@ -0,0 +1,56 @@
1
+ export class Scheduler {
2
+ constructor() {
3
+ this.tasks = []
4
+ }
5
+
6
+ every(interval, handler) {
7
+ this.tasks.push({
8
+ type: 'interval',
9
+ interval: parseInterval(interval),
10
+ handler,
11
+ lastRun: 0,
12
+ })
13
+ return this
14
+ }
15
+
16
+ daily(time, handler) {
17
+ const [hour, minute] = time.split(':').map(Number)
18
+ this.tasks.push({ type: 'daily', hour, minute, handler, lastRunDate: null })
19
+ return this
20
+ }
21
+
22
+ async runDue() {
23
+ const now = new Date()
24
+ for (const task of this.tasks) {
25
+ if (
26
+ task.type === 'interval' &&
27
+ now.getTime() - task.lastRun >= task.interval
28
+ ) {
29
+ task.lastRun = now.getTime()
30
+ await task.handler()
31
+ }
32
+ if (task.type === 'daily') {
33
+ const today = now.toISOString().slice(0, 10)
34
+ if (
35
+ now.getHours() === task.hour &&
36
+ now.getMinutes() === task.minute &&
37
+ task.lastRunDate !== today
38
+ ) {
39
+ task.lastRunDate = today
40
+ await task.handler()
41
+ }
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ function parseInterval(str) {
48
+ const match = /^(\d+)(s|m|h)$/.exec(str)
49
+ if (!match)
50
+ throw new Error(
51
+ `Invalid interval "${str}", expected e.g. "5m", "30s", "1h"`,
52
+ )
53
+ const [, num, unit] = match
54
+ const multipliers = { s: 1000, m: 60000, h: 3600000 }
55
+ return Number(num) * multipliers[unit]
56
+ }