vouchington-tooling 0.80.2 → 0.82.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/README.md CHANGED
@@ -675,6 +675,10 @@ import {
675
675
  parseGfmMarkdown,
676
676
  parseMarkdownTables,
677
677
  } from 'vouchington-tooling/markdown'
678
+ import {
679
+ checkMarkdownArticleLinks,
680
+ discoverMarkdownArticles,
681
+ } from 'vouchington-tooling/markdown-article-links'
678
682
  import { readResponseBody } from 'vouchington-tooling/http-body'
679
683
  import { runAstGrepRule } from 'vouchington-tooling/ast-grep-rule'
680
684
  import { parseReviewPayload, remapReviewComments } from 'vouchington-tooling/gha-review-payload'
@@ -789,6 +793,41 @@ exceedsLargeDiffThreshold(countDiffLineChanges(diffText), {
789
793
  })
790
794
  ```
791
795
 
796
+ `vouchington-tooling/markdown-article-links` checks rendered article links statically. It bundles no
797
+ markdown parser or renderer: the caller supplies all three callbacks.
798
+
799
+ ```ts
800
+ const inputs = await discoverMarkdownArticles('content/articles')
801
+ const offenders = await checkMarkdownArticleLinks({
802
+ inputs,
803
+ routePrefix: '/article/',
804
+ parse: (source) => ({ slug: frontmatter(source).slug, body: bodyOf(source) }),
805
+ rewrite: rewriteArticleLinks,
806
+ render: renderMarkdown, // may return a Promise
807
+ })
808
+ // [{ name: 'a.md', href: '/article/gone', reason: 'missing-target' }]
809
+ ```
810
+
811
+ `checkMarkdownArticleLinks({ inputs, routePrefix, parse, rewrite, render })` takes
812
+ `inputs: { name, source }[]` and derives each slug as `slug || basename(name, '.md')`. It renders
813
+ `rewrite(body)` for each input and reads every `href="…"` from the HTML. Hrefs with a scheme or a
814
+ leading `//` are skipped. For the rest it strips the query and fragment, then returns offenders
815
+ `{ name, href, reason }`:
816
+
817
+ - `residual-md`: the path still ends in `.md`.
818
+ - `missing-target`: the path is exactly `<routePrefix><slug>` with no further `/`, and no input
819
+ provides that slug.
820
+ - `duplicate-slug`: two or more inputs resolve to the same slug. Every such input is reported, with
821
+ the shared slug as `href`.
822
+
823
+ `discoverMarkdownArticles(root, { exclude, allowEmpty, listTrackedFiles })` returns the inputs. It
824
+ runs `git ls-files -z -- '*.md'` from `root` with an argv array and no shell, so only git-tracked
825
+ files count: untracked files are ignored. Only files directly under `root` are used; nested
826
+ directories are never searched. `README.md` is excluded by default, and `exclude` replaces that list
827
+ with the basenames you give it. The result is sorted by name (code-unit order). If nothing is found
828
+ it throws, because a wrong `root` must not pass silently; pass `allowEmpty: true` to get `[]`
829
+ instead. `listTrackedFiles(root)` replaces the git runner, for example in tests.
830
+
792
831
  This breaking minor removes `getDiffAgainstBase`; migrate callers to `processDiffCommand` and pass
793
832
  the command they need to run.
794
833
 
@@ -993,6 +1032,11 @@ random suffixes, viewport sizes, a 1x1 PNG fixture, RFC 6238 TOTP codes, and a t
993
1032
  reporter. The reporter prints one JSON line per test with the marker `playwright-test-lifecycle`.
994
1033
  `@playwright/test` is an optional peer. TOTP setup and cleanup stay with the caller.
995
1034
 
1035
+ `storybookBundleHasStory` returns `false` for a readable index without the requested story.
1036
+ An index request failure or non-OK HTTP response throws `StorybookIndexAccessError`, with
1037
+ `kind` (`request` or `http`) and an HTTP `status` when available. Its diagnostic omits request
1038
+ credentials and response bodies. Malformed JSON remains a hard failure.
1039
+
996
1040
  `createBrowserErrorsFixture`, `withMonitoredPage`, and `BrowserIssueMonitor` take the narrow
