From 4902ed2177d1592714c823fe7830279d743b7850 Mon Sep 17 00:00:00 2001 From: Rayan-and-beyond <263488867+Rayan-and-beyond@users.noreply.github.com> Date: Tue, 15 Sep 2026 19:02:36 +0000 Subject: [PATCH] fix: validate analyze options --- src/index.mjs | 2 ++ test/basic.test.mjs | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/src/index.mjs b/src/index.mjs index ecb07e4..564aa36 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -56,6 +56,8 @@ function units(payload) { // Report the token breakdown of a payload and where the tokens are going. export function analyzePayload(payload, { pricePerMTok = 3, counter = estimateTokens, top = 10 } = {}) { + requireNonNegativeNumber("pricePerMTok", pricePerMTok); + requireNonNegativeNumber("top", top, { integer: true }); const us = units(payload).map((u) => ({ ...u, tokens: counter(u.text) })); const total = us.reduce((a, u) => a + u.tokens, 0); const byKind = {}, byRole = {}; diff --git a/test/basic.test.mjs b/test/basic.test.mjs index 5c4158f..3278c8d 100644 --- a/test/basic.test.mjs +++ b/test/basic.test.mjs @@ -172,3 +172,10 @@ test("units rejects non-array payload.messages with TypeError", () => { { name: "TypeError", message: /payload\.messages must be an array/ }, ); }); + +test("analyzePayload validates pricePerMTok and top", () => { + const payload = { messages: [{ role: "user", content: "hello" }] }; + assert.throws(() => analyzePayload(payload, { pricePerMTok: -5 }), RangeError); + assert.throws(() => analyzePayload(payload, { top: -1 }), RangeError); + assert.throws(() => analyzePayload(payload, { top: 1.5 }), RangeError); +});