everyrss 0.0.0-stage → 0.1.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FeedBrew contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,139 @@
1
- # Temporary Holding Version
1
+ # everyrss
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Feeds for YouTube channels and Spotify shows. <https://everyrss.com>
4
+
5
+ ```
6
+ https://everyrss.com/youtube/@3blue1brown
7
+ https://everyrss.com/spotify/2IqXAVFR4e0Bmyjsdc8QzF
8
+ ```
9
+
10
+ Free, with no accounts. Paste the address into any feed reader, podcast app or read-later app.
11
+
12
+ ## Feeds
13
+
14
+ | Address | What it is |
15
+ | ---------------------------------- | -------------------------------------------------------------------------------------------------------- |
16
+ | `/youtube/{@handle or channel ID}` | A channel's long-form videos, without Shorts or livestreams |
17
+ | `/spotify/{show ID}` | A show's latest episodes, linking to Spotify |
18
+ | `/{link}` or `/?url={link}` | Redirects any YouTube or Spotify link to its feed: videos, `youtu.be`, episodes, `/c/` and `/user/` URLs |
19
+
20
+ Putting `everyrss.com/` in front of a link works too: `everyrss.com/https://www.youtube.com/@3blue1brown`.
21
+
22
+ Add a file name for another format:
23
+
24
+ | File | Format |
25
+ | ------------------- | -------------------------------------------------------------------------------------------------- |
26
+ | `rss.xml` (default) | RSS 2.0 |
27
+ | `feed.json` | [JSON Feed 1.1](https://jsonfeed.org), with each item's kind and duration under `_everyrss` |
28
+ | `matter.xml` | RSS for [Matter](https://getmatter.com), which only picks up new items when the build date changes |
29
+
30
+ ```
31
+ https://everyrss.com/youtube/@3blue1brown/feed.json
32
+ https://everyrss.com/youtube/@3blue1brown/matter.xml
33
+ ```
34
+
35
+ Feeds list the latest 50 items, newest first, and link to the original video or episode. everyrss
36
+ doesn't host any media.
37
+
38
+ ## Limits
39
+
40
+ - Feeds refresh about once an hour and may be cached for 15 minutes.
41
+ - Adding a channel or show nobody has used yet is limited per IP address. Reading feeds that exist isn't.
42
+ - Feeds nobody reads for 30 days are removed, and come back the next time someone opens them.
43
+ - Errors: `404` unknown channel or show, `429` too many new feeds (see `Retry-After`), `503` new feeds paused
44
+ or at capacity. Feeds that already exist keep working.
45
+
46
+ To report abuse or ask for a feed to be taken down, open an issue.
47
+
48
+ ## CLI
49
+
50
+ ```sh
51
+ bunx everyrss https://www.youtube.com/@3blue1brown
52
+ bunx everyrss https://youtu.be/aircAruvnKk --format feed.json --shorts
53
+ ```
54
+
55
+ `npx everyrss` works too. It runs everything locally and prints the feed. Spotify needs `SPOTIFY_CLIENT_ID` and
56
+ `SPOTIFY_CLIENT_SECRET` from a [Spotify app](https://developer.spotify.com/dashboard).
57
+
58
+ ## Engine
59
+
60
+ The `everyrss` package is also the engine behind everyrss.com (`npm install everyrss effect`). Plugins add
61
+ sources, steps that filter or change items, and formats:
62
+
63
+ ```ts
64
+ import { Effect } from "effect"
65
+ import { createEngine, filter, memoryStore } from "everyrss"
66
+ import { json, matter, rss } from "everyrss/formats"
67
+ import { spotify } from "everyrss/spotify"
68
+ import { hideLiveStreams, hideShorts, youtube } from "everyrss/youtube"
69
+
70
+ const engine = createEngine({
71
+ store: memoryStore(),
72
+ plugins: [
73
+ youtube(),
74
+ spotify({ clientId, clientSecret }),
75
+ hideShorts(),
76
+ hideLiveStreams(),
77
+ filter((item) => !item.title.includes("#ad")),
78
+ // A `version` saves each item's result, so expensive checks run once per item.
79
+ filter(async (item) => isAboutProgramming(item.title), { id: "programming", version: "1" }),
80
+ rss(),
81
+ json(),
82
+ matter(),
83
+ ],
84
+ })
85
+
86
+ const source = await Effect.runPromise(engine.open("youtube", "@3blue1brown"))
87
+ const { body } = await Effect.runPromise(engine.render(source, "rss.xml", selfUrl))
88
+ ```
89
+
90
+ - **Providers** turn links into sources and fetch their items. `youtube()` reads YouTube's public
91
+ feeds, without an API key. `youtube({ apiKey })` adds a YouTube Data API key, used only to look up
92
+ an `@handle` when YouTube answers its channel page with a captcha. `youtube({ lists: ["videos"] })` fetches only long-form videos, in one
93
+ request. `spotify()` uses the Spotify Web API.
94
+ - **Steps** run after every refresh, in order. Return `null` from `transform()` to drop an item.
95
+ - **Formats** render a feed. A format's `file` is the last part of its address.
96
+ - **Stores** keep sources and saved step results. `memoryStore()` ships with the engine; the Worker
97
+ uses D1.
98
+
99
+ Write your own with `definePlugin({ id, providers, steps, formats })`.
100
+
101
+ ## Self-hosting
102
+
103
+ everyrss.com is `packages/worker`, a Cloudflare Worker with D1. To run your own:
104
+
105
+ ```sh
106
+ bun install
107
+ cp packages/worker/.dev.vars.example packages/worker/.dev.vars # optional Spotify credentials
108
+ bun run dev # http://localhost:8787
109
+ ```
110
+
111
+ To deploy, create a D1 database, put its ID in `packages/worker/wrangler.jsonc`, then:
112
+
113
+ ```sh
114
+ cd packages/worker
115
+ bunx wrangler d1 migrations apply everyrss --remote
116
+ bunx wrangler secret put SPOTIFY_CLIENT_ID
117
+ bunx wrangler secret put SPOTIFY_CLIENT_SECRET
118
+ bunx wrangler deploy
119
+ ```
120
+
121
+ Limits are variables in `wrangler.jsonc`: `MAX_SOURCES`, `NEW_SOURCES_ENABLED`, `REFRESH_BATCH`, and
122
+ the `NEW_SOURCES` and `READS` rate limits. Take a feed down with:
123
+
124
+ ```sh
125
+ bunx wrangler d1 execute everyrss --remote --command "UPDATE sources SET blocked = 1 WHERE id = 'youtube:UC…'"
126
+ ```
127
+
128
+ ## Development
129
+
130
+ ```sh
131
+ bun run check # Oxlint, TypeScript and Effect diagnostics
132
+ bun run format
133
+ bun run test
134
+ bun run cli https://www.youtube.com/@3blue1brown
135
+ ```
136
+
137
+ ## License
138
+
139
+ MIT
package/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ const result = await main(process.argv.slice(2), process.env);
4
+ (result.code === 0 ? process.stdout : process.stderr).write(result.output);
5
+ process.exitCode = result.code;
package/cli.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export declare function main(argv: readonly string[], env: Readonly<Record<string, string | undefined>>): Promise<{
2
+ output: string;
3
+ code: number;
4
+ }>;
package/cli.js ADDED
@@ -0,0 +1,66 @@
1
+ import { parseArgs } from "node:util";
2
+ import { Effect } from "effect";
3
+ import { createEngine, memoryStore } from "./index.js";
4
+ import { json, matter, rss } from "./formats.js";
5
+ import { spotify } from "./spotify.js";
6
+ import { hideLiveStreams, hideShorts, youtube } from "./youtube.js";
7
+ const help = `Usage: everyrss <url> [options]
8
+
9
+ Print the feed for a YouTube channel or Spotify show.
10
+
11
+ Options:
12
+ --format <file> rss.xml (default), feed.json or matter.xml
13
+ --shorts Include YouTube Shorts
14
+ --live Include YouTube livestreams
15
+ -h, --help Show this help
16
+
17
+ Spotify needs SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in the environment.
18
+ `;
19
+ export async function main(argv, env) {
20
+ const { values, positionals } = parseArgs({
21
+ args: [...argv],
22
+ allowPositionals: true,
23
+ options: {
24
+ format: { type: "string", default: "rss.xml" },
25
+ shorts: { type: "boolean", default: false },
26
+ live: { type: "boolean", default: false },
27
+ help: { type: "boolean", short: "h", default: false },
28
+ },
29
+ });
30
+ const [input] = positionals;
31
+ if (values.help || input === undefined)
32
+ return { output: help, code: input === undefined && !values.help ? 1 : 0 };
33
+ // Links copied without their scheme, like youtube.com/@mkbhd, are fine too.
34
+ const link = /^https?:\/\//.test(input) ? input : `https://${input}`;
35
+ const spotifyCredentials = env.SPOTIFY_CLIENT_ID && env.SPOTIFY_CLIENT_SECRET;
36
+ if (!spotifyCredentials && URL.canParse(link) && new URL(link).hostname === "open.spotify.com")
37
+ return {
38
+ output: "everyrss: Spotify needs SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in the environment\n",
39
+ code: 1,
40
+ };
41
+ const engine = createEngine({
42
+ store: memoryStore(),
43
+ plugins: [
44
+ youtube(),
45
+ ...(env.SPOTIFY_CLIENT_ID && env.SPOTIFY_CLIENT_SECRET
46
+ ? [spotify({ clientId: env.SPOTIFY_CLIENT_ID, clientSecret: env.SPOTIFY_CLIENT_SECRET })]
47
+ : []),
48
+ ...(values.shorts ? [] : [hideShorts()]),
49
+ ...(values.live ? [] : [hideLiveStreams()]),
50
+ rss(),
51
+ json(),
52
+ matter(),
53
+ ],
54
+ });
55
+ const program = Effect.gen(function* () {
56
+ const path = yield* engine.locate(link);
57
+ const [provider = "", ...ref] = path.split("/");
58
+ const source = yield* engine.open(provider, ref.join("/"));
59
+ const rendered = yield* engine.render(source, values.format, `https://everyrss.com/${path}/${values.format}`);
60
+ return rendered.body;
61
+ });
62
+ return Effect.runPromise(Effect.match(program, {
63
+ onFailure: (error) => ({ output: `everyrss: ${error.message}\n`, code: 1 }),
64
+ onSuccess: (output) => ({ output: `${output}\n`, code: 0 }),
65
+ }));
66
+ }
package/engine.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { Effect } from "effect";
2
+ import { NotFound } from "./errors.ts";
3
+ import type { EveryRssError } from "./errors.ts";
4
+ import type { Http } from "./http.ts";
5
+ import type { Plugin } from "./plugin.ts";
6
+ import type { StoredSource } from "./schema.ts";
7
+ import type { Store } from "./store.ts";
8
+ export interface EngineOptions {
9
+ readonly plugins: readonly Plugin[];
10
+ readonly store: Store;
11
+ readonly http?: Http;
12
+ readonly now?: () => number;
13
+ /** Items per feed, newest first. */
14
+ readonly limit?: number;
15
+ }
16
+ export interface OpenOptions {
17
+ /** Runs before a source is added, for limits. Fail to refuse it. */
18
+ readonly beforeCreate?: Effect.Effect<void, EveryRssError>;
19
+ }
20
+ export declare function createEngine(options: EngineOptions): {
21
+ providers: string[];
22
+ formats: string[];
23
+ /** Whether a format renders differently on every request, so responses mustn't be cached. */
24
+ live: (file: string | undefined) => boolean;
25
+ open: (providerId: string, ref: string, openOptions?: OpenOptions | undefined) => Effect.Effect<StoredSource, EveryRssError, never>;
26
+ locate: (input: string, openOptions?: OpenOptions | undefined) => Effect.Effect<string, EveryRssError, never>;
27
+ refresh: (source: StoredSource) => Effect.Effect<StoredSource, EveryRssError, never>;
28
+ render: (source: StoredSource, file: string | undefined, selfUrl: string) => Effect.Effect<never, NotFound, never> | Effect.Effect<{
29
+ contentType: string;
30
+ live: boolean;
31
+ body: string;
32
+ }, never, never>;
33
+ };
34
+ export type Engine = ReturnType<typeof createEngine>;
package/engine.js ADDED
@@ -0,0 +1,165 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { NotFound } from "./errors.js";
3
+ import { fetchHttp } from "./http.js";
4
+ import { registry } from "./plugin.js";
5
+ import { Item } from "./schema.js";
6
+ const SavedResult = Schema.fromJsonString(Schema.NullOr(Item));
7
+ const decodeResult = Schema.decodeSync(SavedResult);
8
+ const encodeResult = Schema.encodeSync(SavedResult);
9
+ const newestFirst = (a, b) => b.publishedAt - a.publishedAt || a.key.localeCompare(b.key);
10
+ export function createEngine(options) {
11
+ const plugins = registry(options.plugins);
12
+ const { store, limit = 50 } = options;
13
+ const clock = options.now ?? Date.now;
14
+ const context = { http: options.http ?? fetchHttp(), now: Effect.sync(clock) };
15
+ const provider = (id) => {
16
+ const found = plugins.providers.get(id);
17
+ return found
18
+ ? Effect.succeed(found)
19
+ : Effect.fail(new NotFound({ message: `Unknown provider ${id}` }));
20
+ };
21
+ const providerFor = (url) => {
22
+ for (const candidate of plugins.providers.values())
23
+ if (candidate.matches(url))
24
+ return Effect.succeed(candidate);
25
+ return Effect.fail(new NotFound({ message: "No provider supports this URL" }));
26
+ };
27
+ const parse = (input) => URL.canParse(input)
28
+ ? Effect.succeed(new URL(input))
29
+ : Effect.fail(new NotFound({ message: "Not a URL" }));
30
+ const runStep = Effect.fn("engine.runStep")(function* (step, items, source) {
31
+ if (step.appliesTo && !step.appliesTo(source))
32
+ return items;
33
+ if (step.version === undefined) {
34
+ const results = yield* Effect.forEach(items, (item) => step.apply(item, source, context));
35
+ return results.filter((item) => item !== null);
36
+ }
37
+ const key = (item) => `${step.id}@${step.version}/${item.key}`;
38
+ const saved = yield* store.getResults(items.map(key));
39
+ const computed = new Map();
40
+ const results = yield* Effect.forEach(items, Effect.fnUntraced(function* (item) {
41
+ const value = saved.get(key(item));
42
+ if (value !== undefined)
43
+ return decodeResult(value);
44
+ const result = yield* step.apply(item, source, context);
45
+ computed.set(key(item), encodeResult(result));
46
+ return result;
47
+ }), { concurrency: 4 });
48
+ if (computed.size > 0)
49
+ yield* store.putResults(computed);
50
+ return results.filter((item) => item !== null);
51
+ });
52
+ const refresh = Effect.fn("engine.refresh")(function* (source) {
53
+ const upstream = yield* provider(source.provider);
54
+ const fetched = yield* upstream.fetch(source, context);
55
+ const byKey = new Map(source.items.map((item) => [item.key, item]));
56
+ for (const item of fetched.items)
57
+ byKey.set(item.key, item);
58
+ const items = [...byKey.values()].sort(newestFirst).slice(0, upstream.retain ?? 100);
59
+ let feed = items;
60
+ for (const step of plugins.steps)
61
+ feed = yield* runStep(step, feed, source);
62
+ const next = {
63
+ ...source,
64
+ name: fetched.name ?? source.name,
65
+ image: fetched.image === undefined ? source.image : fetched.image,
66
+ items,
67
+ feed: feed.slice(0, limit),
68
+ refreshedAt: clock(),
69
+ };
70
+ yield* store.putSource(next);
71
+ return next;
72
+ });
73
+ const create = Effect.fn("engine.create")(function* (upstream, url, alias) {
74
+ const resolved = yield* upstream.resolve(url, context);
75
+ const id = `${upstream.id}:${resolved.key}`;
76
+ const existing = yield* store.getSource(id);
77
+ const source = existing ?? {
78
+ id,
79
+ provider: upstream.id,
80
+ key: resolved.key,
81
+ url: resolved.url,
82
+ name: resolved.name,
83
+ image: resolved.image,
84
+ links: resolved.links ?? [],
85
+ items: [],
86
+ feed: null,
87
+ refreshedAt: null,
88
+ createdAt: clock(),
89
+ };
90
+ if (!existing)
91
+ yield* store.putSource(source);
92
+ yield* store.putAlias(alias, id);
93
+ return source;
94
+ });
95
+ /** The source behind a feed path such as `youtube` + `@3blue1brown`, added and fetched on first use. */
96
+ const open = Effect.fn("engine.open")(function* (providerId, ref, openOptions = {}) {
97
+ const upstream = yield* provider(providerId);
98
+ const url = upstream.url(ref);
99
+ if (!url)
100
+ return yield* new NotFound({ message: `Not a ${upstream.id} reference: ${ref}` });
101
+ const alias = `${upstream.id}:${upstream.ref(url) ?? ref}`;
102
+ const id = yield* store.getAlias(alias);
103
+ let source = id === undefined ? undefined : yield* store.getSource(id);
104
+ if (!source) {
105
+ if (openOptions.beforeCreate)
106
+ yield* openOptions.beforeCreate;
107
+ source = yield* create(upstream, url, alias);
108
+ }
109
+ return source.feed === null ? yield* refresh(source) : source;
110
+ });
111
+ /** The feed path for any supported URL, such as `youtube/@3blue1brown`. */
112
+ const locate = Effect.fn("engine.locate")(function* (input, openOptions = {}) {
113
+ const url = yield* parse(input);
114
+ const upstream = yield* providerFor(url);
115
+ const ref = upstream.ref(url);
116
+ if (ref !== undefined)
117
+ return `${upstream.id}/${ref}`;
118
+ if (openOptions.beforeCreate)
119
+ yield* openOptions.beforeCreate;
120
+ const resolved = yield* upstream.resolve(url, context);
121
+ return `${upstream.id}/${resolved.key}`;
122
+ });
123
+ const format = (file) => file === undefined ? plugins.defaultFormat : plugins.formats.get(file);
124
+ /** Feed paths for a source's links that a provider recognises without network access. */
125
+ const related = (source) => {
126
+ const paths = new Set();
127
+ for (const link of source.links) {
128
+ if (!URL.canParse(link))
129
+ continue;
130
+ const url = new URL(link);
131
+ for (const candidate of plugins.providers.values()) {
132
+ const ref = candidate.matches(url) ? candidate.ref(url) : undefined;
133
+ if (ref !== undefined && `${candidate.id}:${ref}` !== source.id)
134
+ paths.add(`${candidate.id}/${ref}`);
135
+ }
136
+ }
137
+ return [...paths];
138
+ };
139
+ const render = (source, file, selfUrl) => {
140
+ const found = format(file);
141
+ if (!found)
142
+ return Effect.fail(new NotFound({ message: `Unknown format ${file}` }));
143
+ return Effect.sync(() => ({
144
+ contentType: found.contentType,
145
+ live: found.live === true,
146
+ body: found.render({
147
+ source,
148
+ items: source.feed ?? [],
149
+ related: related(source),
150
+ selfUrl,
151
+ now: clock(),
152
+ }),
153
+ }));
154
+ };
155
+ return {
156
+ providers: [...plugins.providers.keys()],
157
+ formats: [...plugins.formats.keys()],
158
+ /** Whether a format renders differently on every request, so responses mustn't be cached. */
159
+ live: (file) => format(file)?.live === true,
160
+ open,
161
+ locate,
162
+ refresh,
163
+ render,
164
+ };
165
+ }
package/errors.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { Schema } from "effect";
2
+ declare const InvalidInput_base: Schema.Class<InvalidInput, Schema.TaggedStruct<"InvalidInput", {
3
+ readonly message: Schema.String;
4
+ }>, import("effect/Cause").YieldableError>;
5
+ export declare class InvalidInput extends InvalidInput_base {
6
+ }
7
+ declare const NotFound_base: Schema.Class<NotFound, Schema.TaggedStruct<"NotFound", {
8
+ readonly message: Schema.String;
9
+ }>, import("effect/Cause").YieldableError>;
10
+ export declare class NotFound extends NotFound_base {
11
+ }
12
+ declare const RateLimited_base: Schema.Class<RateLimited, Schema.TaggedStruct<"RateLimited", {
13
+ readonly message: Schema.String;
14
+ readonly retryAfter: Schema.Finite;
15
+ }>, import("effect/Cause").YieldableError>;
16
+ export declare class RateLimited extends RateLimited_base {
17
+ }
18
+ declare const Unavailable_base: Schema.Class<Unavailable, Schema.TaggedStruct<"Unavailable", {
19
+ readonly message: Schema.String;
20
+ }>, import("effect/Cause").YieldableError>;
21
+ export declare class Unavailable extends Unavailable_base {
22
+ }
23
+ declare const UpstreamError_base: Schema.Class<UpstreamError, Schema.TaggedStruct<"UpstreamError", {
24
+ readonly message: Schema.String;
25
+ }>, import("effect/Cause").YieldableError>;
26
+ export declare class UpstreamError extends UpstreamError_base {
27
+ }
28
+ declare const StorageError_base: Schema.Class<StorageError, Schema.TaggedStruct<"StorageError", {
29
+ readonly message: Schema.String;
30
+ }>, import("effect/Cause").YieldableError>;
31
+ export declare class StorageError extends StorageError_base {
32
+ }
33
+ export type EveryRssError = InvalidInput | NotFound | RateLimited | Unavailable | UpstreamError | StorageError;
34
+ /** Milliseconds to wait, from a Retry-After header in seconds or as an HTTP date. */
35
+ export declare function retryAfter(header: string | undefined, now: number): number;
36
+ export {};
package/errors.js ADDED
@@ -0,0 +1,35 @@
1
+ import { Schema } from "effect";
2
+ export class InvalidInput extends Schema.TaggedError()("InvalidInput", {
3
+ message: Schema.String,
4
+ }) {
5
+ }
6
+ export class NotFound extends Schema.TaggedError()("NotFound", {
7
+ message: Schema.String,
8
+ }) {
9
+ }
10
+ export class RateLimited extends Schema.TaggedError()("RateLimited", {
11
+ message: Schema.String,
12
+ retryAfter: Schema.Finite,
13
+ }) {
14
+ }
15
+ export class Unavailable extends Schema.TaggedError()("Unavailable", {
16
+ message: Schema.String,
17
+ }) {
18
+ }
19
+ export class UpstreamError extends Schema.TaggedError()("UpstreamError", {
20
+ message: Schema.String,
21
+ }) {
22
+ }
23
+ export class StorageError extends Schema.TaggedError()("StorageError", {
24
+ message: Schema.String,
25
+ }) {
26
+ }
27
+ /** Milliseconds to wait, from a Retry-After header in seconds or as an HTTP date. */
28
+ export function retryAfter(header, now) {
29
+ if (header === undefined)
30
+ return 60_000;
31
+ if (/^\d+$/.test(header))
32
+ return Number(header) * 1000;
33
+ const date = Date.parse(header);
34
+ return Number.isNaN(date) ? 60_000 : Math.max(0, date - now);
35
+ }
package/formats.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Format } from "./plugin.ts";
2
+ import type { Feed } from "./schema.ts";
3
+ export declare const rss: () => {
4
+ readonly id: "rss";
5
+ readonly formats: readonly [Format];
6
+ };
7
+ /** RSS for Matter, which only picks up new items when the build date moves. */
8
+ export declare const matter: () => {
9
+ readonly id: "matter";
10
+ readonly formats: readonly [{
11
+ readonly contentType: string;
12
+ readonly file: "matter.xml";
13
+ readonly live: true;
14
+ readonly render: (feed: Feed) => string;
15
+ }];
16
+ };
17
+ /** JSON Feed 1.1, with everyrss fields under `_everyrss`. */
18
+ export declare const json: () => {
19
+ readonly id: "json";
20
+ readonly formats: readonly [{
21
+ readonly file: "feed.json";
22
+ readonly contentType: "application/feed+json; charset=utf-8";
23
+ readonly render: (feed: Feed) => string;
24
+ }];
25
+ };
package/formats.js ADDED
@@ -0,0 +1,104 @@
1
+ import { DateTime } from "effect";
2
+ import { XMLBuilder } from "fast-xml-parser";
3
+ import { definePlugin } from "./plugin.js";
4
+ const builder = new XMLBuilder({
5
+ ignoreAttributes: false,
6
+ cdataPropName: "#cdata",
7
+ suppressEmptyNode: true,
8
+ });
9
+ // oxlint-disable-next-line no-control-regex -- XML 1.0 forbids these characters.
10
+ const illegal = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g;
11
+ const text = (value) => value.replace(/[\uD800-\uDFFF]/gu, "\uFFFD").replace(illegal, "");
12
+ const cdata = (value) => ({ "#cdata": text(value).replaceAll("]]>", "]]&gt;") });
13
+ const date = (value) => DateTime.toDateUtc(DateTime.makeUnsafe(value)).toUTCString();
14
+ const html = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\r?\n/g, "<br>");
15
+ const providerName = (feed) => (feed.source.provider === "youtube" ? "YouTube" : "Spotify");
16
+ const summary = (value) => value
17
+ .split(/\r?\n\s*\r?\n/)[0]
18
+ ?.trim()
19
+ .slice(0, 500) ?? "";
20
+ function rssItem(item, options) {
21
+ return {
22
+ title: cdata(item.title),
23
+ link: text(item.url),
24
+ guid: { "@_isPermaLink": "false", "#text": text(item.url) },
25
+ pubDate: date(item.publishedAt),
26
+ description: cdata(html(options.summary ? summary(item.description) : item.description)),
27
+ "media:thumbnail": item.image === null ? undefined : { "@_url": text(item.image) },
28
+ };
29
+ }
30
+ function renderRss(feed, options = {}) {
31
+ const buildDate = options.buildDate ?? feed.items[0]?.publishedAt ?? 0;
32
+ const link = text(feed.source.url);
33
+ return builder.build({
34
+ "?xml": { "@_version": "1.0", "@_encoding": "UTF-8" },
35
+ rss: {
36
+ "@_version": "2.0",
37
+ "@_xmlns:atom": "http://www.w3.org/2005/Atom",
38
+ "@_xmlns:media": "http://search.yahoo.com/mrss/",
39
+ channel: {
40
+ title: cdata(feed.source.name),
41
+ link,
42
+ description: cdata(`${feed.source.name} on ${providerName(feed)}, via everyrss`),
43
+ image: feed.source.image === null
44
+ ? undefined
45
+ : { url: text(feed.source.image), title: text(feed.source.name), link },
46
+ generator: "everyrss",
47
+ lastBuildDate: date(buildDate),
48
+ "atom:link": {
49
+ "@_href": text(feed.selfUrl),
50
+ "@_rel": "self",
51
+ "@_type": "application/rss+xml",
52
+ },
53
+ item: feed.items.map((item) => rssItem(item, options)),
54
+ },
55
+ },
56
+ });
57
+ }
58
+ const rssFormat = {
59
+ file: "rss.xml",
60
+ contentType: "application/xml; charset=utf-8",
61
+ render: (feed) => renderRss(feed),
62
+ };
63
+ export const rss = () => definePlugin({ id: "rss", formats: [rssFormat] });
64
+ /** RSS for Matter, which only picks up new items when the build date moves. */
65
+ export const matter = () => definePlugin({
66
+ id: "matter",
67
+ formats: [
68
+ {
69
+ ...rssFormat,
70
+ file: "matter.xml",
71
+ live: true,
72
+ render: (feed) => renderRss(feed, { buildDate: feed.now, summary: true }),
73
+ },
74
+ ],
75
+ });
76
+ /** JSON Feed 1.1, with everyrss fields under `_everyrss`. */
77
+ export const json = () => definePlugin({
78
+ id: "json",
79
+ formats: [
80
+ {
81
+ file: "feed.json",
82
+ contentType: "application/feed+json; charset=utf-8",
83
+ render: (feed) => JSON.stringify({
84
+ version: "https://jsonfeed.org/version/1.1",
85
+ title: feed.source.name,
86
+ home_page_url: feed.source.url,
87
+ feed_url: feed.selfUrl,
88
+ description: `${feed.source.name} on ${providerName(feed)}, via everyrss`,
89
+ ...(feed.source.image === null ? {} : { icon: feed.source.image }),
90
+ ...(feed.related.length === 0 ? {} : { _everyrss: { related: feed.related } }),
91
+ items: feed.items.map((item) => ({
92
+ id: item.key,
93
+ url: item.url,
94
+ title: item.title,
95
+ content_text: item.description,
96
+ date_published: DateTime.formatIso(DateTime.makeUnsafe(item.publishedAt)),
97
+ authors: [{ name: item.author }],
98
+ ...(item.image === null ? {} : { image: item.image }),
99
+ _everyrss: { kind: item.kind, duration: item.duration, ...item.metadata },
100
+ })),
101
+ }),
102
+ },
103
+ ],
104
+ });
package/http.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { Effect } from "effect";
2
+ import { UpstreamError } from "./errors.ts";
3
+ export interface HttpReply {
4
+ readonly status: number;
5
+ readonly url: string;
6
+ readonly headers: Readonly<Record<string, string>>;
7
+ readonly text: string;
8
+ }
9
+ export interface Http {
10
+ get(url: string, headers?: Readonly<Record<string, string>>): Effect.Effect<HttpReply, UpstreamError>;
11
+ post(url: string, body: string, headers?: Readonly<Record<string, string>>): Effect.Effect<HttpReply, UpstreamError>;
12
+ }
13
+ export interface FetchHttpOptions {
14
+ readonly timeout?: number;
15
+ readonly maxBytes?: number;
16
+ readonly userAgent?: string;
17
+ }
18
+ /** HTTP through the platform's fetch, with a timeout and a response size cap. */
19
+ export declare function fetchHttp(options?: FetchHttpOptions): Http;