@aeye/resources 0.3.9 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/aeye-resources-converters.md +191 -0
  2. package/aeye-resources-graph.md +61 -7
  3. package/aeye-resources-parsers.md +42 -14
  4. package/aeye-resources-slicers.md +76 -8
  5. package/aeye-resources.md +24 -9
  6. package/dist/converters/data.d.ts +9 -0
  7. package/dist/converters/data.d.ts.map +1 -0
  8. package/dist/converters/data.js +78 -0
  9. package/dist/converters/data.js.map +1 -0
  10. package/dist/converters/folder.d.ts +13 -0
  11. package/dist/converters/folder.d.ts.map +1 -0
  12. package/dist/converters/folder.js +63 -0
  13. package/dist/converters/folder.js.map +1 -0
  14. package/dist/converters/index.d.ts +9 -0
  15. package/dist/converters/index.d.ts.map +1 -0
  16. package/dist/converters/index.js +22 -0
  17. package/dist/converters/index.js.map +1 -0
  18. package/dist/converters/markup.d.ts +6 -0
  19. package/dist/converters/markup.d.ts.map +1 -0
  20. package/dist/converters/markup.js +59 -0
  21. package/dist/converters/markup.js.map +1 -0
  22. package/dist/converters/pdf.d.ts +6 -0
  23. package/dist/converters/pdf.d.ts.map +1 -0
  24. package/dist/converters/pdf.js +70 -0
  25. package/dist/converters/pdf.js.map +1 -0
  26. package/dist/converters/tables.d.ts +12 -0
  27. package/dist/converters/tables.d.ts.map +1 -0
  28. package/dist/converters/tables.js +64 -0
  29. package/dist/converters/tables.js.map +1 -0
  30. package/dist/default.d.ts +9 -5
  31. package/dist/default.d.ts.map +1 -1
  32. package/dist/default.js +23 -8
  33. package/dist/default.js.map +1 -1
  34. package/dist/graph.d.ts +64 -6
  35. package/dist/graph.d.ts.map +1 -1
  36. package/dist/graph.js +127 -32
  37. package/dist/graph.js.map +1 -1
  38. package/dist/html/dom.d.ts +31 -0
  39. package/dist/html/dom.d.ts.map +1 -0
  40. package/dist/html/dom.js +194 -0
  41. package/dist/html/dom.js.map +1 -0
  42. package/dist/html/entities.d.ts +3 -0
  43. package/dist/html/entities.d.ts.map +1 -0
  44. package/dist/html/entities.js +33 -0
  45. package/dist/html/entities.js.map +1 -0
  46. package/dist/html/markdown.d.ts +30 -0
  47. package/dist/html/markdown.d.ts.map +1 -0
  48. package/dist/html/markdown.js +429 -0
  49. package/dist/html/markdown.js.map +1 -0
  50. package/dist/http/index.d.ts +5 -0
  51. package/dist/http/index.d.ts.map +1 -0
  52. package/dist/http/index.js +3 -0
  53. package/dist/http/index.js.map +1 -0
  54. package/dist/http/loader.d.ts +74 -0
  55. package/dist/http/loader.d.ts.map +1 -0
  56. package/dist/http/loader.js +248 -0
  57. package/dist/http/loader.js.map +1 -0
  58. package/dist/http/sniff.d.ts +38 -0
  59. package/dist/http/sniff.d.ts.map +1 -0
  60. package/dist/http/sniff.js +131 -0
  61. package/dist/http/sniff.js.map +1 -0
  62. package/dist/imports.d.ts +29 -0
  63. package/dist/imports.d.ts.map +1 -0
  64. package/dist/imports.js +53 -0
  65. package/dist/imports.js.map +1 -0
  66. package/dist/index.d.ts +28 -7
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +21 -6
  69. package/dist/index.js.map +1 -1
  70. package/dist/optional.d.ts +9 -0
  71. package/dist/optional.d.ts.map +1 -0
  72. package/dist/optional.js +17 -0
  73. package/dist/optional.js.map +1 -0
  74. package/dist/parsers/code.d.ts +1 -1
  75. package/dist/parsers/code.d.ts.map +1 -1
  76. package/dist/parsers/code.js +2 -2
  77. package/dist/parsers/code.js.map +1 -1
  78. package/dist/parsers/convert.d.ts +8 -0
  79. package/dist/parsers/convert.d.ts.map +1 -0
  80. package/dist/parsers/convert.js +40 -0
  81. package/dist/parsers/convert.js.map +1 -0
  82. package/dist/parsers/data.d.ts +8 -0
  83. package/dist/parsers/data.d.ts.map +1 -0
  84. package/dist/parsers/data.js +20 -0
  85. package/dist/parsers/data.js.map +1 -0
  86. package/dist/parsers/docx.d.ts +2 -2
  87. package/dist/parsers/docx.d.ts.map +1 -1
  88. package/dist/parsers/docx.js +9 -68
  89. package/dist/parsers/docx.js.map +1 -1
  90. package/dist/parsers/excel.d.ts +4 -1
  91. package/dist/parsers/excel.d.ts.map +1 -1
  92. package/dist/parsers/excel.js +17 -136
  93. package/dist/parsers/excel.js.map +1 -1
  94. package/dist/parsers/folder.d.ts +3 -0
  95. package/dist/parsers/folder.d.ts.map +1 -0
  96. package/dist/parsers/folder.js +21 -0
  97. package/dist/parsers/folder.js.map +1 -0
  98. package/dist/parsers/html.d.ts +5 -2
  99. package/dist/parsers/html.d.ts.map +1 -1
  100. package/dist/parsers/html.js +11 -33
  101. package/dist/parsers/html.js.map +1 -1
  102. package/dist/parsers/image.d.ts +1 -1
  103. package/dist/parsers/image.d.ts.map +1 -1
  104. package/dist/parsers/image.js +2 -2
  105. package/dist/parsers/image.js.map +1 -1
  106. package/dist/parsers/index.d.ts +13 -9
  107. package/dist/parsers/index.d.ts.map +1 -1
  108. package/dist/parsers/index.js +12 -9
  109. package/dist/parsers/index.js.map +1 -1
  110. package/dist/parsers/markdown.d.ts +1 -1
  111. package/dist/parsers/markdown.d.ts.map +1 -1
  112. package/dist/parsers/markdown.js +2 -2
  113. package/dist/parsers/markdown.js.map +1 -1
  114. package/dist/parsers/pdf.d.ts +2 -2
  115. package/dist/parsers/pdf.d.ts.map +1 -1
  116. package/dist/parsers/pdf.js +99 -119
  117. package/dist/parsers/pdf.js.map +1 -1
  118. package/dist/parsers/text.d.ts +1 -1
  119. package/dist/parsers/text.d.ts.map +1 -1
  120. package/dist/parsers/text.js +2 -2
  121. package/dist/parsers/text.js.map +1 -1
  122. package/dist/parsers/version.d.ts +42 -0
  123. package/dist/parsers/version.d.ts.map +1 -0
  124. package/dist/parsers/version.js +100 -0
  125. package/dist/parsers/version.js.map +1 -0
  126. package/dist/parsers/zip.d.ts +1 -1
  127. package/dist/parsers/zip.d.ts.map +1 -1
  128. package/dist/parsers/zip.js +12 -5
  129. package/dist/parsers/zip.js.map +1 -1
  130. package/dist/registry.d.ts +46 -3
  131. package/dist/registry.d.ts.map +1 -1
  132. package/dist/registry.js +97 -39
  133. package/dist/registry.js.map +1 -1
  134. package/dist/renderers/index.d.ts +2 -2
  135. package/dist/renderers/index.d.ts.map +1 -1
  136. package/dist/renderers/index.js +1 -1
  137. package/dist/renderers/index.js.map +1 -1
  138. package/dist/renderers/poppler.d.ts +1 -1
  139. package/dist/renderers/poppler.d.ts.map +1 -1
  140. package/dist/renderers/poppler.js +1 -1
  141. package/dist/renderers/poppler.js.map +1 -1
  142. package/dist/resolvers/file.d.ts +7 -1
  143. package/dist/resolvers/file.d.ts.map +1 -1
  144. package/dist/resolvers/file.js +26 -6
  145. package/dist/resolvers/file.js.map +1 -1
  146. package/dist/resolvers/folder.d.ts +18 -0
  147. package/dist/resolvers/folder.d.ts.map +1 -0
  148. package/dist/resolvers/folder.js +89 -0
  149. package/dist/resolvers/folder.js.map +1 -0
  150. package/dist/resolvers/index.d.ts +4 -3
  151. package/dist/resolvers/index.d.ts.map +1 -1
  152. package/dist/resolvers/index.js +4 -3
  153. package/dist/resolvers/index.js.map +1 -1
  154. package/dist/resolvers/url.d.ts +5 -1
  155. package/dist/resolvers/url.d.ts.map +1 -1
  156. package/dist/resolvers/url.js +13 -74
  157. package/dist/resolvers/url.js.map +1 -1
  158. package/dist/resolvers/zip.d.ts +1 -1
  159. package/dist/resolvers/zip.d.ts.map +1 -1
  160. package/dist/resolvers/zip.js +2 -2
  161. package/dist/resolvers/zip.js.map +1 -1
  162. package/dist/section-keys.d.ts +16 -0
  163. package/dist/section-keys.d.ts.map +1 -0
  164. package/dist/section-keys.js +24 -0
  165. package/dist/section-keys.js.map +1 -0
  166. package/dist/sections.d.ts +39 -0
  167. package/dist/sections.d.ts.map +1 -0
  168. package/dist/sections.js +118 -0
  169. package/dist/sections.js.map +1 -0
  170. package/dist/segmenters/default.d.ts +1 -1
  171. package/dist/segmenters/default.d.ts.map +1 -1
  172. package/dist/segmenters/default.js +1 -1
  173. package/dist/segmenters/default.js.map +1 -1
  174. package/dist/segmenters/index.d.ts +3 -3
  175. package/dist/segmenters/index.d.ts.map +1 -1
  176. package/dist/segmenters/index.js +2 -2
  177. package/dist/segmenters/index.js.map +1 -1
  178. package/dist/segmenters/langchain.d.ts +1 -1
  179. package/dist/segmenters/langchain.d.ts.map +1 -1
  180. package/dist/segmenters/langchain.js +1 -1
  181. package/dist/segmenters/langchain.js.map +1 -1
  182. package/dist/slicers/code.d.ts +30 -1
  183. package/dist/slicers/code.d.ts.map +1 -1
  184. package/dist/slicers/code.js +118 -32
  185. package/dist/slicers/code.js.map +1 -1
  186. package/dist/slicers/index.d.ts +3 -3
  187. package/dist/slicers/index.d.ts.map +1 -1
  188. package/dist/slicers/index.js +3 -3
  189. package/dist/slicers/index.js.map +1 -1
  190. package/dist/slicers/markdown.d.ts +15 -1
  191. package/dist/slicers/markdown.d.ts.map +1 -1
  192. package/dist/slicers/markdown.js +56 -27
  193. package/dist/slicers/markdown.js.map +1 -1
  194. package/dist/slicers/text.d.ts +1 -1
  195. package/dist/slicers/text.d.ts.map +1 -1
  196. package/dist/slicers/text.js +6 -4
  197. package/dist/slicers/text.js.map +1 -1
  198. package/dist/stack.d.ts +41 -0
  199. package/dist/stack.d.ts.map +1 -0
  200. package/dist/stack.js +56 -0
  201. package/dist/stack.js.map +1 -0
  202. package/dist/summaries.d.ts +11 -0
  203. package/dist/summaries.d.ts.map +1 -0
  204. package/dist/summaries.js +131 -0
  205. package/dist/summaries.js.map +1 -0
  206. package/dist/tables.d.ts +21 -0
  207. package/dist/tables.d.ts.map +1 -0
  208. package/dist/tables.js +113 -0
  209. package/dist/tables.js.map +1 -0
  210. package/dist/types.d.ts +140 -17
  211. package/dist/types.d.ts.map +1 -1
  212. package/dist/utils.d.ts +64 -3
  213. package/dist/utils.d.ts.map +1 -1
  214. package/dist/utils.js +156 -160
  215. package/dist/utils.js.map +1 -1
  216. package/dist/versions.d.ts +207 -0
  217. package/dist/versions.d.ts.map +1 -0
  218. package/dist/versions.js +217 -0
  219. package/dist/versions.js.map +1 -0
  220. package/dist/zip-internal.d.ts +9 -4
  221. package/dist/zip-internal.d.ts.map +1 -1
  222. package/dist/zip-internal.js +45 -19
  223. package/dist/zip-internal.js.map +1 -1
  224. package/package.json +33 -3
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { EmbedTextContext, LoadResourceOptions, ParsedResource, ResourceInput, ResourceLink, ResourcePart, ResourceSlice, ResourceType, SliceContext, SliceOptions } from "./types";
1
+ import { type HtmlToMarkdownOptions } from "./html/markdown.js";
2
+ import type { EmbedTextContext, LoadResourceOptions, ParsedResource, ResourceInput, ResourceLink, ResourcePart, ResourceSlice, ResourceSource, ResourceType, SliceContext, SliceOptions } from "./types.js";
2
3
  export declare const DEFAULT_MAX_CHARS = 2000;
