snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Code scanning - action / CodeQL-Build (push) Failing after 1s
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,343 @@
import type { RoomType, RoomRouteData } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import type {
LocationHash,
LocationPathname,
LocationSearch,
RouteName,
RouteObject,
RouteParameters,
RouterContextValue,
SearchParameters,
To,
} from '@rocket.chat/ui-contexts';
import { Context, Page } from './page';
import { appLayout } from '../lib/appLayout';
import { getRootUrlPathPrefix } from '../lib/meteorRuntimeConfig';
import { roomCoordinator } from '../lib/rooms/roomCoordinator';
export class Router implements RouterContextValue {
private readonly pathRegExp = /(:[\w\(\)\\\+\*\.\?\[\]\-]+)+/g;
private readonly queryRegExp = /\?([^\/\r\n].*)/;
private current:
| Readonly<{
path: string;
params: Map<string, string>;
route: Route;
context: Context;
oldRoute: Route | undefined;
queryParams: URLSearchParams;
}>
| undefined = undefined;
private readonly specialChars = ['/', '%', '+'];
private initialized = false;
private routes = new Set<Route>();
private pathDefById = new Map<Route['pathDef'], Route['id']>();
private readonly basePath = getRootUrlPathPrefix();
private readonly page = new Page();
constructor() {
this.registerRoute('*', { id: 'not-found' });
this.updateCallbacks();
}
private emitter = new Emitter<{ pathChanged: void }>();
private registerRoute(pathDef: string, options: RouteOptions) {
if (!/^\//.test(pathDef) && pathDef !== '*') {
throw new Error("route's path must start with '/'");
}
const route = new Route(pathDef, options);
route.actionHandle = (context: Context) => {
const oldRoute = this.current?.route;
const queryParams = new URLSearchParams(context.querystring);
this.current = Object.freeze({
path: context.path,
params: new Map(Object.entries<string>(context.params)),
route,
context,
oldRoute,
queryParams,
});
this.refresh();
};
this.routes.add(route);
this.pathDefById.set(options.id, route.pathDef);
this.updateCallbacks();
return route;
}
private encodePath(
idOrPathDef: string,
params: Record<string, string | null> = {},
queryParams: Record<string, string | null> = {},
): string {
if (this.pathDefById.has(idOrPathDef)) {
idOrPathDef = this.pathDefById.get(idOrPathDef) ?? idOrPathDef;
}
if (this.queryRegExp.test(idOrPathDef)) {
const [pathDefPart, searchPart] = idOrPathDef.split(this.queryRegExp);
idOrPathDef = pathDefPart;
if (searchPart) {
queryParams = Object.assign(Object.fromEntries(new URLSearchParams(searchPart).entries()), queryParams);
}
}
let path = '';
if (this.basePath) {
path += `/${this.basePath}/`;
}
path += idOrPathDef.replace(this.pathRegExp, (_key) => {
const firstRegexpChar = _key.indexOf('(');
let key = _key.substring(1, firstRegexpChar > 0 ? firstRegexpChar : undefined);
key = key.replace(/[\+\*\?]+/g, '');
if (params[key]) {
return this.encodeParam(`${params[key]}`);
}
return '';
});
path = path.replace(/\/\/+/g, '/');
path = path.match(/^\/{1}$/) ? path : path.replace(/\/$/, '');
const strQueryParams = new URLSearchParams(
Object.entries(queryParams).filter((pair): pair is [string, string] => pair[1] !== null && pair[1] !== undefined),
).toString();
if (strQueryParams) {
path += `?${strQueryParams}`;
}
path = path.replace(/\/\/+/g, '/');
return path;
}
private encodeParam(param: string) {
const paramArr = param.split('');
let buffer = '';
for (const p of paramArr) {
if (this.specialChars.includes(p)) {
buffer += encodeURIComponent(encodeURIComponent(p));
} else {
try {
buffer += encodeURIComponent(p);
} catch (e) {
buffer += p;
}
}
}
return buffer;
}
private initialize() {
if (this.initialized) {
throw new Error('FlowRouter is already initialized');
}
this.updateCallbacks();
this.page.setBase(this.basePath);
this.page.start();
this.initialized = true;
queueMicrotask(() => {
this.emitter.emit('pathChanged');
});
}
private refresh() {
if (!this.current?.route) return;
const currentContext = this.current;
const { route } = currentContext;
let isRouteChange = currentContext.oldRoute !== currentContext.route;
if (!currentContext.oldRoute) {
isRouteChange = false;
}
if (!isRouteChange) {
this.emitter.emit('pathChanged');
}
route.action();
queueMicrotask(() => {
this.emitter.emit('pathChanged');
});
}
private updateCallbacks() {
this.page.clearRoutes();
let catchAll: Route | null = null;
for (const route of this.routes) {
if (route.pathDef === '*') {
catchAll = route;
} else {
this.page.registerRoute(route.pathDef, route.actionHandle);
}
}
if (catchAll) {
this.page.registerRoute(catchAll.pathDef, catchAll.actionHandle);
}
}
// router context implementation
readonly subscribeToRouteChange = (onRouteChange: () => void): (() => void) => {
const unsubscribe = this.emitter.on('pathChanged', onRouteChange);
// FIXME: for some reason this is (and was) necessary to invoke some route actions
this.emitter.emit('pathChanged');
return () => {
unsubscribe();
};
};
readonly getLocationPathname = () => this.current?.path.replace(/\?.*/, '') as LocationPathname;
readonly getLocationSearch = () => location.search as LocationSearch;
readonly getLocationHash = () => location.hash as LocationHash;
readonly getRouteParameters = () => (this.current?.params ? (Object.fromEntries(this.current.params.entries()) as RouteParameters) : {});
readonly getSearchParameters = () =>
this.current?.queryParams ? (Object.fromEntries(this.current.queryParams.entries()) as SearchParameters) : {};
readonly getRouteName = () => this.current?.route?.id as RouteName | undefined;
readonly getPreviousRouteName = () => this.current?.oldRoute?.id as RouteName | undefined;
private encodeSearchParameters(searchParameters: SearchParameters) {
const search = new URLSearchParams();
for (const [key, value] of Object.entries(searchParameters)) {
search.append(key, value);
}
const searchString = search.toString();
return searchString ? `?${searchString}` : '';
}
readonly buildRoutePath = (to: To): LocationPathname | `${LocationPathname}?${LocationSearch}` => {
if (typeof to === 'string') {
return to;
}
if ('pathname' in to) {
const { pathname, search = {} } = to;
return (pathname + this.encodeSearchParameters(search)) as LocationPathname | `${LocationPathname}?${LocationSearch}`;
}
if ('pattern' in to) {
const { pattern, params = {}, search = {} } = to;
return this.encodePath(pattern, params, search) as LocationPathname | `${LocationPathname}?${LocationSearch}`;
}
if ('name' in to) {
const { name, params = {}, search = {} } = to;
return this.encodePath(name, params, search) as LocationPathname | `${LocationPathname}?${LocationSearch}`;
}
throw new Error('Invalid route');
};
readonly navigate = (
toOrDelta: To | number,
options?: {
replace?: boolean;
},
) => {
if (typeof toOrDelta === 'number') {
history.go(toOrDelta);
return;
}
const path = this.buildRoutePath(toOrDelta);
const state = { path };
if (options?.replace) {
history.replaceState(state, '', path);
} else {
history.pushState(state, '', path);
}
dispatchEvent(new PopStateEvent('popstate', { state }));
};
readonly defineRoutes = (routes: readonly RouteObject[]) => {
if (!this.initialized) this.initialize();
const flowRoutes = routes.map((route) =>
this.registerRoute(route.path, {
id: route.id,
action: () => appLayout.render(<>{route.element}</>),
}),
);
if (this.current) this.page.dispatch(new Context(this.page, this.current.path));
return () => {
flowRoutes.forEach((flowRoute) => {
this.routes.delete(flowRoute);
this.pathDefById.delete(flowRoute.id);
});
this.updateCallbacks();
if (this.current) this.page.dispatch(new Context(this.page, this.current.path));
};
};
readonly getRoomRoute = (roomType: RoomType, routeData: RoomRouteData) => {
return { path: roomCoordinator.getRouteLink(roomType, routeData) || '/' };
};
}
type RouteOptions = {
id: string;
action?: () => void;
};
class Route {
readonly action: () => void | Promise<void>;
readonly id: string;
constructor(
public readonly pathDef: string,
public readonly options: RouteOptions,
) {
this.action = options.action ?? (() => undefined);
this.id = options.id;
}
actionHandle: (ctx: Context) => void;
}

