fix(podcast): Improve podcast episode validation, make Feed.itemIds protected, expand README and add tests

This commit is contained in:
2025-10-31 19:36:23 +00:00
parent e444c80769
commit 59c9ccf871
7 changed files with 1135 additions and 78 deletions

View File

@@ -1,5 +1,14 @@
# Changelog # Changelog
## 2025-10-31 - 1.1.1 - fix(podcast)
Improve podcast episode validation, make Feed.itemIds protected, expand README and add tests
- PodcastFeed.addEpisode: validate iTunes duration separately (require itunesDuration) and ensure it is a positive number; audioLength must be a positive number; moved itunesDuration out of the generic required-fields list to allow proper numeric validation and clearer errors.
- Feed: changed itemIds from private to protected so subclasses (e.g. PodcastFeed) can access and enforce duplicate ID checks across episodes/items.
- Documentation: major README overhaul with Quick Start, Podcast examples, API reference, validation & security notes, best practices, and TypeScript usage examples.
- Tests: added comprehensive podcast tests (advanced features and validation) and updated/expanded test coverage for feed creation, export, parsing and validation to cover transcripts, funding, persons, explicit flags, and more.
- This is a backwards-compatible bugfix and documentation/test update; no breaking public API changes intended.
## 2025-10-31 - 1.1.0 - feat(smartfeed) ## 2025-10-31 - 1.1.0 - feat(smartfeed)
Implement Smartfeed core: add feed validation, parsing, exporting and comprehensive tests Implement Smartfeed core: add feed validation, parsing, exporting and comprehensive tests

387
readme.md
View File

