All files / src/components/detail useResourceId.ts

100% Statements 12/12
75% Branches 3/4
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 43 44 45 46 47 48 49 50 51                                                          199x 196x 196x 196x       5x         1096x     449x 449x 449x        
import { useMemo } from "react";
import { useParams } from "react-router-dom";
 
/**
 * Decode a base64 resource id out of the route.
 *
 * fe-core puts ids in the URL base64-encoded (`btoa` on the way in, `atob`
 * on the way out) and 40-odd pages each wrote `id ? atob(id) : ""`. Two
 * things were wrong with that:
 *
 * 1. `atob` **throws** on input that is not valid base64. A hand-typed URL,
 *    a stale bookmark, or a navigation that forgot to encode the id takes
 *    the whole page down with an uncaught `InvalidCharacterError` rather
 *    than showing "not found". `GenerativeSetup.tsx` hit exactly this and
 *    worked around it at the call site; every other route stayed exposed.
 * 2. The empty case was spelled `""` on some pages and `null` on others, so
 *    `enabled: !!id` guards behaved subtly differently across the app.
 *
 * Decoding here returns `null` for both "absent" and "unreadable", which is
 * the only distinction a viewer page actually acts on.
 *
 * ```tsx
 * const agentId = useResourceId("agentId");
 * const { data } = useQuery({ ..., enabled: !!agentId });
 * ```
 */
export function decodeResourceId(
  encoded: string | undefined | null,
): string | null {
  if (!encoded) return null;
  try {
    const decoded = atob(encoded);
    return decoded || null;
  } catch {
    // Not base64 — a malformed or hand-edited URL. The caller renders its
    // not-found state, which is what the user should see either way.
    return null;
  }
}
 
/** Encode an id for a route param. The inverse of {@link decodeResourceId}. */
export const encodeResourceId = (id: string): string => btoa(id);
 
export function useResourceId(param: string): string | null {
  const params = useParams();
  const raw = params[param];
  return useMemo(() => decodeResourceId(raw), [raw]);
}
 
export default useResourceId;