refactor(ids): generate content id unions from the structure documents

scripts/generate-content-types.ts writes the gitignored src/types/content-ids.ts (id unions + project category values) from the four structure documents; wired as generate:ids / predev / prebuild / prepare. src/types/index.ts re-exports them type-only and keeps only the code-owned unions.

Edit mode now writes JSON only: the v4 union leg is deleted (saveIdUnions, diffIdsWithUnions, applyUnionChanges, readUnionBlock, the EditBar union card, edit.union.* labels). Validator rule 7 requires a label for every category a project uses, in both ui/projects.json documents.

Tests: smoke-draft.ts 11/11 (rename re-sluging + category-label rule replace checks 9-12); new scripts/smoke-generated-ids.ts 7/7. Verified: pnpm build (chunk names unchanged, no runtime reference to the generated module), lint with no new warnings, validate:content, resume HTML byte-identical before/after with identical documents.

Docs: spec-v5-generated-content-ids.md added; spec-v4-live-edit.md §3.1 marked superseded + §12 row 23; AGENTS.md and README.md updated.
This commit is contained in:
dong.nguyen committed 2026-10-24 13:16:18 +07:00
1 parent 1a1fc14d0e
commit a3662a9521
18 files changed
+732 -357

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
// 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();
}
+54 -86
View File
@@ -1,19 +1,28 @@
// Smoke test for the draft store (spec-v4 §5.1, §5.5, §5.6; registry per
// spec-v4-data-organization §6.1; id-union legs per §3.1).
// spec-v4-data-organization §6.1). Id unions are no longer the store's
// business — scripts/generate-content-types.ts derives them from these very
// documents (spec-v5), so what is checked here is the draft itself: text
// writes, record add/delete/rename, conflicts and rebase, and the validator
// rules a rejected edit is reported through.
// Run: pnpm tsx scripts/smoke-draft.ts
import { readFileSync } from 'node:fs';
import { DraftStore, applyUnionChanges, bundledBase, diffIdsWithUnions } from '../src/i18n/draft';
import { DraftStore, bundledBase } from '../src/i18n/draft';
import type { CategoryLabels } from '../src/i18n/validate';
import projectsEnUiJson from '../src/i18n/locales/en/ui/projects.json';
import projectsViUiJson from '../src/i18n/locales/vi/ui/projects.json';
const fail = (msg: string): never => {
console.error(`FAIL: ${msg}`);
process.exit(1);
};
// The file the save pipeline patches.
const TYPES = readFileSync(new URL('../src/types/index.ts', import.meta.url), 'utf8');
// Rule 7's read-only input, exactly as the edit session supplies it.
const LABELS: CategoryLabels = {
vi: projectsViUiJson.categories as Record<string, unknown>,
en: projectsEnUiJson.categories as Record<string, unknown>,
};
const bases = bundledBase();
const store = new DraftStore(structuredClone(bases));
const store = new DraftStore(structuredClone(bases), LABELS);
const projects = store.dataOf('projects') as { id: string }[];
const firstProject = projects[0].id;
@@ -65,7 +74,7 @@ if (!same) fail('restored draft differs from saved snapshot');
// 6. Conflict: base changed at a path the draft also touched → rebase reports
// a conflict; take-theirs (discardDocument) clears it.
const store2 = new DraftStore(structuredClone(bases));
const store2 = new DraftStore(structuredClone(bases), LABELS);
store2.setValue('vi', `projects.${firstProject}.summary`, 'MINE');
const driftedBase = structuredClone(bases);
(driftedBase['projects.vi'].data as Record<string, Record<string, string>>)[firstProject].summary = 'THEIRS';
@@ -77,7 +86,7 @@ if (store2.changedPaths('projects.vi').includes(`${firstProject}.summary`))
fail('take-theirs left draft residue');
// 7. Clean rebase: base changed at a DIFFERENT path → draft edit survives.
const store3 = new DraftStore(structuredClone(bases));
const store3 = new DraftStore(structuredClone(bases), LABELS);
store3.setValue('vi', `projects.${firstProject}.summary`, 'MINE');
const otherBase = structuredClone(bases);
const otherId = projects[1].id;
@@ -93,7 +102,7 @@ if (mergedText[otherId].summary !== 'THEIRS') fail('rebase lost the base edit');
// branch — the field still lives in the structure document) must gain a real
// array when a [0] path is committed; an object-keyed pseudo-array crashed
// TagListEditor's items.map on the re-render after the first tag edit.
const store4 = new DraftStore(structuredClone(bases));
const store4 = new DraftStore(structuredClone(bases), LABELS);
const baseVi = store4.dataOf('profile.vi') as Record<string, Record<string, unknown>>;
delete baseVi.currentInterests;
const tagEdit = store4.setValue('vi', 'profile.currentInterests[0]', 'NEW TAG');
@@ -102,55 +111,24 @@ const arr = (store4.dataOf('profile.vi') as Record<string, Record<string, unknow
if (!Array.isArray(arr)) fail(`setPath made ${JSON.stringify(arr)}, not an array`);
if (arr[0] !== 'NEW TAG') fail('array element not set');
// 9. The shipped documents and the shipped id unions agree. This is the check
// that was missing: a skill group deleted in edit mode left 'logistics-
// technology' in SkillGroupId, and `Record<SkillGroupId, …>` then failed the
// build with TS2741.
const drift = diffIdsWithUnions(new DraftStore(structuredClone(bases)), TYPES);
if (drift.added.length + drift.removed.length > 0)
fail(`documents and id unions disagree: ${JSON.stringify(drift)}`);
// 10. A deleted record prunes its union member — and only that line, in
// either line ending (git stores LF, a Windows checkout reads CRLF).
const store5 = new DraftStore(structuredClone(bases));
// 9. A skill-group delete removes the record and its text in both languages,
// and the draft still validates.
const store5 = new DraftStore(structuredClone(bases), LABELS);
const groupIds = (store5.dataOf('skills') as { id: string }[]).map((g) => g.id);
const victim = groupIds[groupIds.length - 1];
const delGroup = store5.deleteRecord('skill-group', { id: victim });
if (delGroup !== null) fail(`skill-group delete rejected: ${JSON.stringify(delGroup)}`);
const afterDelete = store5.validate();
if (afterDelete.length > 0) fail(`validate after delete: ${JSON.stringify(afterDelete)}`);
// The union leg follows ids whose documents actually landed.
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store5.markWritten(id, 'simulated-sha');
const stale = diffIdsWithUnions(store5, TYPES);
if (stale.added.length > 0) fail(`a delete reported additions: ${JSON.stringify(stale.added)}`);
if (stale.removed.length !== 1 || stale.removed[0].id !== victim || stale.removed[0].union !== 'SkillGroupId')
fail(`stale union member not reported: ${JSON.stringify(stale.removed)}`);
const pruned = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (pruned === null) fail('prune refused a multi-line union');
if (pruned.includes(`'${victim}'`)) fail('stale member survived the prune');
const EOL = TYPES.includes('\r\n') ? '\r\n' : '\n';
const expectedBlock = `export type SkillGroupId =${EOL}${groupIds
.filter((id) => id !== victim)
.map((id) => ` | '${id}'`)
.join(EOL)};${EOL}`;
const expected = TYPES.replace(/export type SkillGroupId =\r?\n(?:[ \t]*\| '[^']+';?\r?\n)+/, () => expectedBlock);
if (pruned !== expected) fail('prune rewrote more than the SkillGroupId member list');
const afterPrune = diffIdsWithUnions(store5, pruned);
if (afterPrune.added.length + afterPrune.removed.length > 0)
fail(`union still mismatched after the prune: ${JSON.stringify(afterPrune)}`);
const lfTypes = TYPES.replace(/\r\n/g, '\n');
const prunedLf = applyUnionChanges(lfTypes, [{ union: 'SkillGroupId', add: [], remove: [victim] }]);
if (prunedLf === null) fail('prune refused an LF union');
if (prunedLf.includes('\r\n')) fail('an LF patch introduced CRLF');
if (prunedLf !== expected.replace(/\r\n/g, '\n')) fail('LF patch differs from the LF source');
const afterPruneLf = diffIdsWithUnions(store5, prunedLf);
if (afterPruneLf.added.length + afterPruneLf.removed.length > 0)
fail(`union still mismatched after the LF prune: ${JSON.stringify(afterPruneLf)}`);
if ((store5.dataOf('skills.vi') as Record<string, unknown>)[victim])
fail('vi skill-group text orphan after delete');
if ((store5.dataOf('skills.en') as Record<string, unknown>)[victim])
fail('en skill-group text orphan after delete');
// 11. An id that also reads as a string elsewhere in the file is still
// appended. 'home' is a PageId member, so a substring test would have skipped
// this leg and the build would have broken the other way.
const store6 = new DraftStore(structuredClone(bases));
// 10. A created record keeps following its title: renaming re-sluges the id in
// the structure document and both text documents at once (E3). 'Home' → 'home'
// is the case a naive substring replacement would break.
const store6 = new DraftStore(structuredClone(bases), LABELS);
const addGroup = store6.addRecord('skill-group');
if (addGroup !== null) fail(`skill-group add rejected: ${JSON.stringify(addGroup)}`);
const known = new Set(groupIds);
@@ -158,41 +136,31 @@ const created = (store6.dataOf('skills') as { id: string }[]).find((g) => !known
if (!created) fail('no new skill group created');
const rename = store6.renameRecord('skill-group', { id: created.id }, 'Home');
if (rename !== null) fail(`rename rejected: ${JSON.stringify(rename)}`);
if (!(store6.dataOf('skills') as { id: string }[]).some((g) => g.id === 'home'))
fail('rename did not apply');
const renamed = (store6.dataOf('skills') as { id: string }[]).map((g) => g.id);
if (!renamed.includes('home')) fail('rename did not apply');
if (renamed.includes(created.id)) fail('the pre-rename id survived');
const renamedText = store6.dataOf('skills.vi') as Record<string, unknown>;
if (renamedText[created.id]) fail('text kept the pre-rename id');
if (!renamedText.home) fail('text did not follow the renamed id');
const afterRename = store6.validate();
if (afterRename.length > 0) fail(`validate after rename: ${JSON.stringify(afterRename)}`);
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store6.markWritten(id, 'simulated-sha');
const missing = diffIdsWithUnions(store6, TYPES);
if (!missing.added.some((a) => a.union === 'SkillGroupId' && a.id === 'home'))
fail(`id colliding with another union member was not appended: ${JSON.stringify(missing.added)}`);
if (missing.removed.length > 0) fail(`an add reported removals: ${JSON.stringify(missing.removed)}`);
const appended = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: ['home'], remove: [] }]);
if (appended === null) fail('append refused a multi-line union');
const afterAppend = diffIdsWithUnions(store6, appended);
if (afterAppend.added.length + afterAppend.removed.length > 0)
fail(`union still mismatched after the append: ${JSON.stringify(afterAppend)}`);
// 12. An emptied document prunes its union to `never`, and a record added on
// top of that state is appended back rather than silently skipped.
const emptied = applyUnionChanges(TYPES, [{ union: 'SkillGroupId', add: [], remove: groupIds }]);
if (emptied === null) fail('prune of every member refused');
if (!emptied.includes('export type SkillGroupId = never;')) fail('emptied union is not never');
const store7 = new DraftStore(structuredClone(bases));
if (store7.addRecord('skill-group') !== null) fail('skill-group add rejected on a never union');
const addedGroup = (store7.dataOf('skills') as { id: string }[]).find((g) => !known.has(g.id));
if (!addedGroup) fail('no new skill group created for the never case');
for (const id of ['skills', 'skills.vi', 'skills.en'] as const) store7.markWritten(id, 'simulated-sha');
const revived = diffIdsWithUnions(store7, emptied);
if (!revived.added.some((a) => a.union === 'SkillGroupId' && a.id === addedGroup.id))
fail(`never union skipped the new id: ${JSON.stringify(revived.added)}`);
if (revived.removed.length > 0) fail(`the never case reported removals: ${JSON.stringify(revived.removed)}`);
const back = applyUnionChanges(
emptied,
[{ union: 'SkillGroupId', add: revived.added.map((a) => a.id), remove: [] }],
);
if (back === null) fail('append onto never refused');
const afterNever = diffIdsWithUnions(store7, back);
if (afterNever.added.length + afterNever.removed.length > 0)
fail(`never round-trip left a mismatch: ${JSON.stringify(afterNever)}`);
console.log('draft store smoke: all 12 checks passed');
// 11. Rule 7 (spec-v5 D4): a category a project uses must have a label in
// both languages — the badge would render empty. The category union is
// generated from the documents, so a value written straight into
// src/data/projects.json is exactly what this catches.
const store7 = new DraftStore(structuredClone(bases), LABELS);
const rejectedCategory = store7.setStructured('projects', '[0].category', 'not-a-category');
if (rejectedCategory === null) fail('a label-less category was accepted');
const issuePaths = rejectedCategory.map((issue) => issue.path).sort();
const expectedPaths = [
'src/i18n/locales/en/ui/projects.json: categories.not-a-category',
'src/i18n/locales/vi/ui/projects.json: categories.not-a-category',
].sort();
if (JSON.stringify(issuePaths) !== JSON.stringify(expectedPaths))
fail(`rule 7 reported the wrong issues: ${JSON.stringify(issuePaths)}`);
if (store7.isDirty()) fail('a rejected structure write mutated the draft');
const acceptedCategory = store7.setStructured('projects', '[0].category', 'logistics');
if (acceptedCategory !== null) fail(`labeled category rejected: ${JSON.stringify(acceptedCategory)}`);
console.log('draft store smoke: all 11 checks passed');
+150
View File
@@ -0,0 +1,150 @@
// Smoke test for the content-id generator (spec-v5 §5.5): what the generated
// module must guarantee — the union is exactly the document, in document order,
// an emptied document is `never`, a malformed document is refused with its path,
// and the same documents always produce the same bytes.
// Run: pnpm tsx scripts/smoke-generated-ids.ts
import { readFileSync } from 'node:fs';
import { collectOutput, readDocuments } from './generate-content-types';
const fail = (msg: string): never => {
console.error(`FAIL: ${msg}`);
process.exit(1);
};
const readJson = (relative: string): unknown =>
JSON.parse(readFileSync(new URL(relative, import.meta.url), 'utf8'));
// The documents read the way a reader would: checked, then used.
function idsFrom(value: unknown, label: string): string[] {
if (!Array.isArray(value)) fail(`${label}: expected an array of records`);
return value.map((row, index) => {
const id = row && typeof row === 'object' && 'id' in row ? row.id : undefined;
if (typeof id !== 'string') fail(`${label}: record ${index} has no string id`);
return id;
});
}
function categoriesFrom(value: unknown, label: string): string[] {
if (!Array.isArray(value)) fail(`${label}: expected an array of records`);
const categories: string[] = [];
value.forEach((row, index) => {
const category = row && typeof row === 'object' && 'category' in row ? row.category : undefined;
if (typeof category !== 'string') fail(`${label}: record ${index} has no string category`);
if (!categories.includes(category)) categories.push(category);
});
return categories;
}
// The unions as a reader sees them, parsed straight out of the generated text.
function unionMembers(text: string, name: string): string[] {
const declaration = new RegExp(`export type ${name} =([^;]*);`, 'm').exec(text);
if (!declaration) fail(`no ${name} declaration in the generated module`);
const body = declaration[1].trim();
if (body === 'never') return [];
return [...body.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((literal) => JSON.parse(`"${literal[1]}"`));
}
const throwsWithPath = (fn: () => unknown, file: string, label: string): void => {
try {
fn();
} catch (error) {
const message = (error as Error).message;
if (!message.includes(file)) fail(`${label} did not name ${file}: ${message}`);
return;
}
fail(`${label} was accepted`);
};
const generated = collectOutput(readDocuments());
// 1. The shipped documents and the shipped module agree — every union is exactly
// the ids its document carries, in document order, with nothing left over. This
// is the guarantee the hand-written unions could not keep (a deleted skill group
// left 'logistics-technology' behind and the build failed with TS2741).
const projectsDoc = readJson('../src/data/projects.json');
const projectIds = idsFrom(projectsDoc, 'projects.json');
const categoryValues = categoriesFrom(projectsDoc, 'projects.json');
const experienceIds = idsFrom(readJson('../src/data/experience.json'), 'experience.json');
const skillGroupIds = idsFrom(readJson('../src/data/skills.json'), 'skills.json');
const profileDoc = readJson('../src/data/profile.json');
const philosophyList =
profileDoc && typeof profileDoc === 'object' && 'philosophy' in profileDoc ? profileDoc.philosophy : undefined;
const philosophyIds = idsFrom(philosophyList, 'profile.json → philosophy');
const expected: Record<string, string[]> = {
ProjectId: projectIds,
ExperienceId: experienceIds,
SkillGroupId: skillGroupIds,
PhilosophyId: philosophyIds,
ProjectCategory: categoryValues,
};
for (const [name, ids] of Object.entries(expected)) {
const emitted = unionMembers(generated.output, name);
if (JSON.stringify(emitted) !== JSON.stringify(ids))
fail(`${name} does not match its document: ${JSON.stringify(emitted)} vs ${JSON.stringify(ids)}`);
}
// 2. The file on disk is what these very documents produce right now — a
// generated module that drifted from its sources is a build-time lie.
const onDisk = readFileSync(new URL('../src/types/content-ids.ts', import.meta.url), 'utf8');
if (onDisk !== generated.output) fail('src/types/content-ids.ts is not what the documents generate');
// 3. Determinism: the same documents, the same bytes, twice.
if (collectOutput(readDocuments()).output !== generated.output)
fail('generation is not byte-stable for the same input');
// 4. An emptied document generates `never`, which keeps Record<never, T> valid
// against an empty text document and X[] valid against an empty array.
const emptied = collectOutput({ projects: [], experience: [], skills: [], profile: { philosophy: [] } });
for (const name of Object.keys(expected)) {
if (!emptied.output.includes(`export type ${name} = never;`)) fail(`${name} of an empty document is not never`);
if (unionMembers(emptied.output, name).length !== 0) fail(`${name} never still lists members`);
}
// 5. A duplicate id is refused, naming the file: a duplicate would make the
// union narrower than the document, silently.
throwsWithPath(
() => collectOutput({ projects: [{ id: 'a', category: 'x' }, { id: 'a', category: 'y' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a duplicate id',
);
// 6. A record without a usable id or category is refused, naming the file.
throwsWithPath(
() => collectOutput({ projects: [{ category: 'x' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a record with no id',
);
throwsWithPath(
() => collectOutput({ projects: [{ id: 'a' }], experience: [], skills: [], profile: { philosophy: [] } }),
'src/data/projects.json',
'a record with no category',
);
throwsWithPath(
() => collectOutput({ projects: [], experience: { id: 'oops' }, skills: [], profile: { philosophy: [] } }),
'src/data/experience.json',
'a document that is not an array',
);
throwsWithPath(
() => collectOutput({ projects: [], experience: [], skills: [], profile: {} }),
'src/data/profile.json',
'a missing philosophy array',
);
// 7. Any slug is expressible: a literal is quoted so it round-trips, and the
// document order is preserved rather than sorted.
const odd = collectOutput({
projects: [
{ id: 'b"quote', category: 'a category' },
{ id: 'a-first', category: 'a category' },
],
experience: [],
skills: [],
profile: { philosophy: [] },
});
if (JSON.stringify(unionMembers(odd.output, 'ProjectId')) !== JSON.stringify(['b"quote', 'a-first']))
fail(`quoted or ordered ids were mangled: ${JSON.stringify(unionMembers(odd.output, 'ProjectId'))}`);
if (JSON.stringify(unionMembers(odd.output, 'ProjectCategory')) !== JSON.stringify(['a category']))
fail('a category was duplicated or reordered');
console.log('generated content ids: all 7 checks passed');
+4 -1
View File
@@ -34,7 +34,10 @@ const contentEn: ContentEn = {
const structures = { profile, skills: skillGroups, experience: experiences, projects };
const issues = [
...collectContentIssues(structures, contentVi, contentEn),
...collectContentIssues(structures, contentVi, contentEn, {
vi: UI.vi.projects.categories,
en: UI.en.projects.categories,
}),
...collectManifestIssues(structures, contentVi, contentEn, Object.keys(UI.vi)),
];