feed-slurp 1.0.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/LICENSE ADDED
@@ -0,0 +1,324 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+ (a) that the initial Contributor has otherwise conditioned the
27
+ some portion of the Covered Software on it not being
28
+ available under either of the Secondary Licenses, or
29
+
30
+ (b) that the Covered Software was first made available under
31
+ Mozilla Public License, version 1.1 or earlier, but not also
32
+ under the Mozilla Public License, version 2.0.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+ (a) any file in Source Code Form that results from an addition to,
52
+ deletion from, or modification of the contents of Covered
53
+ Software; or
54
+
55
+ (b) any new file in Source Code Form that contains any Covered
56
+ Software.
57
+
58
+ 1.11. "Patent Claims" of a Contributor
59
+ means any patent claim(s), including without limitation, method,
60
+ process, and apparatus claims, in any patent Licensable by such
61
+ Contributor that would be infringed, but for the grant of the
62
+ License, by the making, using, selling, offering for sale, having
63
+ made, import, or other transfer of either its Contributions or its
64
+ Contributor Version.
65
+
66
+ 1.12. "Secondary Licenses"
67
+ means either the GNU General Public License, Version 2.0, the GNU
68
+ Lesser General Public License, Version 2.1, the GNU Affero General
69
+ Public License, Version 3.0, or any later versions of those
70
+ licenses.
71
+
72
+ 1.13. "Source Code Form"
73
+ means the preferred form of the Covered Software for making
74
+ modifications to it.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your receiving a
136
+ copy of this License from another Person. Any person as a result of
137
+ developing software that becomes Covered Software or a Larger Work will
138
+ be a Contributor of such Covered Software or Larger Work.
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Code Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be available in Source Code Form, as
175
+ described in Section 3.1, and You must inform recipients how they
176
+ can obtain a copy of such Source Code Form by reasonable means in a
177
+ timely manner, at a charge no more than the cost of distribution to
178
+ the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipient's rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of such Secondary License(s).
196
+
197
+ 3.4. Notices
198
+
199
+ You may not remove or alter the substance of any license notices
200
+ (including copyright notices, patent notices, disclaimers of warranty,
201
+ or limitations of liability) contained within the Source Code Form of
202
+ the Covered Software, except that You may alter any license notices to
203
+ the extent required to remedy statutory inaccuracies.
204
+
205
+ 3.5. Application of Additional Terms
206
+
207
+ You may choose to offer, and to charge a fee for, warranty, support,
208
+ indemnity or liability obligations to one or more recipients of Covered
209
+ Software. However, You may do so only on Your own behalf, and not on
210
+ behalf of any Contributor. You must make it absolutely clear that any
211
+ such warranty, support, indemnity, or liability obligation is offered by
212
+ You alone, and You hereby agree to indemnify every Contributor for any
213
+ liability incurred by such Contributor as a result of warranty, support,
214
+ indemnity or liability offered by You. You may include additional
215
+ disclaimers of warranty and limitations of liability specific to any
216
+ jurisdiction.
217
+
218
+ 4. Inability to Comply Due to Statute or Regulation
219
+ ---------------------------------------------------
220
+
221
+ If it is impossible for You to comply with any of the terms of this
222
+ License with respect to some or all of the Covered Software due to
223
+ statute, judicial order, or regulation then You must: (a) comply with
224
+ the terms of this License to the maximum extent possible; and (b)
225
+ describe the limitations and the code they affect. Such description must
226
+ be placed in a text file included with all distributions of the Covered
227
+ Software under this License. Except to the extent prohibited by statute
228
+ or judicial order, such description must be sufficiently detailed for a
229
+ recipient of ordinary skill to be able to understand it.
230
+
231
+ 5. Termination
232
+ --------------
233
+
234
+ 5.1. The rights granted under this License will terminate automatically
235
+ if You fail to comply with any of its terms. However, if You become
236
+ compliant, then the rights granted under this License from a particular
237
+ Contributor are reinstated (a) provisionally, unless and until such
238
+ Contributor explicitly and finally terminates Your grants, and (b) on an
239
+ ongoing basis, if such Contributor fails to notify You of the
240
+ non-compliance by some reasonable means prior to 60 days after You have
241
+ come back into compliance. Moreover, Your grants from a particular
242
+ Contributor are reinstated on an ongoing basis if such Contributor
243
+ notifies You of the non-compliance by some reasonable means, this is the
244
+ first time You have received notice of non-compliance with this License
245
+ from such Contributor, and You become compliant prior to 30 days after
246
+ Your receipt of the notice.
247
+
248
+ 5.2. If You initiate litigation against any entity by asserting a patent
249
+ infringement claim (excluding declaratory judgment actions,
250
+ counter-claims, and cross-claims) alleging that a Contributor Version
251
+ directly or indirectly infringes any patent, then the rights granted to
252
+ You by any and all Contributors for the Covered Software under Section
253
+ 2.1 of this License shall terminate.
254
+
255
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
256
+ end user license agreements (excluding distributors and resellers) which
257
+ have been validly granted by You or Your distributors under this License
258
+ prior to termination shall survive termination.
259
+
260
+ 6. Disclaimer of Warranty
261
+ -------------------------
262
+
263
+ Covered Software is provided under this License on an "as is" basis,
264
+ without warranty of any kind, either expressed, implied, or statutory,
265
+ including, without limitation, warranties that the Covered Software is
266
+ free of defects, merchantable, fit for a particular purpose or
267
+ non-infringing. The entire risk as to the quality and performance of the
268
+ Covered Software is with You. Should any Covered Software prove
269
+ defective in any respect, You (not any Contributor) assume the cost of
270
+ any necessary servicing, repair, or correction. This disclaimer of
271
+ warranty constitutes an essential part of this License. No use of any
272
+ Covered Software is authorized under this License except under this
273
+ disclaimer.
274
+
275
+ 7. Limitation of Liability
276
+ --------------------------
277
+
278
+ Under no circumstances and under no legal theory, whether tort (including
279
+ negligence), contract, or otherwise, shall any Contributor, or anyone
280
+ who distributes Covered Software as permitted above, be liable to You
281
+ for any direct, indirect, special, incidental, or consequential damages
282
+ of any character including, without limitation, damages for lost
283
+ profits, loss of goodwill, work stoppage, computer failure or
284
+ malfunction, or any and all other commercial damages or losses, even if
285
+ such party shall have been informed of the possibility of such damages.
286
+ This limitation of liability shall not apply to liability for death or
287
+ personal injury resulting from such party's negligence to the extent
288
+ applicable law prohibits such limitation. Some jurisdictions do not
289
+ allow the exclusion or limitation of incidental or consequential
290
+ damages, so this exclusion and limitation may not apply to You.
291
+
292
+ 8. Litigation
293
+ -------------
294
+
295
+ Any litigation relating to this License may be brought only in the
296
+ courts of a jurisdiction where the defendant maintains its principal
297
+ place of business and such litigation shall be governed by laws of that
298
+ jurisdiction, without reference to its conflict-of-law provisions.
299
+ Nothing in this Section shall prevent a party's ability to bring
300
+ cross-claims or counter-claims.
301
+
302
+ 9. Miscellaneous
303
+ ----------------
304
+
305
+ This License represents the complete agreement concerning the subject
306
+ matter hereof. If any provision of this License is held to be
307
+ unenforceable, such provision shall be reformed only to the extent
308
+ necessary to make it enforceable. Any law or regulation which provides
309
+ that the language of a contract shall be construed against the drafter
310
+ shall not be used to construe this License against a Contributor.
311
+
312
+ 10. Exhibit A - Mozilla Public License Notice
313
+ ---------------------------------------------
314
+
315
+ This Source Code Form is subject to the terms of the Mozilla Public
316
+ License, v. 2.0. If a copy of the MPL was not distributed with this
317
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
318
+
319
+ If it is inappropriate to include the notice in a particular source code
320
+ file due to its structure, then you may include the notice in a location
321
+ (such as a relevant directory of a notice file) where a recipient would be
322
+ likely to look for such a notice.
323
+
324
+ You may add additional accurate notices of copyright ownership.
package/README.md ADDED
@@ -0,0 +1,92 @@
1
+ # feed-slurp 🥤
2
+
3
+ A lightweight, universal RSS and Atom feed fetcher for the browser. Targeted for speed, reliability, and zero-dependency vibe (built on the `BaryoDev` stack).
4
+
5
+ ## Why feed-slurp?
6
+
7
+ - **Zero Heavy Dependencies**: Instead of 50KB+ XML libraries, it uses the browser's native `DOMParser`.
8
+ - **BaryoDev Powered**: Leverages `resilient-fetcher` for automatic retries and `nano-safe-storage` for robust caching.
9
+ - **Normalized Schema**: No more worrying about the differences between RSS item tags and Atom entry tags. One clean JSON schema for everything.
10
+ - **CORS Friendly**: Built-in support for popular proxies to bypass browser restrictions.
11
+ - **Smart Cache**: Stale-while-revalidate inspired behavior via `localStorage`.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install feed-slurp
17
+ ```
18
+
19
+ ## Basic Usage
20
+
21
+ ```typescript
22
+ import { slurp } from 'feed-slurp';
23
+
24
+ // Slurp a feed with default settings (auto-cache for 1 hour)
25
+ const feed = await slurp('https://medium.com/feed/@BaryoDev');
26
+
27
+ console.log(feed.title); // "BaryoDev - Medium"
28
+ console.log(feed.items[0].thumbnail); // Auto-extracted from content or tags!
29
+ ```
30
+
31
+ ## Advanced Configuration
32
+
33
+ ### CORS Proxies
34
+ Most RSS feeds require a proxy for browser-based fetching. `feed-slurp` makes this easy:
35
+
36
+ ```typescript
37
+ const feed = await slurp(url, {
38
+ proxy: 'allorigins' // Built-in: api.allorigins.win
39
+ // OR
40
+ proxy: 'corsproxy' // Built-in: corsproxy.io
41
+ // OR
42
+ proxy: 'https://my-proxy.com/?url='
43
+ // OR custom function
44
+ proxy: (url) => `https://custom.worker.dev/fetch?target=${encodeURIComponent(url)}`
45
+ });
46
+ ```
47
+
48
+ ### Caching Strategy
49
+ Caching is enabled by default to save bandwidth and improve performance.
50
+
51
+ ```typescript
52
+ const feed = await slurp(url, {
53
+ cache: true,
54
+ cacheTTL: 3600, // 1 hour in seconds
55
+ cacheKey: 'my-feed' // Custom key for localStorage
56
+ });
57
+
58
+ // Manual cache cleanup
59
+ import { clearSlurpCache } from 'feed-slurp';
60
+ clearSlurpCache('my-feed'); // Clear specific
61
+ clearSlurpCache(); // Clear all
62
+ ```
63
+
64
+ ## Output Schema
65
+
66
+ Regardless of whether the source is RSS 2.0 or Atom 1.0, you get this consistent structure:
67
+
68
+ ```typescript
69
+ interface SlurpFeed {
70
+ title: string;
71
+ description: string;
72
+ link: string;
73
+ lastBuildDate: string;
74
+ items: SlurpItem[];
75
+ }
76
+
77
+ interface SlurpItem {
78
+ title: string;
79
+ link: string;
80
+ pubDate: string; // ISO 8601 string
81
+ description: string; // Plain text / snippet
82
+ content: string; // Full HTML content
83
+ author: string;
84
+ categories: string[];
85
+ thumbnail: string | null; // Extracted thumbnail URL
86
+ guid: string;
87
+ }
88
+ ```
89
+
90
+ ## License
91
+
92
+ MPL-2.0 © Arnel I. Robles
@@ -0,0 +1,44 @@
1
+ interface SlurpItem {
2
+ title: string;
3
+ link: string;
4
+ pubDate: string;
5
+ description: string;
6
+ content: string;
7
+ author: string;
8
+ categories: string[];
9
+ thumbnail: string | null;
10
+ guid: string;
11
+ }
12
+ interface SlurpFeed {
13
+ title: string;
14
+ description: string;
15
+ link: string;
16
+ lastBuildDate: string;
17
+ items: SlurpItem[];
18
+ }
19
+ interface SlurpOptions {
20
+ cache?: boolean;
21
+ cacheTTL?: number;
22
+ cacheKey?: string;
23
+ proxy?: string | ((url: string) => string);
24
+ timeout?: number;
25
+ retries?: number;
26
+ }
27
+
28
+ declare function clearSlurpCache(key?: string): void;
29
+
30
+ /**
31
+ * Slurp an RSS or Atom feed.
32
+ * @param url The RSS/Atom feed URL
33
+ * @param options Configuration options
34
+ */
35
+ declare function slurp(url: string, options?: SlurpOptions): Promise<SlurpFeed>;
36
+ /**
37
+ * Fluent API for slurp
38
+ */
39
+ declare function createSlurper(defaultOptions?: SlurpOptions): {
40
+ slurp: (url: string, options?: SlurpOptions) => Promise<SlurpFeed>;
41
+ clearCache: (key?: string) => void;
42
+ };
43
+
44
+ export { type SlurpFeed, type SlurpItem, type SlurpOptions, clearSlurpCache, createSlurper, slurp };
@@ -0,0 +1,44 @@
1
+ interface SlurpItem {
2
+ title: string;
3
+ link: string;
4
+ pubDate: string;
5
+ description: string;
6
+ content: string;
7
+ author: string;
8
+ categories: string[];
9
+ thumbnail: string | null;
10
+ guid: string;
11
+ }
12
+ interface SlurpFeed {
13
+ title: string;
14
+ description: string;
15
+ link: string;
16
+ lastBuildDate: string;
17
+ items: SlurpItem[];
18
+ }
19
+ interface SlurpOptions {
20
+ cache?: boolean;
21
+ cacheTTL?: number;
22
+ cacheKey?: string;
23
+ proxy?: string | ((url: string) => string);
24
+ timeout?: number;
25
+ retries?: number;
26
+ }
27
+
28
+ declare function clearSlurpCache(key?: string): void;
29
+
30
+ /**
31
+ * Slurp an RSS or Atom feed.
32
+ * @param url The RSS/Atom feed URL
33
+ * @param options Configuration options
34
+ */
35
+ declare function slurp(url: string, options?: SlurpOptions): Promise<SlurpFeed>;
36
+ /**
37
+ * Fluent API for slurp
38
+ */
39
+ declare function createSlurper(defaultOptions?: SlurpOptions): {
40
+ slurp: (url: string, options?: SlurpOptions) => Promise<SlurpFeed>;
41
+ clearCache: (key?: string) => void;
42
+ };
43
+
44
+ export { type SlurpFeed, type SlurpItem, type SlurpOptions, clearSlurpCache, createSlurper, slurp };
package/dist/index.js ADDED
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ clearSlurpCache: () => clearSlurpCache,
24
+ createSlurper: () => createSlurper,
25
+ slurp: () => slurp
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/fetcher.ts
30
+ var import_resilient_fetcher = require("resilient-fetcher");
31
+ async function fetchFeedXml(url, options = {}) {
32
+ const { proxy, timeout = 1e4, retries = 3 } = options;
33
+ let requestUrl = url;
34
+ if (proxy) {
35
+ if (typeof proxy === "function") {
36
+ requestUrl = proxy(url);
37
+ } else {
38
+ switch (proxy) {
39
+ case "allorigins":
40
+ requestUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
41
+ break;
42
+ case "corsproxy":
43
+ requestUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
44
+ break;
45
+ default:
46
+ requestUrl = `${proxy}${encodeURIComponent(url)}`;
47
+ }
48
+ }
49
+ }
50
+ const response = await (0, import_resilient_fetcher.resilientFetch)(requestUrl, {
51
+ retries,
52
+ timeout
53
+ });
54
+ if (!response.ok) {
55
+ throw new Error(`Failed to fetch feed: ${response.status} ${response.statusText}`);
56
+ }
57
+ return response.text();
58
+ }
59
+
60
+ // src/parser/xml.ts
61
+ function parseXml(xmlString) {
62
+ const parser = new DOMParser();
63
+ const doc = parser.parseFromString(xmlString, "text/xml");
64
+ const parseError = doc.getElementsByTagName("parsererror");
65
+ if (parseError.length > 0) {
66
+ throw new Error(`XML parsing failed: ${parseError[0].textContent}`);
67
+ }
68
+ return doc;
69
+ }
70
+ function getText(node, selector) {
71
+ if (!node) return "";
72
+ const el = node.querySelector(selector);
73
+ return el?.textContent?.trim() || "";
74
+ }
75
+ function getCDataOrText(node, selectors) {
76
+ if (!node) return "";
77
+ for (const selector of selectors) {
78
+ const el = node.querySelector(selector.replace(":", "\\:"));
79
+ if (el) return el.textContent?.trim() || "";
80
+ }
81
+ return "";
82
+ }
83
+
84
+ // src/parser/rss.ts
85
+ function parseRss(doc) {
86
+ const channel = doc.querySelector("channel");
87
+ if (!channel) throw new Error("Invalid RSS feed: Missing <channel>");
88
+ const items = Array.from(doc.querySelectorAll("item")).map((item) => {
89
+ const description = getText(item, "description");
90
+ const content = getCDataOrText(item, ["content:encoded", "description"]);
91
+ return {
92
+ title: getText(item, "title"),
93
+ link: getText(item, "link"),
94
+ pubDate: new Date(getText(item, "pubDate")).toISOString(),
95
+ description,
96
+ content,
97
+ author: getText(item, "dc\\:creator") || "Unknown",
98
+ categories: Array.from(item.querySelectorAll("category")).map((c) => c.textContent || ""),
99
+ guid: getText(item, "guid") || getText(item, "link"),
100
+ thumbnail: extractThumbnail(item, content)
101
+ };
102
+ });
103
+ return {
104
+ title: getText(channel, "title"),
105
+ description: getText(channel, "description"),
106
+ link: getText(channel, "link"),
107
+ lastBuildDate: getText(channel, "lastBuildDate") || (/* @__PURE__ */ new Date()).toISOString(),
108
+ items
109
+ };
110
+ }
111
+ function extractThumbnail(item, content) {
112
+ const media = item.querySelector("media\\:content, media\\:thumbnail, enclosure[type^='image']");
113
+ if (media) {
114
+ return media.getAttribute("url") || media.getAttribute("src");
115
+ }
116
+ const match = content.match(/<img[^>]+src="([^">]+)"/);
117
+ return match ? match[1] : null;
118
+ }
119
+
120
+ // src/parser/atom.ts
121
+ function parseAtom(doc) {
122
+ const feed = doc.querySelector("feed");
123
+ if (!feed) throw new Error("Invalid Atom feed: Missing <feed>");
124
+ const items = Array.from(doc.querySelectorAll("entry")).map((entry) => {
125
+ const content = getText(entry, "content") || getText(entry, "summary");
126
+ return {
127
+ title: getText(entry, "title"),
128
+ link: entry.querySelector("link[rel='alternate']")?.getAttribute("href") || entry.querySelector("link")?.getAttribute("href") || "",
129
+ pubDate: new Date(getText(entry, "updated") || getText(entry, "published")).toISOString(),
130
+ description: getText(entry, "summary"),
131
+ content,
132
+ author: getText(entry, "author name") || "Unknown",
133
+ categories: Array.from(entry.querySelectorAll("category")).map((c) => c.getAttribute("term") || ""),
134
+ guid: getText(entry, "id"),
135
+ thumbnail: extractThumbnail2(entry, content)
136
+ };
137
+ });
138
+ return {
139
+ title: getText(feed, "title"),
140
+ description: getText(feed, "subtitle") || "",
141
+ link: feed.querySelector("link[rel='alternate']")?.getAttribute("href") || feed.querySelector("link")?.getAttribute("href") || "",
142
+ lastBuildDate: getText(feed, "updated"),
143
+ items
144
+ };
145
+ }
146
+ function extractThumbnail2(entry, content) {
147
+ const enclosure = entry.querySelector("link[rel='enclosure'][type^='image']");
148
+ if (enclosure) return enclosure.getAttribute("href");
149
+ const match = content.match(/<img[^>]+src="([^">]+)"/);
150
+ return match ? match[1] : null;
151
+ }
152
+
153
+ // src/cache.ts
154
+ var import_nano_safe_storage = require("nano-safe-storage");
155
+ var storage = (0, import_nano_safe_storage.createStorage)({
156
+ prefix: "slurp_",
157
+ ttl: 3600
158
+ // Default 1 hour
159
+ });
160
+ function getCachedFeed(key) {
161
+ return storage.get(key);
162
+ }
163
+ function setCachedFeed(key, feed, ttl) {
164
+ storage.set(key, feed, ttl ? { ttl } : void 0);
165
+ }
166
+ function clearSlurpCache(key) {
167
+ if (key) {
168
+ storage.remove(key);
169
+ } else {
170
+ storage.clear();
171
+ }
172
+ }
173
+
174
+ // src/index.ts
175
+ async function slurp(url, options = {}) {
176
+ const { cache = true, cacheTTL, cacheKey = url } = options;
177
+ if (cache) {
178
+ const cached = getCachedFeed(cacheKey);
179
+ if (cached) return cached;
180
+ }
181
+ const xml = await fetchFeedXml(url, options);
182
+ const doc = parseXml(xml);
183
+ const isAtom = doc.querySelector("feed") !== null;
184
+ const feed = isAtom ? parseAtom(doc) : parseRss(doc);
185
+ if (cache) {
186
+ setCachedFeed(cacheKey, feed, cacheTTL);
187
+ }
188
+ return feed;
189
+ }
190
+ function createSlurper(defaultOptions = {}) {
191
+ return {
192
+ slurp: (url, options = {}) => slurp(url, { ...defaultOptions, ...options }),
193
+ clearCache: (key) => clearSlurpCache(key)
194
+ };
195
+ }
196
+ // Annotate the CommonJS export names for ESM import in node:
197
+ 0 && (module.exports = {
198
+ clearSlurpCache,
199
+ createSlurper,
200
+ slurp
201
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,172 @@
1
+ // src/fetcher.ts
2
+ import { resilientFetch } from "resilient-fetcher";
3
+ async function fetchFeedXml(url, options = {}) {
4
+ const { proxy, timeout = 1e4, retries = 3 } = options;
5
+ let requestUrl = url;
6
+ if (proxy) {
7
+ if (typeof proxy === "function") {
8
+ requestUrl = proxy(url);
9
+ } else {
10
+ switch (proxy) {
11
+ case "allorigins":
12
+ requestUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
13
+ break;
14
+ case "corsproxy":
15
+ requestUrl = `https://corsproxy.io/?${encodeURIComponent(url)}`;
16
+ break;
17
+ default:
18
+ requestUrl = `${proxy}${encodeURIComponent(url)}`;
19
+ }
20
+ }
21
+ }
22
+ const response = await resilientFetch(requestUrl, {
23
+ retries,
24
+ timeout
25
+ });
26
+ if (!response.ok) {
27
+ throw new Error(`Failed to fetch feed: ${response.status} ${response.statusText}`);
28
+ }
29
+ return response.text();
30
+ }
31
+
32
+ // src/parser/xml.ts
33
+ function parseXml(xmlString) {
34
+ const parser = new DOMParser();
35
+ const doc = parser.parseFromString(xmlString, "text/xml");
36
+ const parseError = doc.getElementsByTagName("parsererror");
37
+ if (parseError.length > 0) {
38
+ throw new Error(`XML parsing failed: ${parseError[0].textContent}`);
39
+ }
40
+ return doc;
41
+ }
42
+ function getText(node, selector) {
43
+ if (!node) return "";
44
+ const el = node.querySelector(selector);
45
+ return el?.textContent?.trim() || "";
46
+ }
47
+ function getCDataOrText(node, selectors) {
48
+ if (!node) return "";
49
+ for (const selector of selectors) {
50
+ const el = node.querySelector(selector.replace(":", "\\:"));
51
+ if (el) return el.textContent?.trim() || "";
52
+ }
53
+ return "";
54
+ }
55
+
56
+ // src/parser/rss.ts
57
+ function parseRss(doc) {
58
+ const channel = doc.querySelector("channel");
59
+ if (!channel) throw new Error("Invalid RSS feed: Missing <channel>");
60
+ const items = Array.from(doc.querySelectorAll("item")).map((item) => {
61
+ const description = getText(item, "description");
62
+ const content = getCDataOrText(item, ["content:encoded", "description"]);
63
+ return {
64
+ title: getText(item, "title"),
65
+ link: getText(item, "link"),
66
+ pubDate: new Date(getText(item, "pubDate")).toISOString(),
67
+ description,
68
+ content,
69
+ author: getText(item, "dc\\:creator") || "Unknown",
70
+ categories: Array.from(item.querySelectorAll("category")).map((c) => c.textContent || ""),
71
+ guid: getText(item, "guid") || getText(item, "link"),
72
+ thumbnail: extractThumbnail(item, content)
73
+ };
74
+ });
75
+ return {
76
+ title: getText(channel, "title"),
77
+ description: getText(channel, "description"),
78
+ link: getText(channel, "link"),
79
+ lastBuildDate: getText(channel, "lastBuildDate") || (/* @__PURE__ */ new Date()).toISOString(),
80
+ items
81
+ };
82
+ }
83
+ function extractThumbnail(item, content) {
84
+ const media = item.querySelector("media\\:content, media\\:thumbnail, enclosure[type^='image']");
85
+ if (media) {
86
+ return media.getAttribute("url") || media.getAttribute("src");
87
+ }
88
+ const match = content.match(/<img[^>]+src="([^">]+)"/);
89
+ return match ? match[1] : null;
90
+ }
91
+
92
+ // src/parser/atom.ts
93
+ function parseAtom(doc) {
94
+ const feed = doc.querySelector("feed");
95
+ if (!feed) throw new Error("Invalid Atom feed: Missing <feed>");
96
+ const items = Array.from(doc.querySelectorAll("entry")).map((entry) => {
97
+ const content = getText(entry, "content") || getText(entry, "summary");
98
+ return {
99
+ title: getText(entry, "title"),
100
+ link: entry.querySelector("link[rel='alternate']")?.getAttribute("href") || entry.querySelector("link")?.getAttribute("href") || "",
101
+ pubDate: new Date(getText(entry, "updated") || getText(entry, "published")).toISOString(),
102
+ description: getText(entry, "summary"),
103
+ content,
104
+ author: getText(entry, "author name") || "Unknown",
105
+ categories: Array.from(entry.querySelectorAll("category")).map((c) => c.getAttribute("term") || ""),
106
+ guid: getText(entry, "id"),
107
+ thumbnail: extractThumbnail2(entry, content)
108
+ };
109
+ });
110
+ return {
111
+ title: getText(feed, "title"),
112
+ description: getText(feed, "subtitle") || "",
113
+ link: feed.querySelector("link[rel='alternate']")?.getAttribute("href") || feed.querySelector("link")?.getAttribute("href") || "",
114
+ lastBuildDate: getText(feed, "updated"),
115
+ items
116
+ };
117
+ }
118
+ function extractThumbnail2(entry, content) {
119
+ const enclosure = entry.querySelector("link[rel='enclosure'][type^='image']");
120
+ if (enclosure) return enclosure.getAttribute("href");
121
+ const match = content.match(/<img[^>]+src="([^">]+)"/);
122
+ return match ? match[1] : null;
123
+ }
124
+
125
+ // src/cache.ts
126
+ import { createStorage } from "nano-safe-storage";
127
+ var storage = createStorage({
128
+ prefix: "slurp_",
129
+ ttl: 3600
130
+ // Default 1 hour
131
+ });
132
+ function getCachedFeed(key) {
133
+ return storage.get(key);
134
+ }
135
+ function setCachedFeed(key, feed, ttl) {
136
+ storage.set(key, feed, ttl ? { ttl } : void 0);
137
+ }
138
+ function clearSlurpCache(key) {
139
+ if (key) {
140
+ storage.remove(key);
141
+ } else {
142
+ storage.clear();
143
+ }
144
+ }
145
+
146
+ // src/index.ts
147
+ async function slurp(url, options = {}) {
148
+ const { cache = true, cacheTTL, cacheKey = url } = options;
149
+ if (cache) {
150
+ const cached = getCachedFeed(cacheKey);
151
+ if (cached) return cached;
152
+ }
153
+ const xml = await fetchFeedXml(url, options);
154
+ const doc = parseXml(xml);
155
+ const isAtom = doc.querySelector("feed") !== null;
156
+ const feed = isAtom ? parseAtom(doc) : parseRss(doc);
157
+ if (cache) {
158
+ setCachedFeed(cacheKey, feed, cacheTTL);
159
+ }
160
+ return feed;
161
+ }
162
+ function createSlurper(defaultOptions = {}) {
163
+ return {
164
+ slurp: (url, options = {}) => slurp(url, { ...defaultOptions, ...options }),
165
+ clearCache: (key) => clearSlurpCache(key)
166
+ };
167
+ }
168
+ export {
169
+ clearSlurpCache,
170
+ createSlurper,
171
+ slurp
172
+ };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "feed-slurp",
3
+ "version": "1.0.0",
4
+ "description": "A lightweight, zero-dependency (well, almost!) RSS/Atom feed fetcher and parser with built-in caching and proxy support.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
13
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
14
+ "test": "vitest run",
15
+ "lint": "eslint src/**/*.ts"
16
+ },
17
+ "keywords": [
18
+ "rss",
19
+ "atom",
20
+ "feed",
21
+ "parser",
22
+ "fetcher",
23
+ "proxy",
24
+ "cache",
25
+ "slurp"
26
+ ],
27
+ "author": "Arnel I. Robles",
28
+ "license": "MPL-2.0",
29
+ "dependencies": {
30
+ "nano-safe-storage": "^1.0.0",
31
+ "resilient-fetcher": "^1.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "tsup": "^8.0.0",
35
+ "typescript": "^5.0.0",
36
+ "vitest": "^1.0.0",
37
+ "jsdom": "^22.0.0",
38
+ "@types/node": "^20.0.0"
39
+ }
40
+ }