Files
FWS-DiscordBot/src/web/router.js
T
nocodeandClaude Opus 5 e03b184d68 feat(web): add the HTTP layer and Discord-backed sessions
Visitors sign in with Discord and inherit the very same access levels as the
slash commands, so there is no second permission model to keep in sync.

Writes require a header a cross-site form cannot forge, on top of the
`SameSite=Lax` cookie, and a bootstrap token opens the configuration wizard
alone for the case where no Discord application exists yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:13 +02:00

64 lines
2.1 KiB
JavaScript

import { HttpError, notFound } from './http.js';
/**
* Minimal router: `/api/repositories/:owner/:repo` style patterns, no dependency (M16-T01).
* A trailing `*` captures the rest of the path under `params.rest`.
*/
function compile(pattern) {
const segments = pattern.split('/').filter(Boolean);
return { segments, pattern };
}
function match(route, segments) {
const params = {};
for (const [index, expected] of route.segments.entries()) {
if (expected === '*') {
params.rest = segments.slice(index).join('/');
return params;
}
const actual = segments[index];
if (actual === undefined) return null;
if (expected.startsWith(':')) params[expected.slice(1)] = decodeURIComponent(actual);
else if (expected !== actual) return null;
}
return segments.length === route.segments.length ? params : null;
}
export function createRouter() {
const routes = [];
const add = (method, pattern, handler, options = {}) => {
routes.push({ method, ...compile(pattern), handler, options });
};
return {
get: (pattern, handler, options) => add('GET', pattern, handler, options),
post: (pattern, handler, options) => add('POST', pattern, handler, options),
put: (pattern, handler, options) => add('PUT', pattern, handler, options),
patch: (pattern, handler, options) => add('PATCH', pattern, handler, options),
delete: (pattern, handler, options) => add('DELETE', pattern, handler, options),
/**
* Finds the handler for a request.
* Throws 405 when the path exists under another method, which is easier to
* debug from the browser console than a plain 404.
*/
resolve(method, pathname) {
const segments = pathname.split('/').filter(Boolean);
let pathMatched = false;
for (const route of routes) {
const params = match(route, segments);
if (!params) continue;
pathMatched = true;
if (route.method === method) return { ...route, params };
}
throw pathMatched ? new HttpError(405, `Méthode ${method} non autorisée ici`) : notFound();
},
list: () => routes.map((route) => `${route.method} ${route.pattern}`),
};
}