llm-large-files 0.4.1 → 0.7.0
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/CHANGELOG.md +1400 -338
- package/README.md +217 -49
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1022 -138
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
package/src/plan.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { plural, sliceWhole, wellFormed } from "./text.js";
|
|
1
2
|
import type { Budget, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
|
|
2
3
|
|
|
3
4
|
/** Bytes kept free for document cards, the tool declarations, and JSON framing. */
|
|
@@ -84,28 +85,80 @@ export function outlineLines(outline: OutlineEntry[]): string[] {
|
|
|
84
85
|
return outline.map((entry) => `L${entry.line} ${" ".repeat(entry.level - top)}${entry.title}`);
|
|
85
86
|
}
|
|
86
87
|
|
|
88
|
+
/**
|
|
89
|
+
* What the model is told of a text file that was not valid UTF-8, or nothing: in which encoding
|
|
90
|
+
* it was read, so that it can say so when letters look wrong, or why it shows U+FFFD.
|
|
91
|
+
*/
|
|
92
|
+
function readingNote(meta: DocumentMeta, short: boolean): string | undefined {
|
|
93
|
+
const count = meta.replacedCharacters ?? 0;
|
|
94
|
+
const characters = `${count.toLocaleString("en-US")} ${count === 1 ? "character" : "characters"}`;
|
|
95
|
+
const were = count === 1 ? "was" : "were";
|
|
96
|
+
const show = count === 1 ? "shows" : "show";
|
|
97
|
+
if (meta.encoding) {
|
|
98
|
+
if (short) return `read as ${meta.encoding}${count ? `, ${characters} not valid in it, shown as �` : ""}`;
|
|
99
|
+
const read = `This file is not in UTF-8. Its text was read as ${meta.encoding}: if its letters look wrong, ask the user to save it as UTF-8.`;
|
|
100
|
+
// Bytes further on that the encoding does not have.
|
|
101
|
+
return count ? `${read} ${characters} of it ${were} not valid in ${meta.encoding}, and ${show} as �.` : read;
|
|
102
|
+
}
|
|
103
|
+
if (!count) return undefined;
|
|
104
|
+
return short ? `${characters} not valid UTF-8, shown as �` : `${characters} of this file ${were} not valid UTF-8, and ${show} as �.`;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Eight hex digits made from a document ID. The ID is made at random when the file is stored, so
|
|
109
|
+
* the file's own text cannot know them, and they are the same in every request: a provider's
|
|
110
|
+
* prompt cache still reuses the file.
|
|
111
|
+
*/
|
|
112
|
+
export function frameMark(id: string): string {
|
|
113
|
+
// FNV-1a, 32 bits.
|
|
114
|
+
let hash = 0x811c9dc5;
|
|
115
|
+
for (let index = 0; index < id.length; index++) hash = Math.imul(hash ^ id.charCodeAt(index), 0x01000193);
|
|
116
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A file sent whole, between two frame lines. Both carry a mark the file's text cannot hold, and
|
|
121
|
+
* the first one says that only the line with the mark ends the file: a line of the file such as
|
|
122
|
+
* "--- End attached file: report.txt ---", in whatever letters, cannot end it early and start a
|
|
123
|
+
* fake one. The uploader chooses the name with the text, so the mark comes before the name, the
|
|
124
|
+
* name is quoted, and the last line holds the mark alone: a name cannot name a mark of its own.
|
|
125
|
+
*/
|
|
87
126
|
export function renderInline(meta: DocumentMeta, text: string): string {
|
|
88
|
-
|
|
127
|
+
const mark = frameMark(meta.id);
|
|
128
|
+
const note = readingNote(meta, true);
|
|
129
|
+
return `--- Attached file [mark ${mark}]: ${JSON.stringify(meta.name)} (${meta.format}, ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${note ? `, ${note}` : ""}; it ends only at the line with mark ${mark}) ---\n${text}\n--- End attached file [mark ${mark}] ---`;
|
|
89
130
|
}
|
|
90
131
|
|
|
91
132
|
/** How many lines of a file its card shows. */
|
|
92
133
|
export const CARD_LINES = CARD_HEAD_LINES;
|
|
93
134
|
|
|
135
|
+
/**
|
|
136
|
+
* What a card says of a whole-document read: that it can have one ("offered"), that the file is
|
|
137
|
+
* too large for one ("too_large"), or nothing, when the tools have none ("not_offered").
|
|
138
|
+
*/
|
|
139
|
+
export type WholeRead = "offered" | "too_large" | "not_offered";
|
|
140
|
+
|
|
141
|
+
/** The line of a card that says how to read the file. */
|
|
142
|
+
const HOW_TO_READ: Record<WholeRead, string> = {
|
|
143
|
+
offered: "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.",
|
|
144
|
+
too_large: "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
|
|
145
|
+
not_offered: "This file is NOT in your context. Use the document tools to search it and to read line ranges.",
|
|
146
|
+
};
|
|
147
|
+
|
|
94
148
|
/**
|
|
95
149
|
* A compact stand-in for a document that is too large for the prompt. `head` is its first
|
|
96
150
|
* `CARD_LINES` lines, numbered. `viewable` adds a line saying that its pages can be looked at
|
|
97
|
-
* with `view_pages`. `
|
|
98
|
-
* the card then does not offer one.
|
|
151
|
+
* with `view_pages`. `wholeRead` says whether the card offers a whole-document read.
|
|
99
152
|
*/
|
|
100
|
-
export function renderCard(meta: DocumentMeta, head: string, viewable = false,
|
|
153
|
+
export function renderCard(meta: DocumentMeta, head: string, viewable = false, wholeRead: WholeRead = "offered"): string {
|
|
154
|
+
const note = readingNote(meta, false);
|
|
101
155
|
const out = [
|
|
102
156
|
`--- Large attached file: ${meta.name} ---`,
|
|
103
157
|
`document_id: ${meta.id}`,
|
|
104
|
-
`${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} lines${meta.pages ? ` · ${meta.pages} pages` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
|
|
105
|
-
|
|
106
|
-
? "This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it."
|
|
107
|
-
: "This file is NOT in your context. Use the document tools to search it and to read line ranges. It is too large to be analyzed whole.",
|
|
158
|
+
`${meta.format} · ${formatBytes(meta.bytes)} · ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${meta.pages ? ` · ${meta.pages} ${plural(meta.pages, "page")}` : ""} · about ${formatCount(meta.estimatedTokens)} tokens`,
|
|
159
|
+
HOW_TO_READ[wholeRead],
|
|
108
160
|
...(viewable ? ["Its text cannot show pictures. To see a picture, a chart or the layout of a page, look at the page with view_pages."] : []),
|
|
161
|
+
...(note ? [note] : []),
|
|
109
162
|
];
|
|
110
163
|
const profile = meta.logProfile;
|
|
111
164
|
if (profile) {
|
|
@@ -114,14 +167,15 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, r
|
|
|
114
167
|
if (profile.firstTimestamp) out.push(`Time range: ${profile.firstTimestamp} → ${profile.lastTimestamp ?? profile.firstTimestamp}`);
|
|
115
168
|
if (profile.topIssues.length) {
|
|
116
169
|
out.push("Most frequent problems (count, first line):");
|
|
117
|
-
|
|
170
|
+
// 0.5.0 stored some templates cut inside an emoji: half of a character is not sent.
|
|
171
|
+
for (const issue of profile.topIssues.slice(0, 8)) out.push(` [${issue.level} ×${issue.count}, L${issue.firstLine}] ${wellFormed(issue.template)}`);
|
|
118
172
|
}
|
|
119
173
|
}
|
|
120
174
|
if (meta.outline.length) {
|
|
121
175
|
out.push(`Outline (${Math.min(meta.outline.length, CARD_OUTLINE_ENTRIES)} of ${meta.outline.length} headings):`);
|
|
122
176
|
out.push(...outlineLines(meta.outline.slice(0, CARD_OUTLINE_ENTRIES)).map((line) => ` ${line}`));
|
|
123
177
|
}
|
|
124
|
-
out.push(`First lines:`, head.split("\n").map((line) => ` ${line
|
|
178
|
+
out.push(`First lines:`, head.split("\n").map((line) => ` ${sliceWhole(line, 300)}`).join("\n"));
|
|
125
179
|
out.push(`--- End large attached file: ${meta.name} ---`);
|
|
126
180
|
return out.join("\n");
|
|
127
181
|
}
|
|
@@ -130,7 +184,8 @@ export function renderCard(meta: DocumentMeta, head: string, viewable = false, r
|
|
|
130
184
|
* The tool guide for the system prompt. `searchable` are the files the model reads through the
|
|
131
185
|
* text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
|
|
132
186
|
* may be searchable, and some may have their whole text in the prompt. `wholeReads` is false when
|
|
133
|
-
* every searchable file is too large for
|
|
187
|
+
* the tools have no `analyze_whole_document`, or every searchable file is too large for it: the
|
|
188
|
+
* guide then leaves it out.
|
|
134
189
|
*/
|
|
135
190
|
export function documentToolsInstruction(searchable: DocumentMeta[], viewable: DocumentMeta[] = [], wholeReads = true): string {
|
|
136
191
|
// File names come from uploads. Quoting keeps a name that reads like an instruction a name.
|
|
@@ -141,9 +196,10 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
|
|
|
141
196
|
`Some attached files are too large for your context: ${searchable.map((meta) => named(meta)).join("; ")}.`,
|
|
142
197
|
"You see only a summary card for each. Read them through the tools:",
|
|
143
198
|
"- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
|
|
199
|
+
"- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
|
|
144
200
|
"- read_document reads a line range. Read around search hits before you rely on them.",
|
|
145
201
|
"- get_document_overview returns the outline, log profile, and the start and end of a file.",
|
|
146
|
-
...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of
|
|
202
|
+
...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),
|
|
147
203
|
"You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
|
|
148
204
|
"Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.",
|
|
149
205
|
);
|
package/src/retry.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// One rule for sending a model request again, used by the chat loop and by whole-file part reads.
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* How a model request that failed is sent again. A field that is not a finite number (NaN,
|
|
5
|
+
* Infinity) counts as not set: its default applies.
|
|
6
|
+
*/
|
|
7
|
+
export type RetryOptions = {
|
|
8
|
+
/** How many times a failed request is sent again. Defaults to 3. 0 turns it off. */
|
|
9
|
+
retries?: number;
|
|
10
|
+
/** The first wait in milliseconds. Each later one is twice as long. Defaults to 500. */
|
|
11
|
+
baseDelayMs?: number;
|
|
12
|
+
/**
|
|
13
|
+
* The longest wait in milliseconds. Defaults to 60,000. When the provider asks for a longer one
|
|
14
|
+
* (`Retry-After`), the request is not sent again and the error is reported.
|
|
15
|
+
*/
|
|
16
|
+
maxDelayMs?: number;
|
|
17
|
+
/** For tests: the wait itself. */
|
|
18
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
19
|
+
/** For tests: the source of the jitter, a number from 0 up to 1. */
|
|
20
|
+
random?: () => number;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const DEFAULT_RETRIES = 3;
|
|
24
|
+
const DEFAULT_BASE_DELAY_MS = 500;
|
|
25
|
+
const DEFAULT_MAX_DELAY_MS = 60_000;
|
|
26
|
+
|
|
27
|
+
/** The HTTP status of an error, when it carries one. 0 stands for a connection that failed. */
|
|
28
|
+
export function statusOf(error: unknown): number | undefined {
|
|
29
|
+
const status = (error as { status?: unknown } | null)?.status;
|
|
30
|
+
return typeof status === "number" && Number.isFinite(status) ? status : undefined;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether a request that failed with this status is worth sending again: the model could not be
|
|
35
|
+
* reached, timed out, was busy, or failed on its side. A request it refused (400, 401, 403, 404)
|
|
36
|
+
* would be refused again.
|
|
37
|
+
*/
|
|
38
|
+
export function isRetryableStatus(status: number): boolean {
|
|
39
|
+
return status === 0 || status === 408 || status === 409 || status === 429 || status >= 500;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A wait that ends early, with the signal's reason, when the signal aborts. */
|
|
43
|
+
export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
44
|
+
return new Promise<void>((resolve, reject) => {
|
|
45
|
+
if (signal?.aborted) {
|
|
46
|
+
reject(signal.reason);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const done = () => {
|
|
50
|
+
signal?.removeEventListener("abort", stop);
|
|
51
|
+
resolve();
|
|
52
|
+
};
|
|
53
|
+
const timer = setTimeout(done, ms);
|
|
54
|
+
const stop = () => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
reject(signal!.reason);
|
|
57
|
+
};
|
|
58
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The wait a provider asked for, in milliseconds: the `retry-after-ms` or `Retry-After` header
|
|
64
|
+
* (seconds, or a date), or the `retryDelay` of a `google.rpc.RetryInfo` in the error body ("17s").
|
|
65
|
+
*/
|
|
66
|
+
export function retryAfterMs(headers: Headers | undefined, body?: unknown, now: () => number = Date.now): number | undefined {
|
|
67
|
+
const exact = Number(headers?.get("retry-after-ms"));
|
|
68
|
+
if (headers?.get("retry-after-ms") && Number.isFinite(exact) && exact >= 0) return exact;
|
|
69
|
+
const header = headers?.get("retry-after");
|
|
70
|
+
if (header) {
|
|
71
|
+
const seconds = Number(header);
|
|
72
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
|
|
73
|
+
const date = Date.parse(header);
|
|
74
|
+
if (Number.isFinite(date)) return Math.max(0, date - now());
|
|
75
|
+
}
|
|
76
|
+
const details = (body as { error?: { details?: unknown } } | null)?.error?.details;
|
|
77
|
+
if (Array.isArray(details)) {
|
|
78
|
+
for (const detail of details as Array<{ retryDelay?: unknown }>) {
|
|
79
|
+
const match = typeof detail?.retryDelay === "string" ? /^(\d+(?:\.\d+)?)s$/.exec(detail.retryDelay) : null;
|
|
80
|
+
if (match) return Math.round(Number(match[1]) * 1000);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Errors whose provider said not to send the request again: see `noteNoRetry`. */
|
|
87
|
+
const notToRetry = new WeakSet<object>();
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Takes note that the provider said not to send this request again (Claude's
|
|
91
|
+
* `x-should-retry: false`): `withRetry` does not, whatever its status.
|
|
92
|
+
*/
|
|
93
|
+
export function noteNoRetry(error: object): void {
|
|
94
|
+
notToRetry.add(error);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A value of the options, or its default when the value is not a finite number. */
|
|
98
|
+
const finiteOr = (value: number | undefined, fallback: number): number => (typeof value === "number" && Number.isFinite(value) ? value : fallback);
|
|
99
|
+
|
|
100
|
+
/** What `withRetry` tells `onRetry` before it sends a request again. */
|
|
101
|
+
export type RetryNotice = {
|
|
102
|
+
/** The error of the attempt that failed. */
|
|
103
|
+
error: unknown;
|
|
104
|
+
/**
|
|
105
|
+
* The number of the retry to come, 1 for the first. It counts every retry made so far, the one
|
|
106
|
+
* of an error without a status (`unknownErrors: "once"`, which is not told) included.
|
|
107
|
+
*/
|
|
108
|
+
attempt: number;
|
|
109
|
+
/** How long it waits, in milliseconds, before it sends the request again. */
|
|
110
|
+
delayMs: number;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Runs a model request, and runs it again when it failed in a way that another try can mend.
|
|
115
|
+
* - An error with a retryable status (see `isRetryableStatus`) is retried after a wait that doubles
|
|
116
|
+
* each time, with jitter, or after the wait the provider asked for.
|
|
117
|
+
* - An error with another status is not retried.
|
|
118
|
+
* - An error of kind "quota" (a daily cap, no credit left) is not retried: a wait does not mend it.
|
|
119
|
+
* Nor is one of kind "context_overflow", whatever its status: only a smaller request can pass
|
|
120
|
+
* (OpenAI's request larger than a minute's allowance of tokens comes as HTTP 429). Nor is one
|
|
121
|
+
* whose provider said not to try again (Claude's `x-should-retry: false`).
|
|
122
|
+
* - An error of kind "timeout" with status 0 (nothing came from the model for the adapter's whole
|
|
123
|
+
* wait) is retried once: another such wait is long, and a model that went silent twice will most
|
|
124
|
+
* likely do so again. A timeout the provider reports (HTTP 408) is retried like any other.
|
|
125
|
+
* - An error without a status is retried once, at once, when `unknownErrors` is "once"; otherwise not.
|
|
126
|
+
* Nothing is retried after the signal aborted, or once `canRetry` says no.
|
|
127
|
+
*/
|
|
128
|
+
export async function withRetry<T>(run: () => Promise<T>, options: {
|
|
129
|
+
retry?: RetryOptions | undefined;
|
|
130
|
+
signal?: AbortSignal | undefined;
|
|
131
|
+
/** False once the attempt did something that must not happen twice: text was shown to the user. */
|
|
132
|
+
canRetry?: () => boolean;
|
|
133
|
+
onRetry?: (notice: RetryNotice) => void;
|
|
134
|
+
unknownErrors?: "once" | "never";
|
|
135
|
+
} = {}): Promise<T> {
|
|
136
|
+
// NaN would never compare true (`attempt >= NaN`), and a request would be sent again without end.
|
|
137
|
+
const retries = Math.max(0, Math.trunc(finiteOr(options.retry?.retries, DEFAULT_RETRIES)));
|
|
138
|
+
const base = Math.max(0, finiteOr(options.retry?.baseDelayMs, DEFAULT_BASE_DELAY_MS));
|
|
139
|
+
const longest = Math.max(0, finiteOr(options.retry?.maxDelayMs, DEFAULT_MAX_DELAY_MS));
|
|
140
|
+
const wait = options.retry?.sleep ?? sleep;
|
|
141
|
+
const random = options.retry?.random ?? Math.random;
|
|
142
|
+
let unknownRetried = false;
|
|
143
|
+
let timeoutRetried = false;
|
|
144
|
+
for (let attempt = 0; ; attempt++) {
|
|
145
|
+
try {
|
|
146
|
+
return await run();
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (options.signal?.aborted || options.canRetry?.() === false) throw error;
|
|
149
|
+
const kind = (error as { kind?: unknown } | null)?.kind;
|
|
150
|
+
if (kind === "quota" || kind === "context_overflow") throw error;
|
|
151
|
+
if (typeof error === "object" && error !== null && notToRetry.has(error)) throw error;
|
|
152
|
+
if (kind === "timeout" && statusOf(error) === 0) {
|
|
153
|
+
if (timeoutRetried || retries === 0) throw error;
|
|
154
|
+
timeoutRetried = true;
|
|
155
|
+
}
|
|
156
|
+
const status = statusOf(error);
|
|
157
|
+
if (status === undefined) {
|
|
158
|
+
if (options.unknownErrors !== "once" || unknownRetried || retries === 0) throw error;
|
|
159
|
+
unknownRetried = true;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (!isRetryableStatus(status) || attempt >= retries) throw error;
|
|
163
|
+
const asked = (error as { retryAfterMs?: unknown }).retryAfterMs;
|
|
164
|
+
let delayMs: number;
|
|
165
|
+
if (typeof asked === "number" && Number.isFinite(asked) && asked >= 0) {
|
|
166
|
+
// Waiting longer than the caller allows helps no one who is waiting for an answer.
|
|
167
|
+
if (asked > longest) throw error;
|
|
168
|
+
delayMs = asked;
|
|
169
|
+
} else {
|
|
170
|
+
delayMs = Math.min(longest, base * 2 ** attempt * (0.5 + random() / 2));
|
|
171
|
+
}
|
|
172
|
+
options.onRetry?.({ error, attempt: attempt + 1, delayMs });
|
|
173
|
+
await wait(delayMs, options.signal);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
package/src/search.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createContext, Script, type Context } from "node:vm";
|
|
2
|
+
import { pause } from "./pause.js";
|
|
2
3
|
import { PASSAGE_CHARACTERS, PASSAGE_MAX_LINES, positionOf } from "./text-index.js";
|
|
3
|
-
import { foldCase, LineIndex } from "./text.js";
|
|
4
|
+
import { foldCase, LineIndex, sliceWhole } from "./text.js";
|
|
4
5
|
import type { DocumentMeta, StoredDocument } from "./types.js";
|
|
5
6
|
|
|
6
7
|
const MAX_OCCURRENCES_PER_TERM = 200_000;
|
|
@@ -70,8 +71,7 @@ export interface DocumentSource {
|
|
|
70
71
|
*/
|
|
71
72
|
export type ScanFeed = (chunk: TextChunk) => boolean | void | "again";
|
|
72
73
|
|
|
73
|
-
|
|
74
|
-
export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
|
|
74
|
+
export { pause };
|
|
75
75
|
|
|
76
76
|
/** Feeds a document's text, a piece at a time, to `feed` until it returns true or the text ends. */
|
|
77
77
|
export async function scanSource(source: DocumentSource, feed: ScanFeed, signal?: AbortSignal): Promise<void> {
|
|
@@ -227,7 +227,13 @@ export type GrepResult = {
|
|
|
227
227
|
totalMatchingLines: number;
|
|
228
228
|
/** True when the scan stopped early (too many matches or the regex time limit). */
|
|
229
229
|
stoppedEarly: boolean;
|
|
230
|
+
/** The first `maxResults` matching lines. */
|
|
230
231
|
matches: LineMatch[];
|
|
232
|
+
/**
|
|
233
|
+
* The last matching line of the document, when it is not among `matches`. Undefined when the
|
|
234
|
+
* scan stopped early: the last line it found need not be the last of the document.
|
|
235
|
+
*/
|
|
236
|
+
last?: LineMatch;
|
|
231
237
|
};
|
|
232
238
|
|
|
233
239
|
export type GrepOptions = {
|
|
@@ -243,8 +249,12 @@ export type GrepOptions = {
|
|
|
243
249
|
|
|
244
250
|
function clip(line: string, column: number): string {
|
|
245
251
|
if (line.length <= SHOWN_LINE_CHARACTERS) return line;
|
|
246
|
-
|
|
247
|
-
|
|
252
|
+
let start = Math.max(0, Math.min(column - SHOWN_LINE_CHARACTERS / 2, line.length - SHOWN_LINE_CHARACTERS));
|
|
253
|
+
// Never inside a character outside the basic plane (an emoji): half of one is refused by Claude's API.
|
|
254
|
+
const code = line.charCodeAt(start);
|
|
255
|
+
if (start > 0 && code >= 0xdc00 && code <= 0xdfff) start++;
|
|
256
|
+
const end = start + SHOWN_LINE_CHARACTERS;
|
|
257
|
+
return `${start > 0 ? "…" : ""}${sliceWhole(line, end).slice(start)}${end < line.length ? "…" : ""}`;
|
|
248
258
|
}
|
|
249
259
|
|
|
250
260
|
const RUN_SCAN = new Script("scan()");
|
|
@@ -331,6 +341,14 @@ function remember(recent: Array<readonly [number, string]>, chunk: TextChunk, ke
|
|
|
331
341
|
*/
|
|
332
342
|
class LineSearch {
|
|
333
343
|
private readonly hits: Array<{ line: number; column: number; text: string }> = [];
|
|
344
|
+
/** The latest matching line past the first `maxResults`: the last one of the document, once the scan is over. */
|
|
345
|
+
private last?: { line: number; column: number; text: string };
|
|
346
|
+
/** The lines around `last`, by number, kept from the pieces as they are read: they need not be read again. */
|
|
347
|
+
private readonly aroundLast = new Map<number, string>();
|
|
348
|
+
/** The line of the match whose lines `aroundLast` holds. */
|
|
349
|
+
private aroundLine = 0;
|
|
350
|
+
/** True once the lines around `last` are among the lines to show. */
|
|
351
|
+
private lastShown = false;
|
|
334
352
|
private total = 0;
|
|
335
353
|
stoppedEarly = false;
|
|
336
354
|
/** True once nothing more is to be found or counted: the rest of the text need not be read. */
|
|
@@ -397,12 +415,38 @@ class LineSearch {
|
|
|
397
415
|
if (found !== undefined) this.fill(line, found);
|
|
398
416
|
}
|
|
399
417
|
}
|
|
418
|
+
if (this.last && this.context > 0) this.keepAroundLast(chunk);
|
|
400
419
|
this.recent = remember(this.recent, chunk, this.keep);
|
|
401
420
|
return true;
|
|
402
421
|
}
|
|
403
422
|
|
|
404
|
-
/**
|
|
423
|
+
/** Keeps the lines around `last` that are in this piece or in the lines read just before it. */
|
|
424
|
+
private keepAroundLast(chunk: TextChunk): void {
|
|
425
|
+
const { line } = this.last!;
|
|
426
|
+
if (this.aroundLine !== line) {
|
|
427
|
+
this.aroundLast.clear();
|
|
428
|
+
this.aroundLine = line;
|
|
429
|
+
}
|
|
430
|
+
const end = chunk.firstLine + chunk.lines.lineCount - 1;
|
|
431
|
+
for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
|
|
432
|
+
if (other === line || this.aroundLast.has(other)) continue;
|
|
433
|
+
const found = other >= chunk.firstLine && other <= end
|
|
434
|
+
? chunk.lines.line(other - chunk.firstLine + 1)
|
|
435
|
+
: this.recent.find(([number]) => number === other)?.[1];
|
|
436
|
+
if (found !== undefined) this.aroundLast.set(other, found);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Lines to show that were not in the pieces read: those of a scan that stopped early, and those
|
|
442
|
+
* around the last match, which is known only once the scan is over. Read them and `fill` them.
|
|
443
|
+
*/
|
|
405
444
|
missing(): number[] {
|
|
445
|
+
if (this.last && !this.lastShown && !this.stoppedEarly) {
|
|
446
|
+
this.lastShown = true;
|
|
447
|
+
this.showAround(this.last.line);
|
|
448
|
+
if (this.aroundLine === this.last.line) for (const [line, text] of this.aroundLast) this.fill(line, text);
|
|
449
|
+
}
|
|
406
450
|
if (this.unfilled === 0) return [];
|
|
407
451
|
return [...this.shown].filter(([, text]) => text === undefined).map(([line]) => line).sort((left, right) => left - right);
|
|
408
452
|
}
|
|
@@ -415,7 +459,7 @@ class LineSearch {
|
|
|
415
459
|
|
|
416
460
|
result(): GrepResult {
|
|
417
461
|
const lineText = (line: number) => this.shown.get(line) ?? "";
|
|
418
|
-
const
|
|
462
|
+
const show = ({ line, column, text }: { line: number; column: number; text: string }): LineMatch => {
|
|
419
463
|
const match: LineMatch = { line, text: clip(text, column) };
|
|
420
464
|
if (this.context > 0) {
|
|
421
465
|
match.before = [];
|
|
@@ -424,14 +468,23 @@ class LineSearch {
|
|
|
424
468
|
for (let other = line + 1; other <= Math.min(this.lineCount, line + this.context); other++) match.after.push(`${other}| ${clip(lineText(other), 0)}`);
|
|
425
469
|
}
|
|
426
470
|
return match;
|
|
427
|
-
}
|
|
428
|
-
|
|
471
|
+
};
|
|
472
|
+
const last = this.last && !this.stoppedEarly ? { last: show(this.last) } : {};
|
|
473
|
+
return { totalMatchingLines: this.total, stoppedEarly: this.stoppedEarly, matches: this.hits.map(show), ...last };
|
|
429
474
|
}
|
|
430
475
|
|
|
431
476
|
private record(line: number, column: number, text: string): void {
|
|
432
477
|
this.total++;
|
|
433
|
-
if (this.hits.length >= this.settings.maxResults)
|
|
478
|
+
if (this.hits.length >= this.settings.maxResults) {
|
|
479
|
+
this.last = { line, column, text };
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
434
482
|
this.hits.push({ line, column, text });
|
|
483
|
+
this.showAround(line);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Puts the lines around a match among the lines to show. */
|
|
487
|
+
private showAround(line: number): void {
|
|
435
488
|
for (let other = Math.max(1, line - this.context); other <= Math.min(this.lineCount, line + this.context); other++) {
|
|
436
489
|
if (other !== line && !this.shown.has(other)) {
|
|
437
490
|
this.shown.set(other, undefined);
|
package/src/sse.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { bodyPieces } from "./http.js";
|
|
2
|
+
|
|
3
|
+
/** What a stream reader can be told of as the stream goes: see `parseSseJson`. */
|
|
4
|
+
export type SseHooks = {
|
|
5
|
+
/** Bytes arrived: an event, part of one, or a keep-alive comment. */
|
|
6
|
+
onData?: () => void;
|
|
7
|
+
/** The stream said it is done (`data: [DONE]`), as OpenAI-compatible servers do at the end. */
|
|
8
|
+
onDone?: () => void;
|
|
9
|
+
/** When it aborts, the next piece is not waited for: the stream ends with its reason. */
|
|
10
|
+
signal?: AbortSignal | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* The most characters one event may hold: what its data lines hold after `data:` and the spaces
|
|
13
|
+
* after it, and the line feeds that join them. A line of another field (a comment, `event:`)
|
|
14
|
+
* counts in full with the event, as it is held until its end. A longer event ends the stream with
|
|
15
|
+
* an error named `SseEventTooLongError`, rather than fill the memory of the server, however the
|
|
16
|
+
* stream is cut into pieces. Defaults to 64,000,000. `Infinity` sets no limit; a value that is not
|
|
17
|
+
* a positive number counts as not set.
|
|
18
|
+
*/
|
|
19
|
+
maxEventLength?: number;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** The most characters one event holds, by default: see `SseHooks.maxEventLength`. */
|
|
23
|
+
const DEFAULT_MAX_EVENT_LENGTH = 64_000_000;
|
|
24
|
+
/** The data lines of an event are joined this many at a time as they come (see `parseSseJson`). */
|
|
25
|
+
const JOIN_LINES = 1_024;
|
|
26
|
+
|
|
27
|
+
/** An event of a stream held more characters than `SseHooks.maxEventLength`, and was not read. */
|
|
28
|
+
export class SseEventTooLongError extends Error {
|
|
29
|
+
constructor(readonly limit: number) {
|
|
30
|
+
super(`An event of the stream held more than ${limit.toLocaleString("en-US")} characters.`);
|
|
31
|
+
this.name = "SseEventTooLongError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The message of a reply whose stream had an event too long to read. It is not sent again: the same
|
|
37
|
+
* event would most likely come back. `who` is "Gemini's", "Claude's"…
|
|
38
|
+
*/
|
|
39
|
+
export function eventTooLongMessage(who: string, error: SseEventTooLongError): string {
|
|
40
|
+
return `${who} reply could not be read: an event of its stream held more than ${error.limit.toLocaleString("en-US")} characters.`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Parses a `text/event-stream` body into JSON objects, one per `data:` event. The body is a web
|
|
45
|
+
* stream (the global `fetch`), or a Node stream (node-fetch and the like). Lines end with LF, CRLF
|
|
46
|
+
* or CR alone, as the format allows. Each piece of the body is read once, however long the event
|
|
47
|
+
* it belongs to: a line that has not ended waits for the next piece.
|
|
48
|
+
*/
|
|
49
|
+
export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>, hooks: SseHooks = {}): AsyncGenerator<T> {
|
|
50
|
+
const decoder = new TextDecoder();
|
|
51
|
+
const most = typeof hooks.maxEventLength === "number" && hooks.maxEventLength > 0 ? hooks.maxEventLength : DEFAULT_MAX_EVENT_LENGTH;
|
|
52
|
+
/** The data lines of the event being read, since the last ones were joined into `joined`. */
|
|
53
|
+
let data: string[] = [];
|
|
54
|
+
/**
|
|
55
|
+
* Earlier data lines of the event, joined `JOIN_LINES` at a time: an event of millions of empty
|
|
56
|
+
* data lines would otherwise hold a slot for each, far more memory than the characters counted.
|
|
57
|
+
*/
|
|
58
|
+
let joined: string[] = [];
|
|
59
|
+
/** The characters of the event those lines make. */
|
|
60
|
+
let held = 0;
|
|
61
|
+
/** The start of a line whose end has not arrived. */
|
|
62
|
+
let partial = "";
|
|
63
|
+
/**
|
|
64
|
+
* Whether that line is a data line, and if so whether its value has begun after `data:` and the
|
|
65
|
+
* spaces after it. Undefined while what has come of it may still be the start of `data:`.
|
|
66
|
+
*/
|
|
67
|
+
let partialKind: "field" | "value" | "other" | undefined;
|
|
68
|
+
/** The characters of the event that line holds, as `held` counts them. */
|
|
69
|
+
let partialHeld = 0;
|
|
70
|
+
/** The last piece ended with CR: a LF that starts the next one belongs to that line end. */
|
|
71
|
+
let afterCr = false;
|
|
72
|
+
const lineEnd = /\r\n?|\n/g;
|
|
73
|
+
/** The event of the data lines read so far, which a blank line ends. */
|
|
74
|
+
const event = (): T | undefined => {
|
|
75
|
+
if (data.length > 0) joined.push(data.join("\n"));
|
|
76
|
+
const text = joined.join("\n");
|
|
77
|
+
data = [];
|
|
78
|
+
joined = [];
|
|
79
|
+
held = 0;
|
|
80
|
+
if (text === "[DONE]") hooks.onDone?.();
|
|
81
|
+
return text && text !== "[DONE]" ? JSON.parse(text) as T : undefined;
|
|
82
|
+
};
|
|
83
|
+
const take = (line: string): T | undefined => {
|
|
84
|
+
if (!line) return event();
|
|
85
|
+
if (line.startsWith("data:")) {
|
|
86
|
+
const value = line.slice(5).trimStart();
|
|
87
|
+
// The line feed that joins it to the line before counts too: empty data lines add up.
|
|
88
|
+
held += value.length + (data.length > 0 || joined.length > 0 ? 1 : 0);
|
|
89
|
+
if (held > most) throw new SseEventTooLongError(most);
|
|
90
|
+
data.push(value);
|
|
91
|
+
if (data.length >= JOIN_LINES) {
|
|
92
|
+
joined.push(data.join("\n"));
|
|
93
|
+
data = [];
|
|
94
|
+
}
|
|
95
|
+
} else if (held + line.length > most) {
|
|
96
|
+
// Another line is not kept, but it was held until its end: it counts as it did then.
|
|
97
|
+
throw new SseEventTooLongError(most);
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Adds the rest of a piece to the line whose end has not arrived, and counts it as `take` will
|
|
103
|
+
* count the whole line. Only the rest is looked at, not what came of the line before.
|
|
104
|
+
*/
|
|
105
|
+
const hold = (rest: string): void => {
|
|
106
|
+
let at = 0;
|
|
107
|
+
if (partialKind === undefined) {
|
|
108
|
+
const start = partial + rest.slice(0, 5 - partial.length);
|
|
109
|
+
at = start.length - partial.length;
|
|
110
|
+
if (start === "data:") {
|
|
111
|
+
partialKind = "field";
|
|
112
|
+
partialHeld = data.length > 0 || joined.length > 0 ? 1 : 0;
|
|
113
|
+
} else if (!"data:".startsWith(start)) {
|
|
114
|
+
partialKind = "other";
|
|
115
|
+
partialHeld = partial.length;
|
|
116
|
+
at = 0;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (partialKind === "field") {
|
|
120
|
+
const value = rest.slice(at).search(/\S/);
|
|
121
|
+
if (value >= 0) partialKind = "value";
|
|
122
|
+
at = value >= 0 ? at + value : rest.length;
|
|
123
|
+
}
|
|
124
|
+
// What counts starts at `at`: at the end of the rest while the line may still be a data line,
|
|
125
|
+
// or while the value of one has not begun.
|
|
126
|
+
partialHeld += rest.length - at;
|
|
127
|
+
partial += rest;
|
|
128
|
+
if (held + partialHeld > most) throw new SseEventTooLongError(most);
|
|
129
|
+
};
|
|
130
|
+
// The events that end in this text, one at a time: a line that does not end in it waits for more.
|
|
131
|
+
function* lines(text: string): Generator<T> {
|
|
132
|
+
if (!text) return;
|
|
133
|
+
let from = afterCr && text.startsWith("\n") ? 1 : 0;
|
|
134
|
+
afterCr = false;
|
|
135
|
+
lineEnd.lastIndex = from;
|
|
136
|
+
for (let found = lineEnd.exec(text); found; found = lineEnd.exec(text)) {
|
|
137
|
+
const line = partial + text.slice(from, found.index);
|
|
138
|
+
partial = "";
|
|
139
|
+
partialKind = undefined;
|
|
140
|
+
partialHeld = 0;
|
|
141
|
+
from = lineEnd.lastIndex;
|
|
142
|
+
if (found[0] === "\r" && from === text.length) afterCr = true;
|
|
143
|
+
const parsed = take(line);
|
|
144
|
+
if (parsed !== undefined) yield parsed;
|
|
145
|
+
lineEnd.lastIndex = from;
|
|
146
|
+
}
|
|
147
|
+
hold(text.slice(from));
|
|
148
|
+
}
|
|
149
|
+
for await (const value of bodyPieces(stream, hooks.signal)) {
|
|
150
|
+
if (value.length > 0) hooks.onData?.();
|
|
151
|
+
yield* lines(decoder.decode(value, { stream: true }));
|
|
152
|
+
}
|
|
153
|
+
yield* lines(decoder.decode());
|
|
154
|
+
// A last line, and a last event, that the stream ended without a line end or a blank line after.
|
|
155
|
+
if (partial.trim()) take(partial.trim());
|
|
156
|
+
partial = "";
|
|
157
|
+
const last = event();
|
|
158
|
+
if (last !== undefined) yield last;
|
|
159
|
+
}
|
package/src/stores.ts
CHANGED
|
@@ -19,8 +19,11 @@ export class MemoryDocumentStore implements DocumentStore {
|
|
|
19
19
|
this.now = options.now ?? (() => new Date());
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
// The metadata is copied on the way in and on the way out, as a store that writes it somewhere
|
|
23
|
+
// does: an app that changes the metadata it was handed (deletes its owner before sending it to a
|
|
24
|
+
// browser) must not change the document's owner or expiry.
|
|
22
25
|
async put(document: StoredDocument): Promise<void> {
|
|
23
|
-
this.documents.set(document.meta.id, document);
|
|
26
|
+
this.documents.set(document.meta.id, { meta: structuredClone(document.meta), text: document.text });
|
|
24
27
|
}
|
|
25
28
|
|
|
26
29
|
async get(id: string): Promise<StoredDocument | undefined> {
|
|
@@ -29,7 +32,7 @@ export class MemoryDocumentStore implements DocumentStore {
|
|
|
29
32
|
await this.delete(id);
|
|
30
33
|
return undefined;
|
|
31
34
|
}
|
|
32
|
-
return document;
|
|
35
|
+
return document && { meta: structuredClone(document.meta), text: document.text };
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
async getMeta(id: string): Promise<DocumentMeta | undefined> {
|