llm-large-files 0.0.0-stage → 0.2.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.
Files changed (105) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/LICENSE +21 -0
  3. package/README.md +117 -2
  4. package/dist/analyze.d.ts +9 -0
  5. package/dist/analyze.d.ts.map +1 -0
  6. package/dist/analyze.js +106 -0
  7. package/dist/analyze.js.map +1 -0
  8. package/dist/extract.d.ts +30 -0
  9. package/dist/extract.d.ts.map +1 -0
  10. package/dist/extract.js +211 -0
  11. package/dist/extract.js.map +1 -0
  12. package/dist/gemini/chat.d.ts +93 -0
  13. package/dist/gemini/chat.d.ts.map +1 -0
  14. package/dist/gemini/chat.js +208 -0
  15. package/dist/gemini/chat.js.map +1 -0
  16. package/dist/gemini/endpoints.d.ts +36 -0
  17. package/dist/gemini/endpoints.d.ts.map +1 -0
  18. package/dist/gemini/endpoints.js +35 -0
  19. package/dist/gemini/endpoints.js.map +1 -0
  20. package/dist/gemini/generate.d.ts +30 -0
  21. package/dist/gemini/generate.d.ts.map +1 -0
  22. package/dist/gemini/generate.js +48 -0
  23. package/dist/gemini/generate.js.map +1 -0
  24. package/dist/gemini/index.d.ts +8 -0
  25. package/dist/gemini/index.d.ts.map +1 -0
  26. package/dist/gemini/index.js +5 -0
  27. package/dist/gemini/index.js.map +1 -0
  28. package/dist/gemini/sse.d.ts +3 -0
  29. package/dist/gemini/sse.d.ts.map +1 -0
  30. package/dist/gemini/sse.js +39 -0
  31. package/dist/gemini/sse.js.map +1 -0
  32. package/dist/index.d.ts +9 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +8 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/library.d.ts +69 -0
  37. package/dist/library.d.ts.map +1 -0
  38. package/dist/library.js +170 -0
  39. package/dist/library.js.map +1 -0
  40. package/dist/map-reduce.d.ts +34 -0
  41. package/dist/map-reduce.d.ts.map +1 -0
  42. package/dist/map-reduce.js +199 -0
  43. package/dist/map-reduce.js.map +1 -0
  44. package/dist/node/handlers.d.ts +23 -0
  45. package/dist/node/handlers.d.ts.map +1 -0
  46. package/dist/node/handlers.js +111 -0
  47. package/dist/node/handlers.js.map +1 -0
  48. package/dist/node/index.d.ts +3 -0
  49. package/dist/node/index.d.ts.map +1 -0
  50. package/dist/node/index.js +2 -0
  51. package/dist/node/index.js.map +1 -0
  52. package/dist/pdf-layout.d.ts +32 -0
  53. package/dist/pdf-layout.d.ts.map +1 -0
  54. package/dist/pdf-layout.js +790 -0
  55. package/dist/pdf-layout.js.map +1 -0
  56. package/dist/plan.d.ts +18 -0
  57. package/dist/plan.d.ts.map +1 -0
  58. package/dist/plan.js +98 -0
  59. package/dist/plan.js.map +1 -0
  60. package/dist/search.d.ts +57 -0
  61. package/dist/search.d.ts.map +1 -0
  62. package/dist/search.js +227 -0
  63. package/dist/search.js.map +1 -0
  64. package/dist/stores.d.ts +33 -0
  65. package/dist/stores.d.ts.map +1 -0
  66. package/dist/stores.js +126 -0
  67. package/dist/stores.js.map +1 -0
  68. package/dist/text.d.ts +51 -0
  69. package/dist/text.d.ts.map +1 -0
  70. package/dist/text.js +272 -0
  71. package/dist/text.js.map +1 -0
  72. package/dist/tools.d.ts +25 -0
  73. package/dist/tools.d.ts.map +1 -0
  74. package/dist/tools.js +264 -0
  75. package/dist/tools.js.map +1 -0
  76. package/dist/types.d.ts +160 -0
  77. package/dist/types.d.ts.map +1 -0
  78. package/dist/types.js +4 -0
  79. package/dist/types.js.map +1 -0
  80. package/docs/api.md +163 -0
  81. package/docs/configuration.md +157 -0
  82. package/docs/getting-started.md +206 -0
  83. package/docs/how-it-works.md +96 -0
  84. package/docs/publishing.md +81 -0
  85. package/docs/security.md +70 -0
  86. package/package.json +89 -4
  87. package/src/analyze.ts +97 -0
  88. package/src/extract.ts +216 -0
  89. package/src/gemini/chat.ts +290 -0
  90. package/src/gemini/endpoints.ts +64 -0
  91. package/src/gemini/generate.ts +61 -0
  92. package/src/gemini/index.ts +7 -0
  93. package/src/gemini/sse.ts +34 -0
  94. package/src/index.ts +10 -0
  95. package/src/library.ts +241 -0
  96. package/src/map-reduce.ts +228 -0
  97. package/src/node/handlers.ts +122 -0
  98. package/src/node/index.ts +2 -0
  99. package/src/pdf-layout.ts +771 -0
  100. package/src/plan.ts +100 -0
  101. package/src/search.ts +239 -0
  102. package/src/stores.ts +132 -0
  103. package/src/text.ts +246 -0
  104. package/src/tools.ts +274 -0
  105. package/src/types.ts +174 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,100 @@
