From c404c67f0e1b6d30028f6ad10a02c310b5456930 Mon Sep 17 00:00:00 2001 From: shaurya703 Date: Fri, 14 Aug 2026 12:27:10 +0530 Subject: [PATCH] fix: return undefined from getPrefix/parseId for non-string input --- CHANGELOG.md | 4 ++++ src/utils/validate.ts | 2 ++ test/validate.test.ts | 14 ++++++++++++++ 3 files changed, 20 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22dd339..5e88ca9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- `getPrefix(value, separator?)` and `parseId(value, separator?)` now return `undefined` for non-string input instead of throwing, matching `isId` and `getTimestamp`. + ## [1.1.0] - 2026-08-16 ### Added diff --git a/src/utils/validate.ts b/src/utils/validate.ts index b864bec..66a2e16 100644 --- a/src/utils/validate.ts +++ b/src/utils/validate.ts @@ -22,6 +22,7 @@ export function getPrefix( value: string, separator: string = DEFAULT_SEPARATOR, ): string | undefined { + if (typeof value !== "string") return undefined; const index = value.indexOf(separator); return index > 0 ? value.slice(0, index) : undefined; } @@ -30,6 +31,7 @@ export function parseId( value: string, separator: string = DEFAULT_SEPARATOR, ): { prefix: string; id: string } | undefined { + if (typeof value !== "string") return undefined; const index = value.indexOf(separator); if (index > 0) { return { diff --git a/test/validate.test.ts b/test/validate.test.ts index 4fa98ee..fe911fe 100644 --- a/test/validate.test.ts +++ b/test/validate.test.ts @@ -54,6 +54,13 @@ describe("getPrefix()", () => { it("supports a custom separator", () => { expect(getPrefix("user.abc", ".")).toBe("user"); }); + + it("returns undefined for non-strings", () => { + expect(getPrefix(null as unknown as string)).toBeUndefined(); + expect(getPrefix(undefined as unknown as string)).toBeUndefined(); + expect(getPrefix(42 as unknown as string)).toBeUndefined(); + expect(getPrefix({} as unknown as string)).toBeUndefined(); + }); }); describe("parseId()", () => { @@ -72,4 +79,11 @@ describe("parseId()", () => { it("supports a custom separator", () => { expect(parseId("user.abc", ".")).toEqual({ prefix: "user", id: "abc" }); }); + + it("returns undefined for non-strings", () => { + expect(parseId(null as unknown as string)).toBeUndefined(); + expect(parseId(undefined as unknown as string)).toBeUndefined(); + expect(parseId(42 as unknown as string)).toBeUndefined(); + expect(parseId({} as unknown as string)).toBeUndefined(); + }); });