@aeye/resources 0.3.9

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 (125) hide show
  1. package/aeye-resources-graph.md +158 -0
  2. package/aeye-resources-parsers.md +175 -0
  3. package/aeye-resources-slicers.md +158 -0
  4. package/aeye-resources.md +186 -0
  5. package/dist/default.d.ts +8 -0
  6. package/dist/default.d.ts.map +1 -0
  7. package/dist/default.js +31 -0
  8. package/dist/default.js.map +1 -0
  9. package/dist/graph.d.ts +93 -0
  10. package/dist/graph.d.ts.map +1 -0
  11. package/dist/graph.js +154 -0
  12. package/dist/graph.js.map +1 -0
  13. package/dist/index.d.ts +8 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +7 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/parsers/code.d.ts +3 -0
  18. package/dist/parsers/code.d.ts.map +1 -0
  19. package/dist/parsers/code.js +28 -0
  20. package/dist/parsers/code.js.map +1 -0
  21. package/dist/parsers/docx.d.ts +10 -0
  22. package/dist/parsers/docx.d.ts.map +1 -0
  23. package/dist/parsers/docx.js +89 -0
  24. package/dist/parsers/docx.js.map +1 -0
  25. package/dist/parsers/excel.d.ts +9 -0
  26. package/dist/parsers/excel.d.ts.map +1 -0
  27. package/dist/parsers/excel.js +161 -0
  28. package/dist/parsers/excel.js.map +1 -0
  29. package/dist/parsers/html.d.ts +3 -0
  30. package/dist/parsers/html.d.ts.map +1 -0
  31. package/dist/parsers/html.js +37 -0
  32. package/dist/parsers/html.js.map +1 -0
  33. package/dist/parsers/image.d.ts +3 -0
  34. package/dist/parsers/image.d.ts.map +1 -0
  35. package/dist/parsers/image.js +45 -0
  36. package/dist/parsers/image.js.map +1 -0
  37. package/dist/parsers/index.d.ts +10 -0
  38. package/dist/parsers/index.d.ts.map +1 -0
  39. package/dist/parsers/index.js +10 -0
  40. package/dist/parsers/index.js.map +1 -0
  41. package/dist/parsers/markdown.d.ts +3 -0
  42. package/dist/parsers/markdown.d.ts.map +1 -0
  43. package/dist/parsers/markdown.js +28 -0
  44. package/dist/parsers/markdown.js.map +1 -0
  45. package/dist/parsers/pdf.d.ts +10 -0
  46. package/dist/parsers/pdf.d.ts.map +1 -0
  47. package/dist/parsers/pdf.js +165 -0
  48. package/dist/parsers/pdf.js.map +1 -0
  49. package/dist/parsers/text.d.ts +4 -0
  50. package/dist/parsers/text.d.ts.map +1 -0
  51. package/dist/parsers/text.js +42 -0
  52. package/dist/parsers/text.js.map +1 -0
  53. package/dist/parsers/zip.d.ts +3 -0
  54. package/dist/parsers/zip.d.ts.map +1 -0
  55. package/dist/parsers/zip.js +131 -0
  56. package/dist/parsers/zip.js.map +1 -0
  57. package/dist/registry.d.ts +81 -0
  58. package/dist/registry.d.ts.map +1 -0
  59. package/dist/registry.js +322 -0
  60. package/dist/registry.js.map +1 -0
  61. package/dist/renderers/index.d.ts +3 -0
  62. package/dist/renderers/index.d.ts.map +1 -0
  63. package/dist/renderers/index.js +2 -0
  64. package/dist/renderers/index.js.map +1 -0
  65. package/dist/renderers/poppler.d.ts +38 -0
  66. package/dist/renderers/poppler.d.ts.map +1 -0
  67. package/dist/renderers/poppler.js +92 -0
  68. package/dist/renderers/poppler.js.map +1 -0
  69. package/dist/resolvers/file.d.ts +3 -0
  70. package/dist/resolvers/file.d.ts.map +1 -0
  71. package/dist/resolvers/file.js +68 -0
  72. package/dist/resolvers/file.js.map +1 -0
  73. package/dist/resolvers/index.d.ts +4 -0
  74. package/dist/resolvers/index.d.ts.map +1 -0
  75. package/dist/resolvers/index.js +4 -0
  76. package/dist/resolvers/index.js.map +1 -0
  77. package/dist/resolvers/url.d.ts +3 -0
  78. package/dist/resolvers/url.d.ts.map +1 -0
  79. package/dist/resolvers/url.js +91 -0
  80. package/dist/resolvers/url.js.map +1 -0
  81. package/dist/resolvers/zip.d.ts +8 -0
  82. package/dist/resolvers/zip.d.ts.map +1 -0
  83. package/dist/resolvers/zip.js +73 -0
  84. package/dist/resolvers/zip.js.map +1 -0
  85. package/dist/segmenters/default.d.ts +7 -0
  86. package/dist/segmenters/default.d.ts.map +1 -0
  87. package/dist/segmenters/default.js +7 -0
  88. package/dist/segmenters/default.js.map +1 -0
  89. package/dist/segmenters/index.d.ts +4 -0
  90. package/dist/segmenters/index.d.ts.map +1 -0
  91. package/dist/segmenters/index.js +3 -0
  92. package/dist/segmenters/index.js.map +1 -0
  93. package/dist/segmenters/langchain.d.ts +33 -0
  94. package/dist/segmenters/langchain.d.ts.map +1 -0
  95. package/dist/segmenters/langchain.js +110 -0
  96. package/dist/segmenters/langchain.js.map +1 -0
  97. package/dist/slicers/code.d.ts +3 -0
  98. package/dist/slicers/code.d.ts.map +1 -0
  99. package/dist/slicers/code.js +78 -0
  100. package/dist/slicers/code.js.map +1 -0
  101. package/dist/slicers/index.d.ts +4 -0
  102. package/dist/slicers/index.d.ts.map +1 -0
  103. package/dist/slicers/index.js +4 -0
  104. package/dist/slicers/index.js.map +1 -0
  105. package/dist/slicers/markdown.d.ts +3 -0
  106. package/dist/slicers/markdown.d.ts.map +1 -0
  107. package/dist/slicers/markdown.js +70 -0
  108. package/dist/slicers/markdown.js.map +1 -0
  109. package/dist/slicers/text.d.ts +3 -0
  110. package/dist/slicers/text.d.ts.map +1 -0
  111. package/dist/slicers/text.js +43 -0
  112. package/dist/slicers/text.js.map +1 -0
  113. package/dist/types.d.ts +306 -0
  114. package/dist/types.d.ts.map +1 -0
  115. package/dist/types.js +2 -0
  116. package/dist/types.js.map +1 -0
  117. package/dist/utils.d.ts +97 -0
  118. package/dist/utils.d.ts.map +1 -0
  119. package/dist/utils.js +788 -0
  120. package/dist/utils.js.map +1 -0
  121. package/dist/zip-internal.d.ts +28 -0
  122. package/dist/zip-internal.d.ts.map +1 -0
  123. package/dist/zip-internal.js +52 -0
  124. package/dist/zip-internal.js.map +1 -0
  125. package/package.json +104 -0