3
4
  export declare const DEFAULT_MIN_CHARS = 400;
4
5
  export declare const CODE_TYPES: readonly ["javascript", "typescript", "jsx", "tsx", "python", "ruby", "go", "java", "c", "cpp", "csharp", "php", "rust", "swift", "kotlin", "scala", "sql", "shell", "css", "scss", "less", "dockerfile", "graphql", "lua", "r", "dart"];
@@ -13,7 +14,25 @@ export declare const DEFAULT_MIME_TYPE_PATTERNS: Array<[RegExp, ResourceType]>;
13
14
  * options alike, enabling per-type configuration of any behavior from the registry.
14
15
  */
15
16
  export declare function mergeOptions<T extends Partial<LoadResourceOptions>>(base: T | undefined, overrides: T | undefined): T;
17
+ /**
18
+ * Throws when the signal has been aborted. The thrown value is the signal's `reason` (an
19
+ * `AbortError` DOMException by default), so callers can tell a cancellation apart from a failure.
20
+ */
16
21
  export declare function assertNotAborted(signal?: AbortSignal): void;
22
+ /** True when an error is an abort (an `AbortError`), as thrown by {@link assertNotAborted} or `fetch`. */
23
+ export declare function isAbortError(error: unknown): boolean;
24
+ /**
25
+ * True when an input can be read more than once (buffers, strings, URLs, and factory functions).
26
+ * Streams and iterators can only be consumed once.
27
+ */
28
+ export declare function isReplayableInput(input: ResourceInput): boolean;
29
+ /**
30
+ * Runs `fn` with a local file path holding the source's bytes. Uses the source location directly
31
+ * when it is an existing local file; otherwise writes the input to a temporary file, which is removed
32
+ * once `fn` settles. Lets file-based tools (pdf renderers, converters) handle in-memory, URL and
33
+ * zip-entry sources too.
34
+ */
35
+ export declare function withLocalFile<T>(source: ResourceSource, extension: string, fn: (filePath: string) => Promise<T>): Promise<T>;
17
36
  export declare function collectInput(input: ResourceInput): Promise<Uint8Array>;