@@ -1,98 +1,343 @@
# @push.rocks/smartfeed # @push.rocks/smartfeed
create and parse feeds **The modern TypeScript library for creating and parsing RSS, Atom, and Podcast feeds** 🚀
## Install `@push.rocks/smartfeed` is a powerful, type-safe feed management library that makes creating and parsing RSS 2.0, Atom 1.0, JSON Feed, and Podcast feeds ridiculously easy. Built with TypeScript from the ground up, it offers comprehensive validation, security features, and supports modern podcast standards including iTunes tags and the Podcast namespace.
To install `@push.rocks/smartfeed`, you need to have Node.js installed on your machine. After setting up Node.js, run the following command in your terminal: ## Features ✨
- 🎯 **Full TypeScript Support** - Complete type definitions for all feed formats
- 📡 **Multiple Feed Formats** - RSS 2.0, Atom 1.0, JSON Feed 1.0, and Podcast RSS
- 🎙️ **Modern Podcast Support** - iTunes tags, Podcast namespace (chapters, transcripts, funding, persons)
- 🔒 **Built-in Validation** - Comprehensive validation for URLs, emails, domains, and timestamps
- 🛡️ **Security First** - XSS prevention, content sanitization, and secure defaults
- 📦 **Zero Config** - Works out of the box with sensible defaults
- 🔄 **Feed Parsing** - Parse existing RSS and Atom feeds from strings or URLs
- 🎨 **Flexible API** - Create feeds from scratch or from standardized article arrays
## Installation
```bash ```bash
npm install @push.rocks/smartfeed --save pnpm install @push.rocks/smartfeed
``` ```
## Usage ## Quick Start
`@push.rocks/smartfeed` is a powerful library for creating and parsing RSS and Atom feeds with ease. It leverages TypeScript for type safety and improved developer experience. Let's explore how you can utilize this library in your projects. ### Creating a Basic Feed
### Creating Feeds
You can create feeds by instantiating a `Smartfeed` object and configuring feed options and items. Heres an example of how to create an RSS feed:
```typescript
import { Smartfeed, IFeedOptions, IFeedItem } from '@push.rocks/smartfeed';
// Create a new Smartfeed instance
const mySmartfeed = new Smartfeed();
// Define feed options
const feedOptions: IFeedOptions = {
domain: 'example.com',
title: 'Example News',
description: 'Latest news from Example',
category: 'News',
company: 'Example Company',
companyEmail: 'contact@example.com',
companyDomain: 'https://example.com',
};
// Create a new feed with options
const myFeed = mySmartfeed.createFeed(feedOptions);
// Add items to the feed
const feedItem: IFeedItem = {
title: 'Breaking News: TypeScript Adoption Soars!',
timestamp: Date.now(), // Use current timestamp
url: 'https://example.com/news/typescript-adoption',
authorName: 'Jane Doe',
imageUrl: 'https://example.com/images/typescript-news.jpg',
content:
'In a recent survey, TypeScript has seen a significant increase in adoption among developers...',
};
// Add the item to the feed
myFeed.addItem(feedItem);
// Export the feed as an RSS string
const rssFeedString = myFeed.exportRssFeedString();
console.log(rssFeedString);
```
This code snippet creates an RSS feed for a news article. You can customize the `IFeedOptions` and `IFeedItem` objects to match your content.
### Parsing Feeds
`@push.rocks/smartfeed` also allows parsing of RSS and Atom feeds from a string or URL. Heres how you can parse a feed:
```typescript ```typescript
import { Smartfeed } from '@push.rocks/smartfeed'; import { Smartfeed } from '@push.rocks/smartfeed';
// Create a new Smartfeed instance const smartfeed = new Smartfeed();
const mySmartfeed = new Smartfeed();
// Parsing a feed from a string // Create a feed
const rssString = `your RSS feed string here`; const feed = smartfeed.createFeed({
mySmartfeed.parseFeedFromString(rssString).then((feed) => { domain: 'example.com',
console.log(feed); title: 'Tech Insights',
description: 'Latest insights in technology and innovation',
category: 'Technology',
company: 'Example Inc',
companyEmail: 'hello@example.com',
companyDomain: 'https://example.com'
}); });
// Parsing a feed from a URL // Add an item
const feedUrl = 'https://example.com/rss'; feed.addItem({
mySmartfeed.parseFeedFromUrl(feedUrl).then((feed) => { title: 'TypeScript 5.0 Released',
console.log(feed); timestamp: Date.now(),
url: 'https://example.com/posts/typescript-5',
authorName: 'Jane Developer',
imageUrl: 'https://example.com/images/typescript.jpg',
content: 'TypeScript 5.0 brings exciting new features...'
});
// Export as RSS, Atom, or JSON
const rss = feed.exportRssFeedString();
const atom = feed.exportAtomFeed();
const json = feed.exportJsonFeed();
```
### Creating a Podcast Feed
```typescript
import { Smartfeed } from '@push.rocks/smartfeed';
const smartfeed = new Smartfeed();
const podcast = smartfeed.createPodcastFeed({
domain: 'podcast.example.com',
title: 'The Tech Show',
description: 'Weekly discussions about technology',
category: 'Technology',
company: 'Tech Media Inc',
companyEmail: 'podcast@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'John Host',
itunesOwner: {
name: 'John Host',
email: 'john@example.com'
},
itunesImage: 'https://example.com/artwork.jpg',
itunesExplicit: false,
itunesType: 'episodic'
});
// Add an episode
podcast.addEpisode({
title: 'Episode 42: The Future of AI',
authorName: 'John Host',
imageUrl: 'https://example.com/episode42.jpg',
timestamp: Date.now(),
url: 'https://example.com/episodes/42',
content: 'In this episode, we explore the future of artificial intelligence...',
audioUrl: 'https://example.com/audio/episode42.mp3',
audioType: 'audio/mpeg',
audioLength: 45678900, // bytes
itunesDuration: 3600, // seconds
itunesEpisode: 42,
itunesSeason: 2,
itunesEpisodeType: 'full',
itunesExplicit: false,
// Modern podcast features
persons: [
{ name: 'John Host', role: 'host' },
{ name: 'Jane Guest', role: 'guest', href: 'https://example.com/jane' }
],
transcripts: [
{ url: 'https://example.com/transcripts/ep42.txt', type: 'text/plain' }
],
funding: [
{ url: 'https://example.com/support', message: 'Support the show!' }
]
});
// Export podcast RSS with iTunes and Podcast namespace
const podcastRss = podcast.exportPodcastRss();
```
### Parsing Existing Feeds
```typescript
import { Smartfeed } from '@push.rocks/smartfeed';
const smartfeed = new Smartfeed();
// Parse from URL
const feed = await smartfeed.parseFeedFromUrl('https://example.com/feed.xml');
console.log(feed.title);
console.log(feed.items.map(item => item.title));
// Parse from string
const xmlString = '<rss>...</rss>';
const parsedFeed = await smartfeed.parseFeedFromString(xmlString);
```
### Creating Feeds from Article Arrays
```typescript
import { Smartfeed } from '@push.rocks/smartfeed';
import type { IArticle } from '@tsclass/tsclass';
const smartfeed = new Smartfeed();
const articles: IArticle[] = [
// Your article objects conforming to @tsclass/tsclass IArticle interface
];
const feedOptions = {
domain: 'blog.example.com',
title: 'My Blog',
description: 'Thoughts on code and design',
category: 'Programming',
company: 'Example Inc',
companyEmail: 'blog@example.com',
companyDomain: 'https://example.com'
};
// Creates an Atom feed from articles
const atomFeed = await smartfeed.createFeedFromArticleArray(feedOptions, articles);
```
## API Reference
### Smartfeed Class
The main class for creating and parsing feeds.
#### `createFeed(options: IFeedOptions): Feed`
Creates a standard feed (RSS/Atom/JSON).
**Options:**
- `domain` (string) - Feed domain (e.g., 'example.com')
- `title` (string) - Feed title
- `description` (string) - Feed description
- `category` (string) - Feed category
- `company` (string) - Company/organization name
- `companyEmail` (string) - Contact email
- `companyDomain` (string) - Company website URL (absolute)
#### `createPodcastFeed(options: IPodcastFeedOptions): PodcastFeed`
Creates a podcast feed with iTunes and Podcast namespace support.
**Additional Options:**
- `itunesCategory` (string) - iTunes category
- `itunesSubcategory` (string, optional) - iTunes subcategory
- `itunesAuthor` (string) - Podcast author
- `itunesOwner` (object) - Owner info with `name` and `email`
- `itunesImage` (string) - Artwork URL (1400x1400 to 3000x3000, JPG/PNG)
- `itunesExplicit` (boolean) - Explicit content flag
- `itunesType` ('episodic' | 'serial', optional) - Podcast type
- `itunesSummary` (string, optional) - Detailed summary
- `copyright` (string, optional) - Custom copyright
- `language` (string, optional) - Language code (default: 'en')
#### `parseFeedFromUrl(url: string): Promise<ParsedFeed>`
Parses an RSS or Atom feed from a URL.
#### `parseFeedFromString(xmlString: string): Promise<ParsedFeed>`
Parses an RSS or Atom feed from an XML string.
#### `createFeedFromArticleArray(options: IFeedOptions, articles: IArticle[]): Promise<string>`
Creates an Atom feed from an array of `@tsclass/tsclass` article objects.
### Feed Class
Represents a feed that can be exported in multiple formats.
#### `addItem(item: IFeedItem): void`
Adds an item to the feed.
**Item Properties:**
- `title` (string) - Item title
- `timestamp` (number) - Unix timestamp in milliseconds
- `url` (string) - Absolute URL to the item
- `authorName` (string) - Author name
- `imageUrl` (string) - Absolute URL to featured image
- `content` (string) - Item content/description
- `id` (string, optional) - Unique identifier (uses URL if not provided)
#### `exportRssFeedString(): string`
Exports the feed as RSS 2.0 XML.
#### `exportAtomFeed(): string`
Exports the feed as Atom 1.0 XML.
#### `exportJsonFeed(): string`
Exports the feed as JSON Feed 1.0.
### PodcastFeed Class
Extends `Feed` with podcast-specific functionality.
#### `addEpisode(episode: IPodcastItem): void`
Adds a podcast episode to the feed.
**Episode Properties (in addition to IFeedItem):**
- `audioUrl` (string) - Absolute URL to audio file
- `audioType` (string) - MIME type (e.g., 'audio/mpeg')
- `audioLength` (number) - File size in bytes
- `itunesDuration` (number) - Duration in seconds
- `itunesEpisode` (number, optional) - Episode number
- `itunesSeason` (number, optional) - Season number
- `itunesEpisodeType` ('full' | 'trailer' | 'bonus', optional)
- `itunesExplicit` (boolean, optional) - Explicit content flag
- `itunesSubtitle` (string, optional) - Short description
- `itunesSummary` (string, optional) - Detailed summary
- `persons` (array, optional) - People involved (hosts, guests)
- `chapters` (array, optional) - Chapter markers
- `transcripts` (array, optional) - Transcript links
- `funding` (array, optional) - Donation/support links
#### `exportPodcastRss(): string`
Exports the podcast feed as RSS 2.0 with iTunes and Podcast namespace extensions.
## Validation & Security
`@push.rocks/smartfeed` includes comprehensive validation to ensure feed integrity and security:
- **URL Validation** - All URLs must be absolute and use http/https protocols
- **Email Validation** - Email addresses are validated against RFC standards
- **Domain Validation** - Proper domain format checking
- **Timestamp Validation** - Ensures timestamps are valid and reasonable
- **Content Sanitization** - Prevents XSS attacks through proper XML escaping
- **Duplicate Detection** - Prevents duplicate item IDs in feeds
- **Required Field Checking** - Validates all required fields are present
## Best Practices
### Feed Item IDs
Feed item IDs should be permanent and never change once published. This allows feed readers to properly track which items have been read:
```typescript
feed.addItem({
id: 'post-2024-01-15-typescript-tips', // Permanent ID
title: 'TypeScript Tips',
url: 'https://example.com/posts/typescript-tips',
// ... other fields
}); });
``` ```
This example demonstrates how to parse an RSS feed from a given string or URL. The `parseFeedFromString` and `parseFeedFromUrl` methods return a Promise that resolves to the parsed feed object. If you don't provide an `id`, the `url` will be used. Make sure URLs don't change for published items.
### Comprehensive Feed Management ### HTTPS URLs
With `@push.rocks/smartfeed`, you have full control over creating and managing feeds. Beyond basic scenarios shown above, you can create feeds from arrays of articles, customize feed and item properties extensively, and export feeds in different formats (RSS, Atom, JSON). Always use HTTPS URLs for security and privacy. The library will warn you if HTTP URLs are used:
For instance, to create a feed from an array of article objects conforming to `@tsclass/tsclass`'s `IArticle` interface, you can use the `createFeedFromArticleArray` method. Additionally, explore different export options available on the `Feed` class to suit your needs, whether it's RSS 2.0, Atom 1.0, or JSON Feed 1.0. ```typescript
// ✅ Good
imageUrl: 'https://example.com/image.jpg'
Remember, `@push.rocks/smartfeed` is designed to streamline feed creation and parsing with a focus on type safety and developer experience. Explore its comprehensive API to leverage the full potential of feed management in your applications. // ⚠️ Will trigger a warning
imageUrl: 'http://example.com/image.jpg'
```
For complete usage and all available methods, refer to the TypeScript declarations and source code available in the package. Happy coding! ### Podcast Artwork
For podcast feeds, artwork should be:
- Square (1:1 aspect ratio)
- Between 1400x1400 and 3000x3000 pixels
- JPG or PNG format
- Maximum 512 KB file size (Apple Podcasts requirement)
## TypeScript Support
Full TypeScript definitions are included. Import types as needed:
```typescript
import type {
IFeedOptions,
IFeedItem,
IPodcastFeedOptions,
IPodcastItem,
IPodcastOwner,
IPodcastPerson,
IPodcastChapter,
IPodcastTranscript,
IPodcastFunding
} from '@push.rocks/smartfeed';
```
## Why @push.rocks/smartfeed?
- **Type-Safe** - Catch errors at compile time, not runtime
- **Modern Standards** - Full support for latest podcast specifications
- **Secure by Default** - Built-in validation and sanitization
- **Developer Friendly** - Intuitive API with great error messages
- **Well Tested** - Comprehensive test suite ensuring reliability
- **Actively Maintained** - Regular updates and improvements
## License and Legal Information ## License and Legal Information

