@botonic/core
Version:
Runtime and APIs for Botonic bots: actions, context, messaging, and integration hooks used by the **current** framework line.
68 lines • 2.4 kB
JavaScript
export const NOT_FOUND_PATH = '404';
export class NoMatchingRouteError extends Error {
constructor(botonicContext) {
super(`No route found for input '${JSON.stringify(botonicContext.input)}' and no ${NOT_FOUND_PATH} route defined`);
this.botonicContext = botonicContext;
}
}
export class Router {
constructor(routes) {
this.routes = routes;
}
processInput(botonicContext) {
for (const route of this.routes) {
if (this.routeMatches(route, botonicContext)) {
return route;
}
}
throw new NoMatchingRouteError(botonicContext);
}
routeMatches(route, botonicContext) {
var _a, _b, _c;
const hasMatchers = !!(route.text ||
route.payload ||
route.type ||
route.input ||
route.session ||
route.context);
if (!hasMatchers) {
return route.path === NOT_FOUND_PATH;
}
const textValue = botonicContext.input.text;
const payloadValue = botonicContext.input.payload;
const typeValue = botonicContext.input.type;
const stringMatcherChecks = [
{ matcher: route.text, value: textValue },
{ matcher: route.payload, value: payloadValue },
{ matcher: route.type, value: typeValue },
];
for (const { matcher, value } of stringMatcherChecks) {
if (matcher && value && this.matchesStringValue(matcher, value)) {
return true;
}
}
if ((_a = route.input) === null || _a === void 0 ? void 0 : _a.call(route, botonicContext.input)) {
return true;
}
if ((_b = route.session) === null || _b === void 0 ? void 0 : _b.call(route, botonicContext.session)) {
return true;
}
if ((_c = route.context) === null || _c === void 0 ? void 0 : _c.call(route, botonicContext)) {
return true;
}
return false;
}
matchesStringValue(matcher, value) {
if (typeof matcher === 'string') {
return matcher === value;
}
else if (matcher instanceof RegExp) {
return matcher.test(value);
}
else if (typeof matcher === 'function') {
return matcher(value);
}
return false;
}
}
//# sourceMappingURL=router.js.map