@mscode-pl/feed-lint 0.0.0-stage → 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MSCode
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,283 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset=".github/banner-dark.svg">
4
+ <img src=".github/banner-light.svg" alt="feed-lint: catch product feed errors before Google does" width="100%">
5
+ </picture>
6
+ </p>
2
7
 
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.
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/@mscode-pl/feed-lint"><img src="https://badges.mscode.pl/npm/v/@mscode-pl/feed-lint" alt="npm version"></a>
10
+ <a href="https://www.npmjs.com/package/@mscode-pl/feed-lint"><img src="https://badges.mscode.pl/npm/dm/@mscode-pl/feed-lint" alt="npm downloads"></a>
11
+ <a href="https://github.com/mscode-pl/feed-lint/actions/workflows/ci.yml"><img src="https://badges.mscode.pl/github/actions/mscode-pl/feed-lint/ci.yml?branch=master&label=tests" alt="Tests"></a>
12
+ <img src="https://badges.mscode.pl/badge/node/22+/339933?icon=nodejs" alt="Node 22+">
13
+ <a href="LICENSE"><img src="https://badges.mscode.pl/npm/l/@mscode-pl/feed-lint" alt="License"></a>
14
+ </p>
15
+
16
+ <p align="center">
17
+ feed-lint checks Google Merchant and Ceneo XML product feeds before you upload them: missing fields, prices in the wrong format, GTINs with a bad check digit, duplicate ids, placeholder brands, wrong availability codes and links that do not load. Every finding has the line number and the product id, and points to the rule in the official specification.
18
+ </p>
19
+
20
+ <p align="center">
21
+ <a href="#try-it">Try it</a> · <a href="#formats">Formats</a> · <a href="#what-it-checks">Rules</a> · <a href="#use-it-in-ci">CI</a> · <a href="#options">Options</a> · <a href="#use-it-from-code">API</a> · <a href="#use-it-from-an-ai-agent">AI agents</a>
22
+ </p>
23
+
24
+ ## Try it
25
+
26
+ ```bash
27
+ npx @mscode-pl/feed-lint https://shop.example/feed/google.xml
28
+ ```
29
+
30
+ It takes a file, a URL or stdin, reads gzipped feeds, and streams the XML, so a feed with 100,000 products does not have to fit in memory. A 6.7 MB feed with 5,333 products takes about half a second. It needs Node 22 or newer, no account and no API key.
31
+
32
+ ```
33
+ examples/google.xml Google Merchant, 3 products
34
+ error 1 preorder or backorder without a valid g:availability_date google/availability-date
35
+ line 37 id MUG-300-WHITE missing for preorder
36
+ error 1 g:brand is a placeholder like "N/A" or "Generic"; leave it empty instead google/brand-placeholder
37
+ line 40 id MUG-300-WHITE "N/A"
38
+ error 1 The same g:id is used by more than one product google/duplicate-id
39
+ line 32 id MUG-300-WHITE first used on line 8
40
+ error 1 GTIN has a wrong check digit google/gtin-checksum
41
+ line 16 id MUG-300-WHITE "5901234123458"
42
+ error 1 Price is not a number with an ISO 4217 currency, e.g. 15.00 PLN google/price-format
43
+ line 27 id MUG-300-BLACK g:price "29,99 zł": use a dot as the decimal separator
44
+ error 1 g:sale_price is not lower than g:price or uses another currency google/sale-price
45
+ line 15 id MUG-300-WHITE sale 34.99 PLN, regular 29.99 PLN
46
+ warning 1 Title or description is written mostly in capital letters google/all-caps
47
+ line 22 id MUG-300-BLACK g:title
48
+ warning 1 g:color is a number, a code, a single letter or a non-color like "multicolor" google/color-value
49
+ line 29 id MUG-300-BLACK "212"
50
+ warning 1 No g:gtin, no g:brand with g:mpn and g:identifier_exists is not "no" google/identifiers
51
+ line 21 id MUG-300-BLACK
52
+ warning 1 Title has promotional text like "free shipping", "-50%" or "!!" google/promo-text
53
+ line 22 id MUG-300-BLACK "FREE SHIPPING"
54
+
55
+ 6 errors, 4 warnings in 1 feed.
56
+ ```
57
+
58
+ Findings are grouped by rule, so a feed where 9,000 products miss a GTIN gives one line with a count and a few examples instead of 9,000 lines.
59
+
60
+ ## Why
61
+
62
+ Merchant Center and Ceneo tell you what is wrong only after the upload, hours later, product by product, and some problems (a duplicate id, a price with a comma) quietly drop products instead of failing loudly. Feeds are usually generated by a shop platform or an export script, so the same bug repeats on every product and comes back after every deploy.
63
+
64
+ feed-lint runs the documented rules locally, in seconds, on the file the export just wrote. Put it in CI next to the code that generates the feed and a broken export never reaches the shop's ads.
65
+
66
+ ## Formats
67
+
68
+ | Format | Detected by | Records |
69
+ | --- | --- | --- |
70
+ | Google Merchant RSS 2.0 | `<rss>` root, fields in the `g:` namespace (`http://base.google.com/ns/1.0`) | `<item>` |
71
+ | Google Merchant Atom 1.0 | `<feed>` root | `<entry>` |
72
+ | Ceneo | `<offers>` root | `<o>`, including incremental `update="1"` offers and the GPSR `<responsibleProducers>` and `<responsiblePersons>` lists |
73
+
74
+ Google fields are read with or without the `g:` prefix. Meta (Facebook) catalogs use the Google format, so the same rules apply to them. Files can be UTF-8, UTF-16, ISO-8859-2 or Windows-1250, as the XML declaration says.
75
+
76
+ ## What it checks
77
+
78
+ `feed-lint --rules` prints all 101 rules. Errors are what gets a product or the whole feed rejected; warnings are what the specification asks you not to do, or what limits how a product is shown.
79
+
80
+ | Area | Google Merchant | Ceneo |
81
+ | --- | --- | --- |
82
+ | **Required fields** | `id`, `title`, `description`, `link`, `image_link`, `availability`, `price` | `id`, `url`, `price`, `avail` on `<o>`; `<cat>`, `<name>`, `<imgs>`, `<desc>`, `<attrs>`; only `id` for incremental updates |
83
+ | **Limits** | id 50, title 150, description 5,000, brand and mpn 70, up to 10 extra images, URL lengths | id 100, url 1,000, category 255, name 150, description 100,000, 20 images, 500 attributes |
84
+ | **Values** | availability, condition, gender, age group, yes/no fields, energy class, ISO 8601 dates | `avail` codes 1, 3, 7, 14, 90, 99, 110; `basket`; `stock`; `weight`; energy class; CE mark |
85
+ | **Prices** | `15.00 PLN` format, real ISO 4217 code, at most 2 decimals, not 0, sale price lower than the price | dot as the decimal separator, 0 only in incremental mode |
86
+ | **Identifiers** | GTIN length, check digit, restricted and coupon prefixes; GTIN or brand + MPN or `identifier_exists=no` | "Kod EAN" 8 or 13 digits with check digit, "Kod ISBN", "Kod leku", "Marka" or "Producent" present |
87
+ | **Duplicates** | the same `g:id` twice | the same offer `id` twice, the same attribute twice in one offer |
88
+ | **Content** | all caps, "free shipping" and "!!" in titles, HTML in plain-text fields, colors given as numbers or codes, placeholder brands | commercial text in names, temporary categories like "Promocja", HTML tags outside the allowed list, HTML without CDATA |
89
+ | **Links** | http(s) only, https preferred, image URLs ASCII, known image formats | http(s) only; GPSR ids that exist in the lists |
90
+
91
+ With `--check-urls` it also requests product pages and images (HEAD, then GET if the server refuses HEAD) and reports pages that do not load (404, 5xx, timeouts) as errors, and redirects and pages that refuse the check (401, 403, 429) as warnings.
92
+
93
+ Rules come from the [Google Merchant product data specification](https://support.google.com/merchants/answer/7052112) and the [Ceneo XML guide](https://www.ceneo.pl/poradniki/Instrukcja-tworzenia-pliku-XML). Every finding links to its source.
94
+
95
+ ## Use it in CI
96
+
97
+ Commit a config file so everyone runs the same check:
98
+
99
+ ```json
100
+ {
101
+ "feeds": ["public/feeds/google.xml", "public/feeds/ceneo.xml"],
102
+ "ignore": ["google/identifiers"],
103
+ "failOn": "error",
104
+ "checkUrls": false
105
+ }
106
+ ```
107
+
108
+ Save it as `feed-lint.config.json`, and `feed-lint` with no arguments uses it.
109
+
110
+ ### GitHub Action
111
+
112
+ The action marks findings on the feed file in the pull request, and posts the full report as one comment that it updates on every push instead of adding a new one.
113
+
114
+ ```yaml
115
+ name: Feeds
116
+
117
+ on: pull_request
118
+
119
+ permissions:
120
+ contents: read
121
+ pull-requests: write
122
+
123
+ jobs:
124
+ feed-lint:
125
+ runs-on: ubuntu-latest
126
+ steps:
127
+ - uses: actions/checkout@v4
128
+ # Generate the feeds first, e.g. php artisan feeds:export
129
+ - uses: mscode-pl/feed-lint@v1
130
+ with:
131
+ feeds: storage/feeds/*.xml
132
+ ```
133
+
134
+ To watch a live feed instead, run it on a schedule with the URL:
135
+
136
+ ```yaml
137
+ on:
138
+ schedule:
139
+ - cron: '0 6 * * *'
140
+
141
+ jobs:
142
+ feed-lint:
143
+ runs-on: ubuntu-latest
144
+ steps:
145
+ - uses: mscode-pl/feed-lint@v1
146
+ with:
147
+ feeds: https://shop.example/feed/google.xml
148
+ check-urls: true
149
+ ```
150
+
151
+ | Input | Default | |
152
+ | --- | --- | --- |
153
+ | `feeds` | `feeds` from the config | Files, globs or URLs, separated by spaces or new lines |
154
+ | `ignore` | | Rules to skip, comma separated |
155
+ | `check-urls` | `false` | Also request product links and images |
156
+ | `url-limit` | config, then `200` | Unique URLs to check per feed, `0` for all |
157
+ | `fail-on` | config, then `error` | `error`, `warning` or `never` |
158
+ | `config` | `feed-lint.config.json` | Config file to read |
159
+ | `comment` | `true` | Post the report as a pull request comment |
160
+ | `github-token` | `github.token` | Token for the comment |
161
+ | `version` | the action's release | feed-lint version from npm |
162
+
163
+ Outputs: `report` (path to the Markdown report, also shown in the job summary) and `exit-code`. Pull requests from forks get a read-only token, so they get the annotations and the job summary but no comment.
164
+
165
+ ### Any other CI
166
+
167
+ ```yaml
168
+ - run: npx @mscode-pl/feed-lint storage/feeds/google.xml --format github -o feed-report.md
169
+ ```
170
+
171
+ The exit code is `1` when there are errors (or warnings with `--fail-on warning`), `0` otherwise, and `2` for bad arguments or a feed that could not be read.
172
+
173
+ ## Options
174
+
175
+ | Option | |
176
+ | --- | --- |
177
+ | `-i, --ignore <list>` | Rules to skip, e.g. `google/identifiers,ceneo/brand` |
178
+ | `--check-urls` | Also request product links and images |
179
+ | `--url-limit <n>` | Unique URLs to check per feed, `0` for all (default `200`) |
180
+ | `-f, --format <type>` | `text`, `json`, `markdown` or `github` |
181
+ | `-o, --output <file>` | Also save the report; `.json`, `.md` or plain text by extension |
182
+ | `--verbose` | Up to 20 examples per rule and links to the specification |
183
+ | `-q, --quiet` | Errors only |
184
+ | `--fail-on <level>` | `error`, `warning` or `never` |
185
+ | `--config <file>` | Config file (default `feed-lint.config.json`) |
186
+ | `--stdin` | Read the feed from stdin |
187
+ | `--rules` | List all rules |
188
+
189
+ `--check-urls` sends 8 requests at a time with a 10 second timeout and checks the first 200 unique URLs by default, so it does not hammer your own shop. Raise `--url-limit` for a full check.
190
+
191
+ ## Use it from code
192
+
193
+ ```ts
194
+ import { createReadStream } from 'node:fs';
195
+ import { lintFeed } from '@mscode-pl/feed-lint';
196
+
197
+ const result = await lintFeed(createReadStream('google.xml'), { ignore: ['google/identifiers'] });
198
+
199
+ result.format; // 'google'
200
+ result.records; // 5333
201
+ for (const r of result.results) {
202
+ console.log(r.level, r.rule, r.count, r.samples[0]?.line);
203
+ }
204
+ ```
205
+
206
+ `lintFeed` takes any iterable of strings or bytes (a file stream, `fetch(...).body`, an array with the XML). Options: `ignore`, `maxSamples` (examples kept per rule, default 20) and `checkUrls` (`true` or `{ limit, concurrency, timeoutMs }`).
207
+
208
+ ## Use it from an AI agent
209
+
210
+ ### MCP server
211
+
212
+ `feed-lint mcp` starts an [MCP](https://modelcontextprotocol.io) server on stdio, so Claude, Cursor, VS Code and other MCP clients can check a feed while they work on the export code. It has two read-only tools:
213
+
214
+ | Tool | What it does |
215
+ | --- | --- |
216
+ | `lint_feed` | Lints a `path`, a `url` or `xml` passed inline and returns every rule hit with counts, lines, product ids and the source link. With none of them, it lints the feeds from `feed-lint.config.json`. |
217
+ | `explain_rule` | For one rule id, says how severe it is, how to fix it and where the specification says so. |
218
+
219
+ Claude Code:
220
+
221
+ ```bash
222
+ claude mcp add feed-lint -- npx -y @mscode-pl/feed-lint mcp
223
+ ```
224
+
225
+ Cursor, VS Code, Claude Desktop and others take the same command in their MCP config:
226
+
227
+ ```json
228
+ {
229
+ "mcpServers": {
230
+ "feed-lint": {
231
+ "command": "npx",
232
+ "args": ["-y", "@mscode-pl/feed-lint", "mcp"]
233
+ }
234
+ }
235
+ }
236
+ ```
237
+
238
+ ### Agent Skill
239
+
240
+ The repo ships an [Agent Skill](skills/feed-lint/SKILL.md) for Claude Code, Codex, Cursor and other agents. It finds the code that generates the feed, runs feed-lint on its output and fixes the export instead of the XML.
241
+
242
+ ```bash
243
+ npx skills add mscode-pl/feed-lint
244
+ ```
245
+
246
+ ## What it does not check
247
+
248
+ - Category-specific required attributes: Google's apparel rules per country and Ceneo's key attributes per category need their taxonomies, which are not bundled yet.
249
+ - Whether the price and availability in the feed match the product page. Both Google and Ceneo check this and hide offers that do not match.
250
+ - Image size and content. Google's 500 x 500 minimum starts on 31 January 2027.
251
+
252
+ ## Contributing
253
+
254
+ ```bash
255
+ pnpm install
256
+ pnpm test
257
+ pnpm build && node dist/cli/main.js examples/google.xml examples/ceneo.xml
258
+ ```
259
+
260
+ Each rule lives in `src/rules/google.ts` or `src/rules/ceneo.ts` with a link to the paragraph of the specification it comes from, and has a test in `tests/`. Issues with a feed that gets a false report are welcome; strip prices and names you cannot share.
261
+
262
+ ## License
263
+
264
+ MIT
265
+
266
+ ---
267
+
268
+ <p align="center">
269
+ <a href="https://mscode.pl">
270
+ <picture>
271
+ <source media="(prefers-color-scheme: dark)" srcset=".github/mscode-logo-white.svg">
272
+ <img src=".github/mscode-logo-black.svg" alt="MSCode" height="28">
273
+ </picture>
274
+ </a>
275
+ </p>
276
+
277
+ <p align="center">
278
+ Built and maintained by <a href="https://mscode.pl">MSCode</a>, a Polish software house that makes websites and web and mobile apps.
279
+ </p>
280
+
281
+ <p align="center">
282
+ <a href="https://mscode.pl">mscode.pl</a> · <a href="https://github.com/mscode-pl">More packages</a> · <a href="https://github.com/mscode-pl/feed-lint/issues">Report an issue</a>
283
+ </p>
@@ -0,0 +1,13 @@
1
+ declare const CODES: {
2
+ readonly bold: readonly [1, 22];
3
+ readonly dim: readonly [2, 22];
4
+ readonly underline: readonly [4, 24];
5
+ readonly red: readonly [31, 39];
6
+ readonly green: readonly [32, 39];
7
+ readonly yellow: readonly [33, 39];
8
+ };
9
+ export type Style = keyof typeof CODES;
10
+ export type Paint = (style: Style, text: string) => string;
11
+ export declare function colorSupported(): boolean;
12
+ export declare function painter(enabled?: boolean): Paint;
13
+ export {};
@@ -0,0 +1,23 @@
1
+ const CODES = {
2
+ bold: [1, 22],
3
+ dim: [2, 22],
4
+ underline: [4, 24],
5
+ red: [31, 39],
6
+ green: [32, 39],
7
+ yellow: [33, 39],
8
+ };
9
+ export function colorSupported() {
10
+ if (process.env.NO_COLOR)
11
+ return false;
12
+ if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0')
13
+ return true;
14
+ return Boolean(process.stdout.isTTY);
15
+ }
16
+ export function painter(enabled = colorSupported()) {
17
+ if (!enabled)
18
+ return (_, text) => text;
19
+ return (style, text) => {
20
+ const [open, close] = CODES[style];
21
+ return `\u001b[${open}m${text}\u001b[${close}m`;
22
+ };
23
+ }
@@ -0,0 +1,11 @@
1
+ export declare const CONFIG_FILE = "feed-lint.config.json";
2
+ export type FailOn = 'error' | 'warning' | 'never';
3
+ export declare const FAIL_ON: FailOn[];
4
+ export interface Config {
5
+ feeds?: string[];
6
+ ignore?: string[];
7
+ failOn?: FailOn;
8
+ checkUrls?: boolean;
9
+ urlLimit?: number;
10
+ }
11
+ export declare function loadConfig(path?: string): Promise<Config>;
@@ -0,0 +1,59 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ export const CONFIG_FILE = 'feed-lint.config.json';
3
+ export const FAIL_ON = ['error', 'warning', 'never'];
4
+ const KEYS = ['feeds', 'ignore', 'failOn', 'checkUrls', 'urlLimit'];
5
+ function stringList(value, key, path) {
6
+ if (!Array.isArray(value) || value.some((v) => typeof v !== 'string')) {
7
+ throw new Error(`${path}: "${key}" must be an array of strings.`);
8
+ }
9
+ return value;
10
+ }
11
+ export async function loadConfig(path) {
12
+ const file = path ?? CONFIG_FILE;
13
+ let raw;
14
+ try {
15
+ raw = await readFile(file, 'utf8');
16
+ }
17
+ catch (error) {
18
+ if (!path && error.code === 'ENOENT')
19
+ return {};
20
+ throw new Error(`Cannot read config ${file}: ${error.message}`);
21
+ }
22
+ let data;
23
+ try {
24
+ data = JSON.parse(raw);
25
+ }
26
+ catch (error) {
27
+ throw new Error(`${file} is not valid JSON: ${error.message}`);
28
+ }
29
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
30
+ throw new Error(`${file} must contain a JSON object.`);
31
+ }
32
+ const obj = data;
33
+ const unknown = Object.keys(obj).filter((k) => !KEYS.includes(k));
34
+ if (unknown.length) {
35
+ throw new Error(`${file}: unknown option ${unknown.join(', ')}. Allowed: ${KEYS.join(', ')}.`);
36
+ }
37
+ const config = {};
38
+ if (obj.feeds !== undefined)
39
+ config.feeds = stringList(obj.feeds, 'feeds', file);
40
+ if (obj.ignore !== undefined)
41
+ config.ignore = stringList(obj.ignore, 'ignore', file);
42
+ if (obj.failOn !== undefined) {
43
+ if (!FAIL_ON.includes(obj.failOn)) {
44
+ throw new Error(`${file}: "failOn" must be one of ${FAIL_ON.join(', ')}.`);
45
+ }
46
+ config.failOn = obj.failOn;
47
+ }
48
+ if (obj.checkUrls !== undefined) {
49
+ if (typeof obj.checkUrls !== 'boolean')
50
+ throw new Error(`${file}: "checkUrls" must be true or false.`);
51
+ config.checkUrls = obj.checkUrls;
52
+ }
53
+ if (obj.urlLimit !== undefined) {
54
+ if (!Number.isInteger(obj.urlLimit) || obj.urlLimit < 0)
55
+ throw new Error(`${file}: "urlLimit" must be a whole number, 0 for no limit.`);
56
+ config.urlLimit = obj.urlLimit;
57
+ }
58
+ return config;
59
+ }
@@ -0,0 +1,23 @@
1
+ import type { LintResult } from '../core/lint.js';
2
+ import type { Sample } from '../core/report.js';
3
+ import { type Paint } from './colors.js';
4
+ export interface FeedResult extends LintResult {
5
+ feed: string;
6
+ fatal?: string;
7
+ }
8
+ export type Format = 'text' | 'json' | 'markdown' | 'github';
9
+ export declare const FORMATS: Format[];
10
+ export declare function describeFeed(result: FeedResult): string;
11
+ export declare function summary(results: FeedResult[]): string;
12
+ export declare function formatSample(s: Sample): string;
13
+ export interface TextOptions {
14
+ verbose?: boolean;
15
+ samples?: number;
16
+ paint?: Paint;
17
+ }
18
+ export declare function formatText(results: FeedResult[], options?: TextOptions): string;
19
+ export declare function formatMarkdown(results: FeedResult[], samples?: number): string;
20
+ export declare function formatGithub(results: FeedResult[], samples?: number): string;
21
+ export declare function render(results: FeedResult[], format: Format, options?: TextOptions): string;
22
+ export declare function onlyErrors(results: FeedResult[]): FeedResult[];
23
+ export declare function formatFromPath(path: string): Format;
@@ -0,0 +1,129 @@
1
+ import { painter } from './colors.js';
2
+ export const FORMATS = ['text', 'json', 'markdown', 'github'];
3
+ const FORMAT_NAMES = { google: 'Google Merchant', ceneo: 'Ceneo' };
4
+ const RECORD_NAMES = { google: 'product', ceneo: 'offer' };
5
+ const plural = (n, word) => `${n.toLocaleString('en')} ${word}${n === 1 ? '' : 's'}`;
6
+ export function describeFeed(result) {
7
+ if (result.fatal)
8
+ return 'not read';
9
+ if (!result.format)
10
+ return 'unknown format';
11
+ const urls = result.urls ? `, ${result.urls.checked.toLocaleString('en')} of ${plural(result.urls.total, 'URL')} checked` : '';
12
+ return `${FORMAT_NAMES[result.format]}, ${plural(result.records, RECORD_NAMES[result.format])}${urls}`;
13
+ }
14
+ export function summary(results) {
15
+ const errors = results.reduce((n, r) => n + r.errors, 0);
16
+ const warnings = results.reduce((n, r) => n + r.warnings, 0);
17
+ const feeds = plural(results.length, 'feed');
18
+ if (results.some((r) => r.fatal))
19
+ return `${plural(results.filter((r) => r.fatal).length, 'feed')} could not be read.`;
20
+ if (!errors && !warnings)
21
+ return `No issues in ${feeds}.`;
22
+ return `${plural(errors, 'error')}, ${plural(warnings, 'warning')} in ${feeds}.`;
23
+ }
24
+ export function formatSample(s) {
25
+ return [`line ${s.line}`, s.id && `id ${s.id}`, s.detail].filter(Boolean).join(' ');
26
+ }
27
+ export function formatText(results, options = {}) {
28
+ const paint = options.paint ?? painter();
29
+ const shown = options.verbose ? Infinity : (options.samples ?? 3);
30
+ const out = [];
31
+ for (const result of results) {
32
+ out.push(`${paint('underline', result.feed)} ${paint('dim', describeFeed(result))}`);
33
+ if (result.fatal) {
34
+ out.push(` ${paint('red', 'error')} ${result.fatal}`, '');
35
+ continue;
36
+ }
37
+ if (!result.results.length) {
38
+ out.push(` ${paint('green', 'no issues')}`, '');
39
+ continue;
40
+ }
41
+ const countWidth = Math.max(...result.results.map((r) => r.count.toLocaleString('en').length));
42
+ for (const r of result.results) {
43
+ const level = r.level === 'error' ? paint('red', 'error ') : paint('yellow', 'warning');
44
+ out.push(` ${level} ${r.count.toLocaleString('en').padStart(countWidth)} ${paint('bold', r.title)} ${paint('dim', r.rule)}`);
45
+ const pad = ' '.repeat(2 + 7 + 2 + countWidth + 2);
46
+ for (const s of r.samples.slice(0, shown))
47
+ out.push(`${pad}${formatSample(s)}`);
48
+ const more = r.count - Math.min(r.samples.length, shown);
49
+ if (more > 0)
50
+ out.push(paint('dim', `${pad}and ${more.toLocaleString('en')} more`));
51
+ if (options.verbose)
52
+ out.push(paint('dim', `${pad}${r.url}`));
53
+ }
54
+ out.push('');
55
+ }
56
+ const clean = results.every((r) => !r.fatal && !r.results.length);
57
+ out.push(clean ? paint('green', summary(results)) : summary(results));
58
+ if (results.some((r) => r.results.length) && !options.verbose)
59
+ out.push(paint('dim', 'Add --verbose for more examples and links to the specification.'));
60
+ return out.join('\n');
61
+ }
62
+ // Feed text lands in a pull request comment, where "@name" would notify a GitHub user.
63
+ const cell = (text) => text.replaceAll('|', '\\|').replaceAll('@', '&#64;').replace(/\s*\n\s*/g, ' ');
64
+ export function formatMarkdown(results, samples = 5) {
65
+ const out = ['# feed-lint report', '', summary(results), ''];
66
+ for (const result of results) {
67
+ out.push(`## ${cell(result.feed)}`, '', `${describeFeed(result)}.`, '');
68
+ if (result.fatal) {
69
+ out.push(`Could not read the feed: ${cell(result.fatal)}`, '');
70
+ continue;
71
+ }
72
+ if (!result.results.length) {
73
+ out.push('No issues.', '');
74
+ continue;
75
+ }
76
+ out.push('| Level | Count | Rule | Examples |', '| --- | ---: | --- | --- |');
77
+ for (const r of result.results) {
78
+ const examples = r.samples
79
+ .slice(0, samples)
80
+ .map((s) => cell(formatSample(s)))
81
+ .join('<br>');
82
+ out.push(`| ${r.level} | ${r.count} | [${cell(r.title)}](${r.url}) \`${r.rule}\` | ${examples} |`);
83
+ }
84
+ out.push('');
85
+ }
86
+ return out.join('\n').trimEnd() + '\n';
87
+ }
88
+ // Workflow command escaping: https://docs.github.com/actions/reference/workflow-commands-for-github-actions
89
+ const escapeData = (s) => s.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A');
90
+ const escapeProperty = (s) => escapeData(s).replace(/:/g, '%3A').replace(/,/g, '%2C');
91
+ export function formatGithub(results, samples = 5) {
92
+ const out = [];
93
+ for (const result of results) {
94
+ const file = escapeProperty(result.feed.replaceAll('\\', '/'));
95
+ if (result.fatal) {
96
+ out.push(`::error file=${file},title=feed-lint::${escapeData(result.fatal)}`);
97
+ continue;
98
+ }
99
+ for (const r of result.results) {
100
+ const title = escapeProperty(`feed-lint: ${r.title}`);
101
+ const total = r.count > 1 ? ` (${r.count} in this feed)` : '';
102
+ for (const s of r.samples.slice(0, samples)) {
103
+ const message = [s.id && `id ${s.id}`, s.detail].filter(Boolean).join(': ');
104
+ out.push(`::${r.level} file=${file},line=${s.line},title=${title}::${escapeData(`${message || r.title}${total}. ${r.rule} ${r.url}`)}`);
105
+ }
106
+ }
107
+ }
108
+ out.push(summary(results));
109
+ return out.join('\n');
110
+ }
111
+ export function render(results, format, options = {}) {
112
+ if (format === 'json')
113
+ return JSON.stringify(results.map(({ feed, fatal, ...rest }) => ({ feed, ...(fatal ? { fatal } : {}), ...rest })), null, 2);
114
+ if (format === 'markdown')
115
+ return formatMarkdown(results);
116
+ if (format === 'github')
117
+ return formatGithub(results);
118
+ return formatText(results, options);
119
+ }
120
+ export function onlyErrors(results) {
121
+ return results.map((r) => ({ ...r, results: r.results.filter((x) => x.level === 'error'), warnings: 0 }));
122
+ }
123
+ export function formatFromPath(path) {
124
+ if (/\.json$/i.test(path))
125
+ return 'json';
126
+ if (/\.(md|markdown)$/i.test(path))
127
+ return 'markdown';
128
+ return 'text';
129
+ }
@@ -0,0 +1,3 @@
1
+ export declare const USER_AGENT = "feed-lint (+https://github.com/mscode-pl/feed-lint)";
2
+ export declare const isUrl: (input: string) => boolean;
3
+ export declare function openInput(input: string): Promise<AsyncIterable<Uint8Array>>;
@@ -0,0 +1,27 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { stat } from 'node:fs/promises';
3
+ import { Readable } from 'node:stream';
4
+ import { createGunzip } from 'node:zlib';
5
+ export const USER_AGENT = 'feed-lint (+https://github.com/mscode-pl/feed-lint)';
6
+ // Covers the whole download, so it is generous enough for feeds of a few hundred MB.
7
+ const DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
8
+ export const isUrl = (input) => /^https?:\/\//i.test(input);
9
+ export async function openInput(input) {
10
+ if (isUrl(input)) {
11
+ const response = await fetch(input, {
12
+ headers: { 'user-agent': USER_AGENT, accept: 'application/xml, text/xml, */*' },
13
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
14
+ });
15
+ if (!response.ok || !response.body)
16
+ throw new Error(`${input}: HTTP ${response.status} ${response.statusText}`.trim());
17
+ const body = Readable.fromWeb(response.body);
18
+ // fetch only undoes Content-Encoding; a .gz file served as a download stays compressed.
19
+ const gzipFile = /\.gz(?:$|\?)/i.test(input) && /gzip|octet-stream/i.test(response.headers.get('content-type') ?? '');
20
+ return gzipFile ? body.pipe(createGunzip()) : body;
21
+ }
22
+ const info = await stat(input).catch(() => undefined);
23
+ if (!info?.isFile())
24
+ throw new Error(`${input}: file not found`);
25
+ const stream = createReadStream(input);
26
+ return /\.gz$/i.test(input) ? stream.pipe(createGunzip()) : stream;
27
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};