Skip to content

Commit

Permalink
Guard against invalid JSON in "truthy" util
Browse files Browse the repository at this point in the history
Fixes #938
  • Loading branch information
allanlasser committed Dec 4, 2024
1 parent ba7cba2 commit abc8534
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/lib/utils/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,24 @@ export function getEmbedSettings(searchParams: URLSearchParams): EmbedSettings {
return embedSettings;
}

function truthy(
export function truthy(
value: string | number | boolean | null | undefined,
): boolean | number {
if (value === undefined) return false;
if (value === null) return false;

if (typeof value === "boolean") return value;
if (typeof value === "number") return value;
if (typeof value === "string") return JSON.parse(value);
if (typeof value === "string") {
try {
const jsonValue = JSON.parse(value);
if (typeof jsonValue === "boolean") return jsonValue;
if (typeof jsonValue === "number") return jsonValue;
return true;
} catch {
return false;
}
}

return false;
}
Expand Down
32 changes: 32 additions & 0 deletions src/lib/utils/tests/embed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
defaultSettings,
isEmbed,
reroute,
truthy,
} from "../embed";

describe("embed settings", () => {
Expand Down Expand Up @@ -78,3 +79,34 @@ describe("embed utilities", () => {
}
});
});

test("truthy", () => {
// Test undefined
expect(truthy(undefined)).toBe(false);

// Test null
expect(truthy(null)).toBe(false);

// Test boolean inputs
expect(truthy(true)).toBe(true);
expect(truthy(false)).toBe(false);

// Test number inputs
expect(truthy(1)).toBe(1);
expect(truthy(0)).toBe(0);

// Test string inputs for boolean values
expect(truthy("true")).toBe(true);
expect(truthy("false")).toBe(false);

// Test string inputs for number values
expect(truthy("1")).toBe(1);
expect(truthy("0")).toBe(0);

// Test JSON parsing
expect(truthy('{"key": "value"}')).toEqual(true);
expect(truthy("[1, 2, 3]")).toEqual(true);

// Test invalid JSON string
expect(truthy("invalid")).toBe(false);
});

0 comments on commit abc8534

Please sign in to comment.