scan-router.js 9.06 KB
const fs = require("node:fs");
const traverse = require("@babel/traverse").default;

const {
	findProperty,
	locationOf,
	objectEntries,
	parseJavaScript,
	staticPrimitive,
} = require("./ast-utils");
const { relativePath, resolveView } = require("./path-utils");

function routeNodeId(authId) {
	return `route:${authId}`;
}

function addPermission(store, authNode, routeId, filePath, context) {
	if (!authNode || authNode.type !== "ObjectExpression") {
		return;
	}
	const authId = staticPrimitive(findProperty(authNode, "authId")?.value, context.constants);
	if (authId === null) {
		return;
	}
	const permissionId = `permission:${authId}`;
	const label = staticPrimitive(findProperty(authNode, "label")?.value, context.constants);
	const handle = staticPrimitive(findProperty(authNode, "handle")?.value, context.constants);
	store.addNode({
		id: permissionId,
		type: "permission",
		name: label || String(authId),
		path: filePath,
		meta: {
			authId: String(authId),
			handle: handle || null,
		},
	});
	store.addEdge({
		from: routeId,
		to: permissionId,
		type: "requiresPermission",
		evidence: locationOf(authNode, filePath),
	});
	if (context.currentRouterModuleId) {
		store.addEdge({
			from: context.currentRouterModuleId,
			to: permissionId,
			type: "declares",
			evidence: locationOf(authNode, filePath),
		});
	}

	const linkedRoutes = findProperty(authNode, "addRoutePath")?.value;
	if (linkedRoutes?.type === "ArrayExpression") {
		for (const item of linkedRoutes.elements) {
			const linkedAuthId = staticPrimitive(findProperty(item, "authId")?.value, context.constants);
			const linkedName = staticPrimitive(findProperty(item, "name")?.value, context.constants);
			context.pendingRouteLinks.push({
				from: permissionId,
				authId: linkedAuthId === null ? null : String(linkedAuthId),
				name: linkedName,
				evidence: locationOf(item, filePath),
			});
		}
	}
}

function scanRouterFile(rootDir, filePath, store, context) {
	const source = fs.readFileSync(`${rootDir}/${filePath}`, "utf8");
	const sourceId = `module:${filePath}`;
	store.addNode({ id: sourceId, type: "module", name: filePath.split("/").pop(), path: filePath });
	context.currentRouterModuleId = sourceId;
	let ast;
	try {
		ast = parseJavaScript(source, filePath);
	} catch (error) {
		store.addUnresolved({
			kind: "parse",
			path: filePath,
			reason: error.reasonCode || "syntax-error",
			expressionKind: "Program",
		});
		return;
	}

	traverse(ast, {
		VariableDeclarator(path) {
			if (path.node.id.type === "Identifier") {
				const value = staticPrimitive(path.node.init, context.constants);
				if (value !== null) {
					context.constants.set(path.node.id.name, value);
				}
			}
			if (path.node.id.type !== "Identifier" || path.node.id.name !== "routerName") {
				return;
			}
			for (const routeEntry of objectEntries(path.node.init)) {
				const routeObject = routeEntry.value;
				if (routeObject.type !== "ObjectExpression") {
					continue;
				}
				const authId = String(routeEntry.name);
				const routeId = routeNodeId(authId);
				const routePath = staticPrimitive(findProperty(routeObject, "path")?.value, context.constants);
				const routeName = staticPrimitive(findProperty(routeObject, "name")?.value, context.constants);
				const metaNode = findProperty(routeObject, "meta")?.value;
				const title = staticPrimitive(findProperty(metaNode, "title")?.value, context.constants);
				const parentId = staticPrimitive(findProperty(metaNode, "parentId")?.value, context.constants);
				store.addNode({
					id: routeId,
					type: "route",
					name: routeName || title || authId,
					path: filePath,
					meta: {
						authId,
						parentId: parentId === null ? null : String(parentId),
						routeName,
						routePath,
						title,
					},
				});
				store.addEdge({
					from: sourceId,
					to: routeId,
					type: "declares",
					evidence: locationOf(routeEntry.node, filePath),
				});
				context.routesByAuthId.set(authId, routeId);
				if (routeName) {
					context.routesByName.set(String(routeName), routeId);
				}
				if (routePath) {
					context.routesByPath.set(String(routePath), routeId);
				}

				const domainId = filePath.match(/modules\/(\d+)_/)?.[1];
				if (domainId) {
					store.addEdge({
						from: `domain:${domainId}`,
						to: routeId,
						type: "contains",
						evidence: locationOf(routeEntry.node, filePath),
					});
				}
				if (parentId !== null && context.routesByAuthId.has(String(parentId))) {
					store.addEdge({
						from: context.routesByAuthId.get(String(parentId)),
						to: routeId,
						type: "contains",
						evidence: locationOf(metaNode, filePath),
					});
				}

				const componentCall = findProperty(routeObject, "component")?.value;
				if (componentCall?.type === "CallExpression") {
					const importPath = staticPrimitive(componentCall.arguments[0], context.constants);
					if (typeof importPath === "string") {
						const absoluteView = resolveView(rootDir, importPath);
						if (absoluteView) {
							const viewPath = relativePath(rootDir, absoluteView);
							context.routeViewPaths.add(viewPath);
							store.addNode({
								id: `view:${viewPath}`,
								type: "view",
								name: routeName || importPath,
								path: viewPath,
							});
							store.addEdge({
								from: routeId,
								to: `view:${viewPath}`,
								type: "renders",
								evidence: locationOf(componentCall, filePath),
							});
						}
					} else {
						store.addUnresolved({
							kind: "route-component",
							path: filePath,
							line: componentCall.loc?.start.line,
							column: componentCall.loc?.start.column,
							reason: "dynamic-expression",
							expressionKind: componentCall.arguments[0]?.type || "Unknown",
						});
					}
				}

				const authArray = findProperty(routeObject, "auth")?.value;
				if (authArray?.type === "ArrayExpression") {
					authArray.elements.forEach(authNode => addPermission(store, authNode, routeId, filePath, context));
				}
			}
		},
	});
	context.currentRouterModuleId = null;
}