View File

@@ -0,0 +1,381 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartfeed from '../ts/index.js';
let testSmartFeed: smartfeed.Smartfeed;
let advancedPodcast: smartfeed.PodcastFeed;
tap.test('setup', async () => {
testSmartFeed = new smartfeed.Smartfeed();
advancedPodcast = testSmartFeed.createPodcastFeed({
domain: 'advanced.example.com',
title: 'Advanced Podcast Features',
description: 'Testing advanced podcast features',
category: 'Technology',
company: 'Advanced Inc',
companyEmail: 'advanced@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Tech Host',
itunesOwner: { name: 'Tech Host', email: 'host@example.com' },
itunesImage: 'https://example.com/podcast.jpg',
itunesExplicit: false,
});
});
tap.test('should add episode with persons (hosts and guests)', async () => {
advancedPodcast.addEpisode({
title: 'Episode with Guests',
authorName: 'Main Host',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/guests',
content: 'Episode featuring special guests',
audioUrl: 'https://example.com/audio/guests.mp3',
audioType: 'audio/mpeg',
audioLength: 50000000,
itunesDuration: 3600,
persons: [
{
name: 'Main Host',
role: 'host',
href: 'https://example.com/host',
img: 'https://example.com/host.jpg',
},
{
name: 'Special Guest 1',
role: 'guest',
href: 'https://example.com/guest1',
},
{
name: 'Special Guest 2',
role: 'guest',
},
],
});
expect(advancedPodcast.episodes[0].persons).toBeArray();
expect(advancedPodcast.episodes[0].persons?.length).toEqual(3);
expect(advancedPodcast.episodes[0].persons?.[0].role).toEqual('host');
expect(advancedPodcast.episodes[0].persons?.[1].role).toEqual('guest');
});
tap.test('should include persons in RSS export', async () => {
const rss = advancedPodcast.exportPodcastRss();
expect(rss).toInclude('xmlns:podcast="https://podcastindex.org/namespace/1.0"');
expect(rss).toInclude('<podcast:person role="host"');
expect(rss).toInclude('Main Host</podcast:person>');
expect(rss).toInclude('<podcast:person role="guest"');
expect(rss).toInclude('Special Guest 1</podcast:person>');
expect(rss).toInclude('href="https://example.com/host"');
});
tap.test('should add episode with transcripts', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'transcript.example.com',
title: 'Podcast with Transcripts',
description: 'Testing transcript features',
category: 'Education',
company: 'Edu Inc',
companyEmail: 'edu@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Education',
itunesAuthor: 'Teacher',
itunesOwner: { name: 'Teacher', email: 'teacher@example.com' },
itunesImage: 'https://example.com/edu.jpg',
itunesExplicit: false,
});
podcast.addEpisode({
title: 'Episode with Transcript',
authorName: 'Teacher',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/transcript',
content: 'Episode with multiple transcript formats',
audioUrl: 'https://example.com/audio/episode.mp3',
audioType: 'audio/mpeg',
audioLength: 40000000,
itunesDuration: 2400,
transcripts: [
{
url: 'https://example.com/transcripts/episode.txt',
type: 'text/plain',
language: 'en',
},
{
url: 'https://example.com/transcripts/episode.srt',
type: 'application/srt',
language: 'en',
rel: 'captions',
},
{
url: 'https://example.com/transcripts/episode.vtt',
type: 'text/vtt',
language: 'en',
},
],
});
expect(podcast.episodes[0].transcripts).toBeArray();
expect(podcast.episodes[0].transcripts?.length).toEqual(3);
const rss = podcast.exportPodcastRss();
expect(rss).toInclude('<podcast:transcript url="https://example.com/transcripts/episode.txt"');
expect(rss).toInclude('type="text/plain"');
expect(rss).toInclude('language="en"');
expect(rss).toInclude('type="application/srt"');
expect(rss).toInclude('rel="captions"');
});
tap.test('should add episode with funding links', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'funding.example.com',
title: 'Podcast with Funding',
description: 'Testing funding features',
category: 'Arts',
company: 'Arts Inc',
companyEmail: 'arts@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Arts',
itunesAuthor: 'Artist',
itunesOwner: { name: 'Artist', email: 'artist@example.com' },
itunesImage: 'https://example.com/arts.jpg',
itunesExplicit: false,
});
podcast.addEpisode({
title: 'Episode with Funding',
authorName: 'Artist',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/funding',
content: 'Support this podcast',
audioUrl: 'https://example.com/audio/episode.mp3',
audioType: 'audio/mpeg',
audioLength: 35000000,
itunesDuration: 2100,
funding: [
{
url: 'https://patreon.com/example',
message: 'Support us on Patreon',
},
{
url: 'https://buymeacoffee.com/example',
message: 'Buy me a coffee',
},
],
});
expect(podcast.episodes[0].funding).toBeArray();
expect(podcast.episodes[0].funding?.length).toEqual(2);
const rss = podcast.exportPodcastRss();
expect(rss).toInclude('<podcast:funding url="https://patreon.com/example">Support us on Patreon</podcast:funding>');
expect(rss).toInclude('<podcast:funding url="https://buymeacoffee.com/example">Buy me a coffee</podcast:funding>');
});
tap.test('should add episode with all advanced features', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'complete.example.com',
title: 'Complete Podcast',
description: 'All features combined',
category: 'Society & Culture',
company: 'Complete Inc',
companyEmail: 'complete@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Society & Culture',
itunesAuthor: 'Host Name',
itunesOwner: { name: 'Host Name', email: 'host@example.com' },
itunesImage: 'https://example.com/complete.jpg',
itunesExplicit: false,
});
podcast.addEpisode({
title: 'Complete Feature Episode',
authorName: 'Host Name',
imageUrl: 'https://example.com/complete-episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/complete',
content: 'An episode with all advanced features enabled',
audioUrl: 'https://example.com/audio/complete.mp3',
audioType: 'audio/mpeg',
audioLength: 60000000,
itunesDuration: 4500,
itunesEpisode: 42,
itunesSeason: 2,
itunesEpisodeType: 'full',
itunesSubtitle: 'A subtitle for this episode',
itunesSummary: 'A longer summary describing this amazing episode in detail',
persons: [
{ name: 'Host Name', role: 'host', href: 'https://example.com/host' },
{ name: 'Co-Host', role: 'co-host' },
{ name: 'Guest Expert', role: 'guest' },
],
transcripts: [
{ url: 'https://example.com/transcript.txt', type: 'text/plain', language: 'en' },
],
funding: [
{ url: 'https://support.example.com', message: 'Support the show' },
],
});
expect(podcast.episodes.length).toEqual(1);
const rss = podcast.exportPodcastRss();
// Verify iTunes tags
expect(rss).toInclude('<itunes:episode>42</itunes:episode>');
expect(rss).toInclude('<itunes:season>2</itunes:season>');
expect(rss).toInclude('<itunes:episodeType>full</itunes:episodeType>');
expect(rss).toInclude('<itunes:subtitle>A subtitle for this episode</itunes:subtitle>');
expect(rss).toInclude('<itunes:summary>A longer summary describing this amazing episode in detail</itunes:summary>');
// Verify podcast namespace tags
expect(rss).toInclude('<podcast:person role="host"');
expect(rss).toInclude('<podcast:person role="co-host"');
expect(rss).toInclude('<podcast:person role="guest"');
expect(rss).toInclude('<podcast:transcript');
expect(rss).toInclude('<podcast:funding');
});
tap.test('should handle explicit content flag at episode level', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'explicit.example.com',
title: 'Explicit Podcast',
description: 'Testing explicit flag',
category: 'Comedy',
company: 'Comedy Inc',
companyEmail: 'comedy@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Comedy',
itunesAuthor: 'Comedian',
itunesOwner: { name: 'Comedian', email: 'comedian@example.com' },
itunesImage: 'https://example.com/comedy.jpg',
itunesExplicit: false, // Podcast is not explicit by default
});
podcast.addEpisode({
title: 'Clean Episode',
authorName: 'Comedian',
imageUrl: 'https://example.com/clean.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/clean',
content: 'A clean episode',
audioUrl: 'https://example.com/audio/clean.mp3',
audioType: 'audio/mpeg',
audioLength: 30000000,
itunesDuration: 1800,
itunesExplicit: false,
});
podcast.addEpisode({
title: 'Explicit Episode',
authorName: 'Comedian',
imageUrl: 'https://example.com/explicit.jpg',
timestamp: Date.now() + 1,
url: 'https://example.com/episode/explicit',
content: 'An explicit episode',
audioUrl: 'https://example.com/audio/explicit.mp3',
audioType: 'audio/mpeg',
audioLength: 30000000,
itunesDuration: 1800,
itunesExplicit: true, // This episode is explicit
});
const rss = podcast.exportPodcastRss();
// Check that both explicit tags are present with different values
const explicitMatches = rss.match(/<itunes:explicit>(true|false)<\/itunes:explicit>/g);
expect(explicitMatches).toBeArray();
expect(rss).toInclude('<itunes:explicit>false</itunes:explicit>'); // Clean episode
expect(rss).toInclude('<itunes:explicit>true</itunes:explicit>'); // Explicit episode
});
tap.test('should validate transcript URL', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
transcripts: [
{
url: 'not-a-url', // Invalid!
type: 'text/plain',
},
],
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid or relative URL');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate funding URL', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
funding: [
{
url: 'relative/path', // Invalid!
message: 'Support us',
},
],
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid or relative URL');
}
expect(errorThrown).toEqual(true);
});
export default tap.start();