18
37
  export declare function readText(input: ResourceInput): Promise<string>;
19
38
  export declare function basenameFromLocation(location: string): string;
@@ -24,6 +43,16 @@ export declare function basenameFromLocation(location: string): string;
24
43
  export declare function inferTypeFromExtension(location: string, extensionTypes: Map<string, ResourceType>): ResourceType | undefined;
25
44
  /** Infers a resource type from a mime type using the supplied pattern list. */
26
45
  export declare function inferTypeFromMimePatterns(mimeType: string | undefined, patterns: Array<[RegExp, ResourceType]>): ResourceType | undefined;
46
+ /** The type any `text/*` mime type without a more exact rule maps to: it says only that the content is text. */
47
+ export declare const GENERIC_TEXT_TYPE: ResourceType;
48
+ /**
49
+ * Infers a resource type from a location and a mime type with the given rules. A mime type that maps to a specific
50
+ * type wins (`text/markdown` on `notes.txt` is markdown); one that maps only to {@link GENERIC_TEXT_TYPE}
51
+ * (`text/typescript`, `text/plain`) yields to the extension (`a.ts` is typescript), and is the answer when the
52
+ * extension names nothing. With no mime match, the extension decides.
53
+ */
54
+ export declare function inferTypeFromRules(location: string, mimeType: string | undefined, patterns: Array<[RegExp, ResourceType]>, extensionTypes: Map<string, ResourceType>): ResourceType | undefined;
55
+ /** Infers a resource type from a location and mime type with the default rules (see {@link inferTypeFromRules}). */
27
56
  export declare function inferTypeFromLocation(location: string, mimeType?: string): ResourceType | undefined;
