web/src/utils/fetch-line-numbers.ts

98 lines · 2779 bytes

 1import * as yaml from 'js-yaml';
 2import { error } from './logger';
 3import { safeFetch } from './safe-fetch';
 4
 5import type { AwesomePrivacy } from '../types/Service';
 6
 7export interface LineNumberRange {
 8  start: number;
 9  end: number;
10}
11
12export interface ServiceSource {
13  lineNumbers: LineNumberRange | null;
14  yaml: string;
15}
16
17export type LineNumberData = Record<
18  string,
19  Record<string, Record<string, ServiceSource>>
20>;
21
22const awesomePrivacyYamlPath =
23  'https://raw.githubusercontent.com/Lissy93/awesome-privacy/main/awesome-privacy.yml';
24
25const isServiceEnd = (line: string) =>
26  line.trim().length === 0 ||
27  line.startsWith('  - ') ||
28  line.includes('- name:') ||
29  line.includes('notableMentions:') ||
30  line.includes('furtherInfo:') ||
31  line.includes('wordOfWarning:');
32
33const findServiceRange = (
34  serviceName: string,
35  yamlLines: string[],
36  from: number,
37): LineNumberRange | null => {
38  const offset = yamlLines
39    .slice(from)
40    .findIndex((line) => line.trim() === `- name: ${serviceName}`);
41  if (offset === -1) return null;
42
43  const start = from + offset + 1;
44  const endOffset = yamlLines.slice(start).findIndex(isServiceEnd);
45  return {
46    start,
47    end: endOffset === -1 ? yamlLines.length : start + endOffset,
48  };
49};
50
51const makeResults = (
52  yamlObject: AwesomePrivacy,
53  yamlLines: string[],
54): LineNumberData => {
55  const results: LineNumberData = {};
56  let cursor = 0;
57  (yamlObject.categories || []).forEach((category) => {
58    results[category.name] = {};
59    (category.sections || []).forEach((section) => {
60      results[category.name][section.name] = {};
61      (section.services || []).forEach((service) => {
62        const lineNumbers = findServiceRange(service.name, yamlLines, cursor);
63        if (lineNumbers) cursor = lineNumbers.start;
64        results[category.name][section.name][service.name] = {
65          lineNumbers,
66          yaml: yaml.dump(service),
67        };
68      });
69    });
70  });
71  return results;
72};
73
74const buildLineNumbers = async (): Promise<LineNumberData> => {
75  try {
76    const res = await safeFetch(awesomePrivacyYamlPath, {}, 15000);
77    if (!res.ok) {
78      error('Data', `HTTP ${res.status} fetching awesome-privacy.yml`);
79      return {};
80    }
81    const text = await res.text();
82    return makeResults(yaml.load(text) as AwesomePrivacy, text.split('\n'));
83  } catch (err) {
84    error('Data', `Failed to build line numbers: ${err}`);
85    return {};
86  }
87};
88
89let cached: Promise<LineNumberData> | null = null;
90
91export const fetchLineNumbers = (): Promise<LineNumberData> =>
92  (cached ??= buildLineNumbers());
93
94export const fetchServiceSources = async (
95  categoryName: string,
96  sectionName: string,
97): Promise<Record<string, ServiceSource>> =>
98  (await fetchLineNumbers())[categoryName]?.[sectionName] ?? {};