Commit 9a4749b587

9a4749b587b0c61cd4462c16bcabaf5b7d4f2505

parent: 660a1b8ac9

Unsigned

Alicia Sykes <alicia@omg.lol> · 2026-08-09 10:21 UTC

Fefactored fetching for logic

Layout: unified · split

web/.env.sample +1 −1
@@ -19,7 +19,7 @@ SITE_URL=''
19PUBLIC_API_URL='https://api.awesome-privacy.xyz' 19PUBLIC_API_URL='https://api.awesome-privacy.xyz'
20 20
21# Bearer token for the API's enrichment routes (/v1/enrich/*). 21# Bearer token for the API's enrichment routes (/v1/enrich/*).
22# Only needed at build-time, and only if the target API has auth enabled. 22# For build-time. Anon-callers be rate limited to 10 req/sec
23API_TOKEN='' 23API_TOKEN=''
24 24
25# GitHub API key (with pub repo read perms). 25# GitHub API key (with pub repo read perms).
web/src/components/things/DataActions.svelte +3 −3
@@ -31,8 +31,8 @@
31 source, 31 source,
32 }: Props = $props(); 32 }: Props = $props();
33 33
34 const lineNumbers = source?.lineNumbers; 34 const lineNumbers = $derived(source?.lineNumbers);
35 const yamlContent = source?.yaml ?? ''; 35 const yamlContent = $derived(source?.yaml ?? '');
36 36
37 const getGitHubSrcFile = () => { 37 const getGitHubSrcFile = () => {
38 if (lineNumbers) { 38 if (lineNumbers) {
@@ -55,7 +55,7 @@
55{#if history.length > 0} 55{#if history.length > 0}
56 <h4>Change History</h4> 56 <h4>Change History</h4>
57 <ul class="history"> 57 <ul class="history">
58 {#each history as h} 58 {#each history as h (h)}
59 <li> 59 <li>
60 <span class="history-badge {h.type}"> 60 <span class="history-badge {h.type}">
61 {h.type === 'added' 61 {h.type === 'added'
web/src/components/things/DeleteListing.svelte +7 −5
@@ -14,11 +14,13 @@
14 const apYaml = 14 const apYaml =
15 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml'; 15 'https://github.com/lissy93/awesome-privacy/blob/main/awesome-privacy.yml';
16 16
17 const yamlContent = source?.yaml ?? ''; 17 const yamlContent = $derived(source?.yaml ?? '');
18 const lineNumbers = source?.lineNumbers; 18 const lineNumbers = $derived(source?.lineNumbers);
19 const editLink = lineNumbers 19 const editLink = $derived(
20 ? `${apYaml}#L${lineNumbers.start}-L${lineNumbers.end}` 20 lineNumbers
21 : apYaml; 21 ? `${apYaml}#L${lineNumbers.start}-L${lineNumbers.end}`
22 : apYaml,
23 );
22</script> 24</script>
23 25
24<div class="actions"> 26<div class="actions">
web/src/components/things/DiscordDetailedInfo.astro +3 −1
@@ -50,7 +50,9 @@ const { discordData } = Astro.props;
50 class="banner" 50 class="banner"
51 width="300" 51 width="300"
52 src={discordData.banner} 52 src={discordData.banner}
53 alt={`${discordData.name} banner`} loading="lazy" /> 53 alt={`${discordData.name} banner`}
54 loading="lazy"
55 />
54 ) 56 )
55 } 57 }
56</div> 58</div>
web/src/components/things/DockerDetailedInfo.astro +20 −22
@@ -1,5 +1,5 @@
1--- 1---
2import type { TemplateResponse } from '@utils/fetch-docker-instructions'; 2import { dockerHubUrl, type TemplateResponse } from '@utils/fetch-docker-instructions';
3import { formatDate, timeAgo } from '@utils/dates-n-stuff'; 3import { formatDate, timeAgo } from '@utils/dates-n-stuff';
4 4
5interface Props { 5interface Props {
@@ -13,6 +13,10 @@ const formatBigNumber = (num: number): string => {
13 return num.toLocaleString(); 13 return num.toLocaleString();
14}; 14};
15 15
16const { user, name } = docker.dockerHubData || {};
17const imageRef =
18 user && name ? `${user}/${name}` : docker.template?.image || null;
19const imageUrl = imageRef && dockerHubUrl(imageRef);
16--- 20---
17 21
18<div class="docker-info-wrap"> 22<div class="docker-info-wrap">
@@ -54,24 +58,11 @@ const formatBigNumber = (num: number): string => {
54 </ul> 58 </ul>
55 )} 59 )}
56 60
57 {docker.dockerHubData && ( 61 {imageUrl && (
58 <h4>View on DockerHub</h4> 62 <h4>View on DockerHub</h4>
63 <a href={imageUrl} target="_blank" rel="noreferrer">{imageRef}</a>
59 )} 64 )}
60 65
61 {docker.dockerHubData && Object.keys(docker.dockerHubData).length > 0 && (
62 <a href={`https://hub.docker.com/r/${docker.dockerHubData.user}/${docker.dockerHubData.name}`} target="_blank">
63 {docker.dockerHubData.user}/{docker.dockerHubData.name}
64 </a>
65 )}
66
67 {!docker.dockerHubData && docker.template &&
68 (
69 <a href={`https://hub.docker.com/r/${docker.template.image}`} target="_blank">
70 {docker.template.image}
71 </a>
72 )
73 }
74
75 </div> 66 </div>
76 <div class="right"> 67 <div class="right">
77 {docker.usage && docker.usage.dockerRunCommand && ( 68 {docker.usage && docker.usage.dockerRunCommand && (
@@ -110,11 +101,15 @@ const formatBigNumber = (num: number): string => {
110 101
111 {docker.template && docker.template.volumes && ( 102 {docker.template && docker.template.volumes && (
112 <h4>Volume Mounting</h4> 103 <h4>Volume Mounting</h4>
113 <ul class="table"> 104 <ul class="table wide">
105 <li class="header">
106 <span class="lbl">Container Path</span>
107 <span class="val">Host Bind</span>
108 </li>
114 {docker.template.volumes.map((volume) => ( 109 {docker.template.volumes.map((volume) => (
115 <li> 110 <li>
116 <span class="lbl">{volume.bind}</span> 111 <span class="lbl">{volume.container}</span>
117 <span class="val">{volume.container || '(any)'}</span> 112 <span class="val">{volume.bind || '(anonymous)'}</span>
118 </li> 113 </li>
119 ))} 114 ))}
120 </ul> 115 </ul>
@@ -123,10 +118,10 @@ const formatBigNumber = (num: number): string => {
123 {docker.dockerHubData && docker.dockerHubData.permissions && ( 118 {docker.dockerHubData && docker.dockerHubData.permissions && (
124 <h4>Permissions</h4> 119 <h4>Permissions</h4>
125 <ul class="table"> 120 <ul class="table">
126 {Object.keys(docker.dockerHubData.permissions).map((perm) => ( 121 {Object.entries(docker.dockerHubData.permissions).map(([perm, granted]) => (
127 <li> 122 <li>
128 <span class="lbl">{perm}</span> 123 <span class="lbl">{perm}</span>
129 <span class="val">{perm ? '✅ Yes' : '❎ No'}</span> 124 <span class="val">{granted ? '✅ Yes' : '❎ No'}</span>
130 </li> 125 </li>
131 ))} 126 ))}
132 </ul> 127 </ul>
@@ -166,6 +161,9 @@ const formatBigNumber = (num: number): string => {
166 .table { 161 .table {
167 max-width: 15rem; 162 max-width: 15rem;
168 padding-left: 0; 163 padding-left: 0;
164 &.wide {
165 max-width: none;
166 }
169 li { 167 li {
170 display: flex; 168 display: flex;
171 justify-content: space-between; 169 justify-content: space-between;
web/src/components/things/GitHubDetailedInfo.astro +2 −4
@@ -282,10 +282,8 @@ const languageChart = `https://quickchart.io/chart?c=${generateChartData(gitHubD
282 } 282 }
283 } 283 }
284 284
285 .list-table { 285 .list-table li .val a :global(svg) {
286 li .val a :global(svg) { 286 width: 1rem;
287 width: 1rem;
288 }
289 } 287 }
290 288
291 @include detail-info-base; 289 @include detail-info-base;
web/src/components/things/ItemGitHubMetrics.astro +1 −1
@@ -137,7 +137,7 @@ const metrics = await getMetrics(github);
137 } 137 }
138 } 138 }
139 :global(svg) { 139 :global(svg) {
140 color: var(--foregroung); 140 color: var(--foreground);
141 width: var(--text-md); 141 width: var(--text-md);
142 height: var(--text-md); 142 height: var(--text-md);
143 } 143 }
web/src/components/things/RedditDetailedInfo.astro +3 −1
@@ -23,7 +23,9 @@ const { redditData } = Astro.props;
23 class="banner" 23 class="banner"
24 width="300" 24 width="300"
25 src={redditData.info.banner} 25 src={redditData.info.banner}
26 alt="Banner" loading="lazy" /> 26 alt="Banner"
27 loading="lazy"
28 />
27 ) 29 )
28 } 30 }
29 <ul class="list-table"> 31 <ul class="list-table">
web/src/pages/about.astro +26 −6
@@ -138,7 +138,13 @@ const licenseContent = async () => {
138 target="_blank" 138 target="_blank"
139 rel="noreferrer" 139 rel="noreferrer"
140 > 140 >
141 <img src={sponsor.avatarUrl} alt={sponsor.login || ""} width="80" height="80" loading="lazy" /> 141 <img
142 src={sponsor.avatarUrl}
143 alt={sponsor.login || ''}
144 width="80"
145 height="80"
146 loading="lazy"
147 />
142 <p>{sponsor.name || sponsor.login}</p> 148 <p>{sponsor.name || sponsor.login}</p>
143 </a> 149 </a>
144 ))} 150 ))}
@@ -147,7 +153,9 @@ const licenseContent = async () => {
147 <img 153 <img
148 class="fallback-img" 154 class="fallback-img"
149 src="https://readme-contribs.as93.net/sponsors/lissy93?perRow=12&shape=squircle&textColor=ffffff&limit=96" 155 src="https://readme-contribs.as93.net/sponsors/lissy93?perRow=12&shape=squircle&textColor=ffffff&limit=96"
150 alt="Sponsors" loading="lazy" /> 156 alt="Sponsors"
157 loading="lazy"
158 />
151 ) 159 )
152 } 160 }
153 161
@@ -167,7 +175,13 @@ const licenseContent = async () => {
167 target="_blank" 175 target="_blank"
168 rel="noreferrer" 176 rel="noreferrer"
169 > 177 >
170 <img src={contributor.avatar_url} alt={contributor.login || ""} width="80" height="80" loading="lazy" /> 178 <img
179 src={contributor.avatar_url}
180 alt={contributor.login || ''}
181 width="80"
182 height="80"
183 loading="lazy"
184 />
171 <p>{contributor.login}</p> 185 <p>{contributor.login}</p>
172 </a> 186 </a>
173 ))} 187 ))}
@@ -176,7 +190,9 @@ const licenseContent = async () => {
176 <img 190 <img
177 class="fallback-img" 191 class="fallback-img"
178 src="https://readme-contribs.as93.net/contributors/lissy93/awesome-privacy?perRow=12&shape=squircle&textColor=ffffff&limit=96" 192 src="https://readme-contribs.as93.net/contributors/lissy93/awesome-privacy?perRow=12&shape=squircle&textColor=ffffff&limit=96"
179 alt="Contributors" loading="lazy" /> 193 alt="Contributors"
194 loading="lazy"
195 />
180 ) 196 )
181 } 197 }
182 198
@@ -234,7 +250,9 @@ const licenseContent = async () => {
234 width="180" 250 width="180"
235 height="240" 251 height="240"
236 alt="Alicia Sykes" 252 alt="Alicia Sykes"
237 src="https://cdn.as93.net/profile-pictures/dsc_0597" loading="lazy" /> 253 src="https://cdn.as93.net/profile-pictures/dsc_0597"
254 loading="lazy"
255 />
238 </a> 256 </a>
239 <div class="socials"> 257 <div class="socials">
240 { 258 {
@@ -271,7 +289,9 @@ const licenseContent = async () => {
271 width="20" 289 width="20"
272 height="20" 290 height="20"
273 alt={project.title} 291 alt={project.title}
274 src={project.icon} loading="lazy" /> 292 src={project.icon}
293 loading="lazy"
294 />
275 <a href={project.link} target="_blank" rel="noreferrer"> 295 <a href={project.link} target="_blank" rel="noreferrer">
276 {project.title} 296 {project.title}
277 </a>{' '} 297 </a>{' '}
web/src/utils/fetch-android-info.ts +8 −22
@@ -1,30 +1,16 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5const extractPackage = (str: string): string => 3const extractPackage = (str: string): string =>
6 str.includes('id=') ? str.split('id=')[1] : str; 4 str.includes('id=') ? str.split('id=')[1] : str;
7 5
8export const fetchAndroidInfo = async ( 6export const fetchAndroidInfo = (
9 androidPackage: string, 7 androidPackage: string,
10): Promise<AndroidInfo | null> => { 8): Promise<AndroidInfo | null> =>
11 const pkg = extractPackage(androidPackage); 9 fetchEnrich<AndroidInfo>(
12 const endpoint = `${apiBase}/v1/enrich/android/${pkg}`; 10 'Android',
13 try { 11 `/v1/enrich/android/${extractPackage(androidPackage)}`,
14 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 12 androidPackage,
15 if (!res.ok) { 13 );
16 error(
17 'Android',
18 `HTTP ${res.status} for ${androidPackage} (${endpoint})`,
19 );
20 return null;
21 }
22 return await res.json();
23 } catch (err) {
24 error('Android', `Network error for ${androidPackage}: ${err}`);
25 return null;
26 }
27};
28 14
29interface Tracker { 15interface Tracker {
30 id: number; 16 id: number;
web/src/utils/fetch-discord-info.ts +8 −18
@@ -1,23 +1,13 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5export const fetchDiscordInfo = async ( 3export const fetchDiscordInfo = (
6 discordInvite: string, 4 discordInvite: string,
7): Promise<DiscordInfo | null> => { 5): Promise<DiscordInfo | null> =>
8 const endpoint = `${apiBase}/v1/enrich/discord/${discordInvite}`; 6 fetchEnrich<DiscordInfo>(
9 try { 7 'Discord',
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 8 `/v1/enrich/discord/${discordInvite}`,
11 if (!res.ok) { 9 discordInvite,
12 error('Discord', `HTTP ${res.status} for ${discordInvite} (${endpoint})`); 10 );
13 return null;
14 }
15 return await res.json();
16 } catch (err) {
17 error('Discord', `Network error for ${discordInvite}: ${err}`);
18 return null;
19 }
20};
21 11
22export interface DiscordInfo { 12export interface DiscordInfo {
23 inviteCode: string; 13 inviteCode: string;
web/src/utils/fetch-docker-instructions.ts +27 −29
@@ -1,29 +1,27 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5export const fetchDockerData = async ( 3export const fetchDockerData = (
6 serviceName: string, 4 serviceName: string,
7): Promise<TemplateResponse | null> => { 5): Promise<TemplateResponse | null> =>
8 const endpoint = `${apiBase}/v1/enrich/docker/${encodeURIComponent(serviceName)}`; 6 fetchEnrich<TemplateResponse>(
9 try { 7 'Docker',
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 8 `/v1/enrich/docker/${encodeURIComponent(serviceName)}`,
11 if (!res.ok) { 9 serviceName,
12 error('Docker', `HTTP ${res.status} for ${serviceName} (${endpoint})`); 10 { missingIsExpected: true },
13 return null; 11 );
14 }
15 return await res.json();
16 } catch (err) {
17 error('Docker', `Network error for ${serviceName}: ${err}`);
18 return null;
19 }
20};
21 12
22interface DockerTemplatePort { 13export const dockerHubUrl = (image: string): string | null => {
23 privatePort: number; 14 const segments = image.split('/');
24 publicPort: number; 15 if (segments.length > 1 && /[.:]/.test(segments[0])) return null;
25 type: string; // Typically TCP/UDP 16 const path = image.replace(/:[^/]*$/, '');
26} 17 const [namespace, repo] = path.includes('/')
18 ? path.split('/')
19 : ['library', path];
20 if (!repo) return null;
21 return namespace === 'library'
22 ? `https://hub.docker.com/_/${repo}`
23 : `https://hub.docker.com/r/${namespace}/${repo}`;
24};
27 25
28interface DockerTemplateEnvironmentVariable { 26interface DockerTemplateEnvironmentVariable {
29 name: string; 27 name: string;
@@ -33,22 +31,22 @@ interface DockerTemplateEnvironmentVariable {
33} 31}
34 32
35interface DockerTemplateVolume { 33interface DockerTemplateVolume {
36 bind: string;
37 container: string; 34 container: string;
35 bind?: string;
38 readonly?: boolean; 36 readonly?: boolean;
39} 37}
40 38
41interface DockerTemplate { 39interface DockerTemplate {
42 name?: string; 40 name?: string;
43 title: string; 41 title?: string;
44 description?: string; 42 description?: string;
45 logo?: string; 43 logo?: string;
46 image: string; 44 image?: string;
47 categories?: string[]; 45 categories?: string[];
48 ports?: DockerTemplatePort[]; 46 ports?: string[];
49 env?: DockerTemplateEnvironmentVariable[]; 47 env?: DockerTemplateEnvironmentVariable[];
50 volumes?: DockerTemplateVolume[]; 48 volumes?: DockerTemplateVolume[];
51 restart_policy?: string; // Typically "no", "always", "unless-stopped", "on-failure" 49 restart_policy?: string;
52} 50}
53 51
54interface DockerHubData { 52interface DockerHubData {
@@ -82,6 +80,6 @@ export interface TemplateResponse {
82 found: boolean; 80 found: boolean;
83 error: string | null; 81 error: string | null;
84 template?: DockerTemplate; 82 template?: DockerTemplate;
85 dockerHubData?: DockerHubData; 83 dockerHubData?: DockerHubData | null;
86 usage?: DockerUsage; 84 usage?: DockerUsage;
87} 85}
web/src/utils/fetch-enrich.ts added +30
@@ -0,0 +1,30 @@
1import { error, warn } from './logger';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4
5interface EnrichOptions {
6 // Yeah, it's legit got no upstream record, so 404 is correct/expected
7 missingIsExpected?: boolean;
8}
9
10export const fetchEnrich = async <T>(
11 source: string,
12 path: string,
13 subject: string,
14 { missingIsExpected = false }: EnrichOptions = {},
15): Promise<T | null> => {
16 const endpoint = `${apiBase}${path}`;
17 try {
18 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
19 if (res.ok) return (await res.json()) as T;
20 if (res.status !== 404) {
21 error(source, `HTTP ${res.status} for ${subject} (${endpoint})`);
22 } else if (!missingIsExpected) {
23 warn(source, `No upstream record for ${subject} (${endpoint})`);
24 }
25 return null;
26 } catch (err) {
27 error(source, `Network error for ${subject}: ${err}`);
28 return null;
29 }
30};
web/src/utils/fetch-ios-info.ts +7 −19
@@ -1,6 +1,4 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5// Pull the id from an App Store URL's `/id123` segment, else pass it through. 3// Pull the id from an App Store URL's `/id123` segment, else pass it through.
6const extractId = (iosUrl: string): string => { 4const extractId = (iosUrl: string): string => {
@@ -8,22 +6,12 @@ const extractId = (iosUrl: string): string => {
8 return match ? match[1] : iosUrl; 6 return match ? match[1] : iosUrl;
9}; 7};
10 8
11export const fetchIosInfo = async ( 9export const fetchIosInfo = (iosUrl: string): Promise<IoSApiResponse | null> =>
12 iosUrl: string, 10 fetchEnrich<IoSApiResponse>(
13): Promise<IoSApiResponse | null> => { 11 'iOS',
14 const endpoint = `${apiBase}/v1/enrich/ios/${extractId(iosUrl)}`; 12 `/v1/enrich/ios/${extractId(iosUrl)}`,
15 try { 13 iosUrl,
16 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 14 );
17 if (!res.ok) {
18 error('iOS', `HTTP ${res.status} for ${iosUrl} (${endpoint})`);
19 return null;
20 }
21 return await res.json();
22 } catch (err) {
23 error('iOS', `Network error for ${iosUrl}: ${err}`);
24 return null;
25 }
26};
27 15
28export interface IoSApiResponse { 16export interface IoSApiResponse {
29 artistViewUrl: string; 17 artistViewUrl: string;
web/src/utils/fetch-privacy-policy.ts +7 −18
@@ -1,26 +1,15 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5// Wrap the flat ToS;DR v3 record in the shape the app already consumes. 3// Wrap the flat ToS;DR v3 record in the shape the app already consumes.
6export const fetchTosdrPrivacy = async ( 4export const fetchTosdrPrivacy = async (
7 serviceId: string, 5 serviceId: string,
8): Promise<PrivacyPolicyResponse | null> => { 6): Promise<PrivacyPolicyResponse | null> => {
9 const endpoint = `${apiBase}/v1/enrich/privacy/${serviceId}`; 7 const parameters = await fetchEnrich<Params>(
10 try { 8 'ToS;DR',
11 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 9 `/v1/enrich/privacy/${serviceId}`,
12 if (!res.ok) { 10 `service ${serviceId}`,
13 error( 11 );
14 'ToS;DR', 12 return parameters && { error: 0, message: '', parameters };
15 `HTTP ${res.status} for service ${serviceId} (${endpoint})`,
16 );
17 return null;
18 }
19 return { error: 0, message: '', parameters: await res.json() };
20 } catch (err) {
21 error('ToS;DR', `Network error for service ${serviceId}: ${err}`);
22 return null;
23 }
24}; 13};
25 14
26interface Document { 15interface Document {
web/src/utils/fetch-reddit-info.ts +8 −18
@@ -1,23 +1,13 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5export const fetchRedditInfo = async ( 3export const fetchRedditInfo = (
6 subreddit: string, 4 subreddit: string,
7): Promise<RedditData | null> => { 5): Promise<RedditData | null> =>
8 const endpoint = `${apiBase}/v1/enrich/reddit/${subreddit}`; 6 fetchEnrich<RedditData>(
9 try { 7 'Reddit',
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 8 `/v1/enrich/reddit/${subreddit}`,
11 if (!res.ok) { 9 `r/${subreddit}`,
12 error('Reddit', `HTTP ${res.status} for r/${subreddit} (${endpoint})`); 10 );
13 return null;
14 }
15 return await res.json();
16 } catch (err) {
17 error('Reddit', `Network error for r/${subreddit}: ${err}`);
18 return null;
19 }
20};
21 11
22interface SubredditInfo { 12interface SubredditInfo {
23 name: string | null; 13 name: string | null;
web/src/utils/fetch-repo-info.ts +7 −16
@@ -1,26 +1,17 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5const normalizeRepo = (github: string): string => 3const normalizeRepo = (github: string): string =>
6 github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, ''); 4 github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, '');
7 5
8export const fetchGitHubStats = async ( 6export const fetchGitHubStats = (
9 github: string, 7 github: string,
10): Promise<GitHubStatsResponse | null> => { 8): Promise<GitHubStatsResponse | null> => {
11 const repo = normalizeRepo(github); 9 const repo = normalizeRepo(github);
12 const endpoint = `${apiBase}/v1/enrich/github/${repo}`; 10 return fetchEnrich<GitHubStatsResponse>(
13 try { 11 'GitHub Stats',
14 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 12 `/v1/enrich/github/${repo}`,
15 if (!res.ok) { 13 repo,
16 error('GitHub Stats', `HTTP ${res.status} for ${repo} (${endpoint})`); 14 );
17 return null;
18 }
19 return await res.json();
20 } catch (err) {
21 error('GitHub Stats', `Network error for ${repo}: ${err}`);
22 return null;
23 }
24}; 15};
25 16
26export interface GitHubStatsResponse { 17export interface GitHubStatsResponse {
web/src/utils/fetch-security-info.ts +7 −16
@@ -1,26 +1,17 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch';
3import { apiBase, enrichHeaders } from './api-config';
4 2
5const normalizeRepo = (github: string): string => 3const normalizeRepo = (github: string): string =>
6 github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, ''); 4 github.replace(/^https?:\/\/github\.com\//, '').replace(/\/+$/, '');
7 5
8export const fetchSecurityReport = async ( 6export const fetchSecurityReport = (
9 github: string, 7 github: string,
10): Promise<SecurityReportResponse | null> => { 8): Promise<SecurityReportResponse | null> => {
11 const repo = normalizeRepo(github); 9 const repo = normalizeRepo(github);
12 const endpoint = `${apiBase}/v1/enrich/security/${repo}`; 10 return fetchEnrich<SecurityReportResponse>(
13 try { 11 'Security Report',
14 const res = await safeFetch(endpoint, { headers: enrichHeaders() }); 12 `/v1/enrich/security/${repo}`,
15 if (!res.ok) { 13 repo,
16 error('Security Report', `HTTP ${res.status} for ${repo} (${endpoint})`); 14 );
17 return null;
18 }
19 return await res.json();
20 } catch (err) {
21 error('Security Report', `Network error for ${repo}: ${err}`);
22 return null;
23 }
24}; 15};
25 16
26export interface SecurityCheck { 17export interface SecurityCheck {
web/src/utils/fetch-website-info.ts +8 −20
@@ -1,23 +1,11 @@
1import { error } from './logger'; 1import { fetchEnrich } from './fetch-enrich';
2import { safeFetch } from './safe-fetch'; 2
3import { apiBase, enrichHeaders } from './api-config'; 3export const fetchWebsiteInfo = (url: string): Promise<WebsiteData | null> =>
4 4 fetchEnrich<WebsiteData>(
5export const fetchWebsiteInfo = async ( 5 'Website',
6 url: string, 6 `/v1/enrich/website?url=${encodeURIComponent(url)}`,
7): Promise<WebsiteData | null> => { 7 url,
8 const endpoint = `${apiBase}/v1/enrich/website?url=${encodeURIComponent(url)}`; 8 );
9 try {
10 const res = await safeFetch(endpoint, { headers: enrichHeaders() });
11 if (!res.ok) {
12 error('Website', `HTTP ${res.status} for ${url} (${endpoint})`);
13 return null;
14 }
15 return await res.json();
16 } catch (err) {
17 error('Website', `Network error for ${url}: ${err}`);
18 return null;
19 }
20};
21 9
22interface DNSRecord { 10interface DNSRecord {
23 target: string; 11 target: string;
web/src/utils/logger.ts +26 −22
@@ -6,7 +6,15 @@ interface LogEntry {
6 message: string; 6 message: string;
7} 7}
8 8
9const entries: LogEntry[] = []; 9// Astro loads the config and the bundled page code as separate instances of
10// this module, so the entries have to live somewhere both of them can see
11const store = globalThis as typeof globalThis & { buildFetchLog?: LogEntry[] };
12const entries = (store.buildFetchLog ??= []);
13
14const MAX_SHOWN_PER_SOURCE = 5;
15
16const plural = (count: number, noun: string) =>
17 `${count} ${noun}${count === 1 ? '' : 's'}`;
10 18
11export const warn = (source: string, message: string) => { 19export const warn = (source: string, message: string) => {
12 console.warn(`[${source}] ${message}`); 20 console.warn(`[${source}] ${message}`);
@@ -19,33 +27,29 @@ export const error = (source: string, message: string) => {
19}; 27};
20 28
21export const printSummary = () => { 29export const printSummary = () => {
22 if (entries.length === 0) return; 30 if (!entries.length) return;
23 31
24 const grouped: Record< 32 const grouped = new Map<string, LogEntry[]>();
25 string,
26 { errors: number; warnings: number; messages: string[] }
27 > = {};
28 for (const entry of entries) { 33 for (const entry of entries) {
29 if (!grouped[entry.source]) { 34 const group = grouped.get(entry.source);
30 grouped[entry.source] = { errors: 0, warnings: 0, messages: [] }; 35 if (group) group.push(entry);
31 } 36 else grouped.set(entry.source, [entry]);
32 const group = grouped[entry.source];
33 if (entry.level === 'error') group.errors++;
34 else group.warnings++;
35 group.messages.push(` ${entry.level.toUpperCase()}: ${entry.message}`);
36 } 37 }
37 38
38 console.log('\n───────────── Build fetch summary ──────────────'); 39 console.log('\n───────────── Build fetch summary ──────────────');
39 for (const [source, { errors, warnings, messages }] of Object.entries( 40 for (const [source, group] of grouped) {
40 grouped, 41 const errors = group.filter((entry) => entry.level === 'error').length;
41 )) { 42 const warnings = group.length - errors;
42 const parts = []; 43 const tally = [
43 if (errors) parts.push(`${errors} error${errors > 1 ? 's' : ''}`); 44 ...(errors ? [plural(errors, 'error')] : []),
44 if (warnings) parts.push(`${warnings} warning${warnings > 1 ? 's' : ''}`); 45 ...(warnings ? [plural(warnings, 'warning')] : []),
45 console.log(`[${source}] ${parts.join(', ')}`); 46 ];
46 for (const msg of messages) { 47 console.log(`[${source}] ${tally.join(', ')}`);
47 console.log(msg); 48 for (const { level, message } of group.slice(0, MAX_SHOWN_PER_SOURCE)) {
49 console.log(` ${level.toUpperCase()}: ${message}`);
48 } 50 }
51 const hidden = group.length - MAX_SHOWN_PER_SOURCE;
52 if (hidden > 0) console.log(` ...and ${hidden} more`);
49 } 53 }
50 console.log('────────────────────────────────────────────────\n'); 54 console.log('────────────────────────────────────────────────\n');
51 55