The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Pages: copy works on plain-http LANs, workflows filter and page, clips that fail let go
Claudeee358784b124
diff --git a/src/app/(studio)/apps/[id]/page.tsx b/src/app/(studio)/apps/[id]/page.tsxindex e3b71b80..80f7ca03 100644--- a/src/app/(studio)/apps/[id]/page.tsx+++ b/src/app/(studio)/apps/[id]/page.tsx@@ -11,7 +11,8 @@ export function generateStaticParams() {export async function generateMetadata({ params }: PageProps<"/apps/[id]">): Promise<Metadata> {const { id } = await params;- return { title: getPreset(id)?.name ?? "App" };+ const preset = getPreset(id);+ return { title: preset?.type === "app" ? preset.name : "Not found" };}async function AppStudio({ params }: { params: PageProps<"/apps/[id]">["params"] }) {diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsxindex bda91b9c..65f8999f 100644--- a/src/components/color-grade-view.tsx+++ b/src/components/color-grade-view.tsx@@ -12,6 +12,7 @@ import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";import { uploadFile } from "@/lib/api";import { applyPreset, CONTROLS, describeGrade, FRAGMENT, isNeutral, NEUTRAL, PRESETS, uniforms, VERTEX, type Grade } from "@/lib/grade";import { cn } from "@/lib/utils";+import { loseContext as loseGlContext, releaseVideo } from "@/lib/media-release";type Source = HTMLImageElement | HTMLVideoElement;@@ -97,7 +98,12 @@ function loadSource(url: string, kind: "image" | "video"): Promise<Source> {v.muted = true;v.playsInline = true;v.onloadeddata = () => resolve(v);- v.onerror = () => reject(new Error("Couldn't load the video"));+ v.onerror = () => {+ // A clip this browser can't decode (HEVC .mov, a broken file): let go of it right away.+ v.onerror = null;+ releaseVideo(v);+ reject(new Error("Couldn't play that video here — try an MP4 (H.264) or WebM file"));+ };return;}const img = new Image();@@ -112,15 +118,12 @@ const dims = (s: Source) => (s instanceof HTMLVideoElement ? [s.videoWidth, s.vi/** Stop a detached video for good (it would keep decoding after the page or the clip changes). */function release(s: Source | null | undefined) {- if (!(s instanceof HTMLVideoElement)) return;- s.pause();- s.removeAttribute("src");- s.load();+ if (s instanceof HTMLVideoElement) releaseVideo(s);}/** Free a WebGL context now instead of waiting for garbage collection (browsers cap live contexts). */function loseContext(r: GradeRenderer | null | undefined) {- r?.gl.getExtension("WEBGL_lose_context")?.loseContext();+ loseGlContext(r?.gl);}/** Bundled still the looks are previewed on before anything is loaded. */@@ -164,7 +167,13 @@ function Grader() {setSource(s);if (s instanceof HTMLVideoElement) void s.play().catch(() => {});},- (e) => !cancelled && toast.error((e as Error).message),+ (e) => {+ if (cancelled) return;+ toast.error((e as Error).message);+ // Back to the empty stage (upload slots, sample photo) instead of a spinner that never ends.+ setSource(null);+ setInput(null);+ },);return () => {cancelled = true;diff --git a/src/components/element-studio.tsx b/src/components/element-studio.tsxindex 022927f9..53a29dba 100644--- a/src/components/element-studio.tsx+++ b/src/components/element-studio.tsx@@ -77,7 +77,13 @@ export function ElementStudio({ id }: { id: string }) {header={<>{el.kind !== "voice" && (- <Button variant={el.loras.length ? "ghost" : "secondary"} size="sm" onClick={() => setTraining(true)}>+ <Button+ variant={el.loras.length ? "ghost" : "secondary"}+ size="sm"+ onClick={() => setTraining(true)}+ // The label is hidden on phones.+ aria-label={el.status === "training" ? "Training…" : el.loras.length ? `Trained · ${el.loras.length}` : "Train"}+ >{el.status === "training" ? <Loader2 className="animate-spin" /> : <GraduationCap />}<span className="hidden sm:inline">{el.status === "training" ? "Training…" : el.loras.length ? `Trained · ${el.loras.length}` : "Train"}</span></Button>diff --git a/src/components/elements-view.tsx b/src/components/elements-view.tsxindex ab31236b..2a9147c2 100644--- a/src/components/elements-view.tsx+++ b/src/components/elements-view.tsx@@ -29,6 +29,7 @@ import { ELEMENT_ICONS } from "@/components/studio/prompt-input";import { VoiceRecorder } from "@/components/studio/voice-recorder";import { useDeleteElement, useElements, useSaveElement } from "@/lib/api";import { ELEMENT_KINDS, elementKindInfo, handleFor, type ElementKind, type StudioElement } from "@/lib/catalog/elements";+import { copyText } from "@/lib/clipboard";import { cn } from "@/lib/utils";const TIPS: Record<ElementKind, string> = {@@ -229,9 +230,9 @@ function HandleCopy({ handle }: { handle: string }) {const [done, setDone] = useState(false);return (<button- onClick={(e) => {+ onClick={async (e) => {e.preventDefault();- void navigator.clipboard?.writeText(`@${handle}`);+ if (!(await copyText(`@${handle}`))) return void toast.error("Couldn’t copy — select the handle instead");setDone(true);setTimeout(() => setDone(false), 1200);}}@@ -254,7 +255,7 @@ function ElementCard({ el }: { el: StudioElement }) {{el.references[0] && <audio src={el.references[0]} controls className="w-full" />}</div>) : (- <Link href={`/elements/${el.id}`} className="block">+ <Link href={`/elements/${el.id}`} className="block" aria-label={`Open ${el.name}`}><div className="grid aspect-square grid-cols-2 grid-rows-2 gap-0.5 bg-muted">{el.references.length ? (el.references.slice(0, 4).map((r, i, arr) => (diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 7d41c37c..e99894d5 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -8,6 +8,7 @@ import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { copyText } from "@/lib/clipboard";import { timeAgo } from "@/lib/format";interface TokenInfo {@@ -23,6 +24,12 @@ interface AuthStatus {tokens: TokenInfo[];}+/** Copy and say whether it worked (plain-http LAN origins have no Clipboard API; copyText falls back). */+async function copyWithToast(text: string) {+ if (await copyText(text)) toast("Copied");+ else toast.error("Couldn’t copy — select the text and copy it instead");+}+async function call<T>(url: string, method: string, body?: unknown): Promise<T> {const res = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });if (res.status === 204) return undefined as T;@@ -98,10 +105,8 @@ function McpSnippet({ token, needsToken }: { token: string | null; needsToken: b<div className="flex items-center gap-2 rounded-lg bg-muted px-2.5 py-2"><code className="min-w-0 flex-1 overflow-x-auto font-mono text-[11px] whitespace-nowrap">{cmd}</code><button- onClick={() => {- void navigator.clipboard.writeText(cmd);- toast("Copied");- }}+ type="button"+ onClick={() => void copyWithToast(cmd)}className="grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground"aria-label="Copy command">@@ -140,15 +145,11 @@ function Tokens({ status, onChange }: { status: AuthStatus; onChange: () => void<div className="rounded-xl border border-primary/40 bg-brand-faint p-3"><p className="text-[12px] font-medium">Copy this token now — it won't be shown again.</p><div className="mt-2 flex items-center gap-2">- <code className="min-w-0 flex-1 truncate rounded-md bg-background px-2 py-1.5 font-mono text-[12px]">{fresh}</code>- <Button- size="sm"- variant="secondary"- onClick={() => {- void navigator.clipboard.writeText(fresh);- toast("Copied");- }}- >+ {/* The whole token, wrapped (a phone can't show it on one line); one tap selects it all. */}+ <code aria-label="New API token" className="min-w-0 flex-1 rounded-md bg-background px-2 py-1.5 font-mono text-[12px] break-all select-all">+ {fresh}+ </code>+ <Button size="sm" variant="secondary" className="shrink-0" onClick={() => void copyWithToast(fresh)}><Copy /> Copy</Button></div>diff --git a/src/components/settings-form.tsx b/src/components/settings-form.tsxindex 34ad1f6a..f2f72787 100644--- a/src/components/settings-form.tsx+++ b/src/components/settings-form.tsx@@ -2,7 +2,7 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { CheckCircle2, CircleAlert, Cloud, Cpu, ExternalLink, Layers, Loader2 } from "lucide-react";-import { useId, useState } from "react";+import { useEffect, useId, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -218,6 +218,13 @@ export function SettingsForm() {});const get = (n: string) => settings.data?.find((s) => s.name === n);const set = (n: string) => (v: string) => save.mutate({ [n]: v });+ // Deep links (/settings#comfyui) arrive while the form is still a skeleton, so the browser finds+ // no anchor: scroll to it once the sections exist.+ const loaded = !settings.isLoading;+ useEffect(() => {+ if (!loaded || !window.location.hash) return;+ document.getElementById(decodeURIComponent(window.location.hash.slice(1)))?.scrollIntoView({ block: "start" });+ }, [loaded]);if (settings.isLoading)return (diff --git a/src/components/workflows-view.tsx b/src/components/workflows-view.tsxindex eb4bbf5f..8bd31856 100644--- a/src/components/workflows-view.tsx+++ b/src/components/workflows-view.tsx@@ -3,13 +3,16 @@import { useQuery } from "@tanstack/react-query";import { CheckCircle2, Circle, CircleAlert, Copy, ExternalLink, RotateCcw, Search, Workflow } from "lucide-react";import Link from "next/link";-import { useDeferredValue, useMemo, useState } from "react";+import { useDeferredValue, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Skeleton } from "@/components/ui/skeleton";+import { useProgressive } from "@/components/use-progressive";+import { copyText } from "@/lib/clipboard";import type { ManifestWorkflow } from "@/lib/comfy";import { cn } from "@/lib/utils";+import { capabilityGroup, usedByIndex, WORKFLOW_GROUPS, type ComfyRoute } from "@/lib/workflow-usage";type WF = Omit<ManifestWorkflow, "models"> & { models: (ManifestWorkflow["models"][number] & { present: boolean | null })[] };@@ -20,12 +23,6 @@ interface ComfyStatus {workflows: WF[];}-/** An open model's ComfyUI route, from the catalog on the server ("video-concat-{n}" style endpoints match by pattern). */-export interface ComfyRoute {- endpoint: string;- name: string;-}-function downloadScript(wf: WF): string {const lines = wf.models.filter((m) => m.url && m.present !== true)@@ -34,16 +31,6 @@ function downloadScript(wf: WF): string {return ["COMFYUI=${COMFYUI:-$HOME/ComfyUI}", ...nodes, ...lines].join("\n");}-export function usedByIndex(routes: ComfyRoute[]) {- const exact = new Map<string, string[]>();- const patterns: { re: RegExp; name: string }[] = [];- for (const r of routes) {- if (r.endpoint.includes("{n}")) patterns.push({ re: new RegExp(`^${r.endpoint.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace("{n}", "\\d")}$`), name: r.name });- else exact.set(r.endpoint, [...(exact.get(r.endpoint) ?? []), r.name]);- }- return (id: string) => [...new Set([...(exact.get(id) ?? []), ...patterns.filter((p) => p.re.test(id)).map((p) => p.name)])];-}-async function fetchStatus(): Promise<ComfyStatus> {const res = await fetch("/api/comfyui");const body = (await res.json().catch(() => ({}))) as Partial<ComfyStatus> & { error?: string };@@ -58,7 +45,7 @@ function WorkflowCard({ wf, usedBy }: { wf: WF; usedBy: string[] }) {<article className="flex min-w-0 flex-col gap-3 rounded-xl border bg-background p-4"><div className="flex flex-wrap items-start justify-between gap-2"><div className="min-w-0 flex-1 basis-48">- <h3 className="font-medium break-words">{wf.title}</h3>+ <h2 className="font-medium break-words">{wf.title}</h2><p className="font-mono text-[11px] break-all text-muted-foreground">{wf.id}</p></div><div className="flex shrink-0 gap-1">@@ -118,9 +105,9 @@ function WorkflowCard({ wf, usedBy }: { wf: WF; usedBy: string[] }) {variant="secondary"size="sm"className="max-w-full"- onClick={() => {- void navigator.clipboard.writeText(downloadScript(wf));- toast("Install commands copied");+ onClick={async () => {+ if (await copyText(downloadScript(wf))) toast("Install commands copied");+ else toast.error("Couldn’t copy — your browser blocked the clipboard");}}><Copy /> <span className="truncate">{missing ? `Copy install commands (${missing} missing)` : "Copy install commands"}</span>@@ -133,13 +120,28 @@ function WorkflowCard({ wf, usedBy }: { wf: WF; usedBy: string[] }) {export function WorkflowsView({ routes = [] }: { routes?: ComfyRoute[] }) {const q = useQuery({ queryKey: ["comfyui"], queryFn: fetchStatus });const [search, setSearch] = useState("");+ const [cap, setCap] = useState("All");const term = useDeferredValue(search.trim().toLowerCase());const usedBy = useMemo(() => usedByIndex(routes), [routes]);const workflows = useMemo(() => q.data?.workflows ?? [], [q.data]);+ // Filter chips by what a workflow makes (Image, Video, Audio, Text & 3D), with counts.+ const caps = useMemo(() => {+ const n = new Map<string, number>();+ for (const w of workflows) n.set(capabilityGroup(w.capability), (n.get(capabilityGroup(w.capability)) ?? 0) + 1);+ return [["All", workflows.length] as const, ...WORKFLOW_GROUPS.filter((g) => n.has(g)).map((g) => [g, n.get(g)!] as const)];+ }, [workflows]);const list = useMemo(- () => (term ? workflows.filter((w) => `${w.id} ${w.title} ${w.capability} ${usedBy(w.id).join(" ")}`.toLowerCase().includes(term)) : workflows),- [workflows, term, usedBy],+ () =>+ workflows.filter(+ (w) =>+ (cap === "All" || capabilityGroup(w.capability) === cap) &&+ (!term || `${w.id} ${w.title} ${w.capability} ${usedBy(w.id).join(" ")}`.toLowerCase().includes(term)),+ ),+ [workflows, term, cap, usedBy],);+ // 105 cards with model lists: render a page at a time.+ const { shown, hasMore, moreFrom, sentinel, left } = useProgressive(list.length, `${cap}|${term}`, 20, 30);+ const grid = useRef<HTMLDivElement>(null);if (q.isPending)return (@@ -191,21 +193,51 @@ export function WorkflowsView({ routes = [] }: { routes?: ComfyRoute[] }) {className="h-9 w-full rounded-full border bg-background pr-3 pl-9 text-[14px] outline-none placeholder:text-subtle-foreground focus:border-primary focus:ring-4 focus:ring-brand-faint"/></div>- <span className="text-[12px] text-muted-foreground tabular-nums sm:ml-auto">+ <span className="text-[12px] text-muted-foreground tabular-nums sm:ml-auto" aria-live="polite">{list.length === workflows.length ? `${workflows.length} workflows` : `${list.length} of ${workflows.length}`} · {validated} validated</span></div>)}+ {caps.length > 2 && (+ <div role="group" aria-label="What it makes" className="scrollbar-none -mx-1 flex gap-1 overflow-x-auto px-1">+ {caps.map(([c, n]) => (+ <button+ key={c}+ type="button"+ aria-pressed={cap === c}+ onClick={() => setCap(c)}+ className={cn(+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-3 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",+ cap === c && "bg-secondary text-foreground",+ )}+ >+ {c}+ <span className="text-[11px] text-subtle-foreground tabular-nums">{n}</span>+ </button>+ ))}+ </div>+ )}{!workflows.length ? (<p className="text-sm text-muted-foreground">No workflows in workflows/comfyui/manifest.json yet.</p>) : !list.length ? (- <p className="py-10 text-center text-sm text-muted-foreground">No workflows match “{search.trim()}”.</p>+ <p className="py-10 text-center text-sm text-muted-foreground">+ {term ? `No ${cap === "All" ? "" : `${cap} `}workflows match “${search.trim()}”.` : `No ${cap} workflows.`}+ </p>) : (- <div className="grid grid-cols-[minmax(0,1fr)] gap-3 lg:grid-cols-2">- {list.map((wf) => (- <WorkflowCard key={wf.id} wf={wf} usedBy={usedBy(wf.id)} />- ))}- </div>+ <>+ <div ref={grid} className="grid grid-cols-[minmax(0,1fr)] gap-3 lg:grid-cols-2">+ {list.slice(0, shown).map((wf) => (+ <WorkflowCard key={wf.id} wf={wf} usedBy={usedBy(wf.id)} />+ ))}+ </div>+ {hasMore && (+ <div className="flex justify-center">+ <Button ref={sentinel} variant="outline" size="sm" className="rounded-full" onClick={(e) => moreFrom(e, grid.current)}>+ Show more · {left} left+ </Button>+ </div>+ )}+ </>)}</div>);diff --git a/src/lib/api.ts b/src/lib/api.tsindex 0296bfdf..23134d0e 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -406,6 +406,8 @@ export function useElement(id: string) {return useQuery({queryKey: ["elements", id],queryFn: async () => json<StudioElement>(await fetch(`/api/elements/${id}`)),+ // An unknown element is a 404 page, not a network hiccup: don't retry it.+ retry: (n, e) => !/not found|\(404\)/i.test((e as Error).message) && n < 1,// Pick up the trained identity as soon as a training job finishes.refetchInterval: (q) => (q.state.data?.status === "training" ? 3000 : false),});diff --git a/src/lib/clipboard.ts b/src/lib/clipboard.tsnew file mode 100644index 00000000..adc8fb7a--- /dev/null+++ b/src/lib/clipboard.ts@@ -0,0 +1,38 @@+/**+ * Copy text to the clipboard, also where the Clipboard API is missing: a self-hosted Fuobe opened+ * over plain http on a LAN address is not a secure context, so `navigator.clipboard` is undefined+ * there. Falls back to selecting a hidden textarea and `document.execCommand("copy")`.+ * Resolves to whether the text was copied.+ */+export async function copyText(text: string): Promise<boolean> {+ try {+ if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch {+ // Permission denied or not focused: try the fallback.+ }+ return legacyCopy(text);+}++function legacyCopy(text: string): boolean {+ if (typeof document === "undefined") return false;+ const ta = document.createElement("textarea");+ ta.value = text;+ ta.setAttribute("readonly", "");+ // Off-screen but still selectable (display: none can't be selected).+ ta.style.cssText = "position:fixed;top:0;left:-9999px;opacity:0;pointer-events:none";+ const active = document.activeElement as HTMLElement | null;+ document.body.appendChild(ta);+ try {+ ta.select();+ ta.setSelectionRange(0, text.length);+ return document.execCommand("copy");+ } catch {+ return false;+ } finally {+ ta.remove();+ active?.focus?.();+ }+}diff --git a/src/lib/media-release.ts b/src/lib/media-release.tsnew file mode 100644index 00000000..dac328f0--- /dev/null+++ b/src/lib/media-release.ts@@ -0,0 +1,25 @@+/**+ * Letting go of media elements the page created itself (color grading's detached <video>s and+ * WebGL canvases). Browsers keep decoding a detached video until its src is gone, and cap the+ * number of live WebGL contexts, so both are released explicitly.+ */++/** The parts of HTMLVideoElement this needs (a fake in tests). */+export interface ReleasableVideo {+ pause(): void;+ removeAttribute(name: string): void;+ load(): void;+}++/** Stop a detached video for good: pause it, drop its source and reset the element. */+export function releaseVideo(v: ReleasableVideo | null | undefined): void {+ if (!v) return;+ v.pause();+ v.removeAttribute("src");+ v.load();+}++/** Free a WebGL context now instead of waiting for garbage collection. */+export function loseContext(gl: Pick<WebGLRenderingContext, "getExtension"> | null | undefined): void {+ (gl?.getExtension("WEBGL_lose_context") as { loseContext(): void } | null | undefined)?.loseContext();+}diff --git a/src/lib/studios.ts b/src/lib/studios.tsindex 75e1f871..f5f5407a 100644--- a/src/lib/studios.ts+++ b/src/lib/studios.ts@@ -228,13 +228,9 @@ export function appStudio(preset: Preset): StudioConfig {feature: `app:${preset.id}`,title: preset.name,hero: preset.description,- subtitle: [- preset.cloud ? `Cloud: ${getModel(preset.cloud.modelId)?.name}` : "No cloud version yet",- preset.open ? `Open source: ${getModel(preset.open.modelId)?.name}` : "No open-source version yet",- preset.parity,- ]- .filter(Boolean)- .join(" · "),+ // Which model runs it on each engine lives in the preset header's Details popover (U23); the+ // hero only says when an engine has no version, plus how the two versions differ.+ subtitle: [!preset.cloud ? "Open source only for now" : !preset.open ? "Cloud only for now" : undefined, preset.parity].filter(Boolean).join(" · "),placeholder: preset.promptPlaceholder ?? "Add details (optional)",kind,ops,diff --git a/src/lib/workflow-usage.ts b/src/lib/workflow-usage.tsnew file mode 100644index 00000000..c15911d0--- /dev/null+++ b/src/lib/workflow-usage.ts@@ -0,0 +1,44 @@+/**+ * Which open models run each ComfyUI workflow, for the Workflows page ("used by …"). Pure, so the+ * page computes routes on the server and the view only indexes them.+ */++import { OPERATION_OUTPUT, type MediaKind, type Operation } from "./catalog/types";++/** The filter chips on the Workflows page: what a workflow makes. */+export const WORKFLOW_GROUPS = ["Image", "Video", "Audio", "Text & 3D"] as const;+export type WorkflowGroup = (typeof WORKFLOW_GROUPS)[number];++const GROUP_OF: Record<MediaKind, WorkflowGroup> = { image: "Image", video: "Video", audio: "Audio", text: "Text & 3D", model3d: "Text & 3D" };++/** Which group a workflow's capability belongs to (its operation's output; a few capabilities aren't operations). */+export function capabilityGroup(capability: string): WorkflowGroup {+ const kind = OPERATION_OUTPUT[capability as Operation] as MediaKind | undefined;+ if (kind) return GROUP_OF[kind];+ if (/video|motion|vfx/.test(capability)) return "Video";+ if (/audio|voice|music|speech|sound/.test(capability)) return "Audio";+ if (/3d|text|transcri|caption/.test(capability)) return "Text & 3D";+ return "Image";+}++/** An open model's ComfyUI route, from the catalog on the server ("video-concat-{n}" style endpoints match by pattern). */+export interface ComfyRoute {+ endpoint: string;+ name: string;+}++const escapeRe = (s: string) => s.replace(/[.*+?^$()|[\]\\{}]/g, "\\$&");++/**+ * Index routes by workflow id. Endpoints with `{n}` (one workflow per clip count, e.g.+ * "video-concat-{n}") match any number in its place. Names are deduplicated, in route order.+ */+export function usedByIndex(routes: ComfyRoute[]): (workflowId: string) => string[] {+ const exact = new Map<string, string[]>();+ const patterns: { re: RegExp; name: string }[] = [];+ for (const r of routes) {+ if (r.endpoint.includes("{n}")) patterns.push({ re: new RegExp(`^${r.endpoint.split("{n}").map(escapeRe).join("\\d+")}$`), name: r.name });+ else exact.set(r.endpoint, [...(exact.get(r.endpoint) ?? []), r.name]);+ }+ return (id) => [...new Set([...(exact.get(id) ?? []), ...patterns.filter((p) => p.re.test(id)).map((p) => p.name)])];+}