@molecule/api-feed-rss 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,115 @@
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
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-feed-rss` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-feed-rss is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,66 @@
1
+ /**
2
+ * XML / CDATA / URL escape helpers used by every serializer.
3
+ *
4
+ * **All user-supplied content MUST flow through one of these helpers**
5
+ * before it lands in serialized output. The serializers in this package
6
+ * call them defensively at every interpolation site, but consumers
7
+ * extending this package (e.g. adding a custom namespace) MUST do the same.
8
+ *
9
+ * @module
10
+ */
11
+ /**
12
+ * Escape a string for inclusion in an XML text node or attribute value.
13
+ *
14
+ * Maps the five XML predefined entities:
15
+ * - `&` → `&`
16
+ * - `<` → `&lt;`
17
+ * - `>` → `&gt;`
18
+ * - `"` → `&quot;`
19
+ * - `'` → `&apos;`
20
+ *
21
+ * Also strips XML 1.0 illegal control characters (`U+0000`–`U+0008`,
22
+ * `U+000B`, `U+000C`, `U+000E`–`U+001F`). `\t`, `\n`, `\r` are preserved.
23
+ *
24
+ * @param value - Raw string. `undefined` / `null` collapse to `''`.
25
+ * @returns Escaped string safe for any XML position.
26
+ */
27
+ export declare function escapeXml(value: string | number | boolean | null | undefined): string;
28
+ /**
29
+ * Wrap an HTML payload in a `<![CDATA[ ... ]]>` section, splitting any
30
+ * accidental closing-marker (`]]>`) inside the payload across two CDATA
31
+ * sections so the result remains valid XML.
32
+ *
33
+ * Use for `<description>` / `<content:encoded>` / Atom `<content type="html">`
34
+ * where the body is HTML and we want to avoid double-escaping.
35
+ *
36
+ * Also strips XML 1.0 illegal control characters before wrapping (`\t`,
37
+ * `\n`, `\r` preserved). The CDATA payload still cannot contain raw
38
+ * `<![CDATA[` openers, but those are not produced by typical HTML and
39
+ * any literal occurrence is treated as ordinary text by browsers.
40
+ *
41
+ * @param value - Raw HTML / text. `undefined` / `null` collapse to `''`.
42
+ * @returns A complete CDATA section, e.g. `<![CDATA[<p>x</p>]]>`.
43
+ */
44
+ export declare function wrapCdata(value: string | null | undefined): string;
45
+ /**
46
+ * Escape an attribute value (alias of {@link escapeXml} kept distinct so
47
+ * future tightening — e.g. enforcing quote style — has a single call site).
48
+ *
49
+ * @param value - Raw attribute value.
50
+ * @returns Escaped string suitable for `="..."` attribute syntax.
51
+ */
52
+ export declare function escapeAttr(value: string | number | boolean | null | undefined): string;
53
+ /**
54
+ * Validate + escape a URL for safe use as an `href` / `src` / RSS `<link>`
55
+ * value. Strips `javascript:` and other dangerous schemes — those are
56
+ * replaced with `about:blank`.
57
+ *
58
+ * Allowed schemes (case-insensitive): `http`, `https`, `mailto`, `ftp`,
59
+ * `tel`, plus protocol-relative (`//...`) and absolute paths (`/...`) and
60
+ * relative paths (`./...`, `../...`, `name`, `name?...`, `name#...`).
61
+ *
62
+ * @param value - Raw URL. `undefined` / `null` collapse to `''`.
63
+ * @returns Escaped URL or `'about:blank'` for disallowed schemes.
64
+ */
65
+ export declare function escapeUrl(value: string | null | undefined): string;
66
+ //# sourceMappingURL=escape.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../src/escape.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAiBrF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAclE;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAEtF;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAYlE"}
package/dist/escape.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * XML / CDATA / URL escape helpers used by every serializer.
3
+ *
4
+ * **All user-supplied content MUST flow through one of these helpers**
5
+ * before it lands in serialized output. The serializers in this package
6
+ * call them defensively at every interpolation site, but consumers
7
+ * extending this package (e.g. adding a custom namespace) MUST do the same.
8
+ *
9
+ * @module
10
+ */
11
+ /**
12
+ * Escape a string for inclusion in an XML text node or attribute value.
13
+ *
14
+ * Maps the five XML predefined entities:
15
+ * - `&` → `&amp;`
16
+ * - `<` → `&lt;`
17
+ * - `>` → `&gt;`
18
+ * - `"` → `&quot;`
19
+ * - `'` → `&apos;`
20
+ *
21
+ * Also strips XML 1.0 illegal control characters (`U+0000`–`U+0008`,
22
+ * `U+000B`, `U+000C`, `U+000E`–`U+001F`). `\t`, `\n`, `\r` are preserved.
23
+ *
24
+ * @param value - Raw string. `undefined` / `null` collapse to `''`.
25
+ * @returns Escaped string safe for any XML position.
26
+ */
27
+ export function escapeXml(value) {
28
+ if (value === undefined || value === null)
29
+ return '';
30
+ const s = typeof value === 'string' ? value : String(value);
31
+ let out = '';
32
+ for (let i = 0; i < s.length; i++) {
33
+ const ch = s.charCodeAt(i);
34
+ // Strip XML 1.0 illegal control chars (allow \t=9, \n=10, \r=13).
35
+ if (ch < 0x20 && ch !== 0x09 && ch !== 0x0a && ch !== 0x0d)
36
+ continue;
37
+ const c = s[i];
38
+ if (c === '&')
39
+ out += '&amp;';
40
+ else if (c === '<')
41
+ out += '&lt;';
42
+ else if (c === '>')
43
+ out += '&gt;';
44
+ else if (c === '"')
45
+ out += '&quot;';
46
+ else if (c === "'")
47
+ out += '&apos;';
48
+ else
49
+ out += c;
50
+ }
51
+ return out;
52
+ }
53
+ /**
54
+ * Wrap an HTML payload in a `<![CDATA[ ... ]]>` section, splitting any
55
+ * accidental closing-marker (`]]>`) inside the payload across two CDATA
56
+ * sections so the result remains valid XML.
57
+ *
58
+ * Use for `<description>` / `<content:encoded>` / Atom `<content type="html">`
59
+ * where the body is HTML and we want to avoid double-escaping.
60
+ *
61
+ * Also strips XML 1.0 illegal control characters before wrapping (`\t`,
62
+ * `\n`, `\r` preserved). The CDATA payload still cannot contain raw
63
+ * `<![CDATA[` openers, but those are not produced by typical HTML and
64
+ * any literal occurrence is treated as ordinary text by browsers.
65
+ *
66
+ * @param value - Raw HTML / text. `undefined` / `null` collapse to `''`.
67
+ * @returns A complete CDATA section, e.g. `<![CDATA[<p>x</p>]]>`.
68
+ */
69
+ export function wrapCdata(value) {
70
+ if (value === undefined || value === null || value === '') {
71
+ return '<![CDATA[]]>';
72
+ }
73
+ // Strip illegal XML 1.0 control chars first.
74
+ let cleaned = '';
75
+ for (let i = 0; i < value.length; i++) {
76
+ const ch = value.charCodeAt(i);
77
+ if (ch < 0x20 && ch !== 0x09 && ch !== 0x0a && ch !== 0x0d)
78
+ continue;
79
+ cleaned += value[i];
80
+ }
81
+ // Split any embedded `]]>` so it can't terminate the CDATA early.
82
+ const safe = cleaned.split(']]>').join(']]]]><![CDATA[>');
83
+ return `<![CDATA[${safe}]]>`;
84
+ }
85
+ /**
86
+ * Escape an attribute value (alias of {@link escapeXml} kept distinct so
87
+ * future tightening — e.g. enforcing quote style — has a single call site).
88
+ *
89
+ * @param value - Raw attribute value.
90
+ * @returns Escaped string suitable for `="..."` attribute syntax.
91
+ */
92
+ export function escapeAttr(value) {
93
+ return escapeXml(value);
94
+ }
95
+ /**
96
+ * Validate + escape a URL for safe use as an `href` / `src` / RSS `<link>`
97
+ * value. Strips `javascript:` and other dangerous schemes — those are
98
+ * replaced with `about:blank`.
99
+ *
100
+ * Allowed schemes (case-insensitive): `http`, `https`, `mailto`, `ftp`,
101
+ * `tel`, plus protocol-relative (`//...`) and absolute paths (`/...`) and
102
+ * relative paths (`./...`, `../...`, `name`, `name?...`, `name#...`).
103
+ *
104
+ * @param value - Raw URL. `undefined` / `null` collapse to `''`.
105
+ * @returns Escaped URL or `'about:blank'` for disallowed schemes.
106
+ */
107
+ export function escapeUrl(value) {
108
+ if (value === undefined || value === null)
109
+ return '';
110
+ const s = String(value).trim();
111
+ if (s === '')
112
+ return '';
113
+ // Match `<scheme>:` (must start with a letter, then [a-z0-9+.-]).
114
+ const schemeMatch = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(s);
115
+ if (schemeMatch) {
116
+ const scheme = schemeMatch[1].toLowerCase();
117
+ const allowed = new Set(['http', 'https', 'mailto', 'ftp', 'tel']);
118
+ if (!allowed.has(scheme))
119
+ return 'about:blank';
120
+ }
121
+ return escapeXml(s);
122
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Framework-agnostic HTTP handler factory for serving feed output at
3
+ * `GET /<mountPath>.{rss|atom|json}` (or any path scheme the caller wires
4
+ * via the `extensions` map).
5
+ *
6
+ * Returns a request handler whose signature is intentionally minimal so
7
+ * the same builder works with Express (`(req, res, next)` adapter), Hono,
8
+ * Fastify, raw Node `http`, or a worker `fetch` handler.
9
+ *
10
+ * @module
11
+ */
12
+ import type { Feed, FeedOutputFormat } from './types.js';
13
+ /**
14
+ * Configuration for {@link createFeedHandler}.
15
+ */
16
+ export interface CreateFeedHandlerOptions {
17
+ /**
18
+ * Async loader returning the feed snapshot. Called whenever the cache is
19
+ * cold or expired. Must throw on data-source failure — the handler then
20
+ * returns `503 Service Unavailable`.
21
+ */
22
+ loadFeed: () => Promise<Feed> | Feed;
23
+ /**
24
+ * Cache TTL in milliseconds. Defaults to `60_000` (1 minute). Set to
25
+ * `0` to disable caching (every request re-loads).
26
+ */
27
+ cacheTtlMs?: number;
28
+ /**
29
+ * Map of URL-suffix → {@link FeedOutputFormat}.
30
+ *
31
+ * Defaults to `{ rss: 'rss-2.0', atom: 'atom-1.0', json: 'json-feed' }`.
32
+ *
33
+ * The handler reads the request path's extension via {@link FeedRequest.extension}
34
+ * (callers compute this from the URL — see the function-level docs).
35
+ */
36
+ extensions?: Record<string, FeedOutputFormat>;
37
+ /**
38
+ * Optional logger called on errors. Defaults to a no-op.
39
+ */
40
+ onError?: (err: unknown) => void;
41
+ }
42
+ /**
43
+ * Minimal request shape consumed by the generated handler.
44
+ */
45
+ export interface FeedRequest {
46
+ /**
47
+ * URL extension portion — `'rss'`, `'atom'`, `'json'`, or any custom key
48
+ * the caller wired in {@link CreateFeedHandlerOptions.extensions}.
49
+ *
50
+ * Callers compute this from the request URL (e.g.
51
+ * `req.path.split('.').pop()` for Express).
52
+ */
53
+ extension: string;
54
+ /** Optional `If-None-Match` ETag value, for 304 short-circuiting. */
55
+ ifNoneMatch?: string;
56
+ }
57
+ /**
58
+ * Minimal response shape returned by the handler. Framework adapters map
59
+ * this onto their native response API (`res.status().set().send()` for
60
+ * Express, `new Response(body, { status, headers })` for fetch, etc.).
61
+ */
62
+ export interface FeedResponse {
63
+ /** HTTP status code: `200` / `304` / `404` / `503`. */
64
+ status: number;
65
+ /** Headers — always includes `Content-Type` on `200`. */
66
+ headers: Record<string, string>;
67
+ /** Body — empty string on `304` / `404` / errors. */
68
+ body: string;
69
+ }
70
+ /**
71
+ * Create a framework-agnostic feed HTTP handler with built-in TTL caching.
72
+ *
73
+ * The returned handler accepts a {@link FeedRequest} and returns a
74
+ * {@link FeedResponse}. It serves three formats by default — RSS 2.0,
75
+ * Atom 1.0, JSON Feed — keyed by URL extension.
76
+ *
77
+ * **Caching** — feed payloads are cached per-format for `cacheTtlMs`
78
+ * (default 1 minute). Each cache entry carries an ETag computed from the
79
+ * payload hash; matching `If-None-Match` triggers a `304` response.
80
+ *
81
+ * **Error handling** — if `loadFeed` throws, the handler returns `503`
82
+ * with body `''`. The error is forwarded to `onError` if provided.
83
+ *
84
+ * **No XSS surface** — all interpolation runs through the underlying
85
+ * serializers (`serializeRss2` / `serializeAtom1` / `serializeJsonFeed`),
86
+ * which escape every user-supplied field. The handler itself never
87
+ * concatenates request data into the response body.
88
+ *
89
+ * @example Express adapter
90
+ * ```ts
91
+ * import express from 'express'
92
+ * import { createFeedHandler } from '@molecule/api-feed-rss'
93
+ *
94
+ * const handle = createFeedHandler({
95
+ * loadFeed: async () => ({
96
+ * title: 'Blog',
97
+ * link: 'https://example.com',
98
+ * description: '...',
99
+ * items: await db.posts.findMany(...),
100
+ * }),
101
+ * })
102
+ *
103
+ * const app = express()
104
+ * app.get('/feed.:ext', async (req, res) => {
105
+ * const result = await handle({
106
+ * extension: req.params.ext,
107
+ * ifNoneMatch: req.get('If-None-Match'),
108
+ * })
109
+ * res.status(result.status).set(result.headers).send(result.body)
110
+ * })
111
+ * ```
112
+ *
113
+ * @param options - See {@link CreateFeedHandlerOptions}.
114
+ * @returns Async handler function `(req: FeedRequest) => Promise<FeedResponse>`.
115
+ */
116
+ export declare function createFeedHandler(options: CreateFeedHandlerOptions): (req: FeedRequest) => Promise<FeedResponse>;
117
+ //# sourceMappingURL=handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAcxD;;GAEG;AACH,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IAEpC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IAEnB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAA;IAE7C;;OAEG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAA;CACjC;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;;;;;OAMG;IACH,SAAS,EAAE,MAAM,CAAA;IAEjB,qEAAqE;IACrE,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC3B,uDAAuD;IACvD,MAAM,EAAE,MAAM,CAAA;IAEd,yDAAyD;IACzD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAE/B,qDAAqD;IACrD,IAAI,EAAE,MAAM,CAAA;CACb;AAuBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,wBAAwB,GAChC,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC,YAAY,CAAC,CAmD7C"}
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Framework-agnostic HTTP handler factory for serving feed output at
3
+ * `GET /<mountPath>.{rss|atom|json}` (or any path scheme the caller wires
4
+ * via the `extensions` map).
5
+ *
6
+ * Returns a request handler whose signature is intentionally minimal so
7
+ * the same builder works with Express (`(req, res, next)` adapter), Hono,
8
+ * Fastify, raw Node `http`, or a worker `fetch` handler.
9
+ *
10
+ * @module
11
+ */
12
+ import { FEED_CONTENT_TYPES, serializeFeed } from './serializeFeed.js';
13
+ const DEFAULT_EXTENSIONS = {
14
+ rss: 'rss-2.0',
15
+ atom: 'atom-1.0',
16
+ json: 'json-feed',
17
+ };
18
+ /**
19
+ * djb2-style hash, base36-encoded — used for ETag generation. Not
20
+ * cryptographic; collisions are tolerable for HTTP caching.
21
+ *
22
+ * @param s - Input string.
23
+ * @returns Compact base36 hash.
24
+ */
25
+ function hash(s) {
26
+ let h = 5381;
27
+ for (let i = 0; i < s.length; i++) {
28
+ h = (h * 33) ^ s.charCodeAt(i);
29
+ }
30
+ return (h >>> 0).toString(36);
31
+ }
32
+ /**
33
+ * Create a framework-agnostic feed HTTP handler with built-in TTL caching.
34
+ *
35
+ * The returned handler accepts a {@link FeedRequest} and returns a
36
+ * {@link FeedResponse}. It serves three formats by default — RSS 2.0,
37
+ * Atom 1.0, JSON Feed — keyed by URL extension.
38
+ *
39
+ * **Caching** — feed payloads are cached per-format for `cacheTtlMs`
40
+ * (default 1 minute). Each cache entry carries an ETag computed from the
41
+ * payload hash; matching `If-None-Match` triggers a `304` response.
42
+ *
43
+ * **Error handling** — if `loadFeed` throws, the handler returns `503`
44
+ * with body `''`. The error is forwarded to `onError` if provided.
45
+ *
46
+ * **No XSS surface** — all interpolation runs through the underlying
47
+ * serializers (`serializeRss2` / `serializeAtom1` / `serializeJsonFeed`),
48
+ * which escape every user-supplied field. The handler itself never
49
+ * concatenates request data into the response body.
50
+ *
51
+ * @example Express adapter
52
+ * ```ts
53
+ * import express from 'express'
54
+ * import { createFeedHandler } from '@molecule/api-feed-rss'
55
+ *
56
+ * const handle = createFeedHandler({
57
+ * loadFeed: async () => ({
58
+ * title: 'Blog',
59
+ * link: 'https://example.com',
60
+ * description: '...',
61
+ * items: await db.posts.findMany(...),
62
+ * }),
63
+ * })
64
+ *
65
+ * const app = express()
66
+ * app.get('/feed.:ext', async (req, res) => {
67
+ * const result = await handle({
68
+ * extension: req.params.ext,
69
+ * ifNoneMatch: req.get('If-None-Match'),
70
+ * })
71
+ * res.status(result.status).set(result.headers).send(result.body)
72
+ * })
73
+ * ```
74
+ *
75
+ * @param options - See {@link CreateFeedHandlerOptions}.
76
+ * @returns Async handler function `(req: FeedRequest) => Promise<FeedResponse>`.
77
+ */
78
+ export function createFeedHandler(options) {
79
+ const ttl = options.cacheTtlMs ?? 60_000;
80
+ const extMap = { ...DEFAULT_EXTENSIONS, ...(options.extensions ?? {}) };
81
+ const onError = options.onError ?? (() => { });
82
+ const cache = new Map();
83
+ return async function handle(req) {
84
+ const ext = (req.extension ?? '').toLowerCase();
85
+ const format = extMap[ext];
86
+ if (!format) {
87
+ return { status: 404, headers: {}, body: '' };
88
+ }
89
+ const now = Date.now();
90
+ let entry = cache.get(format);
91
+ if (!entry || (ttl > 0 && now - entry.generatedAt > ttl) || ttl === 0) {
92
+ try {
93
+ const feed = await options.loadFeed();
94
+ const body = serializeFeed(feed, format);
95
+ entry = {
96
+ body,
97
+ contentType: FEED_CONTENT_TYPES[format],
98
+ generatedAt: now,
99
+ etag: `"${hash(body)}"`,
100
+ };
101
+ if (ttl > 0)
102
+ cache.set(format, entry);
103
+ else
104
+ cache.delete(format);
105
+ }
106
+ catch (err) {
107
+ onError(err);
108
+ return { status: 503, headers: {}, body: '' };
109
+ }
110
+ }
111
+ if (req.ifNoneMatch && req.ifNoneMatch === entry.etag) {
112
+ return {
113
+ status: 304,
114
+ headers: { ETag: entry.etag },
115
+ body: '',
116
+ };
117
+ }
118
+ return {
119
+ status: 200,
120
+ headers: {
121
+ 'Content-Type': entry.contentType,
122
+ ETag: entry.etag,
123
+ 'Cache-Control': ttl > 0 ? `public, max-age=${Math.floor(ttl / 1000)}` : 'no-store',
124
+ },
125
+ body: entry.body,
126
+ };
127
+ };
128
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * RSS / Atom / JSON Feed **producer** for molecule.dev — pure-function
3
+ * serializers that turn a single normalized {@link Feed} structure into
4
+ * a valid RSS 2.0, Atom 1.0, or JSON Feed 1.1 document.
5
+ *
6
+ * Companion to `@molecule/api-feed-rss-parser` (the consumer side). Both
7
+ * packages share a similar normalized shape, so apps can ingest external
8
+ * feeds, store the items, and re-publish them through this package
9
+ * without intermediate translation layers.
10
+ *
11
+ * Apps that use this:
12
+ * - `blog` — emit `/feed.rss`, `/feed.atom`, `/feed.json` for posts.
13
+ * - `news-aggregator` — re-publish curated cross-source feeds.
14
+ * - `podcast` — RSS 2.0 with the iTunes namespace (set `feed.itunes`).
15
+ *
16
+ * @example One serializer per call
17
+ * ```ts
18
+ * import { serializeRss2, serializeAtom1, serializeJsonFeed } from '@molecule/api-feed-rss'
19
+ *
20
+ * const feed = {
21
+ * title: 'My Blog',
22
+ * link: 'https://example.com',
23
+ * description: 'Posts about software',
24
+ * items: [{ id: '1', title: 'Hello', link: 'https://example.com/p/1' }],
25
+ * }
26
+ *
27
+ * const rss = serializeRss2(feed)
28
+ * const atom = serializeAtom1(feed)
29
+ * const json = serializeJsonFeed(feed)
30
+ * ```
31
+ *
32
+ * @example HTTP handler with caching — Express adapter
33
+ * ```ts
34
+ * import { createFeedHandler, type Feed } from '@molecule/api-feed-rss'
35
+ *
36
+ * const loadFromDb = async (): Promise<Feed> => ({ title: 'My Feed', link: 'https://example.com', description: 'Latest posts', items: [] }) // your DB lookup
37
+ * const app = { get(_path: string, _fn: (req: any, res: any) => void): void {} } // your Express app
38
+ *
39
+ * const handle = createFeedHandler({
40
+ * loadFeed: async () => loadFromDb(),
41
+ * cacheTtlMs: 60_000,
42
+ * })
43
+ *
44
+ * // Serves GET /feed.rss, /feed.atom, /feed.json (keyed by extension).
45
+ * // The handler returns { status, headers, body } — map those onto any
46
+ * // framework's response (Fastify/Hono/raw http look the same).
47
+ * app.get('/feed.:ext', async (req, res) => {
48
+ * const result = await handle({
49
+ * extension: req.params.ext,
50
+ * ifNoneMatch: req.get('If-None-Match'),
51
+ * })
52
+ * res.status(result.status).set(result.headers).send(result.body)
53
+ * })
54
+ * ```
55
+ *
56
+ * **Security**: every user-supplied field is escaped before serialization.
57
+ * RSS / Atom XML use {@link escapeXml} for text nodes, {@link escapeAttr}
58
+ * for attributes, {@link escapeUrl} for URL attributes (which neutralizes
59
+ * `javascript:` URIs), and {@link wrapCdata} for HTML content (with
60
+ * `]]>` splitting). JSON Feed relies on `JSON.stringify` for escaping.
61
+ *
62
+ * @module
63
+ */
64
+ export * from './browser-guard.js';
65
+ export * from './escape.js';
66
+ export * from './handler.js';
67
+ export * from './serializeAtom1.js';
68
+ export * from './serializeFeed.js';
69
+ export * from './serializeJsonFeed.js';
70
+ export * from './serializeRss2.js';
71
+ export * from './types.js';
72
+ export * from './utilities.js';
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8DG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,qBAAqB,CAAA;AACnC,cAAc,oBAAoB,CAAA;AAClC,cAAc,wBAAwB,CAAA;AACtC,cAAc,oBAAoB,CAAA;AAClC,cAAc,YAAY,CAAA;AAC1B,cAAc,gBAAgB,CAAA"}