-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgenerate.ts
More file actions
382 lines (358 loc) · 9.96 KB
/
Copy pathgenerate.ts
File metadata and controls
382 lines (358 loc) · 9.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";
import { FACET_CONFIGS, FIELD_DEFINITIONS } from "./config";
import {
DEFAULT_STORAGE_FINDER_SHEET_URL,
FACET_TREE_FILENAME,
OUTPUT_DIRECTORY,
SERVICE_LIST_FILENAME,
STORAGE_FINDER_ENV_URL_KEY,
} from "./constants";
import { toHtmlBlocks } from "./html";
import {
type CsvRow,
type FacetConfig,
type FacetTreeChoice,
type FacetTreeQuestion,
type ServiceField,
type ServiceRecord,
} from "./types";
interface CliOptions {
csvPath?: string;
outputDir?: string;
pretty: boolean;
silent: boolean;
showHelp: boolean;
}
interface Logger {
log(message: string): void;
warn(message: string): void;
}
function parseArgs(argv: string[]): CliOptions {
const options: CliOptions = {
pretty: true,
silent: false,
showHelp: false,
};
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument.includes("=")) {
const [flag, explicitValue] = argument.split("=", 2);
switch (flag) {
case "--csv": {
options.csvPath = explicitValue;
break;
}
case "--output": {
options.outputDir = explicitValue;
break;
}
default: {
throw new Error(
`Unknown argument "${argument}". Use --help for usage.`,
);
}
}
continue;
}
switch (argument) {
case "--csv": {
options.csvPath = argv[index + 1];
index += 1;
break;
}
case "--output": {
options.outputDir = argv[index + 1];
index += 1;
break;
}
case "--no-pretty": {
options.pretty = false;
break;
}
case "--silent": {
options.silent = true;
break;
}
case "--help": {
options.showHelp = true;
break;
}
default: {
throw new Error(
`Unknown argument "${argument}". Use --help for usage.`,
);
}
}
}
return options;
}
function printHelp(): void {
const lines = [
"Usage: bun scripts/storage-finder-data-generator/generate.ts [options]",
"",
"--csv <path> Use a local CSV file instead of downloading",
"--output <dir> Custom output directory (defaults to src/data/storage-finder/generated)",
"--no-pretty Write minified JSON",
"--silent Suppress informational logs",
"--help Show this message",
"",
`Environment: ${STORAGE_FINDER_ENV_URL_KEY} overrides the CSV download URL.`,
];
console.log(lines.join("\n"));
}
function createLogger(silent: boolean): Logger {
if (silent) {
const noop = (..._args: unknown[]) => {
void _args;
};
return {
log: noop,
warn: noop,
};
}
return {
log(message: string) {
console.log(message);
},
warn(message: string) {
console.warn(message);
},
};
}
async function loadCsvSource(
csvPath: string | undefined,
logger: Logger,
): Promise<string> {
if (csvPath) {
logger.log(`Reading CSV from ${csvPath}`);
return readFile(csvPath, "utf8");
}
const url =
process.env[STORAGE_FINDER_ENV_URL_KEY] ?? DEFAULT_STORAGE_FINDER_SHEET_URL;
logger.log(`Downloading CSV from ${url}`);
const response = await fetch(url, { redirect: "follow" });
if (!response.ok) {
throw new Error(
`Failed to download CSV. HTTP ${response.status} ${response.statusText}`,
);
}
return response.text();
}
function parseCsv(csvContent: string): CsvRow[] {
const parsed = parse<CsvRow>(csvContent, {
columns: true,
skip_empty_lines: true,
trim: true,
});
return parsed.map((row) => mapUndefinedToEmptyStrings(row));
}
function mapUndefinedToEmptyStrings(row: CsvRow): CsvRow {
const mapped: CsvRow = {};
for (const key of Object.keys(row)) {
const value = row[key];
mapped[key] = value === undefined || value === null ? "" : String(value);
}
return mapped;
}
function buildServiceRecords(rows: CsvRow[], logger: Logger): ServiceRecord[] {
const services: ServiceRecord[] = [];
const seenIds = new Map<string, number>();
for (const [index, row] of rows.entries()) {
const title = (row.Title ?? "").trim();
if (title.length === 0) {
logger.warn(`Skipping row ${index + 1} because Title is missing.`);
continue;
}
const baseId = slugify(title);
const serviceId = resolveUniqueId(baseId, seenIds);
services.push(createServiceRecord(serviceId, title, row));
}
return services;
}
function createServiceRecord(
serviceId: string,
title: string,
row: CsvRow,
): ServiceRecord {
const fieldData = buildFieldData(row);
const facetMatches = collectFacetMatches(row, title);
return {
id: serviceId,
title,
facet_matches: facetMatches,
summary: null,
field_data: fieldData,
};
}
function buildFieldData(row: CsvRow): Record<string, ServiceField> {
const entries: [string, ServiceField][] = FIELD_DEFINITIONS.map(
(definition) => {
const rawValue = row[definition.column] ?? "";
const value =
definition.formatter?.(rawValue, row) ?? toHtmlBlocks(rawValue);
return [
definition.fieldKey,
{
value,
label: definition.label,
weight: definition.weight,
},
];
},
);
return Object.fromEntries(entries);
}
function collectFacetMatches(row: CsvRow, serviceTitle: string): string[] {
const identifiers = new Set<string>();
for (const config of FACET_CONFIGS) {
const value = row[config.column] ?? "";
const matches = matchFacetValue(value, config);
if (
config.controlType === "radio" &&
!config.allowMultipleMatches &&
matches.length > 1
) {
throw new Error(
`Service "${serviceTitle}" matched multiple options for radio facet "${config.name}": ${matches.join(", ")}`,
);
}
for (const match of matches) {
identifiers.add(match);
}
if (config.alwaysInclude) {
for (const extra of config.alwaysInclude) {
identifiers.add(extra);
}
}
}
return [...identifiers];
}
function matchFacetValue(value: string, config: FacetConfig): string[] {
const matches = new Set<string>();
for (const matcher of config.matchers) {
if (matcher.pattern.test(value)) {
for (const choice of matcher.choices) {
matches.add(choice);
}
}
}
if (matches.size > 0) {
return [...matches];
}
if (config.fallback === "all") {
return config.choices.map((choice) => choice.id);
}
return [...config.fallback];
}
function resolveUniqueId(baseId: string, seen: Map<string, number>): string {
if (!seen.has(baseId)) {
seen.set(baseId, 1);
return baseId;
}
const current = seen.get(baseId) ?? 1;
const next = current + 1;
seen.set(baseId, next);
return `${baseId}-${next}`;
}
function buildFacetTree(): FacetTreeQuestion[] {
return FACET_CONFIGS.map((config, index) => ({
id: config.id,
name: config.name,
control_type: config.controlType,
parent: "0",
weight: String(index * 2),
selected: false,
description: config.description ?? null,
choices: buildFacetChoices(config),
}));
}
function buildFacetChoices(config: FacetConfig): FacetTreeChoice[] {
return config.choices.map((choice) => ({
id: choice.id,
name: choice.name,
control_type: config.controlType,
parent: config.id,
weight: String(choice.weight),
selected: false,
description: choice.description ?? null,
}));
}
async function writeJson(
path: string,
data: unknown,
pretty: boolean,
): Promise<void> {
const spacing = pretty ? 2 : 0;
const content = JSON.stringify(data, null, spacing);
await writeFile(path, content + "\n", "utf8");
}
function slugify(value: string): string {
const normalized = value.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-");
const trimmed = normalized.replaceAll(/^-+|-+$/g, "");
if (trimmed.length === 0) {
return "service";
}
return trimmed;
}
async function main(): Promise<void> {
const options = parseArgs(process.argv.slice(2));
if (options.showHelp) {
printHelp();
return;
}
const logger = createLogger(options.silent);
const csvContent = await loadCsvSource(options.csvPath, logger);
const rows = parseCsv(csvContent);
if (rows.length === 0) {
throw new Error("CSV file did not contain any data rows.");
}
const services = buildServiceRecords(rows, logger);
const facetTree = buildFacetTree();
const outputDirectory = options.outputDir ?? OUTPUT_DIRECTORY;
await mkdir(outputDirectory, { recursive: true });
const serviceOutputPath = `${outputDirectory}/${SERVICE_LIST_FILENAME}`;
const facetOutputPath = `${outputDirectory}/${FACET_TREE_FILENAME}`;
await writeJson(serviceOutputPath, services, options.pretty);
await writeJson(facetOutputPath, facetTree, options.pretty);
await writeFile(
"src/pages/storage-finder-data.mdx",
buildSearchMdx(services),
"utf8",
);
logger.log(`Wrote ${services.length} services to ${serviceOutputPath}`);
logger.log(`Wrote ${facetTree.length} facets to ${facetOutputPath}`);
}
function stripHtml(value: string | undefined): string {
return (value ?? "")
.replaceAll(/<[^>]+>/g, " ")
.replaceAll(/\s+/g, " ")
.trim();
}
function buildSearchMdx(services: ServiceRecord[]): string {
return [
"# Storage Finder Data",
"",
"This page is generated from the Storage Finder data so the search index can crawl service details.",
"",
...services.map((service) =>
[
`## ${service.title}`,
"",
...Object.values(service.field_data).map((field) =>
[`### ${field.label}`, "", stripHtml(field.value), ""].join("\n"),
),
].join("\n"),
),
"",
].join("\n");
}
// eslint-disable-next-line unicorn/prefer-top-level-await
void (async () => {
try {
await main();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
}
})();