History

Lint: replace try/catch, JSON.parse, and switch in streaming decode

Rhys Sullivan committed 4 months ago

Commit 4a4ef991 parent d0104a31 file · +21 −17Browse files

Unified · Split

packages/plugins/openapi/src/sdk/invoke.ts+21−17
@@ -1,4 +1,4 @@
1−import { Effect, Layer, Option, Stream } from "effect";
1+import { Effect, Exit, Layer, Option, Schema, Stream } from "effect";
22 import { HttpClient, HttpClientRequest } from "effect/unstable/http";
33 import type { ToolFileValue } from "@executor-js/sdk/core";
44
@@ -201,6 +201,8 @@ const isTextContentType = (ct: string | null | undefined): boolean => · 196 unmodified lines
201201 const isOctetStream = (ct: string | null | undefined): boolean =>
202202 normalizeContentType(ct) === "application/octet-stream";
203203
204+const decodeJsonLine = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
205+
204206 const parseStreamingJsonLines = (text: string, truncated: boolean): unknown => {
205207 const lines = text.split(/\r?\n/);
206208 let lastNonEmptyIndex = -1;
@@ -216,32 +218,34 @@ const parseStreamingJsonLines = (text: string, truncated: boolean): unknown => { · 9 unmodified lines
216218 for (let index = 0; index < lines.length; index++) {
217219 const line = lines[index];
218220 if (line === undefined || line.trim() === "") continue;
219− try {
220− rows.push(JSON.parse(line));
221− } catch {
222− if (truncated && index === lastNonEmptyIndex) continue;
223− return text;
221+ const parsed = decodeJsonLine(line);
222+ if (Exit.isSuccess(parsed)) {
223+ rows.push(parsed.value);
224+ continue;
224225 }
226+ // A trailing fragment cut mid-line by the byte/time cap is expected; any
227+ // other unparseable line means the body is not NDJSON after all.
228+ if (truncated && index === lastNonEmptyIndex) continue;
229+ return text;
225230 }
226231
227232 return rows;
228233 };
229234
235+const NDJSON_CONTENT_TYPES = new Set([
236+ "application/stream+json",
237+ "application/x-ndjson",
238+ "application/jsonl",
239+]);
240+
230241 const decodeStreamingResponseBody = (
231242 contentType: string | null,
232243 text: string,
233244 truncated: boolean,
234−): unknown => {
235− switch (normalizeContentType(contentType)) {
236− case "application/stream+json":
237− case "application/x-ndjson":
238− case "application/jsonl":
239− return parseStreamingJsonLines(text, truncated);
240− case "text/event-stream":
241− default:
242− return text;
243− }
244−};
245+): unknown =>
246+ NDJSON_CONTENT_TYPES.has(normalizeContentType(contentType))
247+ ? parseStreamingJsonLines(text, truncated)
248+ : text;
245249
246250 export const collectStreamingBody = (
247251 stream: Stream.Stream<Uint8Array, unknown, never>,