997
1041
  exported `MonitoredTestInfo` type (`attach`, `status`, `expectedStatus`, `timeout`) instead of
998
1042
  Playwright's full `TestInfo`. A real `TestInfo` is assignable to it, so no cast is needed.
@@ -0,0 +1,30 @@
1
+ export interface MarkdownArticleInput {
2
+ name: string;
3
+ source: string;
4
+ }
5
+ export interface ParsedMarkdownArticle {
6
+ slug?: string;
7
+ body: string;
8
+ }
9
+ export type MarkdownArticleLinkReason = 'residual-md' | 'missing-target' | 'duplicate-slug';
10
+ export interface MarkdownArticleLinkOffender {
11
+ name: string;
12
+ /** The offending href, or the shared slug for `duplicate-slug`. */
13
+ href: string;
14
+ reason: MarkdownArticleLinkReason;
15
+ }
16
+ export interface CheckMarkdownArticleLinksOptions {
17
+ inputs: readonly MarkdownArticleInput[];
18
+ /** Article route prefix, for example `/article/`. */
19
+ routePrefix: string;
20
+ parse: (source: string) => ParsedMarkdownArticle;
21
+ rewrite: (body: string) => string;
22
+ render: (markdown: string) => string | Promise<string>;
23
+ }
24
+ export declare function articleSlug(name: string, slug: string | undefined): string;
25
+ /**
26
+ * Renders every article and reports local links that still end in `.md`, links to a
27
+ * `<routePrefix><slug>` target no input provides, and slugs shared by more than one input.
28
+ * The caller supplies the parser, link rewriter and renderer; none is bundled here.
29
+ */
30
+ export declare function checkMarkdownArticleLinks(options: CheckMarkdownArticleLinksOptions): Promise<MarkdownArticleLinkOffender[]>;
@@ -0,0 +1,68 @@
1
+ import { basename } from 'node:path';
2
+ const EXTERNAL_HREF = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
3
+ const HREF_ATTRIBUTE = /(?<=\s)href\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi;
4
+ const ENTITIES = {
5
+ '&quot;': '"',
6
+ '&#39;': "'",
7
+ '&#x27;': "'",
8
+ '&lt;': '<',
9
+ '&gt;': '>',
10
+ };
11
+ function decodeEntities(value) {
12
+ return value
13
+ .replace(/&(?:quot|#39|#x27|lt|gt);/gi, (e) => ENTITIES[e.toLowerCase()])
14
+ .replace(/&amp;/gi, '&');
15
+ }
16
+ function slugExists(catalog, target) {
17
+ try {
18
+ return catalog.has(decodeURIComponent(target));
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ export function articleSlug(name, slug) {
25
+ return slug || basename(name, '.md');
26
+ }
27
+ function hrefsOf(html) {
28
+ return Array.from(html.matchAll(HREF_ATTRIBUTE), (match) => decodeEntities(match[1] ?? match[2] ?? match[3]));
29
+ }
30
+ function duplicateSlugOffenders(articles) {
31
+ const bySlug = new Map();
32
+ for (const { name, slug } of articles)
33
+ bySlug.set(slug, [...(bySlug.get(slug) ?? []), name]);
34
+ return [...bySlug].flatMap(([slug, names]) => names.length > 1
35
+ ? names.map((name) => ({ name, href: slug, reason: 'duplicate-slug' }))
36
+ : []);
37
+ }
38
+ /**
39
+ * Renders every article and reports local links that still end in `.md`, links to a
40
+ * `<routePrefix><slug>` target no input provides, and slugs shared by more than one input.
41
+ * The caller supplies the parser, link rewriter and renderer; none is bundled here.
42
+ */
43
+ export async function checkMarkdownArticleLinks(options) {
44
+ const articles = options.inputs.map((input) => {
45
+ const parsed = options.parse(input.source);
46
+ return { name: input.name, slug: articleSlug(input.name, parsed.slug), body: parsed.body };
47
+ });
48
+ const catalog = new Set(articles.map((article) => article.slug));
49
+ const offenders = duplicateSlugOffenders(articles);
50
+ for (const { name, body } of articles) {
51
+ const html = await options.render(options.rewrite(body));
52
+ for (const href of hrefsOf(html)) {
53
+ if (EXTERNAL_HREF.test(href))
54
+ continue;
55
+ const path = href.split(/[?#]/)[0];
56
+ if (path.endsWith('.md')) {
57
+ offenders.push({ name, href, reason: 'residual-md' });
58
+ }
59
+ else if (path.startsWith(options.routePrefix)) {
60
+ const target = path.slice(options.routePrefix.length);
61
+ if (!target.includes('/') && !slugExists(catalog, target)) {
62
+ offenders.push({ name, href, reason: 'missing-target' });
63
+ }
64
+ }
65
+ }
66
+ }
67
+ return offenders;
68
+ }
@@ -0,0 +1,18 @@
1
+ import type { MarkdownArticleInput } from './check.mts';
2
+ export type GitLsFilesRunner = (root: string) => Promise<string[]>;
3
+ export interface DiscoverMarkdownArticlesOptions {
4
+ /** Basenames to skip. Defaults to `['README.md']`. */
5
+ exclude?: readonly string[];
6
+ /** Return an empty list instead of throwing when nothing is found. Defaults to `false`. */
7
+ allowEmpty?: boolean;
8
+ /** Replaces the `git ls-files` runner; receives `root` and returns root-relative tracked paths. */
9
+ listTrackedFiles?: GitLsFilesRunner;
10
+ }
11
+ /** Runs `git ls-files -z -- '*.md'` with an argv array (no shell) from `root`. */
12
+ export declare function gitLsFiles(root: string): Promise<string[]>;
13
+ /**
14
+ * Lists git-tracked `*.md` files directly under `root` (not recursive), minus exclusions,
15
+ * and returns them as sorted `{ name, source }` inputs. Throws when none are found unless
16
+ * `allowEmpty` is set, so a wrong root cannot pass silently.
17
+ */
18
+ export declare function discoverMarkdownArticles(root: string, options?: DiscoverMarkdownArticlesOptions): Promise<MarkdownArticleInput[]>;
@@ -0,0 +1,29 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { promisify } from 'node:util';
5
+ const execFileAsync = promisify(execFile);
6
+ /** Runs `git ls-files -z -- '*.md'` with an argv array (no shell) from `root`. */
7
+ export async function gitLsFiles(root) {
8
+ const { stdout } = await execFileAsync('git', ['ls-files', '-z', '--', '*.md'], {
9
+ cwd: root,
10
+ maxBuffer: 64 * 1024 * 1024,
11
+ });
12
+ return stdout.split('\0').filter(Boolean);
13
+ }
14
+ /**
15
+ * Lists git-tracked `*.md` files directly under `root` (not recursive), minus exclusions,
16
+ * and returns them as sorted `{ name, source }` inputs. Throws when none are found unless
17
+ * `allowEmpty` is set, so a wrong root cannot pass silently.
18
+ */
19
+ export async function discoverMarkdownArticles(root, options = {}) {
20
+ const exclude = new Set(options.exclude ?? ['README.md']);
21
+ const tracked = await (options.listTrackedFiles ?? gitLsFiles)(root);
22
+ const names = tracked
23
+ .filter((path) => path.endsWith('.md') && !path.includes('/') && !exclude.has(path))
24
+ .sort((a, b) => (a < b ? -1 : 1));
25
+ if (names.length === 0 && !options.allowEmpty) {
26
+ throw new Error(`No git-tracked markdown articles found directly under ${root}`);
27
+ }
28
+ return Promise.all(names.map(async (name) => ({ name, source: await readFile(join(root, name), 'utf8') })));
29
+ }
@@ -0,0 +1,2 @@
1
+ export { articleSlug, checkMarkdownArticleLinks, type CheckMarkdownArticleLinksOptions, type MarkdownArticleInput, type MarkdownArticleLinkOffender, type MarkdownArticleLinkReason, type ParsedMarkdownArticle, } from './check.mts';
2
+ export { discoverMarkdownArticles, gitLsFiles, type DiscoverMarkdownArticlesOptions, type GitLsFilesRunner, } from './discover.mts';
@@ -0,0 +1,2 @@
1
+ export { articleSlug, checkMarkdownArticleLinks, } from "./check.mjs";
2
+ export { discoverMarkdownArticles, gitLsFiles, } from "./discover.mjs";
@@ -23,7 +23,7 @@ export { assertNoHorizontalScroll, getHorizontalOverflowState } from './mobile-a
23
23
  export type { HorizontalOverflowState } from './mobile-assertions.mts';
24
24
  export { openRadixDropdown } from './radix-select.mts';
25
25
  export { randomSuffix } from './random-id.mts';
26
- export { storybookBundleHasStory } from './storybook.mts';
26
+ export { StorybookIndexAccessError, storybookBundleHasStory } from './storybook.mts';
27
27
  export { TEST_PNG } from './test-fixtures.mts';
28
28
  export { TestLifecycleReporter };
29
29
  export type { TestLifecycleReporterOptions } from './test-lifecycle-reporter.mts';
@@ -14,7 +14,7 @@ export { installImageResponseGuard } from "./expect-no-broken-images.mjs";
14
14
  export { assertNoHorizontalScroll, getHorizontalOverflowState } from "./mobile-assertions.mjs";
15
15
  export { openRadixDropdown } from "./radix-select.mjs";
16
16
  export { randomSuffix } from "./random-id.mjs";
17
- export { storybookBundleHasStory } from "./storybook.mjs";
17
+ export { StorybookIndexAccessError, storybookBundleHasStory } from "./storybook.mjs";
18
18
  export { TEST_PNG } from "./test-fixtures.mjs";
19
19
  export { TestLifecycleReporter };
20
20
  export { generateTotpCode } from "./totp.mjs";
@@ -1,2 +1,7 @@
1
1
  import type { Page } from '@playwright/test';
2
+ export declare class StorybookIndexAccessError extends Error {
3
+ readonly kind: 'request' | 'http';
4
+ readonly status: number | undefined;
5
+ constructor(status?: number);
6
+ }
2
7
  export declare function storybookBundleHasStory(page: Page, id: string): Promise<boolean>;
@@ -1,13 +1,28 @@
1
+ const INDEX_PATH = '/storybook/index.json';
2
+ const REQUEST_TIMEOUT_MS = 5000;
3
+ export class StorybookIndexAccessError extends Error {
4
+ kind;
5
+ status;
6
+ constructor(status) {
7
+ super(status === undefined
8
+ ? `Storybook index ${INDEX_PATH} request failed (timeout bound: ${REQUEST_TIMEOUT_MS} ms)`
9
+ : `Storybook index ${INDEX_PATH} returned HTTP ${status}`);
10
+ this.name = 'StorybookIndexAccessError';
11
+ this.kind = status === undefined ? 'request' : 'http';
12
+ this.status = status;
13
+ }
14
+ }
1
15
  export async function storybookBundleHasStory(page, id) {
2
16
  let response;
3
17
  try {
4
- response = await page.request.get('/storybook/index.json', { timeout: 5000 });
18
+ response = await page.request.get(INDEX_PATH, { timeout: REQUEST_TIMEOUT_MS });
5
19
  }
6
20
  catch {
7
- return false;
21
+ // Playwright transport errors can contain request URLs and headers with credentials.
22
+ throw new StorybookIndexAccessError();
8
23
  }
9
24
  if (!response.ok())
10
- return false;
25
+ throw new StorybookIndexAccessError(response.status());
11
26
  const storyIndex = (await response.json());
12
27
  return id in (storyIndex.entries ?? {});
13
28
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vouchington-tooling",
3
- "version": "0.80.2",
3
+ "version": "0.82.0",
4
4
  "description": "Vouchington CLI and extractable tooling libraries.",
5
5
  "homepage": "https://github.com/vouchington/vouchington-tooling/tree/main/packages/vouchington-tooling#readme",
6
6
  "bugs": {
@@ -231,6 +231,11 @@
231
231
  "import": "./dist/markdown/index.mjs",
232
232
  "default": "./dist/markdown/index.mjs"
233
233
  },
234
+ "./markdown-article-links": {
235
+ "types": "./dist/markdown-article-links/index.d.mts",
236
+ "import": "./dist/markdown-article-links/index.mjs",
237
+ "default": "./dist/markdown-article-links/index.mjs"
238
+ },
234
239
  "./http-body": {
235
240
  "types": "./dist/http-body/index.d.mts",
236
241
  "import": "./dist/http-body/index.mjs",