@@ -0,0 +1,158 @@
1
+ # @aeye/resources — Resolvers, locations & the resource graph
2
+
3
+ Parent: [aeye-resources.md](./aeye-resources.md)
4
+
5
+ This covers how links become loadable resources (**resolvers**), how to know exactly how to fetch a
6
+ **location**, the `modifiedAt` staleness signal, and how to build the full **resource graph** of
7
+ everything reachable from a root.
8
+
9
+ ## Resolvers
10
+
11
+ A **resolver** turns a link/location string into a `ResourceSource`.
12
+
13
+ ```ts
14
+ interface ResourceResolver {
15
+ id: string;
16
+ canResolve: (link, ctx) => boolean | Promise<boolean>;
17
+ resolve: (link, ctx) => Promise<ResourceSource | undefined>;
18
+ stat?: (link, ctx) => Promise<ResourceStat | undefined>; // cheap probe, no body
19
+ }
20
+ ```
21
+
22
+ `ctx` is `{ registry, options }` where `options` includes `baseLocation`, `headers`, `signal`,
23
+ `metadata`. The registry tries resolvers in registration order; first `canResolve` wins.
24
+
25
+ ### Built-in resolvers (registered in this order)
26
+
27
+ - **zipResolver** — links to zip entries. Resolves both fully-qualified zip-entry locations
28
+ (`bundle.zip#entry/doc.md`) and links **relative to another entry** (`./other.md`, `../assets/x.png`,
29
+ `/root.md`) within the same archive. Registered first so entry-relative links beat file/url.
30
+ - **fileResolver** — absolute paths, `file://` URLs, and relative paths against a non-web,
31
+ non-zip `baseLocation`. Sets `modifiedAt`/`size` from `fs.stat`.
32
+ - **urlResolver** — http(s) URLs, plus relative/root-relative/protocol-relative links resolved
33
+ against an http(s) `baseLocation` (via `new URL`). Sets `modifiedAt` (`Last-Modified`) and `size`
34
+ (`Content-Length`); `stat` uses a `HEAD` request.
35
+
36
+ ### Resolving links
37
+
38
+ ```ts
39
+ // Relative link needs a base (typically the parent resource's location):
40
+ const src = await registry.resolveLink("./child.md", { baseLocation: parent.location });
41
+
42
+ // Cheap probe for dedup / staleness, without downloading:
43
+ const stat = await registry.statLink("./child.md", { baseLocation: parent.location });
44
+ // → { location, modifiedAt?, size?, mimeType?, type? } | undefined
45
+ ```
46
+
47
+ ## Locations: "know exactly how to get it"
48
+
49
+ Every location the system emits is **canonical and self-contained** (absolute file path, `file://`,
50
+ http(s) URL, or `zip.zip#entry/...` with an absolute archive path). Helpers classify and fetch them:
51
+
52
+ ```ts
53
+ import { inferLocationScheme, isSelfContainedLocation } from "@aeye/resources";
54
+
55
+ inferLocationScheme(loc); // "url" | "file" | "zip-entry" | "relative"
56
+ isSelfContainedLocation(loc); // true unless "relative"
57
+
58
+ await registry.locate(loc); // resolve a self-contained location directly (no base)
59
+ // throws if loc is relative — use resolveLink + baseLocation
60
+ await registry.getResolverId(loc); // which resolver would handle it ("zip"|"file"|"url"|undefined)
61
+ ```
62
+
63
+ Zip-entry helpers: `isZipEntryLocation`, `buildZipEntryLocation(zip, entry)`,
64
+ `parseZipEntryLocation(loc)`, `resolveZipEntryName(baseEntry, link)`, plus `ZIP_ENTRY_MARKER`.
65
+
66
+ > A relative location supplied manually (e.g. a hand-built `ResourceSource`) is **not**
67
+ > self-contained — `locate()` rejects it. The resolvers always emit absolute file locations so they
68
+ > round-trip across processes (on the same host/filesystem).
69
+
70
+ ## `modifiedAt` — staleness & incremental rebuilds
71
+
72
+ `ResourceSource` and `ParsedResource` carry `modifiedAt` (epoch ms) and `size` when known:
73
+ filesystem mtime, HTTP `Last-Modified`, or zip entry date. A target system stores `modifiedAt`
74
+ alongside each built resource and compares it on rebuild to decide whether to reprocess.
75
+
76
+ ## Building the resource graph
77
+
78
+ `buildResourceGraph(registry, inputs, options?)` walks from one or more roots, loading each link
79
+ target as a resource and recursing into its links **and** children — de-duplicated so cycles and
80
+ shared references terminate.
81
+
82
+ ```ts
83
+ import { buildResourceGraph } from "@aeye/resources";
84
+
85
+ const graph = await buildResourceGraph(registry, "/docs/index.md", {
86
+ maxDepth: 5,
87
+ followExternal: false, // don't fetch http links
88
+ });
89
+
90
+ graph.roots; // ResourceLocation[]
91
+ graph.nodes; // Map<location, ResourceGraphNode>
92
+ ```
93
+
94
+ ### Shapes
95
+
96
+ ```ts
97
+ interface ResourceGraph { roots: string[]; nodes: Map<string, ResourceGraphNode>; }
98
+
99
+ interface ResourceGraphNode {
100
+ id; location; type; depth;
101
+ modifiedAt?; resource: ParsedResource;
102
+ slices?: ResourceSlice[]; // present if includeSlices
103
+ reused: boolean; // true if served from cache (incremental)
104
+ edges: ResourceGraphEdge[]; // outgoing links
105
+ children: string[]; // contained child locations (zip entries, pdf pages)
106
+ parents: string[]; // who links to / contains this node
107
+ }
108
+
109
+ interface ResourceGraphEdge {
110
+ link: ResourceLink;
111
+ targetLocation?: string; targetId?: string;
112
+ loaded: boolean; // is the target a node in the graph?
113
+ reason?: "external" | "resource-links-disabled" | "filtered"
114
+ | "unresolved" | "max-depth" | "max-resources" | "skipped" | "error";
115
+ error?: string;
116
+ }
117
+ ```
118
+
119
+ ### `BuildGraphOptions` (extends `LoadResourceOptions`)
120
+
121
+ | Option | Default | Effect |
122
+ | --- | --- | --- |
123
+ | `maxDepth` | ∞ | max link/child distance from a root |
124
+ | `maxResources` | ∞ | cap on nodes loaded (existing nodes never re-counted) |
125
+ | `followChildren` | `true` | traverse children (zip entries, rendered pages) as nodes |
126
+ | `followExternal` | `true` | follow external (http) links |
127
+ | `followResourceLinks` | `true` | follow internal/relative links |
128
+ | `includeSlices` | `false` | also slice each resource → `node.slices` |
129
+ | `shouldFollow(link, from)` | — | per-link filter |
130
+ | `shouldLoad(target)` | — | incremental: return false to skip parsing (target = `{location, modifiedAt, link, depth}`) |
131
+ | `getCached(location, modifiedAt?)` | — | supply a previously-parsed resource to reuse |
132
+ | `onNode(node)` | — | called as each node is added |
133
+
134
+ De-duplication uses `statLink` to get a target's canonical location (and `modifiedAt`) **before**
135
+ loading, so a URL/file referenced many times is fetched once, and cross-zip-entry links connect to
136
+ the existing entry nodes the zip parser already produced.
137
+
138
+ ### Incremental rebuild pattern
139
+
140
+ ```ts
141
+ const cache = new Map<string, ParsedResource>(); // location → last build
142
+ for (const node of previous.nodes.values()) cache.set(node.location, node.resource);
143
+
144
+ const graph = await buildResourceGraph(registry, roots, {
145
+ // skip reparse when our stored mtime matches the probed one
146
+ shouldLoad: ({ location, modifiedAt }) => modifiedAt !== storedMtimes.get(location),
147
+ getCached: (location) => cache.get(location),
148
+ });
149
+ // node.reused === true for resources served from cache; roots always parse fresh.
150
+ ```
151
+
152
+ ## Gotchas
153
+
154
+ - URL-hosted zips are not supported (zip parser/resolver read archives from disk).
155
+ - Relative links *between* zip entries resolve correctly; a link from a zip entry pointing **outside**
156
+ the archive won't (it stays archive-relative) and surfaces as an `unresolved`/`error` edge.
157
+ - `statLink` issues a `HEAD` for URLs; servers that reject HEAD still yield a location (for dedup) but
158
+ no `modifiedAt`.
@@ -0,0 +1,175 @@
1
+ # @aeye/resources — Parsers, stacking & type detection
2
+
3
+ Parent: [aeye-resources.md](./aeye-resources.md)
4
+
5
+ A **parser** turns a `ResourceSource` into a `ParsedResource` (parts + links + children). Parsers are
6
+ registered per type and tried in a **stack**; type detection is fully registry-driven.
7
+
8
+ ## The `ResourceParser` interface
9
+
10
+ ```ts
11
+ interface ResourceParser {
12
+ id: string;
13
+ supportedTypes: ResourceType[];
14
+ defaultSlicer: string | Partial<Record<ResourceType, string>>;
15
+ priority?: number; // higher tried first; ties → most-recently registered
16
+ isSupported?: (type, ctx) => boolean | Promise<boolean>; // env/dep capability
17
+ // Return undefined to DECLINE (fall back to the next parser); throwing also falls back.
18
+ parse: (source, ctx) => Promise<ParsedResource | undefined>;
19
+ }
20
+ ```
21
+
22
+ `ctx` is `{ registry, options }` where `options` is the per-type config merged under the per-call
23
+ options.
24
+
25
+ ## Parser stacking & fallback
26
+
27
+ Multiple parsers can serve one type. `registerParser(parser, { priority })` orders them (higher
28
+ first; equal priority → later registration wins, so you can override built-ins). At parse time the
29
+ registry tries each in order:
30
+
31
+ - returns a `ParsedResource` → success;
32
+ - returns `undefined` → declines, try next;
33
+ - throws → recorded, try next (aborts propagate immediately). If all throw, errors surface
34
+ (single error rethrown, or `AggregateError`).
35
+
36
+ This is how "enhanced" parsers stack ahead of base ones:
37
+
38
+ | Type | priority 10 (tried first) | priority 0 (fallback) |
39
+ | --- | --- | --- |
40
+ | pdf | `pdfRenderParser` (render pages + transcribe) | `pdfParser` (pdf-parse text) |
41
+ | docx | `docxPdfParser` (convert→PDF→delegate) | `docxParser` (mammoth → markdown) |
42
+ | excel/csv/tsv | `excelPdfParser` (convert→PDF) | `excelParser` (xlsx → tables) |
43
+
44
+ A higher-priority parser declines (returns `undefined`) when its capability isn't configured (e.g.
45
+ no `renderPdfPages`), so the base parser handles it.
46
+
47
+ ### Write a custom parser
48
+
49
+ ```ts
50
+ const csvSummaryParser: ResourceParser = {
51
+ id: "csv-summary",
52
+ supportedTypes: ["csv"],
53
+ defaultSlicer: "text",
54
+ priority: 20,
55
+ async parse(source, ctx) {
56
+ if (!ctx.options.summarizeTables) return undefined; // decline → fall back to excelParser
57
+ const resource = createParsedResource(source);
58
+ // ... build resource.parts / resource.links ...
59
+ return resource;
60
+ },
61
+ };
62
+ registry.registerParser(csvSummaryParser);
63
+ ```
64
+
65
+ ## Built-in parsers
66
+
67
+ - **textParser** — `text, json, csv, tsv, yaml, xml, svg, toml, ini`. Decodes UTF-8 into one text
68
+ part. Extracts bare URLs; for **markup types** (`markupTypes`, default `xml`/`svg`) also extracts
69
+ `href`/`src` links.
70
+ - **markdownParser** — `markdown`. Extracts markdown links + URLs. Default slicer `markdown`.
71
+ - **htmlParser** — `html`. Converts HTML → markdown (`htmlToMarkdown`), extracts `href`/`src` + URLs.
72
+ Honors `options.renderUrl(url, signal)` to fetch rendered HTML (e.g. via headless browser) when the
73
+ source is an http(s) URL.
74
+ - **codeParser** — all `CODE_TYPES` (ts, js, py, go, rust, …). Extracts import/require + URLs.
75
+ Default slicer `code`.
76
+ - **imageParser** — `image`. Stores image bytes as an image part; optionally adds text parts from
77
+ `options.transcribeImage` and `options.describeImage`.
78
+ - **pdfRenderParser / pdfParser** — see PDF section.
79
+ - **excelPdfParser / excelParser** — Excel/CSV/TSV. Base parser uses `xlsx`, detects multiple table
80
+ regions per sheet, renders markdown tables, and stores structured tables in
81
+ `resource.metadata.structuredTables`.
82
+ - **docxPdfParser / docxParser** — DOCX. Base parser uses `mammoth` → markdown.
83
+ - **zipParser** — `zip`. Lists entries and parses each entry **through the registry** so its links
84
+ become part of the graph (see graph doc); entries that can't be parsed in-memory fall back to a raw
85
+ representation. Children carry `modifiedAt` from the zip entry date.
86
+
87
+ ## PDF parsing & page rendering
88
+
89
+ `PdfParseOptions` (under `options.pdf`):
90
+
91
+ ```ts
92
+ interface PdfParseOptions {
93
+ renderPages?: boolean; // render pages to images
94
+ renderDpi?: number; // default 150
95
+ transcribePages?: boolean; // transcribe rendered pages → markdown text parts
96
+ extractImages?: boolean;
97
+ }
98
+ ```
99
+
100
+ Plumbing options (top-level `ParseOptions`):
101
+
102
+ - `renderPdfPages?: RenderPdfPagesFn` — `(pdfPath, outDir, dpi, signal) => Promise<RenderedPage[]>`.
103
+ - `convertToPdf?: ConvertToPdfFn` — `(srcPath, signal) => Promise<string>` (for docx/excel→pdf).
104
+ - `transcribeImage?` / `describeImage?` — vision callbacks.
105
+
106
+ ### Poppler renderer (built-in `RenderPdfPagesFn`)
107
+
108
+ Requires `node-poppler` + the poppler binaries.
109
+
110
+ ```ts
111
+ import { createPopplerRenderer, isPopplerAvailable } from "@aeye/resources";
112
+
113
+ registry.configureType("pdf", {
114
+ pdf: { renderPages: true, transcribePages: true },
115
+ renderPdfPages: createPopplerRenderer({ format: "png" /* | "jpeg" | "tiff" */ }),
116
+ transcribeImage: async (bytes) => myVisionModel(bytes),
117
+ });
118
+
119
+ await isPopplerAvailable(); // boolean — binaries present?
120
+ ```
121
+
122
+ `createPopplerRenderer(options?)` → `RenderPdfPagesFn`. Options: `binaryPath`, `format`,
123
+ `antialiasFonts`, `antialiasVectors`. Also exported: `orderRenderedPages(files, dir, format)`
124
+ (pure helper that sorts poppler output into `RenderedPage[]`).
125
+
126
+ When rendering is enabled, `pdfRenderParser` produces page-image **children** and (if
127
+ `transcribePages`) parent text parts; otherwise it declines and `pdfParser` extracts text.
128
+
129
+ ## Registry-driven type detection
130
+
131
+ Detection maps live on the registry (seeded from defaults) and are extensible:
132
+
133
+ ```ts
134
+ registry.registerExtensionType("ipynb", "notebook");
135
+ registry.registerMimeType(/^application\/x-ipynb\+json/i, "notebook");
136
+ registry.registerType({ // one call
137
+ type: "notebook",
138
+ extensions: ["ipynb"],
139
+ mimePatterns: [/^application\/x-ipynb\+json/i],
140
+ });
141
+
142
+ registry.inferType("/x/a.ipynb"); // "notebook"
143
+ registry.inferType("/x/y", "application/x-ipynb+json"); // "notebook"
144
+ ```
145
+
146
+ - Mime patterns take precedence over extensions; newly registered patterns are checked first.
147
+ - Extension matching scans suffixes longest-first, so **compound extensions** like `.tar.gz` and
148
+ `.test.ts` resolve correctly. Dockerfiles are detected by name.
149
+ - Each registry instance has its own maps (no global leakage).
150
+
151
+ Standalone helpers (operate on the default maps): `inferTypeFromLocation`,
152
+ `inferTypeFromMimeType`, `inferTypeFromExtension(loc, map)`, `inferTypeFromMimePatterns(mime, list)`.
153
+ Exposed default tables: `DEFAULT_EXTENSION_TYPES`, `DEFAULT_MIME_TYPE_PATTERNS`, `CODE_TYPES`,
154
+ `DEFAULT_MARKUP_TYPES`, `DEFAULT_IMAGE_EXTENSION_MIME` (+ `imageMimeTypeFromLocation`).
155
+
156
+ ## Parse options (selected `ParseOptions` fields)
157
+
158
+ | Field | Effect |
159
+ | --- | --- |
160
+ | `signal` | abort |
161
+ | `code` | `CodeParserOptions` (declaration/import patterns, `maxImportPrefixes`) |
162
+ | `pdf` | `PdfParseOptions` (see above) |
163
+ | `renderPdfPages`, `convertToPdf` | PDF render / doc→pdf conversion functions |
164
+ | `transcribeImage`, `describeImage` | vision callbacks for images & PDF pages |
165
+ | `renderUrl` | render an http(s) URL to HTML for the html parser |
166
+ | `markupTypes` | which types get `href`/`src` extraction (default xml/svg) |
167
+
168
+ All of these can be set per type via `configureType` or passed per call.
169
+
170
+ ## Capability checks
171
+
172
+ ```ts
173
+ await registry.isTypeSupported("pdf"); // false if pdf-parse missing AND no render configured
174
+ await registry.getTypeSupport("docx"); // { type, parserId, slicerId, parser, slicer, supported }
175
+ ```
@@ -0,0 +1,158 @@
1
+ # @aeye/resources — Slicers & segmenters
2
+
3
+ Parent: [aeye-resources.md](./aeye-resources.md)
4
+
5
+ A **slicer** splits a `ParsedResource` into retrieval-ready `ResourceSlice`s, attaching context
6
+ (headings/declarations), per-slice links, and an `embedText` string. The raw text-splitting step is a
7
+ pluggable **segmenter**, so you can swap in LangChain for overlap / token sizing / language grammars
8
+ without losing the slice model.
9
+
10
+ ## Slicer selection
11
+
12
+ For a resource, the slicer id is chosen as:
13
+ `options.slicer` → `resource.defaultSlicer` (set by the parser) → registry default for the type
14
+ (`getDefaultSlicer`). Register a slicer for a type by giving a parser a matching `defaultSlicer`, or
15
+ configure `slicer` per type via `configureType`.
16
+
17
+ ## The `ResourceSlicer` interface
18
+
19
+ ```ts
20
+ interface ResourceSlicer {
21
+ id: string;
22
+ supportedTypes: ResourceType[]; // ["*"] = any
23
+ isSupported?: (type, ctx) => boolean | Promise<boolean>;
24
+ slice: (resource, ctx) => Promise<ResourceSlice[]>;
25
+ }
26
+ ```
27
+
28
+ ## Built-in slicers
29
+
30
+ ### `text` — `supportedTypes: ["*"]`
31
+ Universal fallback. Splits each text part on boundary strings into contiguous, non-overlapping
32
+ segments. No structural context.
33
+ - Default boundaries: `["\n\n", "\n", " "]`.
34
+ - Per-slice links: part links present in the text + bare URLs in the segment.
35
+
36
+ ### `markdown` — `supportedTypes: ["markdown", "html"]`
37
+ Heading-aware. Detects `#`–`######` headings, builds a heading breadcrumb
38
+ (`slice.context.headings`, e.g. `Intro > Details`), then segments each section.
39
+ - Default boundaries: `["\n\n", "\n", ". ", " "]` (sentence-aware).
40
+ - Per-slice links: markdown `[](…)` links + bare URLs. Used for HTML too (HTML is parsed to markdown).
41
+
42
+ ### `code` — `supportedTypes: [...CODE_TYPES]`
43
+ Declaration-aware. Splits at top-level declarations and attaches import context.
44
+ - `slice.context.declaration` = the block's first line; `slice.context.prefixes` = the first
45
+ `maxImportPrefixes` import lines.
46
+ - Default boundaries: `["\n\n", "\n", " "]`.
47
+ - Per-slice links: import/require specifiers + bare URLs.
48
+
49
+ ## Slice options (`SliceOptions`)
50
+
51
+ All apply to every slicer and can be set **per call** or **per type** via `configureType`.
52
+
53
+ | Option | Default | Effect |
54
+ | --- | --- | --- |
55
+ | `slicer` | per-type default | force a slicer id |
56
+ | `maxChars` | `2000` (`DEFAULT_MAX_CHARS`) | max slice size |
57
+ | `minChars` | `400` (`DEFAULT_MIN_CHARS`) | min size before a boundary break is accepted |
58
+ | `boundaries` | slicer-specific | ordered break strings (longest-context first) |
59
+ | `segmenter` | `defaultTextSegmenter` | pluggable splitting strategy (see below) |
60
+ | `includeResourceLocation` | `true` | add `Resource: <loc>` to embed text |
61
+ | `includeResourceType` | `true` | add `Type: <type>` |
62
+ | `includePartLocation` | `true` | add `Part: <loc>` |
63
+ | `includePartKind` | `false` | add `Kind: text\|image` |
64
+ | `includeContext` | `true` | add headings / declaration / summary / prefixes |
65
+ | `includeLinks` | `true` | add `Links: …` line |
66
+ | `embedSeparator` | `"\n\n"` | joins embed-text lines |
67
+ | `buildEmbedText` | built-in | full override: `(EmbedTextContext) => string` |
68
+ | `code.declarationPattern` | TS/JS regex | what starts a code block |
69
+ | `code.importPattern` | import/require regex | what counts as an import prefix |
70
+ | `code.maxImportPrefixes` | `5` | how many import lines to attach |
71
+ | `signal` | — | abort |
72
+
73
+ `embedText` is assembled by the built-in `buildEmbedText`/`collectEmbedContext` from the include-flags
74
+ above; override `buildEmbedText` to fully control the embedding-facing string.
75
+
76
+ ```ts
77
+ registry.configureType("markdown", { maxChars: 1200, minChars: 200, includePartKind: true });
78
+ const { slices } = await registry.load("/docs/guide.md");
79
+ ```
80
+
81
+ ## Pluggable segmenters
82
+
83
+ The slicers call a `TextSegmenter` for the raw split step:
84
+
85
+ ```ts
86
+ type TextSegmenter = (text: string, ctx: SegmentContext) => TextSegment[] | Promise<TextSegment[]>;
87
+ interface TextSegment { start: number; end: number; text: string; }
88
+ interface SegmentContext { maxChars; minChars; boundaries?; type?; slicerId?; signal?; }
89
+ ```
90
+
91
+ ### `defaultTextSegmenter` (built-in)
92
+ Lossless and offset-exact: contiguous, non-overlapping segments whose concatenation reproduces the
93
+ input. `partText.slice(start, end) === slice.text` always holds. This is the default.
94
+
95
+ ### `createLangchainSegmenter(options?)` (optional)
96
+ Backed by `@langchain/textsplitters`. Adds features the built-in lacks: **chunk overlap**,
97
+ **token-based sizing**, and **language-aware** splitting (~16 languages).
98
+
99
+ ```ts
100
+ import { createLangchainSegmenter, isLangchainSplittersAvailable } from "@aeye/resources";
101
+
102
+ // Overlapping char chunks; language grammar auto-derived from the resource type:
103
+ registry.configureType("typescript", {
104
+ segmenter: createLangchainSegmenter({ chunkSize: 1500, chunkOverlap: 200 }),
105
+ });
106
+
107
+ // Token-accurate sizing (tiktoken):
108
+ registry.configureType("markdown", {
109
+ segmenter: createLangchainSegmenter({ mode: "token", chunkSize: 512, chunkOverlap: 64 }),
110
+ });
111
+
112
+ await isLangchainSplittersAvailable(); // boolean
113
+ ```
114
+
115
+ `LangchainSegmenterOptions`:
116
+
117
+ | Option | Default | Notes |
118
+ | --- | --- | --- |
119
+ | `mode` | `"recursive"` | `"recursive"` (char-sized) or `"token"` (`TokenTextSplitter`) |
120
+ | `language` | derived from `type` | force a LangChain language grammar (recursive) |
121
+ | `languageFromType` | `true` | auto-map resource type → LangChain language |
122
+ | `chunkSize` | slicer `maxChars` | chars (recursive) or tokens (token mode) |
123
+ | `chunkOverlap` | `0` | >0 enables overlap (relaxes round-trip) |
124
+ | `separators` | LangChain default | custom separators (recursive, no language) |
125
+ | `keepSeparator` | `true` | keeps chunks as literal substrings → exact offset recovery |
126
+
127
+ **Offsets**: recovered by locating each chunk in the source. With `keepSeparator: true`, chunks are
128
+ literal substrings so `partText.slice(start, end) === slice.text` still holds, even with overlap.
129
+ **Round-trip**: with overlap (or token mode) segments overlap/trim, so the lossless concat guarantee
130
+ is intentionally relaxed for this segmenter (the default segmenter stays strict).
131
+
132
+ Type→language map covers: ts/tsx/js/jsx→`js`, python, go, java, c/cpp→`cpp`, php, rust, ruby, scala,
133
+ swift, markdown, html. Other types fall back to a generic recursive split.
134
+
135
+ ### Write a custom segmenter
136
+
137
+ ```ts
138
+ const sentenceSegmenter: TextSegmenter = (text) => {
139
+ const out: TextSegment[] = []; let i = 0;
140
+ for (const m of text.matchAll(/[^.!?]+[.!?]+/g)) {
141
+ const s = m.index!, e = s + m[0].length;
142
+ out.push({ start: s, end: e, text: m[0] });
143
+ i = e;
144
+ }
145
+ if (i < text.length) out.push({ start: i, end: text.length, text: text.slice(i) });
146
+ return out;
147
+ };
148
+ registry.configureType("text", { segmenter: sentenceSegmenter });
149
+ ```
150
+
151
+ ## Slicing without the registry
152
+
153
+ ```ts
154
+ const slices = await registry.slice(resource, { maxChars: 800, slicer: "markdown" });
155
+ ```
156
+
157
+ `registry.slice` merges the resource type's registry config under the passed options, then runs the
158
+ resolved slicer.
@@ -0,0 +1,186 @@
1
+ # @aeye/resources
2
+
3
+ Extensible **resource parsing, slicing, and resolution** utilities. Turn a file/URL/zip-entry into a
4
+ `ParsedResource` (typed parts + extracted links + child resources), split it into retrieval-ready
5
+ `ResourceSlice`s (with embed-text), resolve the links it references, and walk the whole reference
6
+ **graph** — all driven from a configurable registry.
7
+
8
+ Use it to build RAG / knowledge-base ingestion: ingest documents of many formats, chunk them for
9
+ embedding, follow links between them, and incrementally rebuild when sources change.
10
+
11
+ > This doc is split for length. See also:
12
+ > - [aeye-resources-parsers.md](./aeye-resources-parsers.md) — parsers, parser stacking, per-type config, PDF rendering, type inference.
13
+ > - [aeye-resources-slicers.md](./aeye-resources-slicers.md) — slicers, slice options, pluggable segmenters (LangChain).
14
+ > - [aeye-resources-graph.md](./aeye-resources-graph.md) — resolvers, locations, `modifiedAt`, the resource graph.
15
+
16
+ ## Install / import
17
+
18
+ ```ts
19
+ import {
20
+ ResourceRegistry, // the engine
21
+ // types: ParsedResource, ResourcePart, ResourceLink, ResourceSlice, ResourceSource, ...
22
+ } from "@aeye/resources";
23
+
24
+ // Batteries-included registry with all built-in parsers/slicers/resolvers:
25
+ import { createDefaultResourceRegistry, defaultResourceRegistry } from "@aeye/resources/default";
26
+ ```
27
+
28
+ Optional peer dependencies are loaded lazily and only needed for specific formats/features:
29
+ `pdf-parse` (PDF text), `mammoth` (DOCX), `xlsx` (Excel/CSV), `jszip` (ZIP), `node-poppler`
30
+ (PDF page rendering), `@langchain/textsplitters` (overlap/token/language-aware chunking). If a
31
+ dependency is missing, the relevant parser/feature simply declines or reports unsupported.
32
+
33
+ ## The pipeline
34
+
35
+ ```
36
+ input (path | URL | ResourceSource)
37
+ └─ resolve → ResourceSource (resolvers: zip, file, url)
38
+ └─ parse → ParsedResource (parser stack per type → parts, links, children)
39
+ └─ slice → ResourceSlice[] (slicer per type → chunks + embedText)
40
+ ```
41
+
42
+ `load()` does all three; `parse()` and `slice()` are also available individually.
43
+
44
+ ```ts
45
+ const registry = createDefaultResourceRegistry();
46
+
47
+ // One call: resolve → parse → slice
48
+ const { source, resource, slices } = await registry.load("/docs/guide.md", {
49
+ maxChars: 1500,
50
+ minChars: 300,
51
+ });
52
+
53
+ resource.type; // "markdown"
54
+ resource.parts; // ResourcePart[] (text/image parts)
55
+ resource.links; // ResourceLink[] (deduped, kind "resource" | "external")
56
+ slices[0].embedText; // string ready to embed
57
+ ```
58
+
59
+ ## Core data model (from `./types`)
60
+
61
+ ```ts
62
+ interface ParsedResource {
63
+ id: string; // `${location}::${type}`
64
+ location: string; // canonical, self-contained location
65
+ type: string; // e.g. "markdown", "pdf", "typescript"
66
+ name: string;
67
+ mimeType?: string;
68
+ modifiedAt?: number; // epoch ms — for staleness/incremental rebuilds
69
+ size?: number;
70
+ defaultSlicer: string; // slicer id chosen by the parser
71
+ parts: ResourcePart[];
72
+ links: ResourceLink[];
73
+ children?: ParsedResource[];// zip entries, rendered PDF pages, …
74
+ parentLocation?: string;
75
+ }
76
+
77
+ interface ResourcePart {
78
+ id: string; location: string;
79
+ kind: "text" | "image";
80
+ text?: string; data?: Uint8Array; mimeType?: string;
81
+ pageNumber?: number; metadata?: Record<string, unknown>;
82
+ links?: ResourceLink[];
83
+ }
84
+
85
+ interface ResourceLink {
86
+ id: string; value: string; location: string;
87
+ kind: "resource" | "external"; // relative/internal vs absolute external
88
+ title?: string; targetType?: string; metadata?: Record<string, unknown>;
89
+ }
90
+
91
+ interface ResourceSlice {
92
+ id: string; resourceId: string; partId: string; location: string;
93
+ text: string; // the slice content
94
+ embedText: string; // text augmented with context/links, ready to embed
95
+ start: number; end: number; // offsets into the part text
96
+ context?: { headings?; declaration?; summary?; prefixes? };
97
+ links: ResourceLink[]; metadata?: Record<string, unknown>;
98
+ }
99
+ ```
100
+
101
+ ## The registry (`ResourceRegistry`)
102
+
103
+ The registry is the configurable core. Everything is pluggable and registry-driven — there are no
104
+ hardcoded type→parser/slicer tables in the hot path.
105
+
106
+ ```ts
107
+ const r = new ResourceRegistry()
108
+ .registerParser(myParser, { priority: 10 }) // higher priority tried first
109
+ .registerSlicer(mySlicer)
110
+ .registerResolver(myResolver);
111
+ ```
112
+
113
+ Key methods (see topic docs for details):
114
+
115
+ | Method | Purpose |
116
+ | --- | --- |
117
+ | `load(input, opts?)` | resolve → parse → slice; returns `{ source, resource, slices }` |
118
+ | `parse(input, opts?)` | resolve + parse; returns `{ source, resource }` |
119
+ | `parseSource(source, opts?)` | run the parser stack on an already-resolved source |
120
+ | `slice(resource, opts?)` | run the slicer for a resource |
121
+ | `resolveLink(link, opts?)` | resolve a link (with optional `baseLocation`) to a `ResourceSource` |
122
+ | `locate(location, opts?)` | resolve a **self-contained** location directly (no base) |
123
+ | `statLink(link, opts?)` | cheap probe → `{ location, modifiedAt, ... }` without loading |
124
+ | `canResolve(link, opts?)` / `getResolverId(link, opts?)` | resolvability checks |
125
+ | `inferType(location, mime?)` | type detection from the registry's maps |
126
+ | `configureType(type, opts)` | set per-type defaults (parse **and** slice options) |
127
+ | `getTypeConfig(type)` | read per-type config |
128
+ | `registerExtensionType` / `registerMimeType` / `registerType` | extend type detection |
129
+ | `registerParser` / `registerSlicer` / `registerResolver` | extend behavior |
130
+ | `getParser(type)` / `getParsers(type)` / `getSlicer(id)` | introspection |
131
+ | `getTypeSupport(type)` / `isTypeSupported(type)` | capability checks (incl. optional deps) |
132
+
133
+ ### Per-type configuration
134
+
135
+ Configure capabilities once per type instead of on every call. Per-call options always win;
136
+ nested `pdf`/`code` objects are shallow-merged.
137
+
138
+ ```ts
139
+ registry.configureType("pdf", {
140
+ pdf: { renderPages: true, transcribePages: true },
141
+ renderPdfPages: createPopplerRenderer(),
142
+ transcribeImage: myVisionTranscriber,
143
+ });
144
+ registry.configureType("markdown", { maxChars: 1200, minChars: 200 });
145
+ ```
146
+
147
+ ## Built-in registry contents (`@aeye/resources/default`)
148
+
149
+ `createDefaultResourceRegistry()` registers:
150
+
151
+ - **Parsers** (stacked where useful): `textParser` (text/json/csv/tsv/yaml/xml/svg/toml/ini),
152
+ `markdownParser`, `htmlParser`, `codeParser` (all `CODE_TYPES`), `imageParser`,
153
+ `pdfRenderParser`→`pdfParser`, `excelPdfParser`→`excelParser`, `docxPdfParser`→`docxParser`,
154
+ `zipParser`.
155
+ - **Slicers**: `textSlicer` (`*`), `markdownSlicer` (markdown/html), `codeSlicer` (code types).
156
+ - **Resolvers** (tried in order): `zipResolver`, `fileResolver`, `urlResolver`.
157
+
158
+ All are exported individually too, so you can compose a custom registry.
159
+
160
+ ## Common recipes
161
+
162
+ ```ts
163
+ // Ingest a folder of mixed docs and embed the slices
164
+ for (const path of paths) {
165
+ const { slices } = await registry.load(path);
166
+ await embed(slices.map((s) => s.embedText));
167
+ }
168
+
169
+ // Know how to fetch a stored location, then load it
170
+ import { inferLocationScheme } from "@aeye/resources";
171
+ inferLocationScheme(loc); // "url" | "file" | "zip-entry" | "relative"
172
+ const source = await registry.locate(loc); // throws if not self-contained
173
+
174
+ // Crawl everything reachable from a root (see graph doc)
175
+ import { buildResourceGraph } from "@aeye/resources";
176
+ const graph = await buildResourceGraph(registry, "/docs/index.md");
177
+ ```
178
+
179
+ ## Gotchas
180
+
181
+ - Optional deps are not bundled; install the ones for formats you use. Missing deps → parser declines
182
+ or `isTypeSupported` returns false, not a hard crash (except when a format has no fallback).
183
+ - File locations are emitted **absolute** so they round-trip; a manually-supplied *relative*
184
+ `location` is not self-contained (`locate()` rejects it).
185
+ - Zips are read from disk (URL-hosted zips are not supported by the zip parser/resolver).
186
+ - `modifiedAt` is best-effort: filesystem mtime, HTTP `Last-Modified`, or zip entry date.