feat(compliance): add resource metadata tab inside req find (#11187)

This commit is contained in:
Pedro Martín
2026-05-21 15:09:43 +02:00
committed by GitHub
parent e55d1d470e
commit dbbefd0558
14 changed files with 569 additions and 63 deletions
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vitest";
import { parseMetadata } from "./resource-metadata";
describe("parseMetadata", () => {
it("should return null for nullish or empty values", () => {
expect(parseMetadata(null)).toBeNull();
expect(parseMetadata(undefined)).toBeNull();
expect(parseMetadata("")).toBeNull();
});
it("should parse a JSON object string into an object", () => {
expect(parseMetadata('{"PkgName":"requests","Versions":["2.0"]}')).toEqual({
PkgName: "requests",
Versions: ["2.0"],
});
});
it("should return null when the string is not valid JSON", () => {
expect(parseMetadata("not-json")).toBeNull();
});
it("should return null when the JSON string is not an object", () => {
expect(parseMetadata("42")).toBeNull();
expect(parseMetadata('"plain string"')).toBeNull();
});
it("should return null when the JSON string is an array", () => {
expect(parseMetadata("[1,2,3]")).toBeNull();
expect(parseMetadata("[]")).toBeNull();
expect(parseMetadata('[{"PkgName":"requests"}]')).toBeNull();
});
it("should return null when the value is already an array", () => {
expect(
parseMetadata([1, 2, 3] as unknown as Record<string, unknown>),
).toBeNull();
});
it("should return the object as-is when already an object", () => {
const metadata = { VulnerabilityID: "CVE-2026-0001" };
expect(parseMetadata(metadata)).toBe(metadata);
});
});
+34
View File
@@ -0,0 +1,34 @@
/**
* Normalizes a resource `metadata` value into a plain object.
*
* The API stores resource metadata as a `TextField`, so it can arrive as a
* JSON string, an already-parsed object, or be empty. Returns `null` when the
* value is missing or not a JSON object so callers can render an empty state.
*/
export const parseMetadata = (
metadata: Record<string, unknown> | string | null | undefined,
): Record<string, unknown> | null => {
if (!metadata) return null;
if (typeof metadata === "string") {
try {
const parsed = JSON.parse(metadata);
return typeof parsed === "object" &&
parsed !== null &&
!Array.isArray(parsed)
? parsed
: null;
} catch {
return null;
}
}
// After the !metadata check above, metadata can only be a non-null object
// here (null was filtered, string was handled). Arrays are excluded too so
// the Record<string, unknown> return type stays honest.
if (typeof metadata === "object" && !Array.isArray(metadata)) {
return metadata as Record<string, unknown>;
}
return null;
};