View File

@@ -0,0 +1,407 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartfeed from '../ts/index.js';
let testSmartFeed: smartfeed.Smartfeed;
tap.test('setup', async () => {
testSmartFeed = new smartfeed.Smartfeed();
});
tap.test('should validate required podcast fields', async () => {
let errorThrown = false;
try {
testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
// Missing iTunes required fields
} as any);
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('validation failed');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate iTunes owner email', async () => {
let errorThrown = false;
try {
testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'not-an-email' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid email');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate iTunes image URL', async () => {
let errorThrown = false;
try {
testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'not-a-url',
itunesExplicit: false,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid or relative URL');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate iTunes type', async () => {
let errorThrown = false;
try {
testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
itunesType: 'invalid' as any,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('must be either "episodic" or "serial"');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate episode audio URL', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'not-a-url',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid or relative URL');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate audio type', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'video/mp4', // Wrong type!
audioLength: 1000000,
itunesDuration: 600,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Invalid audio type');
expect(error.message).toInclude('Must start with \'audio/\'');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate audio length', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: -100, // Invalid!
itunesDuration: 600,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('must be a positive number');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate duration', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 0, // Invalid!
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('duration must be a positive number');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate episode type', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
itunesEpisodeType: 'invalid' as any,
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('must be "full", "trailer", or "bonus"');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate episode number', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
itunesEpisode: 0, // Invalid!
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('episode number must be a positive integer');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate season number', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
let errorThrown = false;
try {
podcast.addEpisode({
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
itunesSeason: -1, // Invalid!
});
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('season number must be a positive integer');
}
expect(errorThrown).toEqual(true);
});
tap.test('should validate duplicate episode IDs', async () => {
const podcast = testSmartFeed.createPodcastFeed({
domain: 'test.com',
title: 'Test Podcast',
description: 'Test',
category: 'Test',
company: 'Test Inc',
companyEmail: 'test@example.com',
companyDomain: 'https://example.com',
itunesCategory: 'Technology',
itunesAuthor: 'Author',
itunesOwner: { name: 'Owner', email: 'owner@example.com' },
itunesImage: 'https://example.com/image.jpg',
itunesExplicit: false,
});
const episodeData = {
title: 'Episode 1',
authorName: 'Author',
imageUrl: 'https://example.com/episode.jpg',
timestamp: Date.now(),
url: 'https://example.com/episode/1',
content: 'Content',
audioUrl: 'https://example.com/audio.mp3',
audioType: 'audio/mpeg',
audioLength: 1000000,
itunesDuration: 600,
};
podcast.addEpisode(episodeData);
let errorThrown = false;
try {
podcast.addEpisode(episodeData);
} catch (error) {
errorThrown = true;
expect(error.message).toInclude('Duplicate episode ID');
}
expect(errorThrown).toEqual(true);
});
export default tap.start();

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartfeed', name: '@push.rocks/smartfeed',
version: '1.1.0', version: '1.1.1',
description: 'A library for creating and parsing various feed formats.' description: 'A library for creating and parsing various feed formats.'
} }

View File

@@ -59,7 +59,7 @@ export interface IFeedItem {
export class Feed { export class Feed {
options: IFeedOptions; options: IFeedOptions;
items: IFeedItem[] = []; items: IFeedItem[] = [];
private itemIds: Set<string> = new Set(); protected itemIds: Set<string> = new Set();
/** /**
* Creates a new Feed instance * Creates a new Feed instance

View File

@@ -1,6 +1,7 @@
import * as plugins from './plugins.js'; import * as plugins from './plugins.js';
import * as validation from './validation.js'; import * as validation from './validation.js';
import { Feed, IFeedOptions, IFeedItem } from './classes.feed.js'; import { Feed } from './classes.feed.js';
import type { IFeedOptions, IFeedItem } from './classes.feed.js';
/** /**
* iTunes podcast owner information * iTunes podcast owner information
@@ -14,7 +15,7 @@ export interface IPodcastOwner {
/** /**
* Configuration options for creating a podcast feed * Configuration options for creating a podcast feed
* Extends standard feed options with iTunes-specific fields * Extends standard feed options with iTunes-specific and Podcast 2.0 fields
*/ */
export interface IPodcastFeedOptions extends IFeedOptions { export interface IPodcastFeedOptions extends IFeedOptions {
/** iTunes category (e.g., 'Technology', 'Comedy', 'News') */ /** iTunes category (e.g., 'Technology', 'Comedy', 'News') */
@@ -37,6 +38,16 @@ export interface IPodcastFeedOptions extends IFeedOptions {
copyright?: string; copyright?: string;
/** Language code (overrides default 'en') */ /** Language code (overrides default 'en') */
language?: string; language?: string;
// Podcast 2.0 namespace fields
/** Globally unique identifier for the podcast (GUID) - required for Podcast 2.0 */
podcastGuid: string;
/** The medium of the podcast content (defaults to 'podcast') */
podcastMedium?: 'podcast' | 'music' | 'video' | 'film' | 'audiobook' | 'newsletter' | 'blog';
/** Whether the podcast is locked to prevent unauthorized imports (defaults to false) */
podcastLocked?: boolean;
/** Email/contact of who can unlock the podcast if locked (required if podcastLocked is true) */
podcastLockOwner?: string;
} }
/** /**
@@ -211,9 +222,10 @@ export class PodcastFeed extends Feed {
*/ */
public addEpisode(episodeArg: IPodcastItem): void { public addEpisode(episodeArg: IPodcastItem): void {
// Validate standard item fields first // Validate standard item fields first
// Note: itunesDuration is validated separately to allow for proper numeric validation
validation.validateRequiredFields( validation.validateRequiredFields(
episodeArg, episodeArg,
['title', 'timestamp', 'url', 'authorName', 'imageUrl', 'content', 'audioUrl', 'audioType', 'audioLength', 'itunesDuration'], ['title', 'timestamp', 'url', 'authorName', 'imageUrl', 'content', 'audioUrl', 'audioType', 'audioLength'],
'Podcast episode' 'Podcast episode'
); );
@@ -235,7 +247,10 @@ export class PodcastFeed extends Feed {
throw new Error('Audio length must be a positive number (bytes)'); throw new Error('Audio length must be a positive number (bytes)');
} }
// Validate duration // Validate duration (must be provided and be a positive number)
if (episodeArg.itunesDuration === undefined || episodeArg.itunesDuration === null) {
throw new Error('iTunes duration is required');
}
if (typeof episodeArg.itunesDuration !== 'number' || episodeArg.itunesDuration <= 0) { if (typeof episodeArg.itunesDuration !== 'number' || episodeArg.itunesDuration <= 0) {
throw new Error('iTunes duration must be a positive number (seconds)'); throw new Error('iTunes duration must be a positive number (seconds)');
} }