mirror of
https://github.com/dong-nz/cv.git
synced 2026-11-22 16:10:40 +07:00
153 lines
6.2 KiB
TypeScript
153 lines
6.2 KiB
TypeScript
// Generates src/types/content-ids.ts from the structure documents (spec-v5).
|
|||
|
|
//
|
||
|
|
// Deliberately imports nothing from src/: this script writes the module the
|
||
|
|
// src/ loaders depend on, so it has to run — and read — before that module
|
||
|
|
// exists. It validates only what a generated union requires (an id is a
|
||
|
|
// non-empty string, ids are unique, a category is a non-empty string);
|
||
|
|
// cross-document rules stay in src/i18n/validate.ts.
|
||
|
|
//
|
||
|
|
// Run by `predev` / `prebuild` / `prepare` (see package.json), so every type
|
||
|
|
// check sees a union that is exactly the id set the documents carry. The pure
|
||
|
|
// parts are exported for scripts/smoke-generated-ids.ts; `main` runs only when
|
||
|
|
// this file is executed.
|
||
|
|
|
||
|
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||
|
|
import { join, resolve } from 'node:path';
|
||
|
|
import { pathToFileURL } from 'node:url';
|
||
|
|
|
||
|
|
const ROOT = resolve(import.meta.dirname, '..');
|
||
|
|
const TARGET = join(ROOT, 'src/types/content-ids.ts');
|
||
|
|
|
||
|
|
export const SOURCE_FILES = {
|
||
|
|
projects: 'src/data/projects.json',
|
||
|
|
experience: 'src/data/experience.json',
|
||
|
|
skills: 'src/data/skills.json',
|
||
|
|
profile: 'src/data/profile.json',
|
||
|
|
} as const;
|
||
|
|
|
||
|
|
export type ContentDocuments = Record<keyof typeof SOURCE_FILES, unknown>;
|
||
|
|
|
||
|
|
export type GeneratedIds = {
|
||
|
|
output: string;
|
||
|
|
counts: { project: number; experience: number; skillGroup: number; philosophy: number; category: number };
|
||
|
|
};
|
||
|
|
|
||
|
|
// A duplicate id would make Record<…> narrower than the document, silently.
|
||
|
|
export function idsOf(rows: unknown, file: string): string[] {
|
||
|
|
if (!Array.isArray(rows)) throw new Error(`${file}: expected an array of records`);
|
||
|
|
const ids: string[] = [];
|
||
|
|
rows.forEach((row, index) => {
|
||
|
|
const id = row && typeof row === 'object' && 'id' in row ? row.id : undefined;
|
||
|
|
if (typeof id !== 'string' || id.length === 0) {
|
||
|
|
throw new Error(`${file}: record ${index} has no string "id"`);
|
||
|
|
}
|
||
|
|
if (ids.includes(id)) throw new Error(`${file}: duplicate id ${JSON.stringify(id)}`);
|
||
|
|
ids.push(id);
|
||
|
|
});
|
||
|
|
return ids;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Category values are whatever the projects use, first-use order — the label
|
||
|
|
// guard is validator rule 7, not a closed union (spec-v5 D4).
|
||
|
|
export function categoriesOf(rows: unknown, file: string): string[] {
|
||
|
|
if (!Array.isArray(rows)) throw new Error(`${file}: expected an array of records`);
|
||
|
|
const categories: string[] = [];
|
||
|
|
rows.forEach((row, index) => {
|
||
|
|
const category = row && typeof row === 'object' && 'category' in row ? row.category : undefined;
|
||
|
|
if (typeof category !== 'string' || category.length === 0) {
|
||
|
|
throw new Error(`${file}: record ${index} has no string "category"`);
|
||
|
|
}
|
||
|
|
if (!categories.includes(category)) categories.push(category);
|
||
|
|
});
|
||
|
|
return categories;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function philosophyIdsOf(document: unknown, file: string): string[] {
|
||
|
|
const list =
|
||
|
|
document && typeof document === 'object' && 'philosophy' in document ? document.philosophy : undefined;
|
||
|
|
if (!Array.isArray(list)) throw new Error(`${file}: "philosophy" must be an array of { id } records`);
|
||
|
|
return idsOf(list, `${file} → philosophy`);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Document order, one member per line, JSON.stringify for the literals so any
|
||
|
|
// slug is expressible. An empty document emits `never`: Record<never, T>
|
||
|
|
// accepts {} and X[] accepts [], which is what an emptied document needs.
|
||
|
|
export function renderUnion(name: string, members: readonly string[]): string {
|
||
|
|
if (members.length === 0) return `export type ${name} = never;`;
|
||
|
|
const literals = members.map((member) => JSON.stringify(member));
|
||
|
|
if (literals.length === 1) return `export type ${name} = ${literals[0]};`;
|
||
|
|
return `export type ${name} =\n${literals.map((literal) => ` | ${literal}`).join('\n')};`;
|
||
|
|
}
|
||
|
|
|
||
|
|
// The whole generated module for one set of documents. Deterministic: the same
|
||
|
|
// documents always produce the same bytes.
|
||
|
|
export function collectOutput(documents: ContentDocuments): GeneratedIds {
|
||
|
|
const projectIds = idsOf(documents.projects, SOURCE_FILES.projects);
|
||
|
|
const categoryValues = categoriesOf(documents.projects, SOURCE_FILES.projects);
|
||
|
|
const experienceIds = idsOf(documents.experience, SOURCE_FILES.experience);
|
||
|
|
const skillGroupIds = idsOf(documents.skills, SOURCE_FILES.skills);
|
||
|
|
const philosophyIds = philosophyIdsOf(documents.profile, SOURCE_FILES.profile);
|
||
|
|
|
||
|
|
const output = [
|
||
|
|
'// Generated by scripts/generate-content-types.ts — do not edit.',
|
||
|
|
`// Sources: ${SOURCE_FILES.projects}, ${SOURCE_FILES.experience},`,
|
||
|
|
`// ${SOURCE_FILES.skills}, ${SOURCE_FILES.profile}`,
|
||
|
|
'',
|
||
|
|
renderUnion('ProjectId', projectIds),
|
||
|
|
'',
|
||
|
|
renderUnion('ExperienceId', experienceIds),
|
||
|
|
'',
|
||
|
|
renderUnion('SkillGroupId', skillGroupIds),
|
||
|
|
'',
|
||
|
|
renderUnion('PhilosophyId', philosophyIds),
|
||
|
|
'',
|
||
|
|
renderUnion('ProjectCategory', categoryValues),
|
||
|
|
'',
|
||
|
|
].join('\n');
|
||
|
|
|
||
|
|
return {
|
||
|
|
output,
|
||
|
|
counts: {
|
||
|
|
project: projectIds.length,
|
||
|
|
experience: experienceIds.length,
|
||
|
|
skillGroup: skillGroupIds.length,
|
||
|
|
philosophy: philosophyIds.length,
|
||
|
|
category: categoryValues.length,
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
export function readDocuments(): ContentDocuments {
|
||
|
|
const documents = {} as ContentDocuments;
|
||
|
|
for (const [key, file] of Object.entries(SOURCE_FILES) as [keyof ContentDocuments, string][]) {
|
||
|
|
const path = join(ROOT, file);
|
||
|
|
if (!existsSync(path)) throw new Error(`${file} not found — the id unions are generated from it`);
|
||
|
|
documents[key] = JSON.parse(readFileSync(path, 'utf-8'));
|
||
|
|
}
|
||
|
|
return documents;
|
||
|
|
}
|
||
|
|
|
||
|
|
function main(): void {
|
||
|
|
let generated: GeneratedIds;
|
||
|
|
try {
|
||
|
|
generated = collectOutput(readDocuments());
|
||
|
|
} catch (error) {
|
||
|
|
console.error(`[FAIL] ${(error as Error).message}`);
|
||
|
|
process.exit(1);
|
||
|
|
}
|
||
|
|
// Byte-identical output for identical input; an unchanged file is not
|
||
|
|
// rewritten, so watchers and editors see no mtime churn on a plain `pnpm dev`.
|
||
|
|
if (!existsSync(TARGET) || readFileSync(TARGET, 'utf-8') !== generated.output) {
|
||
|
|
writeFileSync(TARGET, generated.output);
|
||
|
|
}
|
||
|
|
const { counts } = generated;
|
||
|
|
console.log(
|
||
|
|
`content ids generated (${counts.project} project, ${counts.experience} experience, ` +
|
||
|
|
`${counts.skillGroup} skill group, ${counts.philosophy} philosophy, ` +
|
||
|
|
`${counts.category} category) → src/types/content-ids.ts`,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||
|
|
main();
|
||
|
|
}
|