function scanRouterInfrastructure(rootDir, filePath, store, context) {
	const source = fs.readFileSync(`${rootDir}/${filePath}`, "utf8");
	let ast;
	try {
		ast = parseJavaScript(source, filePath);
	} catch (error) {
		store.addUnresolved({
			kind: "parse",
			path: filePath,
			reason: error.reasonCode || "syntax-error",
			expressionKind: "Program",
		});
		return;
	}
	traverse(ast, {
		ObjectExpression(objectPath) {
			const routePath = staticPrimitive(findProperty(objectPath.node, "path")?.value, context.constants);
			const routeName = staticPrimitive(findProperty(objectPath.node, "name")?.value, context.constants);
			const componentCall = findProperty(objectPath.node, "component")?.value;
			if (typeof routePath !== "string" || typeof routeName !== "string" || !componentCall) {
				return;
			}
			const metaNode = findProperty(objectPath.node, "meta")?.value;
			const authId = staticPrimitive(findProperty(metaNode, "authId")?.value, context.constants);
			const routeId = authId === null ? `route:local:${routeName}` : routeNodeId(String(authId));
			store.addNode({
				id: routeId,
				type: "route",
				name: routeName,
				path: filePath,
				domainIds: authId === null ? [] : [String(authId).slice(0, 3)],
				meta: {
					authId: authId === null ? null : String(authId),
					parentId: null,
					routeName,
					routePath,
					title: staticPrimitive(findProperty(metaNode, "title")?.value, context.constants),
				},
			});
			context.routesByName.set(routeName, routeId);
			context.routesByPath.set(routePath, routeId);
			if (authId !== null) {
				context.routesByAuthId.set(String(authId), routeId);
			}
			const importPath = componentCall.type === "CallExpression"
				? staticPrimitive(componentCall.arguments[0], context.constants)
				: null;
			if (typeof importPath === "string") {
				const absoluteView = resolveView(rootDir, importPath);
				if (absoluteView) {
					const viewPath = relativePath(rootDir, absoluteView);
					context.routeViewPaths.add(viewPath);
					store.addNode({ id: `view:${viewPath}`, type: "view", name: routeName, path: viewPath });
					store.addEdge({
						from: routeId,
						to: `view:${viewPath}`,
						type: "renders",
						evidence: locationOf(componentCall, filePath),
					});
				}
			}
			const authArray = findProperty(objectPath.node, "auth")?.value;
			if (authArray?.type === "ArrayExpression") {
				authArray.elements.forEach(authNode => addPermission(store, authNode, routeId, filePath, context));
			}
			objectPath.skip();
		},
	});
}

function finalizeRouteLinks(store, context) {
	for (const link of context.pendingRouteLinks) {
		const target = (link.authId && context.routesByAuthId.get(link.authId))
			|| (link.name && context.routesByName.get(String(link.name)));
		if (target) {
			store.addEdge({
				from: link.from,
				to: target,
				type: "linksRoute",
				evidence: link.evidence,
			});
		} else {
			store.addUnresolved({
				kind: "route-link",
				path: link.evidence.path,
				line: link.evidence.line,
				column: link.evidence.column,
				reason: "missing-target",
				expressionKind: "addRoutePath",
			});
		}
	}
}

module.exports = {
	finalizeRouteLinks,
	routeNodeId,
	scanRouterInfrastructure,
	scanRouterFile,
};