Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,23 @@ URL は、ほかの URL フィールドと同様に `baseUrl` を基準に絶対

フィードのオプションで `itemImageAsThumbnail: true` を指定すると、各記事の `image` が RSS 2.0 と Atom 1.0 でも `<media:thumbnail>` として出力されます。Media RSS だけを見るリーダーでもプレビューが表示されます。`media.thumbnails` を設定した記事は、その指定を優先し、サムネイルを追加しません。指定しない場合、`image` は JSON Feed だけに出力されます。

## 追加のリンク

`FeedOptions` と `FeedItem` の `links` で、専用のフィールドから出力するもの以外のリンクを追加できます。たとえば関連ページ、元の情報源 (`via`)、ライセンス ([RFC 4946](https://www.rfc-editor.org/rfc/rfc4946))、別言語版です。各エントリーは、Atom 1.0 では `<link>`、RSS 2.0 では `<atom:link>` として出力されます。JSON Feed には対応するものがなく、ほかのバージョンでは無視されます。

```ts
feed.addItem({
title: 'Bonjour',
link: 'https://example.com/fr/bonjour',
links: [
{ rel: 'alternate', href: '/en/hello', hreflang: 'en', type: 'text/html' },
{ rel: 'via', href: 'https://origin.example/post' },
],
})
```

エントリーは `{ rel, href, type?, hreflang?, title?, length? }` の形で、`href` は `baseUrl` を基準に絶対 URL になります。`rel` と `href` は必須です。すでに専用のフィールドがある関係 (`self`、`hub`、`enclosure`、`replies`、ページングのもの)を指定すると例外を投げるので、同じリンクが二重に出力されることはありません。

## カスタムフィールドで拡張する

共通モデルは意図的に小さくしてあります。その範囲外のもの (Dublin Core の追加要素、hono-feed がモデル化していない名前空間付きのモジュール、独自の JSON Feed のキーなど)には、抜け道が必要です。それが `customXml` / `customNamespaces` (XML 形式向け)と `customJson` (JSON Feed 向け)で、`FeedOptions` (フィード単位)と `FeedItem` (記事単位)のどちらにも指定できます。
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,23 @@ URLs are absolutized against `baseUrl` like every other URL field, and every ent

Set `itemImageAsThumbnail: true` in the feed options to also emit each item's `image` as a `<media:thumbnail>` in RSS 2.0 and Atom 1.0, so readers that only look at Media RSS still show a preview. An item that sets `media.thumbnails` keeps its own and gets no extra one. Without the option, `image` stays JSON Feed-only.

## Extra links

`links` on `FeedOptions` and `FeedItem` adds links beyond the ones hono-feed emits from dedicated fields: a related page, the original source (`via`), a license ([RFC 4946](https://www.rfc-editor.org/rfc/rfc4946)), or an alternate-language version. Each entry is an Atom `<link>` (Atom 1.0) or an `<atom:link>` (RSS 2.0); JSON Feed has no equivalent and every other version ignores them.

```ts
feed.addItem({
title: 'Bonjour',
link: 'https://example.com/fr/bonjour',
links: [
{ rel: 'alternate', href: '/en/hello', hreflang: 'en', type: 'text/html' },
{ rel: 'via', href: 'https://origin.example/post' },
],
})
```

Entries are `{ rel, href, type?, hreflang?, title?, length? }`, and `href` is absolutized against `baseUrl`. Both `rel` and `href` are required. Relations that already have a field (`self`, `hub`, `enclosure`, `replies`, and the paging ones) throw, so a link is never emitted twice.

## Extending with custom fields

The neutral model is deliberately small — anything outside it (Media RSS, Dublin Core extras, a namespaced module hono-feed doesn't model, custom JSON Feed keys) needs an escape hatch. `customXml` / `customNamespaces` (XML formats) and `customJson` (JSON Feed) are that hatch, on both `FeedOptions` (feed-level) and `FeedItem` (item-level):
Expand Down
34 changes: 34 additions & 0 deletions base/README.base.md
Original file line number Diff line number Diff line change
Expand Up @@ -1175,6 +1175,23 @@ URLs are absolutized against `baseUrl` like every other URL field, and every ent

Set `itemImageAsThumbnail: true` in the feed options to also emit each item's `image` as a `<media:thumbnail>` in RSS 2.0 and Atom 1.0, so readers that only look at Media RSS still show a preview. An item that sets `media.thumbnails` keeps its own and gets no extra one. Without the option, `image` stays JSON Feed-only.

## Extra links

`links` on `FeedOptions` and `FeedItem` adds links beyond the ones hono-feed emits from dedicated fields: a related page, the original source (`via`), a license ([RFC 4946](https://www.rfc-editor.org/rfc/rfc4946)), or an alternate-language version. Each entry is an Atom `<link>` (Atom 1.0) or an `<atom:link>` (RSS 2.0); JSON Feed has no equivalent and every other version ignores them.

```ts
feed.addItem({
title: 'Bonjour',
link: 'https://example.com/fr/bonjour',
links: [
{ rel: 'alternate', href: '/en/hello', hreflang: 'en', type: 'text/html' },
{ rel: 'via', href: 'https://origin.example/post' },
],
})
```

Entries are `{ rel, href, type?, hreflang?, title?, length? }`, and `href` is absolutized against `baseUrl`. Both `rel` and `href` are required. Relations that already have a field (`self`, `hub`, `enclosure`, `replies`, and the paging ones) throw, so a link is never emitted twice.

## Extending with custom fields

The neutral model is deliberately small — anything outside it (Media RSS, Dublin Core extras, a namespaced module hono-feed doesn't model, custom JSON Feed keys) needs an escape hatch. `customXml` / `customNamespaces` (XML formats) and `customJson` (JSON Feed) are that hatch, on both `FeedOptions` (feed-level) and `FeedItem` (item-level):
Expand All @@ -1184,6 +1201,23 @@ URL は、ほかの URL フィールドと同様に `baseUrl` を基準に絶対

フィードのオプションで `itemImageAsThumbnail: true` を指定すると、各記事の `image` が RSS 2.0 と Atom 1.0 でも `<media:thumbnail>` として出力されます。Media RSS だけを見るリーダーでもプレビューが表示されます。`media.thumbnails` を設定した記事は、その指定を優先し、サムネイルを追加しません。指定しない場合、`image` は JSON Feed だけに出力されます。

## 追加のリンク

`FeedOptions` と `FeedItem` の `links` で、専用のフィールドから出力するもの以外のリンクを追加できます。たとえば関連ページ、元の情報源 (`via`)、ライセンス ([RFC 4946](https://www.rfc-editor.org/rfc/rfc4946))、別言語版です。各エントリーは、Atom 1.0 では `<link>`、RSS 2.0 では `<atom:link>` として出力されます。JSON Feed には対応するものがなく、ほかのバージョンでは無視されます。

```ts
feed.addItem({
title: 'Bonjour',
link: 'https://example.com/fr/bonjour',
links: [
{ rel: 'alternate', href: '/en/hello', hreflang: 'en', type: 'text/html' },
{ rel: 'via', href: 'https://origin.example/post' },
],
})
```

エントリーは `{ rel, href, type?, hreflang?, title?, length? }` の形で、`href` は `baseUrl` を基準に絶対 URL になります。`rel` と `href` は必須です。すでに専用のフィールドがある関係 (`self`、`hub`、`enclosure`、`replies`、ページングのもの)を指定すると例外を投げるので、同じリンクが二重に出力されることはありません。

## カスタムフィールドで拡張する

共通モデルは意図的に小さくしてあります。その範囲外のもの (Dublin Core の追加要素、hono-feed がモデル化していない名前空間付きのモジュール、独自の JSON Feed のキーなど)には、抜け道が必要です。それが `customXml` / `customNamespaces` (XML 形式向け)と `customJson` (JSON Feed 向け)で、`FeedOptions` (フィード単位)と `FeedItem` (記事単位)のどちらにも指定できます。
Expand Down
3 changes: 3 additions & 0 deletions src/formats/atom/atom10.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { FeedInput, FeedItem, FeedOptions, SerializeOptions } from '../../t
import { latestDate, rfc3339 } from '../../utils/date'
import { firstEnclosure } from '../../utils/enclosure'
import { hubList } from '../../utils/hub'
import { extraLinkNodes } from '../../utils/links'
import { pagingMarker, pagingRels } from '../../utils/paging'
import { absolutize } from '../../utils/url'
import { el, type Node, specToNode, tag, xmlDocument } from '../../utils/xml'
Expand Down Expand Up @@ -41,6 +42,7 @@ export function toAtom10(input: FeedInput, opts: SerializeOptions): string {
// RFC 4287 §4.2.8: icon is a small square, logo a 2:1 image — same roles as RSS <image> and JSON Feed icon/favicon.
if (options.favicon) feed.push(tag('icon', absolutize(options.favicon, base)))
if (options.image) feed.push(tag('logo', absolutize(options.image, base)))
feed.push(...extraLinkNodes(options.links, 'link', base))
if (options.customXml) feed.push(...options.customXml.map(specToNode))

for (const item of items) feed.push(atomEntry10(item, options, base))
Expand Down Expand Up @@ -91,6 +93,7 @@ function atomEntry10(item: FeedItem, options: FeedOptions, base?: string): Node

ch.push(...mediaItemNodes(item, options, base))

ch.push(...extraLinkNodes(item.links, 'link', base))
if (item.customXml) ch.push(...item.customXml.map(specToNode))

// renderAttrs drops undefined values, so xml:lang simply vanishes when language is unset.
Expand Down
86 changes: 86 additions & 0 deletions src/formats/links.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import type { FeedInput } from '../types'
import { validateInput } from '../validate'
import { toAtom } from './atom'
import { toJSONFeed } from './json'
import { toRSS } from './rss'

const input: FeedInput = {
options: {
title: 't',
link: 'https://example.com/',
author: { name: 'Ann' },
updated: new Date('2026-01-01T00:00:00Z'),
links: [{ rel: 'license', href: '/license', type: 'text/html', title: 'CC BY' }],
},
items: [
{
title: 'a',
link: 'https://example.com/1',
updated: new Date('2026-01-01T00:00:00Z'),
links: [
{ rel: 'via', href: 'https://origin.test/post' },
{ rel: 'alternate', href: '/fr/1', hreflang: 'fr', type: 'text/html', length: 42 },
],
},
],
}
const opts = { baseUrl: 'https://example.com', feedUrl: 'https://example.com/feed' }

describe('generic links', () => {
it('emits <link> elements in Atom 1.0, absolutized, at feed and entry level', () => {
const out = toAtom(input, opts)
expect(out).toContain(
'<link rel="license" href="https://example.com/license" type="text/html" title="CC BY"/>',
)
expect(out).toContain('<link rel="via" href="https://origin.test/post"/>')
expect(out).toContain(
'<link rel="alternate" href="https://example.com/fr/1" type="text/html" hreflang="fr" length="42"/>',
)
})

it('emits <atom:link> elements in RSS 2.0 at channel and item level', () => {
const out = toRSS(input, opts)
expect(out).toContain('xmlns:atom="http://www.w3.org/2005/Atom"')
expect(out).toContain(
'<atom:link rel="license" href="https://example.com/license" type="text/html" title="CC BY"/>',
)
expect(out).toContain('<atom:link rel="via" href="https://origin.test/post"/>')
})

it('has no effect on older RSS/Atom versions or JSON Feed', () => {
expect(toRSS(input, { ...opts, rssVersion: '0.92' })).not.toContain('license')
expect(toRSS(input, { ...opts, rssVersion: '1.0' })).not.toContain('license')
expect(toAtom(input, { ...opts, atomVersion: '0.3' })).not.toContain('license')
expect(toJSONFeed(input, opts)).not.toContain('license')
})

it('requires rel and href on every link', () => {
const bad = (links: NonNullable<FeedInput['items'][number]['links']>): FeedInput => ({
...input,
items: [{ ...input.items[0], links }],
})
expect(() => validateInput(bad([{ rel: '', href: '/x' }]), 'atom')).toThrow(
/item\[0\]\.links\[0\] requires both "rel" and "href"/,
)
expect(() => validateInput(bad([{ rel: 'via', href: '' }]), 'rss')).toThrow(/"href"/)
expect(() => validateInput(input, 'atom')).not.toThrow()
})

it('rejects relations that have their own field, at feed and item level', () => {
for (const rel of ['self', 'hub', 'enclosure', 'replies', 'next', 'prev-archive', 'SELF']) {
expect(() =>
validateInput(
{ ...input, options: { ...input.options, links: [{ rel, href: '/x' }] } },
'atom',
),
).toThrow(/has its own field/)
expect(() =>
validateInput(
{ ...input, items: [{ ...input.items[0], links: [{ rel, href: '/x' }] }] },
'rss',
),
).toThrow(/has its own field/)
}
})
})
5 changes: 5 additions & 0 deletions src/formats/rss/rss2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { firstAuthor } from '../../utils/author'
import { rfc822 } from '../../utils/date'
import { firstEnclosure } from '../../utils/enclosure'
import { hubList } from '../../utils/hub'
import { extraLinkNodes } from '../../utils/links'
import { pagingMarker, pagingRels } from '../../utils/paging'
import { absolutize, isUrl, selfUrl } from '../../utils/url'
import { cdata, el, type Node, raw, specToNode, tag, xmlDocument } from '../../utils/xml'
Expand Down Expand Up @@ -141,6 +142,8 @@ function channelNodes(
// Podcast metadata (iTunes / Podcasting 2.0) is RSS 2.0-only, like the rest of caps.rss20.
if (caps.rss20) channel.push(...podcastChannelNodes(options.podcast, base))

if (caps.rss20) channel.push(...extraLinkNodes(options.links, 'atom:link', base))

// Escape hatch: appended unconditionally (no caps gating) — the caller opted in explicitly.
if (options.customXml) channel.push(...options.customXml.map(specToNode))
return channel
Expand Down Expand Up @@ -243,6 +246,8 @@ function rssItem(item: FeedItem, options: FeedOptions, caps: Caps, base?: string
if (caps.rss20) ch.push(...podcastItemNodes(item.podcast, enclosure, base))
if (caps.rss20) ch.push(...mediaItemNodes(item, options, base))

if (caps.rss20) ch.push(...extraLinkNodes(item.links, 'atom:link', base))

if (item.customXml) ch.push(...item.customXml.map(specToNode))

return tag('item', ch)
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type {
FeedFormat,
FeedInput,
FeedItem,
FeedLink,
FeedOptions,
FeedPodcast,
ItemMedia,
Expand Down
20 changes: 20 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,22 @@ export interface PodcastEpisode {
display?: string
}

/**
* An additional link beyond the ones hono-feed emits from dedicated fields — a related page, the original source, a license, or an alternate language (Atom 1.0 and RSS 2.0 only).
*/
export interface FeedLink {
/** Relation, e.g. `'related'`, `'via'`, `'license'` (RFC 4946), `'alternate'`. Relations that have their own field (`self`, `hub`, `enclosure`, `replies`, and the paging ones) are rejected. */
rel: string
href: string
/** MIME type of the target. */
type?: string
/** Language of the target, for `rel="alternate"` translations. */
hreflang?: string
title?: string
/** Size in bytes (Atom `length`). */
length?: number
}

/**
* Podcast metadata for the feed as a whole (RSS 2.0 only — ignored by Atom, JSON Feed, and every other RSS version). Covers the iTunes namespace and the Podcasting 2.0 namespace; `xmlns:itunes` / `xmlns:podcast` are declared automatically, only when a field from that namespace is actually set somewhere in the feed. An explicit `customNamespaces` entry for either prefix always wins over the automatic one.
*/
Expand Down Expand Up @@ -289,6 +305,8 @@ export interface FeedOptions {
image?: string
/** Atom icon / JSON favicon. */
favicon?: string
/** Additional links: Atom `<link>` / RSS 2.0 `<atom:link>`. No JSON Feed equivalent. */
links?: FeedLink[]
/**
* Rewrite relative `src` / `href` / `poster` / `srcset` URLs in each item's HTML `content` and `description` to absolute ones against `baseUrl`, so images and links survive in a reader that has no page to resolve them against. Default `false`. Only attribute values inside start tags are touched. Needs a base URL (`baseUrl`, which `serveFeed` defaults to the request origin); without one this does nothing.
*/
Expand Down Expand Up @@ -420,6 +438,8 @@ export interface FeedItem {
comments?: string
/** Media RSS thumbnails and content. `xmlns:media` is declared automatically, only when one is set. RSS 2.0 and Atom 1.0 only; no JSON Feed mapping (use `image`). */
media?: ItemMedia
/** Additional links: Atom `<link>` / RSS 2.0 `<atom:link>`. No JSON Feed equivalent. */
links?: FeedLink[]
/** Where the item was republished from. RSS 2.0 and Atom 1.0 only; no JSON Feed equivalent. */
source?: ItemSource
/** JSON `image`. Also emitted as a `media:thumbnail` in RSS 2.0 / Atom 1.0 when `itemImageAsThumbnail` is `true` and `media.thumbnails` is unset. */
Expand Down
37 changes: 37 additions & 0 deletions src/utils/links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { FeedLink } from '../types'
import { absolutize } from './url'
import { el, type Node } from './xml'

// Relations hono-feed already emits from a dedicated field; accepting them here too would produce duplicate links.
export const RESERVED_LINK_RELS: ReadonlySet<string> = new Set([
'self',
'hub',
'enclosure',
'replies',
'first',
'last',
'next',
'prev',
'previous',
'current',
'prev-archive',
'next-archive',
])

/** One link element per entry, absolutized: `<link>` for Atom, `<atom:link>` for RSS 2.0. */
export function extraLinkNodes(
links: FeedLink[] | undefined,
elementName: 'link' | 'atom:link',
base: string | undefined,
): Node[] {
return (links ?? []).map((link) =>
el(elementName, {
rel: link.rel,
href: absolutize(link.href, base),
type: link.type,
hreflang: link.hreflang,
title: link.title,
length: link.length,
}),
)
}
20 changes: 19 additions & 1 deletion src/validate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { FeedFormat, FeedInput } from './types'
import type { FeedFormat, FeedInput, FeedLink } from './types'
import { hasAuthor } from './utils/author'
import { RESERVED_LINK_RELS } from './utils/links'
import { hasIriScheme } from './utils/url'

/**
Expand All @@ -23,6 +24,8 @@ export function validateInput(input: FeedInput, format: FeedFormat): void {
)
}

assertValidLinks(options.links, 'feed.links')

// RSS <skipHours> holds GMT hours (0–23).
if (options.skipHours?.some((hour) => !Number.isInteger(hour) || hour < 0 || hour > 23)) {
throw new TypeError('hono-feed: "skipHours" values must be integers between 0 and 23')
Expand Down Expand Up @@ -72,6 +75,7 @@ export function validateInput(input: FeedInput, format: FeedFormat): void {
if (item.source && (!item.source.title || !item.source.url)) {
throw new TypeError(`hono-feed: item[${i}] "source" requires both "title" and "url"`)
}
assertValidLinks(item.links, `item[${i}].links`)
assertValidDate(item.published, `item[${i}].published`)
assertValidDate(item.updated, `item[${i}].updated`)

Expand Down Expand Up @@ -112,3 +116,17 @@ function assertValidDate(d: Date | undefined, label: string): void {
throw new TypeError(`hono-feed: ${label} must be a valid Date`)
}
}

// A link needs a relation and a target, and a relation that has its own field would be emitted twice.
function assertValidLinks(links: FeedLink[] | undefined, label: string): void {
links?.forEach((link, j) => {
if (!link.rel || !link.href) {
throw new TypeError(`hono-feed: ${label}[${j}] requires both "rel" and "href"`)
}
if (RESERVED_LINK_RELS.has(link.rel.toLowerCase())) {
throw new TypeError(
`hono-feed: ${label}[${j}] rel "${link.rel}" has its own field and can't be set through "links"`,
)
}
})
}
Loading