View File

@@ -0,0 +1,247 @@
import type { Key } from 'path-to-regexp';
import { pathToRegexp } from 'path-to-regexp';
type State = { readonly path: string };
export class Context {
canonicalPath: string;
path: string;
querystring: string;
pathname: string;
state: State;
title: string;
params: Record<string, string>;
constructor(page: Page, path: string, state?: State) {
const pageBase = page.getBase();
if (path[0] === '/' && path.indexOf(pageBase) !== 0) path = `${pageBase}${path}`;
const i = path.indexOf('?');
this.canonicalPath = path;
this.path = path.replace(pageBase, '') || '/';
this.title = document.title;
this.state = { ...state, path };
this.querystring = ~i ? decodeURLEncodedURIComponent(path.slice(i + 1)) : '';
this.pathname = decodeURLEncodedURIComponent(~i ? path.slice(0, i) : path);
this.params = {};
if (!~this.path.indexOf('#')) return;
const parts = this.path.split('#');
this.path = parts[0];
this.pathname = parts[0];
this.querystring = this.querystring.split('#')[0];
}
pushState() {
history.pushState(this.state, this.title, this.canonicalPath);
}
save() {
if (location.protocol === 'file:') return;
history.replaceState(this.state, this.title, this.canonicalPath);
}
}
class Route {
private readonly regexp: RegExp;
private readonly keys: Key[] = [];
constructor(
path: string,
private readonly fn: (ctx: Context) => void,
) {
this.regexp = pathToRegexp(path === '*' ? '(.*)' : path, this.keys, { strict: false });
}
match(path: string, params: Record<string, string>): boolean {
const { keys } = this;
const qsIndex = path.indexOf('?');
const pathname = ~qsIndex ? path.slice(0, qsIndex) : path;
const m = this.regexp.exec(decodeURIComponent(pathname));
if (!m) return false;
for (let i = 1, len = m.length; i < len; ++i) {
const key = keys[i - 1];
const val = decodeURLEncodedURIComponent(m[i]);
if (val !== undefined || !Object.prototype.hasOwnProperty.call(params, key.name)) {
params[key.name] = val;
}
}
return true;
}
readonly callback = (ctx: Context, next: () => void) => {
if (this.match(ctx.path, ctx.params)) {
this.fn(ctx);
return;
}
next();
};
}
export class Page {
routes: Route[] = [];
current = '';
private running: boolean;
registerRoute(path: string, callback: (ctx: Context) => void): void {
const route = new Route(path, callback);
this.routes.push(route);
}
clearRoutes() {
this.routes = [];
}
start() {
if (this.running) return;
this.running = true;
window.addEventListener('popstate', this.onpopstate, false);
document.addEventListener('click', this.onclick, false);
const url = location.pathname + location.search + location.hash;
this.replace(url, { state: undefined, dispatch: undefined });
}
stop() {
if (!this.running) return;
this.running = false;
this.current = '';
document.removeEventListener('click', this.onclick, false);
window.removeEventListener('popstate', this.onpopstate, false);
}
private readonly onclick = (e: MouseEvent) => {
if (e.button !== 0) return;
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
if (e.defaultPrevented) return;
const el = (e.target as Element | null)?.closest<HTMLAnchorElement | SVGAElement>('a');
if (!el) return;
if (el.hasAttribute('download') || el.getAttribute('rel') === 'external') return;
const isSVGAElement = (e: HTMLAnchorElement | SVGAElement): e is SVGAElement => typeof e.href === 'object';
const link = isSVGAElement(el) ? el.href.baseVal : el.href;
const url = new URL(link, location.toString());
if (url.pathname === location.pathname && url.search === location.search && (url.hash || link === '#')) return;
if (url.protocol === 'mailto:') return;
if (isSVGAElement(el) ? el.target.baseVal : el.target) return;
if (!isSVGAElement(el) && (location.protocol !== url.protocol || location.hostname !== url.hostname || location.port !== url.port))
return;
let path = isSVGAElement(el) ? el.href.baseVal : el.pathname + el.search + (el.hash || '');
path = path[0] !== '/' ? `/${path}` : path;
const orig = path;
const pageBase = this.getBase();
if (path.indexOf(pageBase) === 0) {
path = path.slice(this.getBase().length);
}
if (pageBase && orig === path) return;
e.preventDefault();
this.show(orig);
};
private readonly onpopstate = (e: PopStateEvent) => {
if (e.state) {
this.replace(e.state.path, { state: e.state });
} else {
this.show(location.pathname + location.hash, { push: false });
}
};
show(
this: this,
path: string,
{ state, dispatch = true, push = true, reload = false }: { state?: State; dispatch?: boolean; push?: boolean; reload?: boolean } = {},
) {
if (!path || (!reload && this.current === path)) return;
const pathParts = path.split('?');
pathParts[0] = pathParts[0].replace(/\/\/+/g, '/');
path = pathParts.join('?');
const ctx = new Context(this, path, state);
this.current = ctx.path;
if (dispatch) this.dispatch(ctx);
if (push) ctx.pushState();
}
replace(this: this, path: string, { state, dispatch = true }: { state?: State; dispatch?: boolean } = {}) {
if (!path || this.current === path) return;
const pathParts = path.split('?');
pathParts[0] = pathParts[0].replace(/\/\/+/g, '/');
path = pathParts.join('?');
const ctx = new Context(this, path, state);
this.current = ctx.path;
ctx.save(); // save before dispatching, which may redirect
if (dispatch) this.dispatch(ctx);
}
dispatch(ctx: Context) {
let i = 0;
const nextEnter = () => {
const route = this.routes[i++];
if (ctx.path !== this.current) return;
if (!route) return this.unhandled(ctx);
route.callback(ctx, nextEnter);
};
nextEnter();
}
private unhandled(ctx: Context) {
const current = location.pathname + location.search;
if (current === ctx.canonicalPath) return;
this.stop();
location.href = ctx.canonicalPath;
}
private base = '';
getBase() {
return this.base;
}
setBase(path: string) {
this.base = path;
}
readonly Context = Context;
}
function decodeURLEncodedURIComponent(val: string): string {
if (typeof val !== 'string') return val;
return decodeURIComponent(val.replace(/\+/g, ' '));
}