@aeye/resources 0.3.9 → 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/aeye-resources-converters.md +191 -0
- package/aeye-resources-graph.md +61 -7
- package/aeye-resources-parsers.md +40 -13
- package/aeye-resources-slicers.md +76 -8
- package/aeye-resources.md +24 -9
- package/dist/converters/data.d.ts +9 -0
- package/dist/converters/data.d.ts.map +1 -0
- package/dist/converters/data.js +78 -0
- package/dist/converters/data.js.map +1 -0
- package/dist/converters/folder.d.ts +13 -0
- package/dist/converters/folder.d.ts.map +1 -0
- package/dist/converters/folder.js +63 -0
- package/dist/converters/folder.js.map +1 -0
- package/dist/converters/index.d.ts +9 -0
- package/dist/converters/index.d.ts.map +1 -0
- package/dist/converters/index.js +22 -0
- package/dist/converters/index.js.map +1 -0
- package/dist/converters/markup.d.ts +6 -0
- package/dist/converters/markup.d.ts.map +1 -0
- package/dist/converters/markup.js +59 -0
- package/dist/converters/markup.js.map +1 -0
- package/dist/converters/pdf.d.ts +6 -0
- package/dist/converters/pdf.d.ts.map +1 -0
- package/dist/converters/pdf.js +70 -0
- package/dist/converters/pdf.js.map +1 -0
- package/dist/converters/tables.d.ts +12 -0
- package/dist/converters/tables.d.ts.map +1 -0
- package/dist/converters/tables.js +64 -0
- package/dist/converters/tables.js.map +1 -0
- package/dist/default.d.ts +9 -5
- package/dist/default.d.ts.map +1 -1
- package/dist/default.js +23 -8
- package/dist/default.js.map +1 -1
- package/dist/graph.d.ts +64 -6
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +127 -32
- package/dist/graph.js.map +1 -1
- package/dist/html/dom.d.ts +31 -0
- package/dist/html/dom.d.ts.map +1 -0
- package/dist/html/dom.js +194 -0
- package/dist/html/dom.js.map +1 -0
- package/dist/html/entities.d.ts +3 -0
- package/dist/html/entities.d.ts.map +1 -0
- package/dist/html/entities.js +33 -0
- package/dist/html/entities.js.map +1 -0
- package/dist/html/markdown.d.ts +30 -0
- package/dist/html/markdown.d.ts.map +1 -0
- package/dist/html/markdown.js +429 -0
- package/dist/html/markdown.js.map +1 -0
- package/dist/http/index.d.ts +5 -0
- package/dist/http/index.d.ts.map +1 -0
- package/dist/http/index.js +3 -0
- package/dist/http/index.js.map +1 -0
- package/dist/http/loader.d.ts +74 -0
- package/dist/http/loader.d.ts.map +1 -0
- package/dist/http/loader.js +248 -0
- package/dist/http/loader.js.map +1 -0
- package/dist/http/sniff.d.ts +38 -0
- package/dist/http/sniff.d.ts.map +1 -0
- package/dist/http/sniff.js +131 -0
- package/dist/http/sniff.js.map +1 -0
- package/dist/imports.d.ts +29 -0
- package/dist/imports.d.ts.map +1 -0
- package/dist/imports.js +53 -0
- package/dist/imports.js.map +1 -0
- package/dist/index.d.ts +28 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -6
- package/dist/index.js.map +1 -1
- package/dist/optional.d.ts +9 -0
- package/dist/optional.d.ts.map +1 -0
- package/dist/optional.js +17 -0
- package/dist/optional.js.map +1 -0
- package/dist/parsers/code.d.ts +1 -1
- package/dist/parsers/code.d.ts.map +1 -1
- package/dist/parsers/code.js +2 -2
- package/dist/parsers/code.js.map +1 -1
- package/dist/parsers/convert.d.ts +8 -0
- package/dist/parsers/convert.d.ts.map +1 -0
- package/dist/parsers/convert.js +40 -0
- package/dist/parsers/convert.js.map +1 -0
- package/dist/parsers/data.d.ts +8 -0
- package/dist/parsers/data.d.ts.map +1 -0
- package/dist/parsers/data.js +20 -0
- package/dist/parsers/data.js.map +1 -0
- package/dist/parsers/docx.d.ts +2 -2
- package/dist/parsers/docx.d.ts.map +1 -1
- package/dist/parsers/docx.js +9 -68
- package/dist/parsers/docx.js.map +1 -1
- package/dist/parsers/excel.d.ts +4 -1
- package/dist/parsers/excel.d.ts.map +1 -1
- package/dist/parsers/excel.js +17 -136
- package/dist/parsers/excel.js.map +1 -1
- package/dist/parsers/folder.d.ts +3 -0
- package/dist/parsers/folder.d.ts.map +1 -0
- package/dist/parsers/folder.js +21 -0
- package/dist/parsers/folder.js.map +1 -0
- package/dist/parsers/html.d.ts +5 -2
- package/dist/parsers/html.d.ts.map +1 -1
- package/dist/parsers/html.js +11 -33
- package/dist/parsers/html.js.map +1 -1
- package/dist/parsers/image.d.ts +1 -1
- package/dist/parsers/image.d.ts.map +1 -1
- package/dist/parsers/image.js +2 -2
- package/dist/parsers/image.js.map +1 -1
- package/dist/parsers/index.d.ts +13 -9
- package/dist/parsers/index.d.ts.map +1 -1
- package/dist/parsers/index.js +12 -9
- package/dist/parsers/index.js.map +1 -1
- package/dist/parsers/markdown.d.ts +1 -1
- package/dist/parsers/markdown.d.ts.map +1 -1
- package/dist/parsers/markdown.js +2 -2
- package/dist/parsers/markdown.js.map +1 -1
- package/dist/parsers/pdf.d.ts +2 -2
- package/dist/parsers/pdf.d.ts.map +1 -1
- package/dist/parsers/pdf.js +99 -119
- package/dist/parsers/pdf.js.map +1 -1
- package/dist/parsers/text.d.ts +1 -1
- package/dist/parsers/text.d.ts.map +1 -1
- package/dist/parsers/text.js +2 -2
- package/dist/parsers/text.js.map +1 -1
- package/dist/parsers/version.d.ts +42 -0
- package/dist/parsers/version.d.ts.map +1 -0
- package/dist/parsers/version.js +100 -0
- package/dist/parsers/version.js.map +1 -0
- package/dist/parsers/zip.d.ts +1 -1
- package/dist/parsers/zip.d.ts.map +1 -1
- package/dist/parsers/zip.js +12 -5
- package/dist/parsers/zip.js.map +1 -1
- package/dist/registry.d.ts +46 -3
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +97 -39
- package/dist/registry.js.map +1 -1
- package/dist/renderers/index.d.ts +2 -2
- package/dist/renderers/index.d.ts.map +1 -1
- package/dist/renderers/index.js +1 -1
- package/dist/renderers/index.js.map +1 -1
- package/dist/renderers/poppler.d.ts +1 -1
- package/dist/renderers/poppler.d.ts.map +1 -1
- package/dist/renderers/poppler.js +1 -1
- package/dist/renderers/poppler.js.map +1 -1
- package/dist/resolvers/file.d.ts +7 -1
- package/dist/resolvers/file.d.ts.map +1 -1
- package/dist/resolvers/file.js +26 -6
- package/dist/resolvers/file.js.map +1 -1
- package/dist/resolvers/folder.d.ts +18 -0
- package/dist/resolvers/folder.d.ts.map +1 -0
- package/dist/resolvers/folder.js +89 -0
- package/dist/resolvers/folder.js.map +1 -0
- package/dist/resolvers/index.d.ts +4 -3
- package/dist/resolvers/index.d.ts.map +1 -1
- package/dist/resolvers/index.js +4 -3
- package/dist/resolvers/index.js.map +1 -1
- package/dist/resolvers/url.d.ts +5 -1
- package/dist/resolvers/url.d.ts.map +1 -1
- package/dist/resolvers/url.js +13 -74
- package/dist/resolvers/url.js.map +1 -1
- package/dist/resolvers/zip.d.ts +1 -1
- package/dist/resolvers/zip.d.ts.map +1 -1
- package/dist/resolvers/zip.js +2 -2
- package/dist/resolvers/zip.js.map +1 -1
- package/dist/section-keys.d.ts +16 -0
- package/dist/section-keys.d.ts.map +1 -0
- package/dist/section-keys.js +24 -0
- package/dist/section-keys.js.map +1 -0
- package/dist/sections.d.ts +39 -0
- package/dist/sections.d.ts.map +1 -0
- package/dist/sections.js +118 -0
- package/dist/sections.js.map +1 -0
- package/dist/segmenters/default.d.ts +1 -1
- package/dist/segmenters/default.d.ts.map +1 -1
- package/dist/segmenters/default.js +1 -1
- package/dist/segmenters/default.js.map +1 -1
- package/dist/segmenters/index.d.ts +3 -3
- package/dist/segmenters/index.d.ts.map +1 -1
- package/dist/segmenters/index.js +2 -2
- package/dist/segmenters/index.js.map +1 -1
- package/dist/segmenters/langchain.d.ts +1 -1
- package/dist/segmenters/langchain.d.ts.map +1 -1
- package/dist/segmenters/langchain.js +1 -1
- package/dist/segmenters/langchain.js.map +1 -1
- package/dist/slicers/code.d.ts +30 -1
- package/dist/slicers/code.d.ts.map +1 -1
- package/dist/slicers/code.js +118 -32
- package/dist/slicers/code.js.map +1 -1
- package/dist/slicers/index.d.ts +3 -3
- package/dist/slicers/index.d.ts.map +1 -1
- package/dist/slicers/index.js +3 -3
- package/dist/slicers/index.js.map +1 -1
- package/dist/slicers/markdown.d.ts +15 -1
- package/dist/slicers/markdown.d.ts.map +1 -1
- package/dist/slicers/markdown.js +56 -27
- package/dist/slicers/markdown.js.map +1 -1
- package/dist/slicers/text.d.ts +1 -1
- package/dist/slicers/text.d.ts.map +1 -1
- package/dist/slicers/text.js +6 -4
- package/dist/slicers/text.js.map +1 -1
- package/dist/stack.d.ts +41 -0
- package/dist/stack.d.ts.map +1 -0
- package/dist/stack.js +56 -0
- package/dist/stack.js.map +1 -0
- package/dist/summaries.d.ts +11 -0
- package/dist/summaries.d.ts.map +1 -0
- package/dist/summaries.js +131 -0
- package/dist/summaries.js.map +1 -0
- package/dist/tables.d.ts +21 -0
- package/dist/tables.d.ts.map +1 -0
- package/dist/tables.js +113 -0
- package/dist/tables.js.map +1 -0
- package/dist/types.d.ts +140 -17
- package/dist/types.d.ts.map +1 -1
- package/dist/utils.d.ts +59 -3
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +149 -159
- package/dist/utils.js.map +1 -1
- package/dist/versions.d.ts +207 -0
- package/dist/versions.d.ts.map +1 -0
- package/dist/versions.js +217 -0
- package/dist/versions.js.map +1 -0
- package/dist/zip-internal.d.ts +9 -4
- package/dist/zip-internal.d.ts.map +1 -1
- package/dist/zip-internal.js +45 -19
- package/dist/zip-internal.js.map +1 -1
- package/package.json +33 -3
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# @aeye/resources — versions, converters, sections, fetching and folders
|
|
2
|
+
|
|
3
|
+
A resource has a **raw** form (the bytes as they are stored or served) and, for many formats, an
|
|
4
|
+
**LLM-ready version** made from it by a **converter**: clean markdown from html, tables from a
|
|
5
|
+
spreadsheet, text page by page from a pdf, a pretty form of json or yaml, a listing of a folder. Keep
|
|
6
|
+
both: show either, and cut sections and slices from the version.
|
|
7
|
+
|
|
8
|
+
## Versions (`@aeye/resources/versions`, browser safe)
|
|
9
|
+
|
|
10
|
+
Every shape is a zod schema with its type derived from it, so stored or sent versions can be checked.
|
|
11
|
+
The module imports only zod.
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { resourceVersionSchema, versionText, versionMimeType, type ResourceVersion } from "@aeye/resources/versions";
|
|
15
|
+
|
|
16
|
+
type ResourceVersion =
|
|
17
|
+
| { kind: "markdown"; text: string; ...base } // html, docx, folders
|
|
18
|
+
| { kind: "text"; text: string; ...base }
|
|
19
|
+
| { kind: "code"; language: string; text: string; ...base } // json, yaml (pretty)
|
|
20
|
+
| { kind: "pages"; pages: string[]; ...base } // pdf
|
|
21
|
+
| { kind: "table"; tables: Table[]; ...base }; // csv, tsv, workbooks
|
|
22
|
+
// base: { converter: string; from: string /* source type */; title?: string; metadata?: Record<string, unknown> }
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
What can be worked out is a function, not a field:
|
|
26
|
+
|
|
27
|
+
| Function | Gives |
|
|
28
|
+
| --- | --- |
|
|
29
|
+
| `versionText(v)` | the text: `text`, pages joined by `PAGE_BREAK` (`\f`), or tables as markdown (`## name` + GFM table, blocks joined by a blank line) |
|
|
30
|
+
| `versionMimeType(v)` | `text/markdown`, `text/plain`, or the code language's (`application/json`, `application/yaml`) |
|
|
31
|
+
| `tableToMarkdown(t)` / `tableBlock(t)` | one table as a GFM table / with its heading |
|
|
32
|
+
| `columnKinds(t)` | per column: `empty`, `boolean`, `integer`, `number`, `date` or `text` |
|
|
33
|
+
| `tableRecords(t)` | rows as records keyed by header, cells typed by column kind (blank/repeat headers get `column 3`, `name 2`) |
|
|
34
|
+
|
|
35
|
+
`RESOURCE_VERSION_KINDS` lists the kinds; `ResourceVersionOf<"table">` picks one. `folderListingSchema`
|
|
36
|
+
and `tableSchema` are here too.
|
|
37
|
+
|
|
38
|
+
## Converters
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
interface ResourceConverter {
|
|
42
|
+
id: string;
|
|
43
|
+
supportedTypes: ResourceType[];
|
|
44
|
+
priority?: number; // higher tried first; ties → most recently registered
|
|
45
|
+
isSupported?(type, ctx): boolean | Promise<boolean>; // e.g. its optional dependency is installed
|
|
46
|
+
convert(source: ResourceSource, ctx: { registry, options: ParseOptions }): Promise<ResourceVersion | undefined>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
registry.registerConverter(myConverter, { priority: 10 });
|
|
50
|
+
registry.getConverters("html"); // the stack, first tried first
|
|
51
|
+
registry.hasConverter("html");
|
|
52
|
+
await registry.convertSource(source); // version, or undefined (no converter / all declined → raw is LLM-ready)
|
|
53
|
+
await registry.convert("https://x.dev/page", { renderer }); // resolve + convert; { source (input buffered), version }
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
A converter that returns `undefined` declines and one that throws falls back to the next; if all
|
|
57
|
+
throw, the error (or an `AggregateError`) is thrown. One-shot inputs are buffered so each converter
|
|
58
|
+
gets the whole input. Per-type options from `configureType` apply.
|
|
59
|
+
|
|
60
|
+
Built in (`DEFAULT_CONVERTERS`, registered by `createDefaultResourceRegistry`):
|
|
61
|
+
|
|
62
|
+
| Converter | Types | Version |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `htmlConverter` | html | markdown of the main content; `title`, and `description`, `language`, `canonicalUrl` in metadata |
|
|
65
|
+
| `docxConverter` | docx | markdown, through mammoth's html (needs `mammoth`) |
|
|
66
|
+
| `delimitedConverter` | csv, tsv | tables; RFC 4180, the csv delimiter detected (`, ; tab \|`); no dependency |
|
|
67
|
+
| `workbookConverter` | excel | tables per sheet, formatted cells (needs `xlsx`) |
|
|
68
|
+
| `pdfConverter` | pdf | pages (needs `pdf-parse`); scanned pages are empty — use the render/transcribe parsers for those |
|
|
69
|
+
| `jsonConverter` | json | json indented two spaces; json lines each pretty printed. Declines when already pretty or not json |
|
|
70
|
+
| `yamlConverter` | yaml | even yaml (needs `js-yaml`). Declines when it has comments (they would be lost), is invalid or already even |
|
|
71
|
+
| `folderConverter` | folder | markdown listing: `# name`, `Folder: <path>`, `- entry (type, size)` |
|
|
72
|
+
|
|
73
|
+
### Html to markdown
|
|
74
|
+
|
|
75
|
+
`htmlToCleanMarkdown(html, options)` → `{ markdown, title?, description?, language?, canonicalUrl? }`
|
|
76
|
+
(`htmlToMarkdown` gives the markdown alone). It parses html into a tree (`parseHtml`: void elements,
|
|
77
|
+
raw text, implied end tags; never throws), drops scripts, styles, forms, iframes, svg and hidden
|
|
78
|
+
elements (`hidden`, `aria-hidden`, inline `display:none`), and with `content: "main"` (default) keeps
|
|
79
|
+
the `<main>` (or `role=main`), else the one `<article>`, else the body without its chrome (`nav`,
|
|
80
|
+
`aside`, `header`/`footer` outside content, chrome landmarks, and class/id words like `menu`,
|
|
81
|
+
`sidebar`, `cookie`, `share`). A nearly empty main falls back to the body; a page that is all chrome
|
|
82
|
+
keeps it. Out comes GitHub markdown: headings, paragraphs, nested/numbered lists, tables (colspans,
|
|
83
|
+
captions; one-column layout tables become blocks), fenced code with its language, inline code,
|
|
84
|
+
quotes, definitions, emphasis, links and images made absolute against `baseUrl` (or `<base href>`).
|
|
85
|
+
Fragment, `javascript:` and `data:` links and 1px images are dropped; line starts that would read as
|
|
86
|
+
markdown are escaped. Options: `baseUrl`, `content`, `links`, `images`, `dropTags`. Through the
|
|
87
|
+
registry it is `options.html`, with `baseUrl` defaulting to the resource's URL.
|
|
88
|
+
|
|
89
|
+
## Parsing works from the version
|
|
90
|
+
|
|
91
|
+
Version parsers (`createVersionParser({ id, supportedTypes, defaultSlicer, fallback, links? })`)
|
|
92
|
+
convert through the registry's stack for the type (else `fallback`) and cut parts from the version:
|
|
93
|
+
a page per part (`#page/<n>`), a sheet per part (`#sheet/<i>`), otherwise one part (`#part/0`). The
|
|
94
|
+
version is kept on `resource.version`. Registering another converter for a type (say a Readability
|
|
95
|
+
one for html) changes what is parsed, sliced and sectioned with no other change. When the stack
|
|
96
|
+
declines, the parser declines too and the next parser (e.g. `textParser`) takes the raw text.
|
|
97
|
+
|
|
98
|
+
## Sections of a version
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
registry.sectionVersion(version); // or sectionVersion(version) for the defaults alone
|
|
102
|
+
// → [{ key, path, title, start, end }] offsets into versionText(version), covering it in order
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
| Version | Cut by | Keys |
|
|
106
|
+
| --- | --- | --- |
|
|
107
|
+
| markdown | headings (fences ignored) | heading path `Guide > Usage`, `(root)` before the first heading |
|
|
108
|
+
| pages | page (its page break included) | `Page 1`, `Page 2` |
|
|
109
|
+
| table | table | `Sheet > Sheet - Table 2`, or the table's name, or `Table 1` |
|
|
110
|
+
| code (json, yaml) | top-level key (text before the first joins it) | `name`, `list` |
|
|
111
|
+
| anything else | whole | `(root)` |
|
|
112
|
+
|
|
113
|
+
Keys come from structure (`sectionKeys`; repeats get ` ~2`), so they survive edits around them.
|
|
114
|
+
`registry.registerSectioner({ id, supports(version), sections(version) })` adds a sectioner; newer
|
|
115
|
+
ones are asked first, so one can override a default for the versions it supports.
|
|
116
|
+
|
|
117
|
+
## Fetching URLs
|
|
118
|
+
|
|
119
|
+
The url resolver fetches with `fetchResource(url, registry, options)`, also usable on its own:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const page = await fetchResource("https://site.dev/docs", registry, {
|
|
123
|
+
fetch, // FetchFn, default global fetch (inject to test or proxy)
|
|
124
|
+
headers, timeoutMs /* 30000 */, maxBytes /* 50 MiB */, signal,
|
|
125
|
+
renderer, // PageRenderer, optional
|
|
126
|
+
render: "auto", // "never" | "auto" | "always"
|
|
127
|
+
});
|
|
128
|
+
page.source; // { location: final URL, input: Uint8Array, type?, mimeType (always), size, modifiedAt?, metadata }
|
|
129
|
+
page.detectedBy; // "content" | "header" | "extension" | "text" | "default"
|
|
130
|
+
page.charset; page.renderedBy; page.renderError; page.requestedUrl; page.url; page.status;
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- **Type detection** (`detectType`): magic numbers first (pdf, png, jpeg, gif, webp, bmp, ico; zips
|
|
134
|
+
told apart as docx or workbook by their entry names), then a specific `Content-Type`, then the URL
|
|
135
|
+
path's extension, then how the text starts (html, svg, xml, json), else `text`, or no type for
|
|
136
|
+
binary bytes. Generic types (`application/octet-stream`, `text/plain`) are looked past, and so is
|
|
137
|
+
a `text/*` type with no rule of its own (`text/typescript` says only `text`, so `a.ts` is
|
|
138
|
+
`typescript` by its extension; with no extension it labels plain `text`).
|
|
139
|
+
- **Mime type**: `source.mimeType` is always set. A specific declared mime type is kept as it is
|
|
140
|
+
(`application/javascript`); else the detected type's from `DEFAULT_TYPE_MIME_TYPES` (`markdown` →
|
|
141
|
+
`text/markdown`, `docx` → the wordprocessingml type, an image's by its extension); else
|
|
142
|
+
`text/plain` for text and `application/octet-stream` for binary bytes (`effectiveMimeType`).
|
|
143
|
+
- **Text** is decoded by BOM, declared charset, or (html) `<meta charset>`, and stored as utf-8
|
|
144
|
+
(`metadata.charset` keeps the original).
|
|
145
|
+
- **Redirects** are followed; the source is located at the final URL (`metadata.requestedUrl` keeps the
|
|
146
|
+
asked one). Non-2xx, timeouts and bodies over `maxBytes` throw; aborts throw an `AbortError`.
|
|
147
|
+
- `statUrl` probes with HEAD for type, size and modified time (falls back to the URL itself).
|
|
148
|
+
|
|
149
|
+
### Content sniffing helpers
|
|
150
|
+
|
|
151
|
+
The pieces `detectType` is made of are exported for code that fetches its own way:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import {
|
|
155
|
+
detectType, parseContentType, isGenericMimeType, sniffMagic, sniffText, looksBinary, decodeText, isUtf8Charset,
|
|
156
|
+
effectiveMimeType, DEFAULT_TYPE_MIME_TYPES,
|
|
157
|
+
} from "@aeye/resources";
|
|
158
|
+
|
|
159
|
+
detectType(registry, url, bytes, parseContentType(header)); // { type?, mimeType, detectedBy, binary }
|
|
160
|
+
parseContentType("Text/HTML; charset=UTF-8"); // { mimeType: "text/html", charset: "utf-8" }; undefined for none
|
|
161
|
+
isGenericMimeType("application/octet-stream"); // true (also text/plain, binary/octet-stream, application/unknown, …)
|
|
162
|
+
sniffMagic(bytes); // { type: "pdf", mimeType: "application/pdf" } by the first bytes, or undefined
|
|
163
|
+
sniffText(text); // { type: "html" | "svg" | "xml" | "json", mimeType } by how the text starts, or undefined
|
|
164
|
+
looksBinary(bytes); // true for a NUL byte, or many control characters, in the first 1024 bytes
|
|
165
|
+
decodeText(bytes, charset?, html?); // { text, charset }: BOM, then the declared charset, then <meta charset> for html
|
|
166
|
+
isUtf8Charset("us-ascii"); // true for utf-8 or ascii (no transcoding needed)
|
|
167
|
+
effectiveMimeType("markdown", "text/plain", { location: "/a.md", binary: false }); // "text/markdown"
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Page renderers
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
interface PageRenderer {
|
|
174
|
+
readonly id: string;
|
|
175
|
+
render(request: { url; html; headers?; signal? }): Promise<{ html: string; url?: string }>;
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
The library ships none; plug in a headless browser. With `render: "auto"` only pages that look built
|
|
180
|
+
by scripts go through it (`looksScriptRendered`: an empty app root like `<div id="root"></div>`, a
|
|
181
|
+
`<noscript>` asking for JavaScript, or scripts with almost no visible text). The rendered html
|
|
182
|
+
replaces the fetched html (`metadata.renderedBy`). In `auto` a failed render keeps the fetched html
|
|
183
|
+
(`metadata.renderError`); in `always` it throws. Pass `renderer`/`render` with the call that fetches, e.g. `registry.load(url, { renderer })`.
|
|
184
|
+
|
|
185
|
+
## Folders
|
|
186
|
+
|
|
187
|
+
`folderResolver` (in the default registry, ahead of the file resolver) resolves an existing folder to a
|
|
188
|
+
`folder` resource: raw form a json `FolderListing` (`listFolder` gives it directly), version a
|
|
189
|
+
markdown listing, links one per entry, so `buildResourceGraph(registry, dir)` walks the tree. Options
|
|
190
|
+
under `folder`: `includeHidden`, `ignore` (`DEFAULT_FOLDER_IGNORE`), `maxEntries`
|
|
191
|
+
(`DEFAULT_FOLDER_MAX_ENTRIES`). `FOLDER_TYPE` is `"folder"`, `FOLDER_MIME_TYPE` is `"inode/directory"`.
|
package/aeye-resources-graph.md
CHANGED
|
@@ -28,7 +28,16 @@ interface ResourceResolver {
|
|
|
28
28
|
(`bundle.zip#entry/doc.md`) and links **relative to another entry** (`./other.md`, `../assets/x.png`,
|
|
29
29
|
`/root.md`) within the same archive. Registered first so entry-relative links beat file/url.
|
|
30
30
|
- **fileResolver** — absolute paths, `file://` URLs, and relative paths against a non-web,
|
|
31
|
-
non-zip `baseLocation`. Sets `modifiedAt`/`size` from `fs.stat`.
|
|
31
|
+
non-zip `baseLocation`. Sets `modifiedAt`/`size` from `fs.stat`. When the base is a script
|
|
32
|
+
(`javascript`, `typescript`, `jsx`, `tsx`), links are imports: see
|
|
33
|
+
[Script imports](#script-imports).
|
|
34
|
+
- **folderResolver** — absolute paths, `file://` URLs and relative links (against a local base) that name an
|
|
35
|
+
existing **folder**. It resolves to a `folder` resource whose raw form is its listing (json,
|
|
36
|
+
`folderListingSchema`): entries folders-first, each with location, kind, detected type, size and
|
|
37
|
+
modified time. `options.folder`: `includeHidden` (default false), `ignore` (default `.git`,
|
|
38
|
+
`node_modules`), `maxEntries` (default 1000; the rest are counted, `truncated` set). A script's
|
|
39
|
+
relative import of a folder (`./lib`) is not taken: module resolution gives its index file. Registered
|
|
40
|
+
ahead of the file resolver.
|
|
32
41
|
- **urlResolver** — http(s) URLs, plus relative/root-relative/protocol-relative links resolved
|
|
33
42
|
against an http(s) `baseLocation` (via `new URL`). Sets `modifiedAt` (`Last-Modified`) and `size`
|
|
34
43
|
(`Content-Length`); `stat` uses a `HEAD` request.
|
|
@@ -44,6 +53,33 @@ const stat = await registry.statLink("./child.md", { baseLocation: parent.locati
|
|
|
44
53
|
// → { location, modifiedAt?, size?, mimeType?, type? } | undefined
|
|
45
54
|
```
|
|
46
55
|
|
|
56
|
+
### Script imports
|
|
57
|
+
|
|
58
|
+
From a script base, the file resolver follows node and TypeScript module resolution:
|
|
59
|
+
|
|
60
|
+
- Only a relative specifier (`./a`, `../a`, `/a`, `.`, `..`) names a file. A bare one (`react`,
|
|
61
|
+
`node:fs`, `@scope/pkg`) names a package, so `canResolve` is `false` and the graph records the
|
|
62
|
+
edge as `unresolved`.
|
|
63
|
+
- A relative import resolves to the first of its candidates that is a file: the path as written,
|
|
64
|
+
the TypeScript source its extension stands for (`./a.js` → `a.ts`, `a.tsx`; `.jsx` → `.tsx`;
|
|
65
|
+
`.mjs` → `.mts`; `.cjs` → `.cts`), the path plus each of `IMPORT_EXTENSIONS`
|
|
66
|
+
(`.ts .tsx .d.ts .mts .cts .js .jsx .mjs .cjs .json`), then `<path>/index` plus each of them.
|
|
67
|
+
With no candidate on disk, `stat` returns `undefined` and `resolve` resolves nothing.
|
|
68
|
+
|
|
69
|
+
The same steps are exported for code that checks files its own way (a sandbox, a virtual file
|
|
70
|
+
system):
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { diskIsFile, importCandidates, isRelativeSpecifier, isScriptType, resolveImportPath, SCRIPT_TYPES } from "@aeye/resources";
|
|
74
|
+
|
|
75
|
+
isScriptType("tsx"); // true — one of SCRIPT_TYPES
|
|
76
|
+
isRelativeSpecifier("./store"); // true; "react" → false
|
|
77
|
+
importCandidates("/src/store.js"); // ["/src/store.js", "/src/store.ts", "/src/store.tsx", "/src/store.js.ts", …]
|
|
78
|
+
await resolveImportPath("/src/lib"); // "/src/lib/index.ts" — the first candidate that is a file on disk
|
|
79
|
+
await resolveImportPath("/src/lib", isFile); // with your own IsFile: (path) => Promise<boolean>
|
|
80
|
+
await diskIsFile("/src/lib/index.ts"); // true — the default IsFile: a file on disk (false for folders and missing paths)
|
|
81
|
+
```
|
|
82
|
+
|
|
47
83
|
## Locations: "know exactly how to get it"
|
|
48
84
|
|
|
49
85
|
Every location the system emits is **canonical and self-contained** (absolute file path, `file://`,
|
|
@@ -84,7 +120,8 @@ import { buildResourceGraph } from "@aeye/resources";
|
|
|
84
120
|
|
|
85
121
|
const graph = await buildResourceGraph(registry, "/docs/index.md", {
|
|
86
122
|
maxDepth: 5,
|
|
87
|
-
followExternal:
|
|
123
|
+
followExternal: true, // also fetch pages the docs link to (off by default)
|
|
124
|
+
concurrency: 8, // load up to 8 targets at once (default 4)
|
|
88
125
|
});
|
|
89
126
|
|
|
90
127
|
graph.roots; // ResourceLocation[]
|
|
@@ -99,6 +136,9 @@ interface ResourceGraph { roots: string[]; nodes: Map<string, ResourceGraphNode>
|
|
|
99
136
|
interface ResourceGraphNode {
|
|
100
137
|
id; location; type; depth;
|
|
101
138
|
modifiedAt?; resource: ParsedResource;
|
|
139
|
+
fetch?: GraphNodeFetch; // web nodes: { requestedUrl, url (final, = location), status, rendered, renderedBy?, renderError? }
|
|
140
|
+
bytes?: Uint8Array; // the raw bytes parsed, with keepBytes: true
|
|
141
|
+
contentRef?: string; // the ref keepBytes(fn) returned after storing them
|
|
102
142
|
slices?: ResourceSlice[]; // present if includeSlices
|
|
103
143
|
reused: boolean; // true if served from cache (incremental)
|
|
104
144
|
edges: ResourceGraphEdge[]; // outgoing links
|
|
@@ -110,7 +150,7 @@ interface ResourceGraphEdge {
|
|
|
110
150
|
link: ResourceLink;
|
|
111
151
|
targetLocation?: string; targetId?: string;
|
|
112
152
|
loaded: boolean; // is the target a node in the graph?
|
|
113
|
-
reason?: "external" | "resource-links-disabled" | "filtered"
|
|
153
|
+
reason?: "external" | "resource-links-disabled" | "filtered" | "cross-origin"
|
|
114
154
|
| "unresolved" | "max-depth" | "max-resources" | "skipped" | "error";
|
|
115
155
|
error?: string;
|
|
116
156
|
}
|
|
@@ -121,16 +161,28 @@ interface ResourceGraphEdge {
|
|
|
121
161
|
| Option | Default | Effect |
|
|
122
162
|
| --- | --- | --- |
|
|
123
163
|
| `maxDepth` | ∞ | max link/child distance from a root |
|
|
124
|
-
| `maxResources` |
|
|
164
|
+
| `maxResources` | `1000` (`DEFAULT_GRAPH_MAX_RESOURCES`) | cap on nodes loaded (existing nodes never re-counted); `Infinity` lifts it |
|
|
165
|
+
| `concurrency` | `4` (`DEFAULT_GRAPH_CONCURRENCY`) | link targets probed/loaded at once |
|
|
125
166
|
| `followChildren` | `true` | traverse children (zip entries, rendered pages) as nodes |
|
|
126
|
-
| `followExternal` | `
|
|
127
|
-
| `followResourceLinks` | `true` | follow internal/relative links |
|
|
167
|
+
| `followExternal` | `false` | follow external links: http links from local files, or links to another site |
|
|
168
|
+
| `followResourceLinks` | `true` | follow internal/relative links (includes same-site links on web pages) |
|
|
169
|
+
| `sameOrigin` | `true` | with `followExternal`, a link found on a web page is only followed to the same origin (else `cross-origin`); local files can still link out to any site |
|
|
170
|
+
| `keepBytes` | `false` | keep each loaded node's raw bytes: `true` → `node.bytes`; `async ({location, type, mimeType?, bytes}) => ref` stores them and puts the ref on `node.contentRef` (reused and child nodes carry none) |
|
|
128
171
|
| `includeSlices` | `false` | also slice each resource → `node.slices` |
|
|
129
172
|
| `shouldFollow(link, from)` | — | per-link filter |
|
|
130
173
|
| `shouldLoad(target)` | — | incremental: return false to skip parsing (target = `{location, modifiedAt, link, depth}`) |
|
|
131
174
|
| `getCached(location, modifiedAt?)` | — | supply a previously-parsed resource to reuse |
|
|
132
175
|
| `onNode(node)` | — | called as each node is added |
|
|
133
176
|
|
|
177
|
+
The walk goes one depth level at a time, so `node.depth` is the true shortest distance from a root
|
|
178
|
+
even with concurrency. `node.edges` stay in link order, but `graph.nodes` insertion order can vary
|
|
179
|
+
between runs. Concurrent links to the same target share one load.
|
|
180
|
+
|
|
181
|
+
**Safe defaults**: starting from a web page, the graph only crawls that site (relative and absolute
|
|
182
|
+
same-origin links), stops at 1000 nodes, and never leaves the site unless you set `followExternal`
|
|
183
|
+
(plus `sameOrigin: false` to crawl freely). URL fetches time out after 30 s and stop at 50 MiB
|
|
184
|
+
(`timeoutMs` / `maxBytes` on the options).
|
|
185
|
+
|
|
134
186
|
De-duplication uses `statLink` to get a target's canonical location (and `modifiedAt`) **before**
|
|
135
187
|
loading, so a URL/file referenced many times is fetched once, and cross-zip-entry links connect to
|
|
136
188
|
the existing entry nodes the zip parser already produced.
|
|
@@ -151,7 +203,9 @@ const graph = await buildResourceGraph(registry, roots, {
|
|
|
151
203
|
|
|
152
204
|
## Gotchas
|
|
153
205
|
|
|
154
|
-
-
|
|
206
|
+
- Zips that are not local files (fetched from a URL, nested in another zip, passed in memory) are
|
|
207
|
+
parsed from their bytes and kept in an in-memory cache (8 archives, LRU) under their location, so
|
|
208
|
+
links between their entries resolve while they stay cached.
|
|
155
209
|
- Relative links *between* zip entries resolve correctly; a link from a zip entry pointing **outside**
|
|
156
210
|
the archive won't (it stays archive-relative) and surfaces as an `unresolved`/`error` edge.
|
|
157
211
|
- `statLink` issues a `HEAD` for URLs; servers that reject HEAD still yield a location (for dedup) but
|
|
@@ -64,22 +64,33 @@ registry.registerParser(csvSummaryParser);
|
|
|
64
64
|
|
|
65
65
|
## Built-in parsers
|
|
66
66
|
|
|
67
|
+
Parsers for formats with a **converter** (html, docx, csv/tsv, workbooks, pdf, json, yaml, folders) are
|
|
68
|
+
*version parsers* (`createVersionParser`): they convert the source to its LLM-ready version through the
|
|
69
|
+
registry's converter stack and cut their parts from it, keeping it on `resource.version`. See
|
|
70
|
+
[aeye-resources-converters.md](./aeye-resources-converters.md).
|
|
71
|
+
|
|
67
72
|
- **textParser** — `text, json, csv, tsv, yaml, xml, svg, toml, ini`. Decodes UTF-8 into one text
|
|
68
73
|
part. Extracts bare URLs; for **markup types** (`markupTypes`, default `xml`/`svg`) also extracts
|
|
69
|
-
`href`/`src` links.
|
|
74
|
+
`href`/`src` links. The fallback for json and yaml that are already pretty.
|
|
70
75
|
- **markdownParser** — `markdown`. Extracts markdown links + URLs. Default slicer `markdown`.
|
|
71
|
-
- **htmlParser** — `html`.
|
|
72
|
-
|
|
73
|
-
|
|
76
|
+
- **htmlParser** — `html`. One part from the clean markdown version (main content, absolute links);
|
|
77
|
+
links come from the raw html (every `href`/`src`, navigation included) so crawls see them; each link's
|
|
78
|
+
`metadata` names its `tag` (`a`, `img`, `link`, `base`, …) and its `rel` words, so a crawl can follow anchors only,
|
|
79
|
+
skip `nofollow` and resolve against `<base href>` (`extractLinksFromHtml`). Rendering
|
|
80
|
+
script-built pages happens when fetching (see `renderer` in the converters doc).
|
|
81
|
+
- **jsonParser / yamlParser** — json and yaml through their pretty forms; they decline (falling back to
|
|
82
|
+
textParser) when the file is already pretty, does not parse, or (yaml) has comments.
|
|
83
|
+
- **folderParser** — `folder` (from the folder resolver). A markdown listing; every entry is a link.
|
|
74
84
|
- **codeParser** — all `CODE_TYPES` (ts, js, py, go, rust, …). Extracts import/require + URLs.
|
|
75
85
|
Default slicer `code`.
|
|
76
86
|
- **imageParser** — `image`. Stores image bytes as an image part; optionally adds text parts from
|
|
77
87
|
`options.transcribeImage` and `options.describeImage`.
|
|
78
88
|
- **pdfRenderParser / pdfParser** — see PDF section.
|
|
79
|
-
- **excelPdfParser / excelParser** —
|
|
80
|
-
|
|
81
|
-
`
|
|
82
|
-
- **
|
|
89
|
+
- **excelPdfParser / excelParser / delimitedParser** — workbooks through `xlsx`; csv/tsv read in-house
|
|
90
|
+
(no dependency). Blank rows split a sheet into tables; the table version is on `resource.version`
|
|
91
|
+
(`tables`, typed with `columnKinds` / `tableRecords`), one part per sheet (`#sheet/<i>`).
|
|
92
|
+
- **pdfParser** — page text through `pdf-parse`, one part per page (`#page/<n>`, `pageNumber` set).
|
|
93
|
+
- **docxPdfParser / docxParser** — DOCX. Base parser: `mammoth` → html → clean markdown.
|
|
83
94
|
- **zipParser** — `zip`. Lists entries and parses each entry **through the registry** so its links
|
|
84
95
|
become part of the graph (see graph doc); entries that can't be parsed in-memory fall back to a raw
|
|
85
96
|
representation. Children carry `modifiedAt` from the zip entry date.
|
|
@@ -94,6 +105,7 @@ interface PdfParseOptions {
|
|
|
94
105
|
renderDpi?: number; // default 150
|
|
95
106
|
transcribePages?: boolean; // transcribe rendered pages → markdown text parts
|
|
96
107
|
extractImages?: boolean;
|
|
108
|
+
pageOutputDir?: string; // keep page images here (caller owns them); default: temp dir, deleted
|
|
97
109
|
}
|
|
98
110
|
```
|
|
99
111
|
|
|
@@ -126,6 +138,13 @@ await isPopplerAvailable(); // boolean — binaries present?
|
|
|
126
138
|
When rendering is enabled, `pdfRenderParser` produces page-image **children** and (if
|
|
127
139
|
`transcribePages`) parent text parts; otherwise it declines and `pdfParser` extracts text.
|
|
128
140
|
|
|
141
|
+
- Page images render to a temporary directory that is deleted afterwards; their bytes are kept in
|
|
142
|
+
each page's image part (`part.data`). Set `pdf.pageOutputDir` to keep the files there instead
|
|
143
|
+
(parts then carry `metadata.filePath` and no `data`).
|
|
144
|
+
- PDFs (and docx/excel for `convertToPdf`) do not need to be local files: in-memory, URL and
|
|
145
|
+
zip-entry sources are written to a temporary file for the renderer/converter, and `pdfParser`
|
|
146
|
+
reads the source's bytes directly.
|
|
147
|
+
|
|
129
148
|
## Registry-driven type detection
|
|
130
149
|
|
|
131
150
|
Detection maps live on the registry (seeded from defaults) and are extensible:
|
|
@@ -143,26 +162,34 @@ registry.inferType("/x/a.ipynb"); // "notebook"
|
|
|
143
162
|
registry.inferType("/x/y", "application/x-ipynb+json"); // "notebook"
|
|
144
163
|
```
|
|
145
164
|
|
|
146
|
-
-
|
|
165
|
+
- A mime type that maps to a specific type takes precedence over the extension
|
|
166
|
+
(`inferType("notes.txt", "text/markdown")` is `markdown`). One that matches only the catch-all
|
|
167
|
+
`^text/` pattern (`GENERIC_TEXT_TYPE`, `"text"`: `text/typescript`, `text/plain`) yields to the
|
|
168
|
+
extension (`inferType("a.ts", "text/typescript")` is `typescript`) and is the answer only when the
|
|
169
|
+
extension names nothing. Newly registered patterns are checked first.
|
|
147
170
|
- Extension matching scans suffixes longest-first, so **compound extensions** like `.tar.gz` and
|
|
148
171
|
`.test.ts` resolve correctly. Dockerfiles are detected by name.
|
|
149
172
|
- Each registry instance has its own maps (no global leakage).
|
|
150
173
|
|
|
151
174
|
Standalone helpers (operate on the default maps): `inferTypeFromLocation`,
|
|
152
|
-
`inferTypeFromMimeType`, `inferTypeFromExtension(loc, map)`, `inferTypeFromMimePatterns(mime, list)
|
|
175
|
+
`inferTypeFromMimeType`, `inferTypeFromExtension(loc, map)`, `inferTypeFromMimePatterns(mime, list)`,
|
|
176
|
+
and `inferTypeFromRules(loc, mime, patterns, map)` (the precedence above, on your own tables).
|
|
153
177
|
Exposed default tables: `DEFAULT_EXTENSION_TYPES`, `DEFAULT_MIME_TYPE_PATTERNS`, `CODE_TYPES`,
|
|
154
|
-
`DEFAULT_MARKUP_TYPES`, `DEFAULT_IMAGE_EXTENSION_MIME` (+ `imageMimeTypeFromLocation`)
|
|
178
|
+
`DEFAULT_MARKUP_TYPES`, `DEFAULT_IMAGE_EXTENSION_MIME` (+ `imageMimeTypeFromLocation`),
|
|
179
|
+
`DEFAULT_TYPE_MIME_TYPES` (type → mime, + `effectiveMimeType`), `GENERIC_TEXT_TYPE`.
|
|
155
180
|
|
|
156
181
|
## Parse options (selected `ParseOptions` fields)
|
|
157
182
|
|
|
158
183
|
| Field | Effect |
|
|
159
184
|
| --- | --- |
|
|
160
|
-
| `signal` | abort |
|
|
185
|
+
| `signal` | abort; an aborted operation throws the signal's reason (an `AbortError`; see `isAbortError`) |
|
|
186
|
+
| `timeoutMs` | URL fetch timeout, headers + body (default 30000; 0 disables) |
|
|
187
|
+
| `maxBytes` | max bytes downloaded per URL (default 50 MiB; 0 disables) |
|
|
161
188
|
| `code` | `CodeParserOptions` (declaration/import patterns, `maxImportPrefixes`) |
|
|
162
189
|
| `pdf` | `PdfParseOptions` (see above) |
|
|
163
190
|
| `renderPdfPages`, `convertToPdf` | PDF render / doc→pdf conversion functions |
|
|
164
191
|
| `transcribeImage`, `describeImage` | vision callbacks for images & PDF pages |
|
|
165
|
-
| `
|
|
192
|
+
| `html` | `HtmlToMarkdownOptions`: `baseUrl` (defaults to the resource's URL), `content` (`main`/`body`), `links`, `images`, `dropTags` |
|
|
166
193
|
| `markupTypes` | which types get `href`/`src` extraction (default xml/svg) |
|
|
167
194
|
|
|
168
195
|
All of these can be set per type via `configureType` or passed per call.
|
|
@@ -31,20 +31,61 @@ interface ResourceSlicer {
|
|
|
31
31
|
Universal fallback. Splits each text part on boundary strings into contiguous, non-overlapping
|
|
32
32
|
segments. No structural context.
|
|
33
33
|
- Default boundaries: `["\n\n", "\n", " "]`.
|
|
34
|
-
- Per-slice links: part links
|
|
34
|
+
- Per-slice links: the part's links that appear in the slice + bare URLs in the segment.
|
|
35
|
+
- `slice.sectionId` = the part location (one section per part).
|
|
35
36
|
|
|
36
37
|
### `markdown` — `supportedTypes: ["markdown", "html"]`
|
|
37
|
-
Heading-aware. Detects `#`–`######` headings
|
|
38
|
-
(`slice.context.headings`, e.g. `Intro > Details`), then
|
|
38
|
+
Heading-aware. Detects `#`–`######` headings (ignoring `#` lines inside `` ``` `` / `~~~` code
|
|
39
|
+
fences), builds a heading breadcrumb (`slice.context.headings`, e.g. `Intro > Details`), then
|
|
40
|
+
segments each section. Text before the first heading is its own section with no headings, so the
|
|
41
|
+
slices always cover the whole text. `slice.sectionId` = `<part>#section/<key>`, where the key comes
|
|
42
|
+
from the heading path (see [Stable section keys](#stable-section-keys)).
|
|
43
|
+
`splitMarkdownSections(text)` is exported and returns `{ start, end, headings, key }` per section.
|
|
39
44
|
- Default boundaries: `["\n\n", "\n", ". ", " "]` (sentence-aware).
|
|
40
45
|
- Per-slice links: markdown `[](…)` links + bare URLs. Used for HTML too (HTML is parsed to markdown).
|
|
41
46
|
|
|
42
47
|
### `code` — `supportedTypes: [...CODE_TYPES]`
|
|
43
|
-
Declaration-aware. Splits at top-level declarations and attaches import context.
|
|
44
|
-
-
|
|
45
|
-
|
|
48
|
+
Declaration-aware. Splits at top-level (unindented) declarations and attaches import context.
|
|
49
|
+
- Text before the first declaration (license header, imports) is its own block, so the slices
|
|
50
|
+
always cover the whole file. Doc comments, decorators and attributes directly above a declaration
|
|
51
|
+
stay with it.
|
|
52
|
+
- Declaration patterns per language (`CODE_DECLARATION_PATTERNS`): JS/TS, python, ruby, go, rust,
|
|
53
|
+
lua, shell, sql, graphql; other languages use a generic pattern (class/struct/fn/func/def/…).
|
|
54
|
+
- `slice.context.declaration` = the declaration line (undefined for the preamble);
|
|
55
|
+
`slice.context.prefixes` = the first `maxImportPrefixes` import lines.
|
|
56
|
+
- `slice.sectionId` = `<part>#block/<key>`, where the key comes from the declared name (see
|
|
57
|
+
[Stable section keys](#stable-section-keys)). `splitCodeBlocks(text, type, codeOptions)` is
|
|
58
|
+
exported and returns `{ start, end, declaration?, name?, path, key }` per block.
|
|
59
|
+
- The declared name is the identifier after the declaration keyword (`function add`, `class Store`,
|
|
60
|
+
`func (s *Server) Serve`, `impl<T> Store<T>`, `declare module "x"`), or group 1 of the type's
|
|
61
|
+
`CODE_NAME_PATTERNS` entry (`shell`: `deploy()` / `function deploy`; `sql`: `create table users`).
|
|
62
|
+
`declarationName(line, pattern, type?)` is exported. A nameless declaration (`export default
|
|
63
|
+
function () {}`) is keyed by its declaration line.
|
|
46
64
|
- Default boundaries: `["\n\n", "\n", " "]`.
|
|
47
|
-
- Per-slice links: import/require specifiers + bare URLs.
|
|
65
|
+
- Per-slice links: the part's links that appear in the slice + import/require specifiers + bare URLs.
|
|
66
|
+
|
|
67
|
+
## Stable section keys
|
|
68
|
+
|
|
69
|
+
A section's key comes from its place in the structure, never from its position, so it stays the
|
|
70
|
+
same when text is added or moved around it. That keeps `sectionId`s (and the section summaries
|
|
71
|
+
cached under them) valid across edits.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { sectionKeys, ROOT_SECTION_KEY, SECTION_PATH_SEPARATOR } from "@aeye/resources";
|
|
75
|
+
// or, with no node imports (safe in a browser): from "@aeye/resources/section-keys"
|
|
76
|
+
|
|
77
|
+
sectionKeys([[], ["Guide"], ["Guide", "Usage"], ["Guide"]]);
|
|
78
|
+
// → ["(root)", "Guide", "Guide > Usage", "Guide ~2"]
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- A key is the path joined with `SECTION_PATH_SEPARATOR` (`" > "`); an empty path (text before
|
|
82
|
+
the first heading or declaration) is `ROOT_SECTION_KEY` (`"(root)"`).
|
|
83
|
+
- A path seen before in the same document gets ` ~2`, ` ~3`, … so keys stay unique.
|
|
84
|
+
- The markdown slicer's path is the heading breadcrumb; the code slicer's is the declared name (else
|
|
85
|
+
the declaration line). Use `sectionKeys` for your own slicers so their keys follow the same rules.
|
|
86
|
+
|
|
87
|
+
Every slicer de-duplicates a slice's links by value, so the `Links:` line in `embedText` lists each
|
|
88
|
+
link once, and only links that are in that slice.
|
|
48
89
|
|
|
49
90
|
## Slice options (`SliceOptions`)
|
|
50
91
|
|
|
@@ -65,9 +106,14 @@ All apply to every slicer and can be set **per call** or **per type** via `confi
|
|
|
65
106
|
| `includeLinks` | `true` | add `Links: …` line |
|
|
66
107
|
| `embedSeparator` | `"\n\n"` | joins embed-text lines |
|
|
67
108
|
| `buildEmbedText` | built-in | full override: `(EmbedTextContext) => string` |
|
|
68
|
-
| `code.declarationPattern` |
|
|
109
|
+
| `code.declarationPattern` | per language (`CODE_DECLARATION_PATTERNS`) | what starts a code block |
|
|
110
|
+
| `code.topLevelOnly` | `true` | only unindented lines can start a block |
|
|
69
111
|
| `code.importPattern` | import/require regex | what counts as an import prefix |
|
|
70
112
|
| `code.maxImportPrefixes` | `5` | how many import lines to attach |
|
|
113
|
+
| `summarize` | — | `(SummaryRequest) => Promise<string \| undefined>`; see [Summaries](#summaries) |
|
|
114
|
+
| `summaryScope` | `"resource"` | `"resource"`, `"section"` or `"both"` |
|
|
115
|
+
| `summaryConcurrency` | `4` | max concurrent `summarize` calls |
|
|
116
|
+
| `minSectionSummaryChars` | `0` | skip summarizing sections shorter than this |
|
|
71
117
|
| `signal` | — | abort |
|
|
72
118
|
|
|
73
119
|
`embedText` is assembled by the built-in `buildEmbedText`/`collectEmbedContext` from the include-flags
|
|
@@ -78,6 +124,28 @@ registry.configureType("markdown", { maxChars: 1200, minChars: 200, includePartK
|
|
|
78
124
|
const { slices } = await registry.load("/docs/guide.md");
|
|
79
125
|
```
|
|
80
126
|
|
|
127
|
+
## Summaries
|
|
128
|
+
|
|
129
|
+
Pass `summarize` to add model-written context to every slice. It is called for the whole resource
|
|
130
|
+
and/or for each section (markdown section, code block, or text part). The results land in
|
|
131
|
+
`slice.context.summary` / `slice.context.sectionSummary` and in `embedText` as `Summary: …` and
|
|
132
|
+
`Section summary: …` lines.
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
registry.configureType("markdown", {
|
|
136
|
+
summaryScope: "both",
|
|
137
|
+
summarize: async ({ scope, text, headings, signal }) =>
|
|
138
|
+
myModel(`Summarize this ${scope}${headings ? ` (${headings.join(" > ")})` : ""} in one sentence:\n\n${text}`, signal),
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
- `SummaryRequest` = `{ scope, resource, text, sectionId?, headings?, declaration?, signal? }`.
|
|
143
|
+
- Results are cached on `resource.metadata.summary` and `resource.metadata.sectionSummaries`
|
|
144
|
+
(keyed by `sectionId`), so slicing the same resource again, or one reused from a graph cache, does
|
|
145
|
+
not call `summarize` again. Clear those fields to force a refresh.
|
|
146
|
+
- With `"both"`, a section that is the whole resource is not summarized twice.
|
|
147
|
+
- Return `undefined` to skip a summary. Errors from `summarize` propagate.
|
|
148
|
+
|
|
81
149
|
## Pluggable segmenters
|
|
82
150
|
|
|
83
151
|
The slicers call a `TextSegmenter` for the raw split step:
|
package/aeye-resources.md
CHANGED
|
@@ -12,6 +12,8 @@ embedding, follow links between them, and incrementally rebuild when sources cha
|
|
|
12
12
|
> - [aeye-resources-parsers.md](./aeye-resources-parsers.md) — parsers, parser stacking, per-type config, PDF rendering, type inference.
|
|
13
13
|
> - [aeye-resources-slicers.md](./aeye-resources-slicers.md) — slicers, slice options, pluggable segmenters (LangChain).
|
|
14
14
|
> - [aeye-resources-graph.md](./aeye-resources-graph.md) — resolvers, locations, `modifiedAt`, the resource graph.
|
|
15
|
+
> - [aeye-resources-converters.md](./aeye-resources-converters.md) — LLM-ready versions (converters), sectioning
|
|
16
|
+
> versions, fetching URLs (type detection, page renderers), folders.
|
|
15
17
|
|
|
16
18
|
## Install / import
|
|
17
19
|
|
|
@@ -26,7 +28,7 @@ import { createDefaultResourceRegistry, defaultResourceRegistry } from "@aeye/re
|
|
|
26
28
|
```
|
|
27
29
|
|
|
28
30
|
Optional peer dependencies are loaded lazily and only needed for specific formats/features:
|
|
29
|
-
`pdf-parse` (PDF text), `mammoth` (DOCX), `xlsx` (Excel/
|
|
31
|
+
`pdf-parse` (PDF text), `mammoth` (DOCX), `xlsx` (Excel; csv/tsv need nothing), `js-yaml` (yaml pretty form), `jszip` (ZIP), `node-poppler`
|
|
30
32
|
(PDF page rendering), `@langchain/textsplitters` (overlap/token/language-aware chunking). If a
|
|
31
33
|
dependency is missing, the relevant parser/feature simply declines or reports unsupported.
|
|
32
34
|
|
|
@@ -34,11 +36,15 @@ dependency is missing, the relevant parser/feature simply declines or reports un
|
|
|
34
36
|
|
|
35
37
|
```
|
|
36
38
|
input (path | URL | ResourceSource)
|
|
37
|
-
└─ resolve → ResourceSource (resolvers: zip, file, url)
|
|
38
|
-
└─
|
|
39
|
+
└─ resolve → ResourceSource (resolvers: zip, folder, file, url)
|
|
40
|
+
└─ convert → ResourceVersion (converter stack per type → markdown, tables, pages, pretty code)
|
|
41
|
+
└─ parse → ParsedResource (parser stack per type → parts cut from the version, links, children)
|
|
39
42
|
└─ slice → ResourceSlice[] (slicer per type → chunks + embedText)
|
|
40
43
|
```
|
|
41
44
|
|
|
45
|
+
`convert()` resolves and converts only (the raw source plus its LLM-ready version, for storing both);
|
|
46
|
+
`sectionVersion()` cuts a version into sections keyed by structure.
|
|
47
|
+
|
|
42
48
|
`load()` does all three; `parse()` and `slice()` are also available individually.
|
|
43
49
|
|
|
44
50
|
```ts
|
|
@@ -63,6 +69,7 @@ interface ParsedResource {
|
|
|
63
69
|
id: string; // `${location}::${type}`
|
|
64
70
|
location: string; // canonical, self-contained location
|
|
65
71
|
type: string; // e.g. "markdown", "pdf", "typescript"
|
|
72
|
+
version?: ResourceVersion; // the LLM-ready version the parts were cut from (html, docx, sheets, pdf, …)
|
|
66
73
|
name: string;
|
|
67
74
|
mimeType?: string;
|
|
68
75
|
modifiedAt?: number; // epoch ms — for staleness/incremental rebuilds
|
|
@@ -93,8 +100,10 @@ interface ResourceSlice {
|
|
|
93
100
|
text: string; // the slice content
|
|
94
101
|
embedText: string; // text augmented with context/links, ready to embed
|
|
95
102
|
start: number; end: number; // offsets into the part text
|
|
96
|
-
context?: { headings?; declaration?; summary?; prefixes? };
|
|
97
|
-
links: ResourceLink[];
|
|
103
|
+
context?: { headings?; declaration?; summary?; sectionSummary?; prefixes? };
|
|
104
|
+
links: ResourceLink[]; // links that appear in this slice, each once
|
|
105
|
+
sectionId?: string; // markdown section / code block / text part the slice came from
|
|
106
|
+
metadata?: Record<string, unknown>;
|
|
98
107
|
}
|
|
99
108
|
```
|
|
100
109
|
|
|
@@ -148,12 +157,14 @@ registry.configureType("markdown", { maxChars: 1200, minChars: 200 });
|
|
|
148
157
|
|
|
149
158
|
`createDefaultResourceRegistry()` registers:
|
|
150
159
|
|
|
160
|
+
- **Converters** (`DEFAULT_CONVERTERS`): html → markdown, docx → markdown, csv/tsv → tables, workbooks →
|
|
161
|
+
tables, pdf → pages, json → pretty json, yaml → even yaml, folder → markdown listing.
|
|
151
162
|
- **Parsers** (stacked where useful): `textParser` (text/json/csv/tsv/yaml/xml/svg/toml/ini),
|
|
152
163
|
`markdownParser`, `htmlParser`, `codeParser` (all `CODE_TYPES`), `imageParser`,
|
|
153
|
-
`pdfRenderParser`→`pdfParser`, `excelPdfParser`→`excelParser`, `
|
|
154
|
-
`zipParser`.
|
|
164
|
+
`pdfRenderParser`→`pdfParser`, `excelPdfParser`→`excelParser`, `delimitedParser` (csv/tsv),
|
|
165
|
+
`docxPdfParser`→`docxParser`, `jsonParser`/`yamlParser`→`textParser`, `folderParser`, `zipParser`.
|
|
155
166
|
- **Slicers**: `textSlicer` (`*`), `markdownSlicer` (markdown/html), `codeSlicer` (code types).
|
|
156
|
-
- **Resolvers** (tried in order): `zipResolver`, `fileResolver`, `urlResolver`.
|
|
167
|
+
- **Resolvers** (tried in order): `zipResolver`, `folderResolver`, `fileResolver`, `urlResolver`.
|
|
157
168
|
|
|
158
169
|
All are exported individually too, so you can compose a custom registry.
|
|
159
170
|
|
|
@@ -182,5 +193,9 @@ const graph = await buildResourceGraph(registry, "/docs/index.md");
|
|
|
182
193
|
or `isTypeSupported` returns false, not a hard crash (except when a format has no fallback).
|
|
183
194
|
- File locations are emitted **absolute** so they round-trip; a manually-supplied *relative*
|
|
184
195
|
`location` is not self-contained (`locate()` rejects it).
|
|
185
|
-
- Zips
|
|
196
|
+
- Zips and PDFs can come from anywhere (disk, URL, memory, another zip). Non-local zips are cached
|
|
197
|
+
in memory (8, LRU) so their entry links resolve.
|
|
198
|
+
- `buildResourceGraph` is bounded by default: no external links, same-site web crawling, 1000
|
|
199
|
+
nodes max. Opt in with `followExternal`, `sameOrigin: false`, `maxResources: Infinity`.
|
|
200
|
+
- Aborts throw an `AbortError` (the signal's reason), not a plain `Error`.
|
|
186
201
|
- `modifiedAt` is best-effort: filesystem mtime, HTTP `Last-Modified`, or zip entry date.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ResourceConverter } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Json indented two spaces. Json lines (one value per line, `.jsonl`) have each line pretty printed, separated by a
|
|
4
|
+
* blank line. Text that is neither is declined.
|
|
5
|
+
*/
|
|
6
|
+
export declare const jsonConverter: ResourceConverter;
|
|
7
|
+
/** Yaml written out evenly: two-space indents, block style, documents separated by `---`. */
|
|
8
|
+
export declare const yamlConverter: ResourceConverter;
|
|
9
|
+
//# sourceMappingURL=data.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src/converters/data.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,iBAAiB,EAAkB,MAAM,aAAa,CAAC;AA4BrE;;;GAGG;AACH,eAAO,MAAM,aAAa,EAAE,iBAa3B,CAAC;AAEF,6FAA6F;AAC7F,eAAO,MAAM,aAAa,EAAE,iBAsB3B,CAAC"}
|