all repos — kitten @ b219fb2f774165981101cc0bf3ba30e9fd84fa65

pkgs/types/src/lib/router.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
import { RouteNode } from "./types";
import { toCamelCase, toPascalCase } from "./utils";
import { ComponentRegistry } from "./registry";

export function parseToRouteTree(
	pathsObj: Record<string, unknown>,
	registry: ComponentRegistry,
): Record<string, RouteNode> {
	const root: Record<string, RouteNode> = {};

	for (const [path, data] of Object.entries(pathsObj)) {
		const parts = path.split("/").filter(Boolean);
		let currentChildren = root;
		let lastNode: RouteNode | null = null;

		for (const part of parts) {
			if (part.startsWith("{") && part.endsWith("}")) {
				const paramRaw = part.slice(1, -1);

				if (lastNode) {
					lastNode.params = {
						name: toCamelCase(paramRaw),
						type: paramRaw.endsWith("_id")
							? toPascalCase(paramRaw.slice(0, -3)) + "Snowflake"
							: toPascalCase(paramRaw),
					};
				}
			} else {
				const name = toCamelCase(part.startsWith("@") ? part.slice(1) : part);
				if (!currentChildren[name]) {
					currentChildren[name] = { name, children: {} };
				}
				lastNode = currentChildren[name];
				if (lastNode.children) currentChildren = lastNode.children;
			}
		}

		if (lastNode) lastNode.data = registry.resolveDeep(data);
	}

	return root;
}