@hilbras/sdk 4.0.2 → 4.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  </p>
4
4
 
5
5
  <p align="center">
6
- <img src="https://img.shields.io/badge/version-4.0.2-blue" alt="version">
6
+ <img src="https://img.shields.io/badge/version-4.0.3-blue" alt="version">
7
7
  <img src="https://img.shields.io/badge/license-MIT-green" alt="license">
8
8
  <img src="https://img.shields.io/badge/node-%3E%3D18-brightgreen" alt="node">
9
9
  <img src="https://img.shields.io/badge/types-strict-blueviolet" alt="types">
package/dist/index.d.ts CHANGED
@@ -31,8 +31,8 @@ export { zodSchema, jsonSchema } from "./output/schema-helpers.js";
31
31
  export { tool, toolDef, dynamicTool } from "./types/tool-builder.js";
32
32
  export type { DefinedTool, ToolDefinition, ParameterSchema } from "./types/tool-builder.js";
33
33
  export { generateId, createIdGenerator, shortId } from "./utils/id.js";
34
- export { parseSSEStream, parseJsonEventStream, collectSSEEvents, findSSEEvent } from "./utils/sse.js";
35
- export type { SSEEvent } from "./utils/sse.js";
34
+ export { parseSSEStream, parseJsonEventStream, collectSSEEvents, findSSEEvent, splitSseFrames, MAX_SSE_FRAME_BYTES, SseFrameTooLargeError, } from "./utils/sse.js";
35
+ export type { SSEEvent, ParseSSEOptions } from "./utils/sse.js";
36
36
  export { OpenTelemetryExporter } from "./telemetry/opentelemetry.js";
37
37
  export type { OpenTelemetryConfig } from "./telemetry/opentelemetry.js";
38
38
  export { StructuredLogger } from "./telemetry/structured-logger.js";
package/dist/index.js CHANGED
@@ -24,7 +24,7 @@ export { zodSchema, jsonSchema } from "./output/schema-helpers.js";
24
24
  export { tool, toolDef, dynamicTool } from "./types/tool-builder.js";
25
25
  // ─── Utilities ──────────────────────────────────────────────────────────────
26
26
  export { generateId, createIdGenerator, shortId } from "./utils/id.js";
27
- export { parseSSEStream, parseJsonEventStream, collectSSEEvents, findSSEEvent } from "./utils/sse.js";
27
+ export { parseSSEStream, parseJsonEventStream, collectSSEEvents, findSSEEvent, splitSseFrames, MAX_SSE_FRAME_BYTES, SseFrameTooLargeError, } from "./utils/sse.js";
28
28
  // ─── Telemetry (Production Observability) ───────────────────────────────────
29
29
  export { OpenTelemetryExporter } from "./telemetry/opentelemetry.js";
30
30
  export { StructuredLogger } from "./telemetry/structured-logger.js";
@@ -41,7 +41,15 @@ export interface SSEEvent {
41
41
  * }
42
42
  * }
43
43
  */
44
- export declare function parseSSEStream(stream: ReadableStream<Uint8Array>): AsyncGenerator<SSEEvent>;
44
+ export interface ParseSSEOptions {
45
+ /**
46
+ * Maximum bytes retained for a single unterminated frame.
47
+ * Defaults to {@link MAX_SSE_FRAME_BYTES} (1 MiB). Raise it for providers
48
+ * that legitimately emit very large single frames (e.g. inline media).
49
+ */
50
+ maxFrameBytes?: number;
51
+ }
52
+ export declare function parseSSEStream(stream: ReadableStream<Uint8Array>, options?: ParseSSEOptions): AsyncGenerator<SSEEvent>;
45
53
  /** One complete SSE event, in the shape the adapters consume. */
