@neurowire/ingest 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +201 -0
- package/README.md +41 -0
- package/dist/index.d.ts +133 -0
- package/dist/index.js +611 -0
- package/package.json +63 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or Derivative
|
|
95
|
+
Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Médéric Burlet
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# @neurowire/ingest
|
|
2
|
+
|
|
3
|
+
Fetch, detect, and parse layer for [Neurowire](https://github.com/starside-io/neurowire). It turns a URL or a raw document into the canonical [`@neurowire/core`](https://www.npmjs.com/package/@neurowire/core) model: RSS, Atom, RDF, and JSON Feed, plus HTML auto-detection with a CSS-template fallback.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @neurowire/ingest
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## What it gives you
|
|
12
|
+
|
|
13
|
+
- **`fetchFeed(url, options?)`**: fetch a URL and return a `NeurowireFeed`, whatever the source format.
|
|
14
|
+
- **`fetchMesh(mesh, options?)`**: fetch every source in a mesh in parallel and merge them into one feed.
|
|
15
|
+
- **`ingestDocument(...)`**: parse an already-fetched document. Resolution order is explicit template, then discovered feed link, then registry tap (by host), then heuristic auto-detect.
|
|
16
|
+
- **Parsers**: `parseFeedString`, `parseRss`, `parseAtom`, `parseRdf`, `parseJsonFeed`.
|
|
17
|
+
- **HTML**: `autodetect`, `discoverFeedLink`, and the CSS-template engine (`applyTemplate`, `FeedTemplate`, `FeedTemplateSchema`).
|
|
18
|
+
- **Template registry**: `registerTemplate`, `findTemplate`, `listTemplates`. Curated per-host templates ship in [`@neurowire/taps`](https://www.npmjs.com/package/@neurowire/taps).
|
|
19
|
+
- **Utilities**: `resolveUrl`, `normDate`, `stripHtml`, `finalizeFeed`, and types `FeedDraft` / `ParseContext`.
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { fetchFeed, fetchMesh } from '@neurowire/ingest'
|
|
25
|
+
|
|
26
|
+
const feed = await fetchFeed('https://example.com/blog')
|
|
27
|
+
|
|
28
|
+
const mesh = await fetchMesh({
|
|
29
|
+
name: 'AI News',
|
|
30
|
+
sources: [
|
|
31
|
+
{ name: 'Claude Blog', url: 'https://claude.com/blog' },
|
|
32
|
+
{ name: 'Releases', url: 'https://github.com/anthropics/claude-code/releases.atom' },
|
|
33
|
+
],
|
|
34
|
+
})
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Pair it with `serialize` from `@neurowire/core` to emit Atom, JSON Feed, Markdown, or nwf.
|
|
38
|
+
|
|
39
|
+
## License
|
|
40
|
+
|
|
41
|
+
Apache-2.0
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { Person, NeurowireEntry, NeurowireFeed, Mesh } from '@neurowire/core';
|
|
2
|
+
import { CheerioAPI } from 'cheerio';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
type FeedKind = 'atom' | 'rss' | 'rdf' | 'jsonfeed' | 'html';
|
|
6
|
+
/** Classify a fetched document by content-type, then by sniffing the body. */
|
|
7
|
+
declare function detectKind(contentType: string, body: string): FeedKind;
|
|
8
|
+
|
|
9
|
+
interface RawDocument {
|
|
10
|
+
/** Final URL after redirects. */
|
|
11
|
+
url: string;
|
|
12
|
+
contentType: string;
|
|
13
|
+
body: string;
|
|
14
|
+
}
|
|
15
|
+
interface FetchOptions {
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
/** Fetch a URL over HTTP(S), following redirects, returning the body and final URL. */
|
|
19
|
+
declare function fetchDocument(url: string, options?: FetchOptions): Promise<RawDocument>;
|
|
20
|
+
|
|
21
|
+
/** Context passed to every parser: the final URL of the fetched document. */
|
|
22
|
+
interface ParseContext {
|
|
23
|
+
sourceUrl: string;
|
|
24
|
+
}
|
|
25
|
+
/** A loose, in-progress feed that `finalizeFeed` turns into a valid NeurowireFeed. */
|
|
26
|
+
interface FeedDraft {
|
|
27
|
+
id?: string;
|
|
28
|
+
title?: string;
|
|
29
|
+
home?: string;
|
|
30
|
+
self?: string;
|
|
31
|
+
updated?: string;
|
|
32
|
+
authors?: Person[];
|
|
33
|
+
entries: NeurowireEntry[];
|
|
34
|
+
}
|
|
35
|
+
/** Resolve a possibly-relative href against a base URL. Returns the input on failure. */
|
|
36
|
+
declare function resolveUrl(href: string, base: string): string;
|
|
37
|
+
/** Normalize any parseable date string (RFC 822, RFC 3339, ...) to ISO 8601. */
|
|
38
|
+
declare function normDate(value: string | undefined): string | undefined;
|
|
39
|
+
/** Strip HTML tags and collapse whitespace, for turning rich descriptions into summaries. */
|
|
40
|
+
declare function stripHtml(value: string | undefined): string | undefined;
|
|
41
|
+
/** Fill in defaults and stamp the generator to produce a valid NeurowireFeed. */
|
|
42
|
+
declare function finalizeFeed(draft: FeedDraft, ctx: ParseContext): NeurowireFeed;
|
|
43
|
+
|
|
44
|
+
/** A per-site recipe of CSS selectors for extracting articles from a listing page. */
|
|
45
|
+
declare const FeedTemplateSchema: z.ZodObject<{
|
|
46
|
+
/** Hostname this template applies to, e.g. "blog.example.com". */
|
|
47
|
+
host: z.ZodOptional<z.ZodString>;
|
|
48
|
+
/** Override feed title (otherwise the page <title> is used). */
|
|
49
|
+
feedTitle: z.ZodOptional<z.ZodString>;
|
|
50
|
+
/** Selector matching each article row. */
|
|
51
|
+
item: z.ZodString;
|
|
52
|
+
/** Selector (within an item) for the title text. */
|
|
53
|
+
title: z.ZodString;
|
|
54
|
+
/** Selector for the link (its href is read). Omit when the item element itself is the link. */
|
|
55
|
+
link: z.ZodOptional<z.ZodString>;
|
|
56
|
+
/** Selector for the date; reads [datetime] then text. */
|
|
57
|
+
date: z.ZodOptional<z.ZodString>;
|
|
58
|
+
/** Selector for the summary text. */
|
|
59
|
+
summary: z.ZodOptional<z.ZodString>;
|
|
60
|
+
/** Selector for the author name. */
|
|
61
|
+
author: z.ZodOptional<z.ZodString>;
|
|
62
|
+
/** Selector matching tag elements. */
|
|
63
|
+
tags: z.ZodOptional<z.ZodString>;
|
|
64
|
+
}, "strip", z.ZodTypeAny, {
|
|
65
|
+
title: string;
|
|
66
|
+
item: string;
|
|
67
|
+
author?: string | undefined;
|
|
68
|
+
host?: string | undefined;
|
|
69
|
+
feedTitle?: string | undefined;
|
|
70
|
+
link?: string | undefined;
|
|
71
|
+
date?: string | undefined;
|
|
72
|
+
summary?: string | undefined;
|
|
73
|
+
tags?: string | undefined;
|
|
74
|
+
}, {
|
|
75
|
+
title: string;
|
|
76
|
+
item: string;
|
|
77
|
+
author?: string | undefined;
|
|
78
|
+
host?: string | undefined;
|
|
79
|
+
feedTitle?: string | undefined;
|
|
80
|
+
link?: string | undefined;
|
|
81
|
+
date?: string | undefined;
|
|
82
|
+
summary?: string | undefined;
|
|
83
|
+
tags?: string | undefined;
|
|
84
|
+
}>;
|
|
85
|
+
type FeedTemplate = z.infer<typeof FeedTemplateSchema>;
|
|
86
|
+
/** Extract a feed from an HTML page using a CSS-selector template. */
|
|
87
|
+
declare function applyTemplate($: CheerioAPI, template: FeedTemplate, ctx: ParseContext): NeurowireFeed;
|
|
88
|
+
|
|
89
|
+
interface FetchFeedOptions {
|
|
90
|
+
/** Force a CSS-selector template instead of auto-detecting. */
|
|
91
|
+
template?: FeedTemplate;
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
/** Max number of feed-link redirects to follow (default 3). */
|
|
94
|
+
maxDepth?: number;
|
|
95
|
+
}
|
|
96
|
+
/** Fetch a URL (website, RSS, or Atom) and normalize it to a NeurowireFeed. */
|
|
97
|
+
declare function fetchFeed(url: string, options?: FetchFeedOptions): Promise<NeurowireFeed>;
|
|
98
|
+
/** Turn an already-fetched document into a feed. Exposed for testing without a network. */
|
|
99
|
+
declare function ingestDocument(doc: RawDocument, options?: FetchFeedOptions, depth?: number): Promise<NeurowireFeed>;
|
|
100
|
+
|
|
101
|
+
interface FetchMeshOptions {
|
|
102
|
+
signal?: AbortSignal;
|
|
103
|
+
/** Keep only the newest N merged entries. */
|
|
104
|
+
limit?: number;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Fetch every source in a mesh (in parallel) and merge them into one feed.
|
|
108
|
+
* Sources that fail to fetch are skipped; throws only if none succeed.
|
|
109
|
+
*/
|
|
110
|
+
declare function fetchMesh(mesh: Mesh, options?: FetchMeshOptions): Promise<NeurowireFeed>;
|
|
111
|
+
|
|
112
|
+
declare function parseAtom(doc: Record<string, unknown>, ctx: ParseContext): NeurowireFeed;
|
|
113
|
+
declare function parseRss(doc: Record<string, unknown>, ctx: ParseContext): NeurowireFeed;
|
|
114
|
+
declare function parseRdf(doc: Record<string, unknown>, ctx: ParseContext): NeurowireFeed;
|
|
115
|
+
declare function parseJsonFeed(raw: unknown, ctx: ParseContext): NeurowireFeed;
|
|
116
|
+
/** Parse a feed document (Atom / RSS / RDF / JSON Feed) by inspecting its root. */
|
|
117
|
+
declare function parseFeedString(body: string, ctx: ParseContext): NeurowireFeed;
|
|
118
|
+
|
|
119
|
+
/** Find a feed URL declared via <link rel="alternate" type="...feed..."> (atom preferred). */
|
|
120
|
+
declare function discoverFeedLink($: CheerioAPI, base: string): string | undefined;
|
|
121
|
+
/**
|
|
122
|
+
* Try to extract a feed from an HTML page without a template:
|
|
123
|
+
* JSON-LD first, then semantic <article> markup. Returns null if nothing solid is found.
|
|
124
|
+
*/
|
|
125
|
+
declare function autodetect($: CheerioAPI, ctx: ParseContext): NeurowireFeed | null;
|
|
126
|
+
|
|
127
|
+
/** Register a per-host template. Validated with zod; ignored if it has no `host`. */
|
|
128
|
+
declare function registerTemplate(template: FeedTemplate): void;
|
|
129
|
+
/** Look up a template for a URL's hostname. */
|
|
130
|
+
declare function findTemplate(url: string): FeedTemplate | undefined;
|
|
131
|
+
declare function listTemplates(): FeedTemplate[];
|
|
132
|
+
|
|
133
|
+
export { type FeedDraft, type FeedKind, type FeedTemplate, FeedTemplateSchema, type FetchFeedOptions, type FetchMeshOptions, type FetchOptions, type ParseContext, type RawDocument, applyTemplate, autodetect, detectKind, discoverFeedLink, fetchDocument, fetchFeed, fetchMesh, finalizeFeed, findTemplate, ingestDocument, listTemplates, normDate, parseAtom, parseFeedString, parseJsonFeed, parseRdf, parseRss, registerTemplate, resolveUrl, stripHtml };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
// src/detect.ts
|
|
2
|
+
function detectKind(contentType, body) {
|
|
3
|
+
const ct = contentType.toLowerCase();
|
|
4
|
+
if (ct.includes("atom")) return "atom";
|
|
5
|
+
if (ct.includes("rss")) return "rss";
|
|
6
|
+
if (ct.includes("feed+json")) return "jsonfeed";
|
|
7
|
+
const head = body.slice(0, 2e3).toLowerCase();
|
|
8
|
+
if (ct.includes("json") || body.trimStart().startsWith("{")) {
|
|
9
|
+
if (head.includes("jsonfeed.org") || head.includes('"items"')) return "jsonfeed";
|
|
10
|
+
}
|
|
11
|
+
if (head.includes("<feed")) return "atom";
|
|
12
|
+
if (head.includes("<rss")) return "rss";
|
|
13
|
+
if (head.includes("rdf:rdf")) return "rdf";
|
|
14
|
+
if (head.includes("jsonfeed.org")) return "jsonfeed";
|
|
15
|
+
return "html";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/fetch.ts
|
|
19
|
+
var USER_AGENT = "Neurowire/0.1 (+https://github.com/neurowire/neurowire)";
|
|
20
|
+
var ACCEPT = "application/atom+xml, application/rss+xml, application/feed+json, application/json;q=0.9, text/html;q=0.8, */*;q=0.5";
|
|
21
|
+
async function fetchDocument(url, options = {}) {
|
|
22
|
+
let parsed;
|
|
23
|
+
try {
|
|
24
|
+
parsed = new URL(url);
|
|
25
|
+
} catch {
|
|
26
|
+
throw new Error(`Invalid URL: ${url}`);
|
|
27
|
+
}
|
|
28
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
29
|
+
throw new Error(`Unsupported protocol: ${parsed.protocol}`);
|
|
30
|
+
}
|
|
31
|
+
const res = await fetch(url, {
|
|
32
|
+
redirect: "follow",
|
|
33
|
+
signal: options.signal,
|
|
34
|
+
headers: { "user-agent": USER_AGENT, accept: ACCEPT }
|
|
35
|
+
});
|
|
36
|
+
if (!res.ok) {
|
|
37
|
+
throw new Error(`Upstream responded ${res.status} ${res.statusText} for ${url}`);
|
|
38
|
+
}
|
|
39
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
40
|
+
const body = await res.text();
|
|
41
|
+
return { url: res.url || url, contentType, body };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/ingest.ts
|
|
45
|
+
import { load } from "cheerio";
|
|
46
|
+
|
|
47
|
+
// src/parsers/xml.ts
|
|
48
|
+
import { XMLParser } from "fast-xml-parser";
|
|
49
|
+
var parser = new XMLParser({
|
|
50
|
+
ignoreAttributes: false,
|
|
51
|
+
attributeNamePrefix: "@_",
|
|
52
|
+
textNodeName: "#text",
|
|
53
|
+
trimValues: true,
|
|
54
|
+
parseTagValue: false,
|
|
55
|
+
parseAttributeValue: false,
|
|
56
|
+
// Feeds that embed full HTML can reference far more than the default 1000
|
|
57
|
+
// entities. Raise the count limit, but keep the total expanded length bounded
|
|
58
|
+
// so entity-expansion bombs (billion laughs) are still rejected.
|
|
59
|
+
processEntities: {
|
|
60
|
+
enabled: true,
|
|
61
|
+
maxTotalExpansions: 2e7,
|
|
62
|
+
maxExpandedLength: 5e7
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
function parseXml(body) {
|
|
66
|
+
const result = parser.parse(body);
|
|
67
|
+
return result ?? {};
|
|
68
|
+
}
|
|
69
|
+
function get(node, key) {
|
|
70
|
+
if (node && typeof node === "object" && !Array.isArray(node)) {
|
|
71
|
+
return node[key];
|
|
72
|
+
}
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
function toArray(value) {
|
|
76
|
+
if (value === void 0 || value === null) return [];
|
|
77
|
+
return Array.isArray(value) ? value : [value];
|
|
78
|
+
}
|
|
79
|
+
function text(node) {
|
|
80
|
+
if (node === void 0 || node === null) return void 0;
|
|
81
|
+
if (typeof node === "string") return node.trim() || void 0;
|
|
82
|
+
if (typeof node === "number" || typeof node === "boolean") return String(node);
|
|
83
|
+
const inner = get(node, "#text");
|
|
84
|
+
if (typeof inner === "string") return inner.trim() || void 0;
|
|
85
|
+
if (typeof inner === "number") return String(inner);
|
|
86
|
+
return void 0;
|
|
87
|
+
}
|
|
88
|
+
function attr(node, name) {
|
|
89
|
+
const value = get(node, `@_${name}`);
|
|
90
|
+
if (typeof value === "string") return value.trim() || void 0;
|
|
91
|
+
if (typeof value === "number") return String(value);
|
|
92
|
+
return void 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/util.ts
|
|
96
|
+
import { GENERATOR } from "@neurowire/core";
|
|
97
|
+
function resolveUrl(href, base) {
|
|
98
|
+
try {
|
|
99
|
+
return new URL(href, base).toString();
|
|
100
|
+
} catch {
|
|
101
|
+
return href;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function normDate(value) {
|
|
105
|
+
if (!value) return void 0;
|
|
106
|
+
const ms = Date.parse(value);
|
|
107
|
+
return Number.isNaN(ms) ? void 0 : new Date(ms).toISOString();
|
|
108
|
+
}
|
|
109
|
+
function stripHtml(value) {
|
|
110
|
+
if (!value) return void 0;
|
|
111
|
+
const plain = value.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
|
|
112
|
+
return plain || void 0;
|
|
113
|
+
}
|
|
114
|
+
function newestEntryDate(entries) {
|
|
115
|
+
let max = Number.NEGATIVE_INFINITY;
|
|
116
|
+
for (const entry of entries) {
|
|
117
|
+
const value = entry.updated ?? entry.published;
|
|
118
|
+
if (!value) continue;
|
|
119
|
+
const ms = Date.parse(value);
|
|
120
|
+
if (!Number.isNaN(ms) && ms > max) max = ms;
|
|
121
|
+
}
|
|
122
|
+
return max === Number.NEGATIVE_INFINITY ? void 0 : new Date(max).toISOString();
|
|
123
|
+
}
|
|
124
|
+
function finalizeFeed(draft, ctx) {
|
|
125
|
+
const updated = normDate(draft.updated) ?? newestEntryDate(draft.entries) ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
126
|
+
const feed = {
|
|
127
|
+
id: draft.id?.trim() || ctx.sourceUrl,
|
|
128
|
+
title: draft.title?.trim() || "Untitled",
|
|
129
|
+
updated,
|
|
130
|
+
entries: draft.entries,
|
|
131
|
+
generator: { name: GENERATOR.name, version: GENERATOR.version }
|
|
132
|
+
};
|
|
133
|
+
if (draft.home) feed.home = resolveUrl(draft.home, ctx.sourceUrl);
|
|
134
|
+
if (draft.self) feed.self = draft.self;
|
|
135
|
+
if (draft.authors?.length) feed.authors = draft.authors;
|
|
136
|
+
return feed;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// src/html/autodetect.ts
|
|
140
|
+
var FEED_TYPES = [
|
|
141
|
+
"application/atom+xml",
|
|
142
|
+
"application/rss+xml",
|
|
143
|
+
"application/feed+json",
|
|
144
|
+
"application/json"
|
|
145
|
+
];
|
|
146
|
+
function discoverFeedLink($, base) {
|
|
147
|
+
const found = [];
|
|
148
|
+
$('link[rel="alternate"]').each((_, el) => {
|
|
149
|
+
const type = ($(el).attr("type") ?? "").toLowerCase();
|
|
150
|
+
const href = $(el).attr("href");
|
|
151
|
+
if (href && FEED_TYPES.includes(type)) found.push({ type, href });
|
|
152
|
+
});
|
|
153
|
+
for (const type of FEED_TYPES) {
|
|
154
|
+
const match = found.find((f) => f.type === type);
|
|
155
|
+
if (match) return resolveUrl(match.href, base);
|
|
156
|
+
}
|
|
157
|
+
return void 0;
|
|
158
|
+
}
|
|
159
|
+
var ARTICLE_TYPES = ["BlogPosting", "Article", "NewsArticle", "TechArticle", "Report"];
|
|
160
|
+
var COLLECTION_TYPES = ["Blog", "CollectionPage", "ItemList"];
|
|
161
|
+
function asTypes(type) {
|
|
162
|
+
if (typeof type === "string") return [type];
|
|
163
|
+
if (Array.isArray(type)) return type.filter((t) => typeof t === "string");
|
|
164
|
+
return [];
|
|
165
|
+
}
|
|
166
|
+
function str(value) {
|
|
167
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
168
|
+
}
|
|
169
|
+
function flatten(data) {
|
|
170
|
+
const out = [];
|
|
171
|
+
const visit = (node) => {
|
|
172
|
+
if (Array.isArray(node)) {
|
|
173
|
+
for (const child of node) visit(child);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (node && typeof node === "object") {
|
|
177
|
+
out.push(node);
|
|
178
|
+
const graph = node["@graph"];
|
|
179
|
+
if (Array.isArray(graph)) for (const child of graph) visit(child);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
visit(data);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
function jsonLdAuthors(value) {
|
|
186
|
+
const list = Array.isArray(value) ? value : value ? [value] : [];
|
|
187
|
+
const persons = list.map((author) => str(typeof author === "string" ? author : get2(author, "name"))).filter((name) => Boolean(name)).map((name) => ({ name }));
|
|
188
|
+
return persons.length ? persons : void 0;
|
|
189
|
+
}
|
|
190
|
+
function get2(node, key) {
|
|
191
|
+
return node && typeof node === "object" ? node[key] : void 0;
|
|
192
|
+
}
|
|
193
|
+
function jsonLdKeywords(value) {
|
|
194
|
+
if (Array.isArray(value)) {
|
|
195
|
+
const tags = value.filter((t) => typeof t === "string");
|
|
196
|
+
return tags.length ? tags : void 0;
|
|
197
|
+
}
|
|
198
|
+
if (typeof value === "string") {
|
|
199
|
+
const tags = value.split(",").map((t) => t.trim()).filter(Boolean);
|
|
200
|
+
return tags.length ? tags : void 0;
|
|
201
|
+
}
|
|
202
|
+
return void 0;
|
|
203
|
+
}
|
|
204
|
+
function jsonLdEntry(node, ctx) {
|
|
205
|
+
const url = str(node.url) ?? str(node["@id"]);
|
|
206
|
+
const title = str(node.headline) ?? str(node.name);
|
|
207
|
+
if (!url || !title) return null;
|
|
208
|
+
const link = resolveUrl(url, ctx.sourceUrl);
|
|
209
|
+
const entry = { id: link, title, link };
|
|
210
|
+
const published = normDate(str(node.datePublished));
|
|
211
|
+
const updated = normDate(str(node.dateModified));
|
|
212
|
+
if (published) entry.published = published;
|
|
213
|
+
if (updated) entry.updated = updated;
|
|
214
|
+
const summary = str(node.description) ?? stripHtml(str(node.articleBody));
|
|
215
|
+
if (summary) entry.summary = summary;
|
|
216
|
+
const authors = jsonLdAuthors(node.author);
|
|
217
|
+
if (authors) entry.authors = authors;
|
|
218
|
+
const tags = jsonLdKeywords(node.keywords);
|
|
219
|
+
if (tags) entry.tags = tags;
|
|
220
|
+
return entry;
|
|
221
|
+
}
|
|
222
|
+
function fromJsonLd($, ctx) {
|
|
223
|
+
const entries = [];
|
|
224
|
+
$('script[type="application/ld+json"]').each((_, el) => {
|
|
225
|
+
let data;
|
|
226
|
+
try {
|
|
227
|
+
data = JSON.parse($(el).text());
|
|
228
|
+
} catch {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
for (const node of flatten(data)) {
|
|
232
|
+
const types = asTypes(node["@type"]);
|
|
233
|
+
if (types.some((t) => ARTICLE_TYPES.includes(t))) {
|
|
234
|
+
const entry = jsonLdEntry(node, ctx);
|
|
235
|
+
if (entry) entries.push(entry);
|
|
236
|
+
} else if (types.some((t) => COLLECTION_TYPES.includes(t))) {
|
|
237
|
+
const posts = [...toArray(node.blogPost), ...toArray(node.itemListElement)];
|
|
238
|
+
for (const post of posts) {
|
|
239
|
+
const target = post && typeof post === "object" && "item" in post ? post.item : post;
|
|
240
|
+
const entry = jsonLdEntry(target ?? {}, ctx);
|
|
241
|
+
if (entry) entries.push(entry);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
return dedupe(entries);
|
|
247
|
+
}
|
|
248
|
+
function fromSemantic($, ctx) {
|
|
249
|
+
const entries = [];
|
|
250
|
+
$("article").each((_, el) => {
|
|
251
|
+
const $el = $(el);
|
|
252
|
+
const $a = $el.find("h1 a, h2 a, h3 a, h4 a").first();
|
|
253
|
+
const $titleEl = $a.length ? $a : $el.find("h1, h2, h3, h4").first();
|
|
254
|
+
const title = $titleEl.text().trim();
|
|
255
|
+
const href = $a.attr("href") ?? $el.find("a[href]").first().attr("href");
|
|
256
|
+
if (!title || !href) return;
|
|
257
|
+
const link = resolveUrl(href, ctx.sourceUrl);
|
|
258
|
+
const entry = { id: link, title, link };
|
|
259
|
+
const $time = $el.find("time[datetime]").first();
|
|
260
|
+
const date = normDate($time.attr("datetime") ?? $el.find("time").first().text().trim());
|
|
261
|
+
if (date) entry.published = date;
|
|
262
|
+
const summary = $el.find("p").first().text().trim();
|
|
263
|
+
if (summary) entry.summary = summary;
|
|
264
|
+
entries.push(entry);
|
|
265
|
+
});
|
|
266
|
+
return dedupe(entries);
|
|
267
|
+
}
|
|
268
|
+
function dedupe(entries) {
|
|
269
|
+
const seen = /* @__PURE__ */ new Set();
|
|
270
|
+
const out = [];
|
|
271
|
+
for (const entry of entries) {
|
|
272
|
+
if (seen.has(entry.link)) continue;
|
|
273
|
+
seen.add(entry.link);
|
|
274
|
+
out.push(entry);
|
|
275
|
+
}
|
|
276
|
+
return out;
|
|
277
|
+
}
|
|
278
|
+
function autodetect($, ctx) {
|
|
279
|
+
const siteTitle = $('meta[property="og:site_name"]').attr("content")?.trim() || $("title").first().text().trim() || ctx.sourceUrl;
|
|
280
|
+
const draft = (entries) => finalizeFeed(
|
|
281
|
+
{ id: ctx.sourceUrl, title: siteTitle, home: ctx.sourceUrl, self: ctx.sourceUrl, entries },
|
|
282
|
+
ctx
|
|
283
|
+
);
|
|
284
|
+
const jsonld = fromJsonLd($, ctx);
|
|
285
|
+
if (jsonld.length) return draft(jsonld);
|
|
286
|
+
const semantic = fromSemantic($, ctx);
|
|
287
|
+
if (semantic.length >= 2) return draft(semantic);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// src/html/template.ts
|
|
292
|
+
import { z } from "zod";
|
|
293
|
+
var FeedTemplateSchema = z.object({
|
|
294
|
+
/** Hostname this template applies to, e.g. "blog.example.com". */
|
|
295
|
+
host: z.string().optional(),
|
|
296
|
+
/** Override feed title (otherwise the page <title> is used). */
|
|
297
|
+
feedTitle: z.string().optional(),
|
|
298
|
+
/** Selector matching each article row. */
|
|
299
|
+
item: z.string(),
|
|
300
|
+
/** Selector (within an item) for the title text. */
|
|
301
|
+
title: z.string(),
|
|
302
|
+
/** Selector for the link (its href is read). Omit when the item element itself is the link. */
|
|
303
|
+
link: z.string().optional(),
|
|
304
|
+
/** Selector for the date; reads [datetime] then text. */
|
|
305
|
+
date: z.string().optional(),
|
|
306
|
+
/** Selector for the summary text. */
|
|
307
|
+
summary: z.string().optional(),
|
|
308
|
+
/** Selector for the author name. */
|
|
309
|
+
author: z.string().optional(),
|
|
310
|
+
/** Selector matching tag elements. */
|
|
311
|
+
tags: z.string().optional()
|
|
312
|
+
});
|
|
313
|
+
function applyTemplate($, template, ctx) {
|
|
314
|
+
const entries = [];
|
|
315
|
+
$(template.item).each((_, el) => {
|
|
316
|
+
const $el = $(el);
|
|
317
|
+
const title2 = $el.find(template.title).first().text().trim();
|
|
318
|
+
const $link = template.link ? $el.find(template.link).first() : $el;
|
|
319
|
+
const href = $link.attr("href") ?? $link.find("a").first().attr("href");
|
|
320
|
+
if (!title2 || !href) return;
|
|
321
|
+
const link = resolveUrl(href, ctx.sourceUrl);
|
|
322
|
+
const entry = { id: link, title: title2, link };
|
|
323
|
+
if (template.date) {
|
|
324
|
+
const $date = $el.find(template.date).first();
|
|
325
|
+
const date = normDate($date.attr("datetime") ?? $date.text().trim());
|
|
326
|
+
if (date) entry.published = date;
|
|
327
|
+
}
|
|
328
|
+
if (template.summary) {
|
|
329
|
+
const summary = $el.find(template.summary).first().text().trim();
|
|
330
|
+
if (summary) entry.summary = summary;
|
|
331
|
+
}
|
|
332
|
+
if (template.author) {
|
|
333
|
+
const author = $el.find(template.author).first().text().trim();
|
|
334
|
+
if (author) entry.authors = [{ name: author }];
|
|
335
|
+
}
|
|
336
|
+
if (template.tags) {
|
|
337
|
+
const tags = $el.find(template.tags).map((_i, t) => $(t).text().trim()).get().filter((t) => t.length > 0);
|
|
338
|
+
if (tags.length) entry.tags = tags;
|
|
339
|
+
}
|
|
340
|
+
entries.push(entry);
|
|
341
|
+
});
|
|
342
|
+
const title = template.feedTitle ?? ($("title").first().text().trim() || ctx.sourceUrl);
|
|
343
|
+
return finalizeFeed(
|
|
344
|
+
{ id: ctx.sourceUrl, title, home: ctx.sourceUrl, self: ctx.sourceUrl, entries },
|
|
345
|
+
ctx
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// src/html/registry.ts
|
|
350
|
+
var registry = /* @__PURE__ */ new Map();
|
|
351
|
+
function registerTemplate(template) {
|
|
352
|
+
const parsed = FeedTemplateSchema.parse(template);
|
|
353
|
+
if (parsed.host) registry.set(parsed.host, parsed);
|
|
354
|
+
}
|
|
355
|
+
function findTemplate(url) {
|
|
356
|
+
try {
|
|
357
|
+
return registry.get(new URL(url).hostname);
|
|
358
|
+
} catch {
|
|
359
|
+
return void 0;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function listTemplates() {
|
|
363
|
+
return [...registry.values()];
|
|
364
|
+
}
|
|
365
|
+
registerTemplate({
|
|
366
|
+
host: "example-blog.test",
|
|
367
|
+
feedTitle: "Example Blog",
|
|
368
|
+
item: ".post-list .post",
|
|
369
|
+
title: ".post-title",
|
|
370
|
+
link: ".post-title a",
|
|
371
|
+
date: "time",
|
|
372
|
+
summary: ".post-excerpt"
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
// src/parsers/feed.ts
|
|
376
|
+
function categories(node) {
|
|
377
|
+
const tags = toArray(node).map((c) => attr(c, "term") ?? text(c)).filter((t) => Boolean(t));
|
|
378
|
+
return tags.length ? tags : void 0;
|
|
379
|
+
}
|
|
380
|
+
function pickLink(links, rel) {
|
|
381
|
+
for (const link of links) {
|
|
382
|
+
const linkRel = attr(link, "rel") ?? "alternate";
|
|
383
|
+
if (linkRel === rel) return attr(link, "href");
|
|
384
|
+
}
|
|
385
|
+
return void 0;
|
|
386
|
+
}
|
|
387
|
+
function atomPersons(node) {
|
|
388
|
+
const persons = toArray(node).map((author) => {
|
|
389
|
+
const person = { name: text(get(author, "name")) ?? text(author) ?? "Unknown" };
|
|
390
|
+
const url = text(get(author, "uri"));
|
|
391
|
+
const email = text(get(author, "email"));
|
|
392
|
+
if (url) person.url = url;
|
|
393
|
+
if (email) person.email = email;
|
|
394
|
+
return person;
|
|
395
|
+
});
|
|
396
|
+
return persons.length ? persons : void 0;
|
|
397
|
+
}
|
|
398
|
+
function atomEntry(node, ctx) {
|
|
399
|
+
const links = toArray(get(node, "link"));
|
|
400
|
+
const href = pickLink(links, "alternate") ?? attr(links[0], "href") ?? text(get(node, "id")) ?? "";
|
|
401
|
+
const link = resolveUrl(href, ctx.sourceUrl);
|
|
402
|
+
const entry = {
|
|
403
|
+
id: text(get(node, "id")) ?? link,
|
|
404
|
+
title: text(get(node, "title")) ?? "Untitled",
|
|
405
|
+
link
|
|
406
|
+
};
|
|
407
|
+
const published = normDate(text(get(node, "published")));
|
|
408
|
+
const updated = normDate(text(get(node, "updated")));
|
|
409
|
+
if (published) entry.published = published;
|
|
410
|
+
if (updated) entry.updated = updated;
|
|
411
|
+
const summary = stripHtml(text(get(node, "summary")));
|
|
412
|
+
if (summary) entry.summary = summary;
|
|
413
|
+
const authors = atomPersons(get(node, "author"));
|
|
414
|
+
if (authors) entry.authors = authors;
|
|
415
|
+
const tags = categories(get(node, "category"));
|
|
416
|
+
if (tags) entry.tags = tags;
|
|
417
|
+
return entry;
|
|
418
|
+
}
|
|
419
|
+
function parseAtom(doc, ctx) {
|
|
420
|
+
const feed = get(doc, "feed");
|
|
421
|
+
const links = toArray(get(feed, "link"));
|
|
422
|
+
return finalizeFeed(
|
|
423
|
+
{
|
|
424
|
+
id: text(get(feed, "id")),
|
|
425
|
+
title: text(get(feed, "title")),
|
|
426
|
+
home: pickLink(links, "alternate"),
|
|
427
|
+
self: pickLink(links, "self") ?? ctx.sourceUrl,
|
|
428
|
+
updated: text(get(feed, "updated")),
|
|
429
|
+
authors: atomPersons(get(feed, "author")),
|
|
430
|
+
entries: toArray(get(feed, "entry")).map((entry) => atomEntry(entry, ctx))
|
|
431
|
+
},
|
|
432
|
+
ctx
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
function rssItem(node, ctx) {
|
|
436
|
+
const guid = text(get(node, "guid"));
|
|
437
|
+
const link = resolveUrl(text(get(node, "link")) ?? guid ?? "", ctx.sourceUrl);
|
|
438
|
+
const entry = {
|
|
439
|
+
id: guid ?? link,
|
|
440
|
+
title: text(get(node, "title")) ?? "Untitled",
|
|
441
|
+
link
|
|
442
|
+
};
|
|
443
|
+
const published = normDate(text(get(node, "pubDate")) ?? text(get(node, "dc:date")));
|
|
444
|
+
if (published) entry.published = published;
|
|
445
|
+
const summary = stripHtml(text(get(node, "description")) ?? text(get(node, "content:encoded")));
|
|
446
|
+
if (summary) entry.summary = summary;
|
|
447
|
+
const creator = text(get(node, "dc:creator")) ?? text(get(node, "author"));
|
|
448
|
+
if (creator) entry.authors = [{ name: creator }];
|
|
449
|
+
const tags = categories(get(node, "category"));
|
|
450
|
+
if (tags) entry.tags = tags;
|
|
451
|
+
return entry;
|
|
452
|
+
}
|
|
453
|
+
function channelAuthors(channel) {
|
|
454
|
+
const name = text(get(channel, "dc:creator")) ?? text(get(channel, "managingEditor"));
|
|
455
|
+
return name ? [{ name }] : void 0;
|
|
456
|
+
}
|
|
457
|
+
function parseRss(doc, ctx) {
|
|
458
|
+
const channel = get(get(doc, "rss"), "channel");
|
|
459
|
+
return finalizeFeed(
|
|
460
|
+
{
|
|
461
|
+
id: text(get(channel, "link")),
|
|
462
|
+
title: text(get(channel, "title")),
|
|
463
|
+
home: text(get(channel, "link")),
|
|
464
|
+
self: ctx.sourceUrl,
|
|
465
|
+
updated: text(get(channel, "lastBuildDate")) ?? text(get(channel, "pubDate")),
|
|
466
|
+
authors: channelAuthors(channel),
|
|
467
|
+
entries: toArray(get(channel, "item")).map((item) => rssItem(item, ctx))
|
|
468
|
+
},
|
|
469
|
+
ctx
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
function parseRdf(doc, ctx) {
|
|
473
|
+
const rdf = get(doc, "rdf:RDF");
|
|
474
|
+
const channel = get(rdf, "channel");
|
|
475
|
+
return finalizeFeed(
|
|
476
|
+
{
|
|
477
|
+
id: text(get(channel, "link")),
|
|
478
|
+
title: text(get(channel, "title")),
|
|
479
|
+
home: text(get(channel, "link")),
|
|
480
|
+
self: ctx.sourceUrl,
|
|
481
|
+
updated: text(get(channel, "dc:date")),
|
|
482
|
+
entries: toArray(get(rdf, "item")).map((item) => rssItem(item, ctx))
|
|
483
|
+
},
|
|
484
|
+
ctx
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
function jsonAuthors(authors, author) {
|
|
488
|
+
const list = authors ?? (author ? [author] : []);
|
|
489
|
+
const persons = list.filter((a) => Boolean(a.name)).map((a) => a.url ? { name: a.name, url: a.url } : { name: a.name });
|
|
490
|
+
return persons.length ? persons : void 0;
|
|
491
|
+
}
|
|
492
|
+
function parseJsonFeed(raw, ctx) {
|
|
493
|
+
const data = raw ?? {};
|
|
494
|
+
const entries = toArray(data.items).map((item) => {
|
|
495
|
+
const link = resolveUrl(item.url ?? item.external_url ?? "", ctx.sourceUrl);
|
|
496
|
+
const entry = {
|
|
497
|
+
id: item.id !== void 0 ? String(item.id) : link,
|
|
498
|
+
title: item.title ?? "Untitled",
|
|
499
|
+
link
|
|
500
|
+
};
|
|
501
|
+
const published = normDate(item.date_published);
|
|
502
|
+
const modified = normDate(item.date_modified);
|
|
503
|
+
if (published) entry.published = published;
|
|
504
|
+
if (modified) entry.updated = modified;
|
|
505
|
+
const summary = item.summary ?? stripHtml(item.content_html) ?? item.content_text;
|
|
506
|
+
if (summary) entry.summary = summary;
|
|
507
|
+
const authors = jsonAuthors(item.authors, item.author);
|
|
508
|
+
if (authors) entry.authors = authors;
|
|
509
|
+
if (item.tags?.length) entry.tags = item.tags;
|
|
510
|
+
return entry;
|
|
511
|
+
});
|
|
512
|
+
return finalizeFeed(
|
|
513
|
+
{
|
|
514
|
+
id: data.feed_url,
|
|
515
|
+
title: data.title,
|
|
516
|
+
home: data.home_page_url,
|
|
517
|
+
self: data.feed_url ?? ctx.sourceUrl,
|
|
518
|
+
authors: jsonAuthors(data.authors, data.author),
|
|
519
|
+
entries
|
|
520
|
+
},
|
|
521
|
+
ctx
|
|
522
|
+
);
|
|
523
|
+
}
|
|
524
|
+
function parseFeedString(body, ctx) {
|
|
525
|
+
if (body.trimStart().startsWith("{")) return parseJsonFeed(JSON.parse(body), ctx);
|
|
526
|
+
const doc = parseXml(body);
|
|
527
|
+
if (get(doc, "feed")) return parseAtom(doc, ctx);
|
|
528
|
+
if (get(doc, "rss")) return parseRss(doc, ctx);
|
|
529
|
+
if (get(doc, "rdf:RDF")) return parseRdf(doc, ctx);
|
|
530
|
+
throw new Error("Unrecognized feed format (expected Atom, RSS, RDF or JSON Feed)");
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// src/ingest.ts
|
|
534
|
+
async function fetchFeed(url, options = {}) {
|
|
535
|
+
return ingest(url, options, 0);
|
|
536
|
+
}
|
|
537
|
+
async function ingest(url, options, depth) {
|
|
538
|
+
const doc = await fetchDocument(url, { signal: options.signal });
|
|
539
|
+
return ingestDocument(doc, options, depth);
|
|
540
|
+
}
|
|
541
|
+
async function ingestDocument(doc, options = {}, depth = 0) {
|
|
542
|
+
const ctx = { sourceUrl: doc.url };
|
|
543
|
+
if (detectKind(doc.contentType, doc.body) !== "html") {
|
|
544
|
+
return parseFeedString(doc.body, ctx);
|
|
545
|
+
}
|
|
546
|
+
const $ = load(doc.body);
|
|
547
|
+
if (options.template) return applyTemplate($, options.template, ctx);
|
|
548
|
+
const maxDepth = options.maxDepth ?? 3;
|
|
549
|
+
if (depth < maxDepth) {
|
|
550
|
+
const discovered = discoverFeedLink($, doc.url);
|
|
551
|
+
if (discovered && discovered !== doc.url) {
|
|
552
|
+
try {
|
|
553
|
+
return await ingest(discovered, { ...options, template: void 0 }, depth + 1);
|
|
554
|
+
} catch {
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
const template = findTemplate(doc.url);
|
|
559
|
+
if (template) {
|
|
560
|
+
const fromTemplate = applyTemplate($, template, ctx);
|
|
561
|
+
if (fromTemplate.entries.length) return fromTemplate;
|
|
562
|
+
}
|
|
563
|
+
const auto = autodetect($, ctx);
|
|
564
|
+
if (auto?.entries.length) return auto;
|
|
565
|
+
throw new Error(`Neurowire could not extract a feed from ${doc.url}`);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// src/mesh.ts
|
|
569
|
+
import { mergeFeeds } from "@neurowire/core";
|
|
570
|
+
async function fetchMesh(mesh, options = {}) {
|
|
571
|
+
const fetchOptions = { signal: options.signal };
|
|
572
|
+
const results = await Promise.allSettled(
|
|
573
|
+
mesh.sources.map(
|
|
574
|
+
async (source) => ({
|
|
575
|
+
feed: await fetchFeed(source.url, fetchOptions),
|
|
576
|
+
source: { name: source.name, url: source.url }
|
|
577
|
+
})
|
|
578
|
+
)
|
|
579
|
+
);
|
|
580
|
+
const parts = [];
|
|
581
|
+
for (const result of results) {
|
|
582
|
+
if (result.status === "fulfilled") parts.push(result.value);
|
|
583
|
+
}
|
|
584
|
+
if (!parts.length) {
|
|
585
|
+
throw new Error(`Mesh "${mesh.name}": no sources could be fetched`);
|
|
586
|
+
}
|
|
587
|
+
return mergeFeeds(mesh.name, parts, { limit: options.limit });
|
|
588
|
+
}
|
|
589
|
+
export {
|
|
590
|
+
FeedTemplateSchema,
|
|
591
|
+
applyTemplate,
|
|
592
|
+
autodetect,
|
|
593
|
+
detectKind,
|
|
594
|
+
discoverFeedLink,
|
|
595
|
+
fetchDocument,
|
|
596
|
+
fetchFeed,
|
|
597
|
+
fetchMesh,
|
|
598
|
+
finalizeFeed,
|
|
599
|
+
findTemplate,
|
|
600
|
+
ingestDocument,
|
|
601
|
+
listTemplates,
|
|
602
|
+
normDate,
|
|
603
|
+
parseAtom,
|
|
604
|
+
parseFeedString,
|
|
605
|
+
parseJsonFeed,
|
|
606
|
+
parseRdf,
|
|
607
|
+
parseRss,
|
|
608
|
+
registerTemplate,
|
|
609
|
+
resolveUrl,
|
|
610
|
+
stripHtml
|
|
611
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@neurowire/ingest",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Fetch, detect, and parse RSS/Atom/RDF/JSON feeds and HTML pages into the Neurowire model.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"CHANGELOG.md"
|
|
17
|
+
],
|
|
18
|
+
"keywords": [
|
|
19
|
+
"neurowire",
|
|
20
|
+
"feed",
|
|
21
|
+
"rss",
|
|
22
|
+
"atom",
|
|
23
|
+
"rdf",
|
|
24
|
+
"json-feed",
|
|
25
|
+
"feed-parser",
|
|
26
|
+
"rss-parser",
|
|
27
|
+
"scraper",
|
|
28
|
+
"cheerio"
|
|
29
|
+
],
|
|
30
|
+
"author": "Médéric Burlet <mederic.burlet@gmail.com>",
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/starside-io/neurowire.git",
|
|
35
|
+
"directory": "packages/ingest"
|
|
36
|
+
},
|
|
37
|
+
"homepage": "https://github.com/starside-io/neurowire#readme",
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/starside-io/neurowire/issues"
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=20"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"cheerio": "^1.0.0",
|
|
49
|
+
"fast-xml-parser": "^4.5.1",
|
|
50
|
+
"zod": "^3.24.1",
|
|
51
|
+
"@neurowire/core": "0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@types/node": "^22.10.5",
|
|
55
|
+
"tsup": "^8.3.5",
|
|
56
|
+
"typescript": "^5.7.3"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsup",
|
|
60
|
+
"dev": "tsup --watch",
|
|
61
|
+
"typecheck": "tsc --noEmit"
|
|
62
|
+
}
|
|
63
|
+
}
|