1
+ # Changelog
2
+
3
+ All notable changes to this package are recorded here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
5
+ [semantic versioning](https://semver.org).
6
+
7
+ ## [0.2.0] - 2026-11-10
8
+
9
+ ### Fixed
10
+
11
+ - **Token estimates were far too low for logs and data files.** `estimateTokens` assumed 4
12
+ characters per token, which holds for prose only: Gemini counts about one token per digit. A
13
+ service log was estimated at 37% of its real size and a CSV of numbers at 26%, so such files were
14
+ sent whole, and split into parts, at about three times the configured budget. The estimate now
15
+ prices each kind of character and was fitted to Gemini's `countTokens` on 60 texts; it lands
16
+ between 0.98 and 1.7 times the real count. Documents already in a store keep the estimate they
17
+ were ingested with until they expire.
18
+ - **A regex search could freeze the server.** Patterns such as `((a+))+$` and `(a|a)+$` passed the
19
+ nested-quantifier check and never finished on a 40-character line; the 3-second limit was only
20
+ checked between lines. Regex scans now run under a hard time limit that interrupts a match in
21
+ progress.
22
+ - **`askGemini` could return a remark instead of an answer.** If the model wrote "Let me search…"
23
+ with a tool call and its next turn came back empty (cut off, or a malformed tool call), that
24
+ remark was returned as the answer. The tool-free request is now sent whenever the model's last
25
+ turn has no text.
26
+ - **A blocked prompt resolved as an empty answer with no reason.** The result now has
27
+ `answered: false` and `blockReason`.
28
+ - **One model request was wasted when the tool turns ran out.** The last request was sent with
29
+ tools, its calls were discarded, and then another was sent without tools. `askGemini` now goes
30
+ straight to the tool-free request, so it never makes more than `maxToolTurns` requests.
31
+ - **Case-insensitive search found nothing in a file containing "İ"** (U+0130), in exact and
32
+ keyword mode: the whole file silently fell back to case-sensitive matching.
33
+ - **Coloured logs lost their profile.** Only the ESC byte of a terminal colour code was removed,
34
+ leaving `[31mERROR[0m`, which no longer matched as a level. Whole escape sequences are removed.
35
+ - **Compressed files were accepted as text.** A `.gz` log became a document of garbage. Gzip and
36
+ ZIP files are refused with a message that says what to do, and other binary files without zero
37
+ bytes are now detected too.
38
+ - **Ingest failed with "Maximum call stack size exceeded"** on files with a few hundred thousand
39
+ short heading-like lines.
40
+ - **A file name could add lines to the prompt.** Control characters, line breaks, and
41
+ text-direction overrides are removed from names at ingest, and names are quoted in the system
42
+ instruction.
43
+ - **Whole-document reads hid that they were incomplete.** When part notes or the final answer
44
+ reach the output limit, the tool result now says so (`notes_cut_short`, `answer_cut_short`, and a
45
+ `note` telling the model to say so and to use exact search for complete lists). If no part can be
46
+ read, the tool returns an error instead of an answer written from nothing.
47
+ - `read_document` reported a line range past the end of the file when no end line was given.
48
+
49
+ - **Words of right-to-left text in a PDF were glued together** when the file stores them piece by
50
+ piece (as Word does): `יתרת סגירה4,167.90`. pdf.js adds the space only between pieces that run
51
+ left to right. The space is now added from the positions.
52
+
53
+ ### Changed
54
+
55
+ - **PDF tables are rebuilt.** A PDF stores text at positions, not tables. In file order, a row
56
+ with an empty cell reads like a row without that column, so a model takes the next value for the
57
+ missing one. The PDF extractor now finds tables by the position of their text and writes each
58
+ row as `| cell | cell | | cell |`. In a live test (`gemini-3.5-flash-lite`, 110 questions about
59
+ single cells of seven PDFs made by Word and Chrome), 44 answers were right from the old text and
60
+ 110 from the new. It also handles tables in one column of a two-column page, right-to-left and
61
+ sideways tables, headings that span columns, and wrapped cells; text that is not a table is left
62
+ as it was. Two-column tables are left as text. See
63
+ [PDF tables](docs/configuration.md#pdf-tables) for the limits.
64
+ `createPdfExtractor({ tables: false })` gives the previous text. Documents already in a store
65
+ keep the text they were ingested with.
66
+ - **A PDF page without any text is marked** `[No text on this page. It may be a scan, a photo, or a
67
+ chart.]` instead of being left empty, so the model can say that it cannot see the page.
68
+ - **Documents are placed at the start of the first user turn**, not appended to the latest one.
69
+ The document then stays in the same place as the conversation grows, so Gemini's prompt cache
70
+ reuses it: in a live test, a follow-up question about a 53,000-token document had 96% of its
71
+ input served from cache, against 0% before. Pass `documentPlacement: "last"` to `askGemini` for
72
+ the previous layout.
73
+ - `maxToolTurns` is now the most requests one question can make, counting the answer. Tools still
74
+ run in at most `maxToolTurns - 1` of them, as before.
75
+
76
+ ### Added
77
+
78
+ - `createPdfExtractor({ tables })`, exported from the main entry point.
79
+ - `AskGeminiResult.answered` and `AskGeminiResult.blockReason`.
80
+ - `GenerateText` requests carry an optional `onTruncated` callback; `createGeminiGenerateText`
81
+ calls it when Gemini stops at `MAX_TOKENS`.
82
+
83
+ ## [0.1.0] - 2026-11-06
84
+
85
+ First release, extracted from the large-file support in the Gemini Prep chatbot.
86
+
87
+ ### Added
88
+
89
+ - `createLargeFiles`: ingest, per-request planning against a token *and* byte budget, summary
90
+ cards, and scoped tools (`search_document`, `read_document`, `get_document_overview`,
91
+ `analyze_whole_document`).
92
+ - Extraction for text, Markdown, logs (UTF-8/UTF-16), JSON/JSONL, CSV/TSV, DOCX and PPTX (optional
93
+ `jszip`), and PDF (optional `unpdf`).
94
+ - Log profiles (levels, time range, most frequent error shapes) and outlines for books and documents.
95
+ - Map-reduce over whole documents with parallel part reads, a retry, and rounds of merging.
96
+ - `MemoryDocumentStore` and `FileDocumentStore` with expiry.
97
+ - Document owners: documents are private to the user who uploaded them.
98
+ - `llm-large-files/gemini`: `askGemini` (streaming tool loop that always ends in an answer),
99
+ `geminiApi` and `vertexAi` endpoints, and lower-level adapters.
100
+ - `llm-large-files/node`: upload, get, and delete handlers for any Node HTTP server.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 renanbazinin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # llm-large-files
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Let an LLM answer questions about **books, logs, and other files larger than its request limit or
4
+ context window**.
5
+
6
+ Your users upload a 50 MB log or a 900-page book. Your model connector accepts 10 MB per request
7
+ and 1M tokens of context. This package bridges the gap:
8
+
9
+ - **Files that fit** go into the prompt whole.
10
+ - **Files that don't** become a short summary card, and the model gets tools to **search**,
11
+ **read line ranges**, or **read the whole file in parts** (map-reduce). Answers cite line numbers.
12
+
13
+ It's a small library, not a framework: no model SDK, no server, and no UI are required. A drop-in
14
+ Gemini / Vertex AI helper and Node HTTP handlers are included for the common case.
15
+
16
+ ```bash
17
+ npm install llm-large-files
18
+ ```
19
+
20
+ ## Quickstart (Gemini, 10 lines)
21
+
22
+ ```ts
23
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
24
+ import { askGemini, geminiApi } from "llm-large-files/gemini";
25
+
26
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
27
+
28
+ // When a user uploads a file:
29
+ const doc = await files.ingest({ name: "app.log", bytes: fileBytes });
30
+
31
+ // When they ask about it:
32
+ const { text, steps } = await askGemini({
33
+ files,
34
+ endpoint: geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }),
35
+ documentIds: [doc.id],
36
+ messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
37
+ onText: (delta) => process.stdout.write(delta), // optional streaming
38
+ });
39
+ ```
40
+
41
+ `steps` lists what the model did, for example
42
+ `Search app.log (exact) for “failover” — 1 matching lines`. Show it under the answer so users can
43
+ see where the answer came from.
44
+
45
+ Using **Vertex AI** or an **enterprise gateway**? Swap the endpoint:
46
+
47
+ ```ts
48
+ import { vertexAi } from "llm-large-files/gemini";
49
+ const endpoint = vertexAi({ project: "my-project", model: "gemini-3.8-flash", accessToken: getToken });
50
+ // or your own proxy:
51
+ const endpoint = { url: "https://llm-gw.corp/v1/gemini:generateContent", headers: { Authorization: `Bearer ${key}` } };
52
+ ```
53
+
54
+ ## Add it to a web app
55
+
56
+ ```ts
57
+ import express from "express";
58
+ import { createDocumentHandlers } from "llm-large-files/node";
59
+
60
+ const documents = createDocumentHandlers(files, { getOwner: (req) => req.user?.id });
61
+ app.post("/api/documents", documents.upload); // mount before express.json()
62
+ app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
63
+ ```
64
+
65
+ The browser uploads the raw file:
66
+
67
+ ```ts
68
+ await fetch("/api/documents", {
69
+ method: "POST",
70
+ headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },
71
+ body: file,
72
+ }); // → { id, name, format, lines, estimatedTokens, expiresAt, ... }
73
+ ```
74
+
75
+ The full walkthrough, with streaming to the browser, is in the [integration guide](docs/getting-started.md).
76
+ There's also a [one-file demo server](examples/server.ts).
77
+
78
+ ## What it handles
79
+
80
+ | | |
81
+ |---|---|
82
+ | **Formats** | Text, Markdown, logs (UTF-8 and UTF-16), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty) |
83
+ | **Logs** | Detected automatically; the card shows level counts, the time range, and the most frequent errors grouped by shape (`timeout after <n>ms to <ip>`) |
84
+ | **Books and documents** | An outline of headings with line numbers, including Markdown, "Chapter 12", numbered sections, and Hebrew chapter titles |
85
+ | **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit |
86
+ | **Privacy** | Documents can belong to an `owner`; other users can't plan, read, or delete them |
87
+ | **Storage** | In memory, on disk with expiry, or your own store (Redis, S3, a database) |
88
+
89
+ ## Live results
90
+
91
+ With `gemini-3.8-flash` on the Gemini API:
92
+
93
+ | File | Question | Result |
94
+ |---|---|---|
95
+ | 5 MB log, about 1.27M tokens (over the 1M limit) | "What caused the outage?" | Correct root cause, citing the right lines, in about 60 s over 11 tool calls |
96
+ | 467 KB novel, about 117K tokens | "Where was the ledger hidden?" | Sent whole; correct. Estimated 116,840 tokens; Gemini billed 116,842 |
97
+ | Same novel, map-reduce | "Read all of it…" | 4 parts read in parallel; correct, cited answer in 32 s |
98
+
99
+ ## Documentation
100
+
101
+ - [Integration guide](docs/getting-started.md): Express, plain Node, browser upload, streaming, Vertex AI, gateways, existing chat history
102
+ - [API reference](docs/api.md)
103
+ - [Configuration](docs/configuration.md): budget, stores, formats, extractors
104
+ - [How it works](docs/how-it-works.md): planner, cards, tools, map-reduce, and the Gemini quirks it handles
105
+ - [Security](docs/security.md): owners, tool scoping, retention, regex safety
106
+
107
+ ## Requirements
108
+
109
+ Node.js 20.19 or newer. The package is ESM; CommonJS projects can `require()` it on Node 20.19+ and 22.12+.
110
+ For DOCX/PPTX install `jszip`, and for PDF install `unpdf`. Both are optional:
111
+
112
+ ```bash
113
+ npm install jszip unpdf
114
+ ```
115
+
116
+ ## License
117
+
118
+ [MIT](LICENSE)
@@ -0,0 +1,9 @@
1
+ import type { DocumentFormat, LogProfile, OutlineEntry } from "./types.js";
2
+ /** Treats text as a log when most early lines start with a timestamp or a level. */
3
+ export declare function looksLikeLog(lines: string[]): boolean;
4
+ /** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
5
+ export declare function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[];
6
+ /** Replaces the variable parts of a log message so repeated failures group together. */
7
+ export declare function logTemplate(line: string): string;
8
+ export declare function buildLogProfile(lines: string[]): LogProfile;
9
+ //# sourceMappingURL=analyze.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAKrD;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CA6BpF;AAED,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAgC3D"}
@@ -0,0 +1,106 @@
1
+ const MAX_OUTLINE_ENTRIES = 400;
2
+ const MAX_TEMPLATES = 50_000;
3
+ const TIMESTAMP = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?(?:Z|[+-]\d{2}:?\d{2})?/;
4
+ const LINE_START_TIMESTAMP = /^\[?(?:\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}|\d{2}\/\d{2}\/\d{4}|\w{3} {1,2}\d{1,2} \d{2}:\d{2}:\d{2}|\d{2}:\d{2}:\d{2})/;
5
+ const LEVEL = /\b(FATAL|CRITICAL|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b/;
6
+ const LEVEL_NAMES = { ERR: "ERROR", WARNING: "WARN", CRITICAL: "FATAL" };
7
+ /** Treats text as a log when most early lines start with a timestamp or a level. */
8
+ export function looksLikeLog(lines) {
9
+ const sample = lines.filter((line) => line.trim()).slice(0, 200);
10
+ if (sample.length < 5)
11
+ return false;
12
+ const hits = sample.filter((line) => LINE_START_TIMESTAMP.test(line.trim()) || /^\[?(FATAL|ERROR|WARN|WARNING|INFO|DEBUG|TRACE)\b/.test(line.trim())).length;
13
+ return hits / sample.length >= 0.4;
14
+ }
15
+ /** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
16
+ export function buildOutline(lines, format) {
17
+ if (format === "log" || format === "json" || format === "csv")
18
+ return [];
19
+ const entries = [];
20
+ for (let index = 0; index < lines.length; index++) {
21
+ const line = (lines[index] ?? "").trim();
22
+ if (!line || line.length > 120)
23
+ continue;
24
+ const previousBlank = index === 0 || !(lines[index - 1] ?? "").trim();
25
+ let entry;
26
+ const markdown = /^(#{1,6})\s+(.+)$/.exec(line);
27
+ if (markdown)
28
+ entry = { line: index + 1, level: markdown[1].length, title: markdown[2].trim() };
29
+ // A lookahead, not \b: JavaScript's \b does not treat Hebrew letters as word characters.
30
+ else if (/^(chapter|part|book|section|appendix|פרק|חלק|נספח)(?=[\s:.\d]|$)/iu.test(line) && previousBlank) {
31
+ entry = { line: index + 1, level: /^(part|book|חלק)(?=[\s:.\d]|$)/iu.test(line) ? 1 : 2, title: line };
32
+ }
33
+ else if (/^\d+(\.\d+){0,2}\s+\S/.test(line) && previousBlank && line.length <= 80 && !/[.:;,]$/.test(line)) {
34
+ entry = { line: index + 1, level: (line.split(" ")[0].match(/\./g)?.length ?? 0) + 2, title: line };
35
+ }
36
+ else if (previousBlank && line.length >= 4 && line.length <= 60 && /\p{Lu}/u.test(line) && line === line.toUpperCase() && /\p{L}{3}/u.test(line)) {
37
+ entry = { line: index + 1, level: 2, title: line };
38
+ }
39
+ if (entry)
40
+ entries.push(entry);
41
+ }
42
+ if (entries.length <= MAX_OUTLINE_ENTRIES)
43
+ return entries;
44
+ // Keep the top levels first, then sample evenly so the outline still spans the document.
45
+ // A loop, not Math.min(...levels): spreading a few hundred thousand values overflows the stack.
46
+ let minLevel = Number.POSITIVE_INFINITY;
47
+ for (const entry of entries)
48
+ if (entry.level < minLevel)
49
+ minLevel = entry.level;
50
+ const top = entries.filter((entry) => entry.level === minLevel);
51
+ const pool = top.length >= 20 ? top : entries;
52
+ const step = pool.length / MAX_OUTLINE_ENTRIES;
53
+ return Array.from({ length: Math.min(pool.length, MAX_OUTLINE_ENTRIES) }, (_, index) => pool[Math.floor(index * step)]);
54
+ }
55
+ /** Replaces the variable parts of a log message so repeated failures group together. */
56
+ export function logTemplate(line) {
57
+ return line
58
+ .replace(TIMESTAMP, "")
59
+ .replace(/^\W*\d{2}:\d{2}:\d{2}(?:[.,]\d+)?/, "")
60
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<id>")
61
+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g, "<ip>")
62
+ .replace(/\b0x[0-9a-f]+\b|\b[0-9a-f]{12,}\b/gi, "<hex>")
63
+ .replace(/"[^"]{0,200}"|'[^']{0,200}'/g, "<s>")
64
+ .replace(/\d+(?:\.\d+)?/g, "<n>")
65
+ .replace(/\s+/g, " ")
66
+ .trim()
67
+ .slice(0, 180);
68
+ }
69
+ export function buildLogProfile(lines) {
70
+ const levels = {};
71
+ const templates = new Map();
72
+ let firstTimestamp;
73
+ let lastTimestamp;
74
+ for (let index = 0; index < lines.length; index++) {
75
+ const line = lines[index] ?? "";
76
+ const stamp = TIMESTAMP.exec(line)?.[0];
77
+ if (stamp) {
78
+ firstTimestamp ??= stamp;
79
+ lastTimestamp = stamp;
80
+ }
81
+ const raw = LEVEL.exec(line)?.[1];
82
+ if (!raw)
83
+ continue;
84
+ const level = LEVEL_NAMES[raw] ?? raw;
85
+ levels[level] = (levels[level] ?? 0) + 1;
86
+ if (level !== "ERROR" && level !== "FATAL" && level !== "WARN")
87
+ continue;
88
+ const template = logTemplate(line);
89
+ const existing = templates.get(template);
90
+ if (existing)
91
+ existing.count++;
92
+ else if (templates.size < MAX_TEMPLATES)
93
+ templates.set(template, { template, level, count: 1, firstLine: index + 1 });
94
+ }
95
+ const severity = (issue) => (issue.level === "FATAL" ? 2 : issue.level === "ERROR" ? 1 : 0);
96
+ const topIssues = [...templates.values()]
97
+ .sort((left, right) => severity(right) - severity(left) || right.count - left.count)
98
+ .slice(0, 15);
99
+ return {
100
+ levels,
101
+ ...(firstTimestamp ? { firstTimestamp } : {}),
102
+ ...(lastTimestamp ? { lastTimestamp } : {}),
103
+ topIssues,
104
+ };
105
+ }
106
+ //# sourceMappingURL=analyze.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyze.js","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAEA,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,aAAa,GAAG,MAAM,CAAC;AAC7B,MAAM,SAAS,GAAG,6EAA6E,CAAC;AAChG,MAAM,oBAAoB,GAAG,qHAAqH,CAAC;AACnJ,MAAM,KAAK,GAAG,8DAA8D,CAAC;AAC7E,MAAM,WAAW,GAA2B,EAAE,GAAG,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAEjG,oFAAoF;AACpF,MAAM,UAAU,YAAY,CAAC,KAAe;IAC1C,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACjE,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,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,EAAE,SAAS,EAAE,KAAK,GAAG,CAAC,EAAE,CAAC,CAAC;IACxH,CAAC;IACD,MAAM,QAAQ,GAAG,CAAC,KAAe,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtG,MAAM,SAAS,GAAG,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC;SACtC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;SACnF,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChB,OAAO;QACL,MAAM;QACN,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7C,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC3C,SAAS;KACV,CAAC;AACJ,CAAC"}
@@ -0,0 +1,30 @@
1
+ import type { DocumentFormat, ExtractedText, Extractor } from "./types.js";
2
+ /** Picks a format from the file name, then the MIME type. Unknown text-like files are "text". */
3
+ export declare function detectFormat(name: string, mimeType: string): DocumentFormat;
4
+ /**
5
+ * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
6
+ * Throws a readable error for compressed and other binary files.
7
+ */
8
+ export declare function decodeText(bytes: Uint8Array): string;
9
+ /** Text of each `<prefix:p>` paragraph in Office XML. Regex keeps this free of an XML parser dependency. */
10
+ export declare function officeXmlParagraphs(xml: string, prefix: "w" | "a"): string[];
11
+ export type PdfExtractorOptions = {
12
+ /**
13
+ * Rebuild tables from the position of the text, and write each row as `| cell | cell | |`, so an
14
+ * empty cell stays an empty cell. Defaults to true. With false, the text is in pdf.js order, as
15
+ * in version 0.1.0.
16
+ */
17
+ tables?: boolean;
18
+ };
19
+ /**
20
+ * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
21
+ * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
22
+ */
23
+ export declare function createPdfExtractor(options?: PdfExtractorOptions): Extractor;
24
+ export declare const defaultExtractors: Record<DocumentFormat, Extractor>;
25
+ export declare function extractText(bytes: Uint8Array, input: {
26
+ name: string;
27
+ mimeType: string;
28
+ format: DocumentFormat;
29
+ }, extractors?: Partial<Record<DocumentFormat, Extractor>>): Promise<ExtractedText>;
30
+ //# sourceMappingURL=extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["../src/extract.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAmB3E,iGAAiG;AACjG,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,cAAc,CAG3E;AAID;;;GAGG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAkCpD;AAiBD,4GAA4G;AAC5G,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG,MAAM,EAAE,CAY5E;AA6CD,MAAM,MAAM,mBAAmB,GAAG;IAChC;;;;OAIG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAKF;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,SAAS,CAsC/E;AAED,eAAO,MAAM,iBAAiB,EAAE,MAAM,CAAC,cAAc,EAAE,SAAS,CAS/D,CAAC;AAEF,wBAAsB,WAAW,CAC/B,KAAK,EAAE,UAAU,EACjB,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,cAAc,CAAA;CAAE,EACjE,UAAU,GAAE,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,SAAS,CAAC,CAAM,GAC1D,OAAO,CAAC,aAAa,CAAC,CAGxB"}
@@ -0,0 +1,211 @@
1
+ import { layoutPageText, plainPageText } from "./pdf-layout.js";
2
+ const EXTENSION_FORMATS = {
3
+ log: "log", out: "log", err: "log",
4
+ md: "markdown", markdown: "markdown",
5
+ json: "json", jsonl: "json", ndjson: "json",
6
+ csv: "csv", tsv: "csv",
7
+ pdf: "pdf", docx: "docx", pptx: "pptx",
8
+ };
9
+ const MIME_FORMATS = {
10
+ "application/pdf": "pdf",
11
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
12
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
13
+ "text/markdown": "markdown",
14
+ "application/json": "json",
15
+ "text/csv": "csv",
16
+ };
17
+ /** Picks a format from the file name, then the MIME type. Unknown text-like files are "text". */
18
+ export function detectFormat(name, mimeType) {
19
+ const extension = name.toLowerCase().split(".").at(-1) ?? "";
20
+ return EXTENSION_FORMATS[extension] ?? MIME_FORMATS[mimeType.toLowerCase()] ?? "text";
21
+ }
22
+ const NOT_TEXT = "This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.";
23
+ /**
24
+ * Decodes text bytes, honoring UTF-8 and UTF-16 byte-order marks (common for Windows logs).
25
+ * Throws a readable error for compressed and other binary files.
26
+ */
27
+ export function decodeText(bytes) {
28
+ if (bytes[0] === 0xff && bytes[1] === 0xfe)
29
+ return new TextDecoder("utf-16le").decode(bytes.subarray(2));
30
+ if (bytes[0] === 0xfe && bytes[1] === 0xff)
31
+ return new TextDecoder("utf-16be").decode(bytes.subarray(2));
32
+ // Rotated logs often arrive as app.log.gz. Compressed bytes have few zeros, so name them here.
33
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
34
+ throw new Error("This file is gzip-compressed. Decompress it, then attach the text file inside.");
35
+ }
36
+ if (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) {
37
+ throw new Error("This file is a ZIP archive. Extract it, then attach the text file you need.");
38
+ }
39
+ const sample = bytes.subarray(0, 8_192);
40
+ let zeros = 0;
41
+ for (const byte of sample)
42
+ if (byte === 0)
43
+ zeros++;
44
+ // UTF-16 without a BOM: about half the bytes of ASCII text are zero.
45
+ if (sample.length > 64 && zeros / sample.length > 0.3) {
46
+ let oddZeros = 0;
47
+ let evenText = 0;
48
+ for (let index = 0; index < sample.length; index++) {
49
+ if (index % 2 === 1 && sample[index] === 0)
50
+ oddZeros++;
51
+ if (index % 2 === 0 && sample[index] !== 0)
52
+ evenText++;
53
+ }
54
+ const half = sample.length / 2;
55
+ if (oddZeros / half > 0.6 && evenText / half > 0.6)
56
+ return new TextDecoder("utf-16le").decode(bytes);
57
+ }
58
+ if (sample.length > 0 && zeros / sample.length > 0.01)
59
+ throw new Error(NOT_TEXT);
60
+ // Compressed, encrypted, and media files spread control bytes evenly: about 1 byte in 10.
61
+ // Text has almost none, in UTF-8 or in a legacy single-byte encoding. Tab, line breaks, form
62
+ // feed, and ESC (colour codes) do not count.
63
+ let controls = 0;
64
+ for (const byte of sample) {
65
+ if (byte < 0x09 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f)
66
+ controls++;
67
+ }
68
+ if (sample.length >= 64 && controls / sample.length > 0.03)
69
+ throw new Error(NOT_TEXT);
70
+ return new TextDecoder("utf-8").decode(bytes);
71
+ }
72
+ const plainText = async (bytes) => ({ text: decodeText(bytes) });
73
+ function decodeXmlEntities(value) {
74
+ return value.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (match, entity) => {
75
+ const lower = entity.toLowerCase();
76
+ if (lower === "amp")
77
+ return "&";
78
+ if (lower === "lt")
79
+ return "<";
80
+ if (lower === "gt")
81
+ return ">";
82
+ if (lower === "quot")
83
+ return "\"";
84
+ if (lower === "apos")
85
+ return "'";
86
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : Number.parseInt(lower.slice(1), 10);
87
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
88
+ });
89
+ }
90
+ /** Text of each `<prefix:p>` paragraph in Office XML. Regex keeps this free of an XML parser dependency. */
91
+ export function officeXmlParagraphs(xml, prefix) {
92
+ const paragraphs = xml.match(new RegExp(`<${prefix}:p[\\s>][\\s\\S]*?</${prefix}:p>`, "g")) ?? [];
93
+ const textPattern = new RegExp(`<${prefix}:t(?:\\s[^>]*)?>([\\s\\S]*?)</${prefix}:t>|<${prefix}:(tab|br)\\b[^>]*/>`, "g");
94
+ return paragraphs.map((paragraph) => {
95
+ let text = "";
96
+ for (const match of paragraph.matchAll(textPattern)) {
97
+ if (match[2] === "tab")
98
+ text += "\t";
99
+ else if (match[2] === "br")
100
+ text += "\n";
101
+ else
102
+ text += decodeXmlEntities(match[1] ?? "");
103
+ }
104
+ return text;
105
+ }).filter((text) => text.trim());
106
+ }
107
+ async function loadZip(bytes) {
108
+ let JSZip;
109
+ try {
110
+ JSZip = (await import("jszip")).default;
111
+ }
112
+ catch {
113
+ throw new Error("Reading DOCX and PPTX files needs the optional dependency \"jszip\".");
114
+ }
115
+ return JSZip.loadAsync(bytes);
116
+ }
117
+ const docx = async (bytes) => {
118
+ const archive = await loadZip(bytes);
119
+ const names = Object.keys(archive.files)
120
+ .filter((name) => /^word\/(document|header\d+|footer\d+|footnotes|endnotes)\.xml$/i.test(name))
121
+ .sort((left, right) => left === "word/document.xml" ? -1 : right === "word/document.xml" ? 1 : left.localeCompare(right));
122
+ if (!names.includes("word/document.xml"))
123
+ throw new Error("This DOCX does not contain word/document.xml.");
124
+ const sections = [];
125
+ for (const name of names) {
126
+ const xml = await archive.file(name)?.async("string");
127
+ if (xml)
128
+ sections.push(officeXmlParagraphs(xml, "w").join("\n"));
129
+ }
130
+ return { text: sections.filter(Boolean).join("\n\n") };
131
+ };
132
+ const pptx = async (bytes) => {
133
+ const archive = await loadZip(bytes);
134
+ const slideNumber = (name) => Number(/slide(\d+)\.xml$/i.exec(name)?.[1] ?? Number.MAX_SAFE_INTEGER);
135
+ const names = Object.keys(archive.files)
136
+ .filter((name) => /^ppt\/slides\/slide\d+\.xml$/i.test(name))
137
+ .sort((left, right) => slideNumber(left) - slideNumber(right));
138
+ if (names.length === 0)
139
+ throw new Error("This PPTX does not contain any slides.");
140
+ const slides = [];
141
+ for (const name of names) {
142
+ const xml = await archive.file(name)?.async("string");
143
+ const text = xml ? officeXmlParagraphs(xml, "a").join("\n") : "";
144
+ slides.push(`## Slide ${slideNumber(name)}\n${text || "[No text on this slide]"}`);
145
+ }
146
+ return { text: slides.join("\n\n"), pages: names.length };
147
+ };
148
+ /** Written in place of a page that has no text at all, so the model can say so instead of guessing. */
149
+ const PAGE_WITHOUT_TEXT = "[No text on this page. It may be a scan, a photo, or a chart.]";
150
+ /**
151
+ * The built-in PDF extractor (needs `unpdf`). Use it to change an option:
152
+ * `createLargeFiles({ extractors: { pdf: createPdfExtractor({ tables: false }) } })`.
153
+ */
154
+ export function createPdfExtractor(options = {}) {
155
+ const tables = options.tables ?? true;
156
+ return async (bytes) => {
157
+ let unpdf;
158
+ try {
159
+ unpdf = await import("unpdf");
160
+ }
161
+ catch {
162
+ throw new Error("Reading PDF files needs the optional dependency \"unpdf\".");
163
+ }
164
+ // pdf.js may detach the buffer it reads, so give it a copy.
165
+ const document = await unpdf.getDocumentProxy(new Uint8Array(bytes));
166
+ const pages = [];
167
+ let hasText = false;
168
+ for (let number = 1; number <= document.numPages; number++) {
169
+ const page = await document.getPage(number);
170
+ const content = await page.getTextContent();
171
+ const items = content.items.filter((item) => typeof item.str === "string");
172
+ let text = "";
173
+ if (tables) {
174
+ try {
175
+ text = layoutPageText(items, page.getViewport({ scale: 1 }).transform);
176
+ }
177
+ catch {
178
+ // Unusual geometry must never lose a page: fall back to the plain order.
179
+ text = plainPageText(items);
180
+ }
181
+ }
182
+ else {
183
+ text = plainPageText(items);
184
+ }
185
+ text = text.trim();
186
+ if (text)
187
+ hasText = true;
188
+ pages.push(`--- Page ${number} ---\n${text || PAGE_WITHOUT_TEXT}`);
189
+ page.cleanup();
190
+ }
191
+ if (!hasText) {
192
+ throw new Error("This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.");
193
+ }
194
+ return { text: pages.join("\n\n"), pages: document.numPages };
195
+ };
196
+ }
197
+ export const defaultExtractors = {
198
+ text: plainText,
199
+ markdown: plainText,
200
+ log: plainText,
201
+ json: plainText,
202
+ csv: plainText,
203
+ pdf: createPdfExtractor(),
204
+ docx,
205
+ pptx,
206
+ };
207
+ export async function extractText(bytes, input, extractors = {}) {
208
+ const extractor = extractors[input.format] ?? defaultExtractors[input.format];
209
+ return extractor(bytes, input);
210
+ }
211
+ //# sourceMappingURL=extract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.js","sourceRoot":"","sources":["../src/extract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,aAAa,EAAoB,MAAM,iBAAiB,CAAC;AAGlF,MAAM,iBAAiB,GAAmC;IACxD,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK;IAClC,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU;IACpC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC3C,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK;IACtB,GAAG,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM;CACvC,CAAC;AAEF,MAAM,YAAY,GAAmC;IAC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