46
54
  export interface SseFrame {
47
55
  /** Concatenated `data:` payload, with the `data:` prefix removed. */
@@ -49,6 +57,22 @@ export interface SseFrame {
49
57
  /** `event:` field value, or "" when the event carried none. */
50
58
  event: string;
51
59
  }
60
+ /**
61
+ * Largest amount of unterminated SSE data we will buffer for a single frame.
62
+ *
63
+ * A frame is a line of JSON from the provider; real ones are kilobytes. The
64
+ * bound exists because a hostile or broken upstream can send one enormous
65
+ * line and never terminate it: without a cap the parser retains the whole
66
+ * response in memory and, because the retained buffer is rescanned on every
67
+ * chunk, parse time grows quadratically with response size.
68
+ */
69
+ export declare const MAX_SSE_FRAME_BYTES: number;
70
+ /** Error raised when a single SSE frame exceeds {@link MAX_SSE_FRAME_BYTES}. */
71
+ export declare class SseFrameTooLargeError extends Error {
72
+ readonly bytes: number;
73
+ readonly limit: number;
74
+ constructor(bytes: number, limit: number);
75
+ }
52
76
  /**
53
77
  * Append a decoded chunk to `buffer` and return the SSE events it completes,
54
78
  * advancing `buffer` past them.
@@ -57,8 +81,13 @@ export interface SseFrame {
57
81
  * three defects: CRLF framing never matched (a CRLF upstream produced nothing
58
82
  * and grew the buffer for the whole response), `data:` without a space was
59
83
  * rejected, and a `data:` payload split over several lines kept only the last.
84
+ *
85
+ * Scanning is incremental: only the region after the last emitted frame is
86
+ * examined, so feeding N bytes of well-framed events costs O(N) rather than
87
+ * re-splitting the retained buffer for every chunk. Unterminated data is
88
+ * bounded by {@link MAX_SSE_FRAME_BYTES} and fails closed beyond it.
60
89
  */
61
- export declare function splitSseFrames(buffer: string, chunk: string): {
90
+ export declare function splitSseFrames(buffer: string, chunk: string, maxFrameBytes?: number): {
62
91
  buffer: string;
63
92
  frames: SseFrame[];
64
93
  };
package/dist/utils/sse.js CHANGED
@@ -17,20 +17,8 @@
17
17
  * console.log(data); // parsed JSON object
18
18
  * }
19
19
  */
20
- /**
21
- * Parse a ReadableStream<Uint8Array> into SSE events.
22
- * Handles multi-line data fields and optional fields.
23
- *
24
- * @example
25
- * const events = parseSSEStream(response.body);
26
- * for await (const event of events) {
27
- * if (event.event === "message") {
28
- * const data = JSON.parse(event.data);
29
- * processMessage(data);
30
- * }
31
- * }
32
- */
33
- export async function* parseSSEStream(stream) {
20
+ export async function* parseSSEStream(stream, options = {}) {
21
+ const maxFrameBytes = options.maxFrameBytes ?? MAX_SSE_FRAME_BYTES;
34
22
  const reader = stream.getReader();
35
23
  const decoder = new TextDecoder();
36
24
  let buffer = "";
@@ -40,18 +28,26 @@ export async function* parseSSEStream(stream) {
40
28
  if (done)
41
29
  break;
42
30
  buffer += decoder.decode(value, { stream: true });
43
- // Accept CRLF framing as well as LF: `split("\n\n")` never matches a
44
- // `\r\n\r\n` boundary, so a CRLF upstream yielded no events at all while
45
- // the buffer grew for the whole response.
46
- const parts = buffer.split(/\r?\n\r?\n/);
47
- buffer = parts.pop() ?? "";
48
- for (const part of parts) {
49
- if (!part.trim())
31
+ // Scan incrementally for frame boundaries instead of re-splitting the
32
+ // whole retained buffer on every chunk (which cost O(n^2) over a
33
+ // response). CRLF, LF and CR-only boundaries are all recognised.
34
+ let start = 0;
35
+ for (;;) {
36
+ const sep = findFrameSeparator(buffer, start);
37
+ if (sep === -1)
38
+ break;
39
+ const block = buffer.slice(start, sep.start);
40
+ start = sep.end;
41
+ if (!block.trim())
50
42
  continue;
51
- const event = parseSSEBlock(part);
43
+ const event = parseSSEBlock(block);
52
44
  if (event)
53
45
  yield event;
54
46
  }
47
+ buffer = start === 0 ? buffer : buffer.slice(start);
48
+ if (buffer.length > maxFrameBytes) {
49
+ throw new SseFrameTooLargeError(buffer.length, maxFrameBytes);
50
+ }
55
51
  }
56
52
  // Process remaining buffer
57
53
  if (buffer.trim()) {
@@ -114,6 +110,28 @@ function splitFrame(block) {
114
110
  }
115
111
  return { data, event };
116
112
  }
113
+ /**
114
+ * Largest amount of unterminated SSE data we will buffer for a single frame.
115
+ *
116
+ * A frame is a line of JSON from the provider; real ones are kilobytes. The
117
+ * bound exists because a hostile or broken upstream can send one enormous
118
+ * line and never terminate it: without a cap the parser retains the whole
119
+ * response in memory and, because the retained buffer is rescanned on every
120
+ * chunk, parse time grows quadratically with response size.
121
+ */
122
+ export const MAX_SSE_FRAME_BYTES = 1 << 20; // 1 MiB
123
+ /** Error raised when a single SSE frame exceeds {@link MAX_SSE_FRAME_BYTES}. */
124
+ export class SseFrameTooLargeError extends Error {
125
+ bytes;
126
+ limit;
127
+ constructor(bytes, limit) {
128
+ super(`SSE frame exceeded ${limit} bytes without a terminator (${bytes} buffered); ` +
129
+ `the upstream stream is malformed or hostile`);
130
+ this.bytes = bytes;
131
+ this.limit = limit;
132
+ this.name = "SseFrameTooLargeError";
133
+ }
134
+ }
117
135
  /**
118
136
  * Append a decoded chunk to `buffer` and return the SSE events it completes,
119
137
  * advancing `buffer` past them.
@@ -122,18 +140,67 @@ function splitFrame(block) {
122
140
  * three defects: CRLF framing never matched (a CRLF upstream produced nothing
123
141
  * and grew the buffer for the whole response), `data:` without a space was
124
142
  * rejected, and a `data:` payload split over several lines kept only the last.
143
+ *
144
+ * Scanning is incremental: only the region after the last emitted frame is
145
+ * examined, so feeding N bytes of well-framed events costs O(N) rather than
146
+ * re-splitting the retained buffer for every chunk. Unterminated data is
147
+ * bounded by {@link MAX_SSE_FRAME_BYTES} and fails closed beyond it.
125
148
  */
126
- export function splitSseFrames(buffer, chunk) {
127
- const parts = (buffer + chunk).split(/\r?\n\r?\n/);
128
- const rest = parts.pop() ?? "";
149
+ export function splitSseFrames(buffer, chunk, maxFrameBytes = MAX_SSE_FRAME_BYTES) {
150
+ const combined = buffer + chunk;
129
151
  const frames = [];
130
- for (const part of parts) {
152
+ // Walk separators forwards with indexOf instead of split(), which would
153
+ // allocate a substring for every part of the retained buffer on each chunk.
154
+ let start = 0;
155
+ for (;;) {
156
+ const sep = findFrameSeparator(combined, start);
157
+ if (sep === -1)
158
+ break;
159
+ const part = combined.slice(start, sep.start);
160
+ start = sep.end;
131
161
  if (!part.trim())
132
162
  continue;
133
163
  frames.push(splitFrame(part));
134
164
  }
165
+ const rest = start === 0 ? combined : combined.slice(start);
166
+ if (rest.length > maxFrameBytes) {
167
+ throw new SseFrameTooLargeError(rest.length, maxFrameBytes);
168
+ }
135
169
  return { buffer: rest, frames };
136
170
  }
171
+ /**
172
+ * Length of the line break starting at `index`, or 0 if none starts there.
173
+ * Recognises `\r\n` (2), `\n` (1) and bare `\r` (1).
174
+ */
175
+ function lineBreakLength(text, index) {
176
+ const code = text.charCodeAt(index);
177
+ if (code === 13)
178
+ return text.charCodeAt(index + 1) === 10 ? 2 : 1;
179
+ if (code === 10)
180
+ return 1;
181
+ return 0;
182
+ }
183
+ /**
184
+ * Find the next blank-line frame separator at or after `from`.
185
+ *
186
+ * A frame ends at a line break immediately followed by another line break, so
187
+ * `\n\n`, `\r\n\r\n`, `\r\n\n`, `\n\r\n` and CR-only `\r\r` all terminate a
188
+ * frame. Matching on the pair (rather than a fixed literal) is what makes a
189
+ * CRLF upstream work; the previous `/\r?\n\r?\n/` split silently matched
190
+ * nothing for `\r\n\r\n` because `\r?\n\r?\n` consumed only one CRLF pair.
191
+ */
192
+ function findFrameSeparator(text, from) {
193
+ for (let i = from; i < text.length; i++) {
194
+ const first = lineBreakLength(text, i);
195
+ if (first === 0)
196
+ continue;
197
+ const second = lineBreakLength(text, i + first);
198
+ if (second === 0)
199
+ continue;
200
+ return { start: i, end: i + first + second };
201
+ }
202
+ return -1;
203
+ }
137
204
  /**
138
205
  * Parse SSE stream and auto-parse JSON data.
139
206
  * Yields parsed JSON objects for each event with JSON data.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hilbras/sdk",
3
- "version": "4.0.2",
3
+ "version": "4.0.3",
4
4
  "description": "Provider-agnostic LLM client SDK — streaming, tool calling, embeddings, image generation, speech synthesis, transcription, reranking, circuit breaker, retry, reasoning normalization, cost enforcement, structured output with schema validation, type-safe tool builder, and SSRF-safe provider registration. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",