28
57
  export declare function inferTypeFromMimeType(mimeType?: string): ResourceType | undefined;
29
58
  export declare function createResourceId(location: string, type: ResourceType): string;
@@ -31,6 +60,12 @@ export declare function createPartId(resource: ParsedResource, index: number, su
31
60
  export declare function createSliceId(part: ResourcePart, index: number): string;
32
61
  export declare function createLinkId(location: string, value: string, index: number): string;
33
62
  export declare function dedupeLinks(links: ResourceLink[]): ResourceLink[];
63
+ /**
64
+ * De-duplicates a slice's links by value, keeping the first occurrence. A slice often finds the same
65
+ * link twice (once from its part, once re-extracted from its own text, or as both a markdown link and
66
+ * a bare URL); the first one is kept, so put the richest source (e.g. titled links) first.
67
+ */
68
+ export declare function dedupeSliceLinks(links: ResourceLink[]): ResourceLink[];
34
69
  export declare function splitTextByBoundaries(text: string, maxChars?: number, minChars?: number, boundaries?: string[]): Array<{
35
70
  start: number;
36
71
  end: number;
@@ -39,7 +74,17 @@ export declare function splitTextByBoundaries(text: string, maxChars?: number, m
39
74
  export declare function buildEmbedText(context: EmbedTextContext, options: SliceOptions): string;
40
75
  export declare function collectEmbedContext(resource: ParsedResource, part: ResourcePart, slice: ResourceSlice, options: SliceOptions): string[];
41
76
  export declare function finalizeSlice(resource: ParsedResource, part: ResourcePart, slice: Omit<ResourceSlice, "embedText">, options: SliceOptions): ResourceSlice;
77
+ /**
78
+ * Every inline markdown link (`[label](target)`) and image (`![alt](src)`), as written. An image's link has
79
+ * `targetType` `image` and its alt text as its `title`, so a reader can tell the pictures a document shows from the
80
+ * pages it links to without guessing from the target's extension.
81
+ */
42
82
  export declare function extractLinksFromMarkdown(text: string, location: string): ResourceLink[];
83
+ /**
84
+ * Every `href` and `src` in html, as written. Each link's `metadata` says which tag it came from (`tag`: `a`, `img`,
85
+ * `link`, `script`, `base`, …) and its `rel` words when it has any (`nofollow`, `stylesheet`), so a crawler can follow
86
+ * only anchors, skip `nofollow`, and resolve against the page's `<base href>`.
87
+ */
43
88
  export declare function extractLinksFromHtml(text: string, location: string): ResourceLink[];
44
89
  export declare function extractLinksFromCode(text: string, location: string): ResourceLink[];
45
90
  export declare function extractLinksFromText(text: string, location: string): ResourceLink[];
@@ -53,8 +98,8 @@ export declare function hasUriScheme(value: string): boolean;
53
98
  * Handles relative paths, root-relative paths (`/x`), protocol-relative (`//host/x`), and fragments.
54
99
  */
55
100
  export declare function resolveAgainstUrl(link: string, baseUrl: string): string;
56
- export declare function htmlToMarkdown(html: string): string;
57
- export declare function stripTags(value: string): string;
101
+ /** Html as clean markdown (see {@link htmlToCleanMarkdown}), without the page facts. */
102
+ export declare function htmlToMarkdown(html: string, options?: HtmlToMarkdownOptions): string;
58
103
  export declare function toFilePath(location: string): string;
59
104
  /**
60
105
  * How a resource location should be fetched. `relative` means the location is NOT self-contained and
@@ -73,6 +118,22 @@ export declare function isSelfContainedLocation(location: string): boolean;
73
118
  export declare const DEFAULT_MARKUP_TYPES: ResourceType[];
74
119
  /** Default image file-extension → mime sub-type mappings, used to label binary image parts. */
75
120
  export declare const DEFAULT_IMAGE_EXTENSION_MIME: Record<string, string>;
121
+ /**
122
+ * Default resource type → mime type mappings: the mime type content of each type is labelled with when its server or
123
+ * source named none, or only a generic one (see {@link effectiveMimeType}). Types not here are labelled `text/plain`
124
+ * when they are text and `application/octet-stream` when they are binary; images by their extension.
125
+ */
126
+ export declare const DEFAULT_TYPE_MIME_TYPES: Readonly<Record<ResourceType, string>>;
127
+ /**
128
+ * The mime type to label content with: a specific declared one as it is (`application/javascript`); else the
129
+ * type's, from {@link DEFAULT_TYPE_MIME_TYPES} (an image's from its location's extension); else `text/plain` for text
130
+ * and `application/octet-stream` for binary content. A declared mime type that says nothing
131
+ * ({@link isGenericMimeType}: `application/octet-stream`, `text/plain`) is not specific.
132
+ */
133
+ export declare function effectiveMimeType(type: ResourceType | undefined, declared: string | undefined, options: {
134
+ location?: string;
135
+ binary: boolean;
136
+ }): string;
76
137
  /** Resolves an image mime type from a file name's extension, falling back to image/png. */
77
138
  export declare function imageMimeTypeFromLocation(fileName: string, fallback?: string): string;
78
139
  /** Separator embedded in a resource location to address an entry inside a zip archive. */
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,gBAA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,SAAc,GAAG,MAAM,CAG1F;AAED,0FAA0F;AAC1F,eAAO,MAAM,gBAAgB,YAAY,CAAC;AAE1C,qGAAqG;AACrG,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAE5D;AAED,uEAAuE;AACvE,wBAAgB,qBAAqB,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAEpF;AAED,0FAA0F;AAC1F,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAS9G;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAS/E;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,YAAY,GAAG,SAAS,CAMjF"}
package/dist/utils.js CHANGED
@@ -2,6 +2,11 @@ import { Buffer } from "node:buffer";
2
2
  import { Readable } from "node:stream";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
+ import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
6
+ import { tmpdir } from "node:os";
7
+ import { parseHtmlAttributes } from "./html/dom.js";
8
+ import { htmlToCleanMarkdown } from "./html/markdown.js";
9
+ import { isGenericMimeType } from "./http/sniff.js";
5
10
  export const DEFAULT_MAX_CHARS = 2000;
6
11
  export const DEFAULT_MIN_CHARS = 400;
7
12
  export const CODE_TYPES = [
@@ -151,11 +156,62 @@ export function mergeOptions(base, overrides) {
151
156
  if (base.code || overrides.code) {
152
157
  merged.code = { ...base.code, ...overrides.code };
153
158
  }
159
+ if (base.html || overrides.html) {
160
+ merged.html = { ...base.html, ...overrides.html };
161
+ }
162
+ if (base.folder || overrides.folder) {
163
+ merged.folder = { ...base.folder, ...overrides.folder };
164
+ }
154
165
  return merged;
155
166
  }
167
+ /**
168
+ * Throws when the signal has been aborted. The thrown value is the signal's `reason` (an
169
+ * `AbortError` DOMException by default), so callers can tell a cancellation apart from a failure.
170
+ */
156
171
  export function assertNotAborted(signal) {
157
172
  if (signal?.aborted) {
158
- throw new Error("Operation aborted");
173
+ throw signal.reason ?? new DOMException("Operation aborted", "AbortError");
174
+ }
175
+ }
176
+ /** True when an error is an abort (an `AbortError`), as thrown by {@link assertNotAborted} or `fetch`. */
177
+ export function isAbortError(error) {
178
+ return Boolean(error && typeof error === "object" && error.name === "AbortError");
179
+ }
180
+ /**
181
+ * True when an input can be read more than once (buffers, strings, URLs, and factory functions).
182
+ * Streams and iterators can only be consumed once.
183
+ */
184
+ export function isReplayableInput(input) {
185
+ return typeof input === "string"
186
+ || typeof input === "function"
187
+ || input instanceof Uint8Array
188
+ || input instanceof ArrayBuffer
189
+ || input instanceof URL;
190
+ }
191
+ /**
192
+ * Runs `fn` with a local file path holding the source's bytes. Uses the source location directly
193
+ * when it is an existing local file; otherwise writes the input to a temporary file, which is removed
194
+ * once `fn` settles. Lets file-based tools (pdf renderers, converters) handle in-memory, URL and
195
+ * zip-entry sources too.
196
+ */
197
+ export async function withLocalFile(source, extension, fn) {
198
+ if (!isZipEntryLocation(source.location) && !isHttpUrl(source.location)) {
199
+ const candidate = toFilePath(source.location);
200
+ if (path.isAbsolute(candidate)) {
201
+ const stats = await stat(candidate).catch(() => undefined);
202
+ if (stats?.isFile()) {
203
+ return fn(candidate);
204
+ }
205
+ }
206
+ }
207
+ const dir = await mkdtemp(path.join(tmpdir(), "aeye-resource-"));
208
+ try {
209
+ const filePath = path.join(dir, `input${extension}`);
210
+ await writeFile(filePath, await collectInput(source.input));
211
+ return await fn(filePath);
212
+ }
213
+ finally {
214
+ await rm(dir, { recursive: true, force: true }).catch(() => undefined);
159
215
  }
160
216
  }
161
217
  export async function collectInput(input) {
@@ -259,9 +315,23 @@ export function inferTypeFromMimePatterns(mimeType, patterns) {
259
315
  }
260
316
  return undefined;
261
317
  }
318
+ /** The type any `text/*` mime type without a more exact rule maps to: it says only that the content is text. */
319
+ export const GENERIC_TEXT_TYPE = "text";
320
+ /**
321
+ * Infers a resource type from a location and a mime type with the given rules. A mime type that maps to a specific
322
+ * type wins (`text/markdown` on `notes.txt` is markdown); one that maps only to {@link GENERIC_TEXT_TYPE}
323
+ * (`text/typescript`, `text/plain`) yields to the extension (`a.ts` is typescript), and is the answer when the
324
+ * extension names nothing. With no mime match, the extension decides.
325
+ */
326
+ export function inferTypeFromRules(location, mimeType, patterns, extensionTypes) {
327
+ const byMime = inferTypeFromMimePatterns(mimeType, patterns);
328
+ if (byMime !== undefined && byMime !== GENERIC_TEXT_TYPE)
329
+ return byMime;
330
+ return inferTypeFromExtension(location, extensionTypes) ?? byMime;
331
+ }
332
+ /** Infers a resource type from a location and mime type with the default rules (see {@link inferTypeFromRules}). */
262
333
  export function inferTypeFromLocation(location, mimeType) {
263
- return inferTypeFromMimePatterns(mimeType, DEFAULT_MIME_TYPE_PATTERNS)
264
- ?? inferTypeFromExtension(location, DEFAULT_EXTENSION_TYPE_MAP);
334
+ return inferTypeFromRules(location, mimeType, DEFAULT_MIME_TYPE_PATTERNS, DEFAULT_EXTENSION_TYPE_MAP);
265
335
  }
266
336
  export function inferTypeFromMimeType(mimeType) {
267
337
  return inferTypeFromMimePatterns(mimeType, DEFAULT_MIME_TYPE_PATTERNS);
@@ -289,6 +359,21 @@ export function dedupeLinks(links) {
289
359
  return true;
290
360
  });
291
361
  }
362
+ /**
363
+ * De-duplicates a slice's links by value, keeping the first occurrence. A slice often finds the same
364
+ * link twice (once from its part, once re-extracted from its own text, or as both a markdown link and
365
+ * a bare URL); the first one is kept, so put the richest source (e.g. titled links) first.
366
+ */
367
+ export function dedupeSliceLinks(links) {
368
+ const seen = new Set();
369
+ return links.filter((link) => {
370
+ if (seen.has(link.value)) {
371
+ return false;
372
+ }
373
+ seen.add(link.value);
374
+ return true;
375
+ });
376
+ }
292
377
  export function splitTextByBoundaries(text, maxChars = DEFAULT_MAX_CHARS, minChars = DEFAULT_MIN_CHARS, boundaries = ["\n\n", "\n", " "]) {
293
378
  if (text.length <= maxChars) {
294
379
  return [{ start: 0, end: text.length, text }];
@@ -354,6 +439,9 @@ export function collectEmbedContext(resource, part, slice, options) {
354
439
  if (slice.context?.summary) {
355
440
  lines.push(`Summary: ${slice.context.summary}`);
356
441
  }
442
+ if (slice.context?.sectionSummary) {
443
+ lines.push(`Section summary: ${slice.context.sectionSummary}`);
444
+ }
357
445
  if (slice.context?.prefixes?.length) {
358
446
  lines.push(...slice.context.prefixes.map((prefix) => `Context: ${prefix}`));
359
447
  }
@@ -371,6 +459,11 @@ export function finalizeSlice(resource, part, slice, options) {
371
459
  embedText: buildEmbedText({ resource, part, slice: incomplete, contextLines }, options)
372
460
  };
373
461
  }
462
+ /**
463
+ * Every inline markdown link (`[label](target)`) and image (`![alt](src)`), as written. An image's link has
464
+ * `targetType` `image` and its alt text as its `title`, so a reader can tell the pictures a document shows from the
465
+ * pages it links to without guessing from the target's extension.
466
+ */
374
467
  export function extractLinksFromMarkdown(text, location) {
375
468
  const links = [];
376
469
  let index = 0;
@@ -397,16 +490,26 @@ export function extractLinksFromMarkdown(text, location) {
397
490
  value,
398
491
  location,
399
492
  title: label || undefined,
400
- kind: isExternalLink(value) ? "external" : "resource"
493
+ kind: isExternalLink(value) ? "external" : "resource",
494
+ ...(text[cursor - 1] === "!" ? { targetType: "image" } : {})
401
495
  });
402
496
  cursor = valueEnd;
403
497
  }
404
498
  return links;
405
499
  }
500
+ /**
501
+ * Every `href` and `src` in html, as written. Each link's `metadata` says which tag it came from (`tag`: `a`, `img`,
502
+ * `link`, `script`, `base`, …) and its `rel` words when it has any (`nofollow`, `stylesheet`), so a crawler can follow
503
+ * only anchors, skip `nofollow`, and resolve against the page's `<base href>`.
504
+ */
406
505
  export function extractLinksFromHtml(text, location) {
407
506
  const links = [];
408
507
  let index = 0;
409
- forEachHtmlTag(text, ({ attributes }) => {
508
+ forEachHtmlTag(text, ({ name, closing, attributes }) => {
509
+ if (closing) {
510
+ return;
511
+ }
512
+ const rel = attributes.rel?.trim().toLowerCase().split(/\s+/).filter((word) => word !== "");
410
513
  for (const attribute of ["href", "src"]) {
411
514
  const value = attributes[attribute];
412
515
  if (!value) {
@@ -416,7 +519,8 @@ export function extractLinksFromHtml(text, location) {
416
519
  id: createLinkId(location, value, index++),
417
520
  value,
418
521
  location,
419
- kind: isExternalLink(value) ? "external" : "resource"
522
+ kind: isExternalLink(value) ? "external" : "resource",
523
+ metadata: { tag: name, ...(rel !== undefined && rel.length > 0 ? { rel } : {}) }
420
524
  });
421
525
  }
422
526
  });
@@ -436,41 +540,6 @@ function readQuotedValue(text, start) {
436
540
  end
437
541
  };
438
542
  }
439
- function parseHtmlAttributes(input) {
440
- const attributes = {};
441
- let cursor = 0;
442
- while (cursor < input.length) {
443
- while (cursor < input.length && /\s/.test(input[cursor])) {
444
- cursor++;
445
- }
446
- if (cursor >= input.length) {
447
- break;
448
- }
449
- let nameEnd = cursor;
450
- while (nameEnd < input.length && /[^\s=]/.test(input[nameEnd])) {
451
- nameEnd++;
452
- }
453
- const name = input.slice(cursor, nameEnd).toLowerCase();
454
- cursor = nameEnd;
455
- while (cursor < input.length && /\s/.test(input[cursor])) {
456
- cursor++;
457
- }
458
- if (input[cursor] !== "=") {
459
- continue;
460
- }
461
- cursor++;
462
- while (cursor < input.length && /\s/.test(input[cursor])) {
463
- cursor++;
464
- }
465
- const quoted = readQuotedValue(input, cursor);
466
- if (!quoted) {
467
- continue;
468
- }
469
- attributes[name] = quoted.value;
470
- cursor = quoted.end + 1;
471
- }
472
- return attributes;
473
- }
474
543
  function forEachHtmlTag(text, onTag) {
475
544
  let cursor = 0;
476
545
  while (cursor < text.length) {
@@ -549,9 +618,14 @@ export function extractLinksFromText(text, location) {
549
618
  let match;
550
619
  let index = 0;
551
620
  while ((match = pattern.exec(text))) {
621
+ // Sentence punctuation right after a URL ("see https://x.com.") is not part of it.
622
+ const value = match[0].replace(/[.,;:!?]+$/, "");
623
+ if (!/^https?:\/\/[^/]/.test(value)) {
624
+ continue;
625
+ }
552
626
  links.push({
553
- id: createLinkId(location, match[0], index++),
554
- value: match[0],
627
+ id: createLinkId(location, value, index++),
628
+ value,
555
629
  location,
556
630
  kind: "external"
557
631
  });
@@ -576,68 +650,9 @@ export function hasUriScheme(value) {
576
650
  export function resolveAgainstUrl(link, baseUrl) {
577
651
  return new URL(link, baseUrl).toString();
578
652
  }
579
- export function htmlToMarkdown(html) {
580
- const safeHtml = stripHtmlBlocks(html, ["script", "style"]);
581
- const parts = [];
582
- let cursor = 0;
583
- while (cursor < safeHtml.length) {
584
- const tagStart = safeHtml.indexOf("<", cursor);
585
- if (tagStart === -1) {
586
- parts.push(safeHtml.slice(cursor));
587
- break;
588
- }
589
- parts.push(safeHtml.slice(cursor, tagStart));
590
- const tagEnd = safeHtml.indexOf(">", tagStart + 1);
591
- if (tagEnd === -1) {
592
- break;
593
- }
594
- const rawTag = safeHtml.slice(tagStart + 1, tagEnd).trim();
595
- const closing = rawTag.startsWith("/");
596
- const normalized = closing ? rawTag.slice(1).trim() : rawTag;
597
- const name = normalized.split(/\s+/, 1)[0]?.toLowerCase();
598
- const attributes = parseHtmlAttributes(normalized.slice(name?.length ?? 0));
599
- if (name) {
600
- if (!closing && /^h[1-6]$/.test(name)) {
601
- parts.push(`\n\n${"#".repeat(Number(name[1]))} `);
602
- }
603
- else if (!closing && name === "li") {
604
- parts.push("\n- ");
605
- }
606
- else if (!closing && name === "br") {
607
- parts.push("\n");
608
- }
609
- else if (!closing && name === "img" && attributes.src) {
610
- parts.push(`![${attributes.alt || attributes.src}](${attributes.src})`);
611
- }
612
- else if (closing && /^h[1-6]$/.test(name)) {
613
- parts.push("\n\n");
614
- }
615
- else if (closing && ["p", "div", "section", "article", "header", "footer", "ul", "ol", "li"].includes(name)) {
616
- parts.push("\n\n");
617
- }
618
- }
619
- cursor = tagEnd + 1;
620
- }
621
- return collapseWhitespace(decodeHtmlEntities(parts.join(""))).trim();
622
- }
623
- export function stripTags(value) {
624
- let output = "";
625
- let insideTag = false;
626
- for (const character of value) {
627
- if (character === "<") {
628
- insideTag = true;
629
- output += " ";
630
- continue;
631
- }
632
- if (character === ">") {
633
- insideTag = false;
634
- continue;
635
- }
636
- if (!insideTag) {
637
- output += character;
638
- }
639
- }
640
- return collapseInlineWhitespace(decodeHtmlEntities(output)).trim();
653
+ /** Html as clean markdown (see {@link htmlToCleanMarkdown}), without the page facts. */
654
+ export function htmlToMarkdown(html, options) {
655
+ return htmlToCleanMarkdown(html, options).markdown;
641
656
  }
642
657
  export function toFilePath(location) {
643
658
  return location.startsWith("file://") ? fileURLToPath(location) : location;
@@ -680,6 +695,42 @@ export const DEFAULT_IMAGE_EXTENSION_MIME = {
680
695
  tiff: "image/tiff",
681
696
  svg: "image/svg+xml",
682
697
  };
698
+ /**
699
+ * Default resource type → mime type mappings: the mime type content of each type is labelled with when its server or
700
+ * source named none, or only a generic one (see {@link effectiveMimeType}). Types not here are labelled `text/plain`
701
+ * when they are text and `application/octet-stream` when they are binary; images by their extension.
702
+ */
703
+ export const DEFAULT_TYPE_MIME_TYPES = {
704
+ html: "text/html",
705
+ markdown: "text/markdown",
706
+ text: "text/plain",
707
+ json: "application/json",
708
+ yaml: "text/yaml",
709
+ xml: "application/xml",
710
+ svg: "image/svg+xml",
711
+ csv: "text/csv",
712
+ tsv: "text/tab-separated-values",
713
+ pdf: "application/pdf",
714
+ zip: "application/zip",
715
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
716
+ excel: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
717
+ };
718
+ /**
719
+ * The mime type to label content with: a specific declared one as it is (`application/javascript`); else the
720
+ * type's, from {@link DEFAULT_TYPE_MIME_TYPES} (an image's from its location's extension); else `text/plain` for text
721
+ * and `application/octet-stream` for binary content. A declared mime type that says nothing
722
+ * ({@link isGenericMimeType}: `application/octet-stream`, `text/plain`) is not specific.
723
+ */
724
+ export function effectiveMimeType(type, declared, options) {
725
+ if (declared !== undefined && !isGenericMimeType(declared))
726
+ return declared;
727
+ if (type === "image" && options.location !== undefined)
728
+ return imageMimeTypeFromLocation(options.location, declared ?? "application/octet-stream");
729
+ const known = type === undefined ? undefined : DEFAULT_TYPE_MIME_TYPES[type];
730
+ if (known !== undefined)
731
+ return known;
732
+ return options.binary ? "application/octet-stream" : "text/plain";
733
+ }
683
734
  /** Resolves an image mime type from a file name's extension, falling back to image/png. */
684
735
  export function imageMimeTypeFromLocation(fileName, fallback = "image/png") {
685
736
  const ext = fileName.split(".").pop()?.toLowerCase() ?? "";
@@ -730,59 +781,4 @@ export function toHeadingContext(pathSegments) {
730
781
  }
731
782
  return { headings: pathSegments.slice() };
732
783
  }
733
- function stripHtmlBlocks(html, tagNames) {
734
- const lower = html.toLowerCase();
735
- let result = "";
736
- let cursor = 0;
737
- while (cursor < html.length) {
738
- let matchedTag;
739
- let matchedStart = html.length;
740
- for (const tagName of tagNames) {
741
- const candidate = lower.indexOf(`<${tagName}`, cursor);
742
- if (candidate !== -1 && candidate < matchedStart) {
743
- matchedStart = candidate;
744
- matchedTag = tagName;
745
- }
746
- }
747
- if (!matchedTag) {
748
- result += html.slice(cursor);
749
- break;
750
- }
751
- result += html.slice(cursor, matchedStart);
752
- const openEnd = html.indexOf(">", matchedStart);
753
- if (openEnd === -1) {
754
- break;
755
- }
756
- const closeTagStart = lower.indexOf(`</${matchedTag}`, openEnd + 1);
757
- if (closeTagStart === -1) {
758
- cursor = openEnd + 1;
759
- continue;
760
- }
761
- const closeTagEnd = html.indexOf(">", closeTagStart + matchedTag.length + 2);
762
- if (closeTagEnd === -1) {
763
- break;
764
- }
765
- cursor = closeTagEnd + 1;
766
- }
767
- return result;
768
- }
769
- function collapseWhitespace(text) {
770
- return text
771
- .replace(/\r/g, "")
772
- .replace(/[ \t]+\n/g, "\n")
773
- .replace(/\n[ \t]+/g, "\n")
774
- .replace(/\n{3,}/g, "\n\n");
775
- }
776
- function collapseInlineWhitespace(text) {
777
- return text.replace(/\s+/g, " ");
778
- }
779
- function decodeHtmlEntities(text) {
780
- return text
781
- .replace(/&nbsp;/g, " ")
782
- .replace(/&lt;/g, "<")
783
- .replace(/&gt;/g, ">")
784
- .replace(/&quot;/g, "\"")
785
- .replace(/&#39;/g, "'")
786
- .replace(/&amp;/g, "&");
787
- }
788
784
  //# sourceMappingURL=utils.js.map