diff --git a/src/index.test.ts b/src/index.test.ts index 5d386cb..cba91b3 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -104,9 +104,9 @@ describe("node-version", () => { expect(typeof v.build).toBe("string"); }); - test("object should have exactly 16 properties", () => { - expect(Object.keys(version)).toHaveLength(16); - expect(Object.keys(getVersion())).toHaveLength(16); + test("object should have exactly 17 properties (including toJSON)", () => { + expect(Object.keys(version)).toHaveLength(17); + expect(Object.keys(getVersion())).toHaveLength(17); }); test("original property should start with v", () => { @@ -139,6 +139,25 @@ describe("node-version", () => { expect(String(version)).toBe(version.original); }); + test("toJSON should return pure object representation", () => { + const v = getVersion(); + const json = v.toJSON(); + + expect(json).toHaveProperty("original"); + expect(json).toHaveProperty("major"); + // Ensure functions are stripped + expect(json).not.toHaveProperty("isAtLeast"); + expect(json).not.toHaveProperty("toJSON"); + + // Verify round-trip via JSON.stringify + const str = JSON.stringify(v); + const parsed = JSON.parse(str); + expect(parsed.original).toBe(v.original); + expect(parsed.major).toBe(v.major); + // Functions should be missing in parsed object + expect(parsed.isAtLeast).toBeUndefined(); + }); + describe("robustness", () => { test("should handle malformed version string", () => { mockVersion.node = "10"; diff --git a/src/index.ts b/src/index.ts index 625ca80..98d21e1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -82,13 +82,21 @@ export const getVersion = (): NodeVersion => { return 0; }; - return { + const versionObject = { original: `v${nodeVersion}`, short: `${split[0] || "0"}.${split[1] || "0"}`, long: nodeVersion, major: major, minor: split[1] || "0", build: split[2] || "0", + isLTS: !!release.lts, + ltsName: String(release.lts || "") || undefined, + isEOL: checkEOL(major), + eolDate: eolString ? new Date(eolString) : undefined, + }; + + return { + ...versionObject, isAtLeast: (version: string): boolean => { return compareTo(version) >= 0; }, @@ -104,11 +112,8 @@ export const getVersion = (): NodeVersion => { isAtMost: (version: string): boolean => { return compareTo(version) <= 0; }, - isLTS: !!release.lts, - ltsName: String(release.lts || "") || undefined, - isEOL: checkEOL(major), - eolDate: eolString ? new Date(eolString) : undefined, toString: () => `v${nodeVersion}`, + toJSON: () => versionObject, }; }; diff --git a/src/types.ts b/src/types.ts index 4de0667..9cb9375 100644 --- a/src/types.ts +++ b/src/types.ts @@ -97,4 +97,9 @@ export interface NodeVersion { * Returns the original version string. */ toString(): string; + /** + * Returns a JSON representation of the version object. + * This method allows `JSON.stringify(version)` to work correctly. + */ + toJSON(): Omit; }