2026-10-22 09:55:24 +07:00
|
|
|
// Draft store (spec-v4 §5.1, §5.5, §5.6, §6.1): the live branch documents
|
|
|
|
|
// fetched through the proxy, a copy-on-write draft over them, changed-path
|
|
|
|
|
// tracking, cross-document validation on every accepted edit, sessionStorage
|
2026-10-23 09:51:28 +07:00
|
|
|
// durability, and the sequential-PUT save pipeline with blob-sha
|
2026-10-22 09:55:24 +07:00
|
|
|
// optimistic concurrency. Pure logic — the React glue lives in EditModeShell.
|
2026-10-23 10:55:29 +07:00
|
|
|
import experienceEnTextJson from './locales/en/content/experience.json';
|
|
|
|
|
import experienceViTextJson from './locales/vi/content/experience.json';
|
|
|
|
|
import profileEnTextJson from './locales/en/content/profile.json';
|
|
|
|
|
import profileViTextJson from './locales/vi/content/profile.json';
|
|
|
|
|
import projectsEnTextJson from './locales/en/content/projects.json';
|
|
|
|
|
import projectsViTextJson from './locales/vi/content/projects.json';
|
|
|
|
|
import skillsEnTextJson from './locales/en/content/skills.json';
|
|
|
|
|
import skillsViTextJson from './locales/vi/content/skills.json';
|
2026-10-22 09:55:24 +07:00
|
|
|
import experienceJson from '../data/experience.json';
|
|
|
|
|
import profileJson from '../data/profile.json';
|
|
|
|
|
import projectsJson from '../data/projects.json';
|
|
|
|
|
import skillsJson from '../data/skills.json';
|
|
|
|
|
import { collectContentIssues } from './validate';
|
|
|
|
|
import type { ContentIssue, ContentStructures } from './validate';
|
|
|
|
|
import type { ContentEn, ContentVi } from './dict-types';
|
|
|
|
|
import type { Language } from '../types/index';
|
|
|
|
|
|
|
|
|
|
export type DraftDocId =
|
|
|
|
|
| 'profile'
|
|
|
|
|
| 'skills'
|
|
|
|
|
| 'experience'
|
|
|
|
|
| 'projects'
|
2026-10-23 10:55:29 +07:00
|
|
|
| 'profile.vi'
|
|
|
|
|
| 'profile.en'
|
|
|
|
|
| 'skills.vi'
|
|
|
|
|
| 'skills.en'
|
|
|
|
|
| 'experience.vi'
|
|
|
|
|
| 'experience.en'
|
|
|
|
|
| 'projects.vi'
|
|
|
|
|
| 'projects.en';
|
2026-10-22 09:55:24 +07:00
|
|
|
|
|
|
|
|
export type DraftDocMeta = {
|
|
|
|
|
id: DraftDocId;
|
|
|
|
|
file: string;
|
|
|
|
|
kind: 'structure' | 'text';
|
|
|
|
|
lang?: Language;
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// The twelve documents an edit session may write: four structure documents
|
|
|
|
|
// plus one text document per entity per language (spec-v4-data-organization
|
|
|
|
|
// §6.1). The page manifests and the UI group files are read-only in the app
|
|
|
|
|
// and never enter a draft.
|
2026-10-22 09:55:24 +07:00
|
|
|
export const DRAFT_DOCS: readonly DraftDocMeta[] = [
|
|
|
|
|
{ id: 'profile', file: 'src/data/profile.json', kind: 'structure' },
|
|
|
|
|
{ id: 'skills', file: 'src/data/skills.json', kind: 'structure' },
|
|
|
|
|
{ id: 'experience', file: 'src/data/experience.json', kind: 'structure' },
|
|
|
|
|
{ id: 'projects', file: 'src/data/projects.json', kind: 'structure' },
|
2026-10-23 10:55:29 +07:00
|
|
|
{ id: 'profile.vi', file: 'src/i18n/locales/vi/content/profile.json', kind: 'text', lang: 'vi' },
|
|
|
|
|
{ id: 'profile.en', file: 'src/i18n/locales/en/content/profile.json', kind: 'text', lang: 'en' },
|
|
|
|
|
{ id: 'skills.vi', file: 'src/i18n/locales/vi/content/skills.json', kind: 'text', lang: 'vi' },
|
|
|
|
|
{ id: 'skills.en', file: 'src/i18n/locales/en/content/skills.json', kind: 'text', lang: 'en' },
|
|
|
|
|
{ id: 'experience.vi', file: 'src/i18n/locales/vi/content/experience.json', kind: 'text', lang: 'vi' },
|
|
|
|
|
{ id: 'experience.en', file: 'src/i18n/locales/en/content/experience.json', kind: 'text', lang: 'en' },
|
|
|
|
|
{ id: 'projects.vi', file: 'src/i18n/locales/vi/content/projects.json', kind: 'text', lang: 'vi' },
|
|
|
|
|
{ id: 'projects.en', file: 'src/i18n/locales/en/content/projects.json', kind: 'text', lang: 'en' },
|
2026-10-22 09:55:24 +07:00
|
|
|
];
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Text entities, keyed by the leading path segment a text write carries
|
|
|
|
|
// (`profile.bio` → entity `profile`). The record name is the joined-record
|
|
|
|
|
// key the page manifests use (spec-v4-data-organization §3) — the mapping is
|
|
|
|
|
// needed only there, so it lives in src/data/pages.ts.
|
|
|
|
|
export const TEXT_ENTITIES = ['profile', 'skills', 'experience', 'projects'] as const;
|
|
|
|
|
export type TextEntity = (typeof TEXT_ENTITIES)[number];
|
|
|
|
|
|
|
|
|
|
export function textDocId(entity: TextEntity, lang: Language): DraftDocId {
|
|
|
|
|
return `${entity}.${lang}` as DraftDocId;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// A text path carries its entity as the first segment; inside the entity's
|
|
|
|
|
// text document the pointer is the rest (E7: the provenance chip shows
|
|
|
|
|
// `locales/vi/content/profile.json → bio`).
|
|
|
|
|
export function splitTextPath(path: string): { entity: TextEntity; rest: string } | null {
|
|
|
|
|
const dot = path.indexOf('.');
|
|
|
|
|
const head = dot < 0 ? path : path.slice(0, dot);
|
|
|
|
|
if (!TEXT_ENTITIES.includes(head as TextEntity)) return null;
|
|
|
|
|
return { entity: head as TextEntity, rest: dot < 0 ? '' : path.slice(dot + 1) };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The entity a draft document belongs to: text documents carry it in the id
|
|
|
|
|
// (`projects.vi`), structure documents are named by it. EditBar uses this to
|
|
|
|
|
// group changed paths against the page manifests (spec-v4-data-organization §6.3).
|
|
|
|
|
const STRUCTURE_ENTITY: Record<string, TextEntity> = {
|
|
|
|
|
profile: 'profile',
|
|
|
|
|
skills: 'skills',
|
|
|
|
|
experience: 'experience',
|
|
|
|
|
projects: 'projects',
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export function entityOfDoc(id: DraftDocId): TextEntity | null {
|
|
|
|
|
const dot = id.indexOf('.');
|
|
|
|
|
if (dot >= 0) return id.slice(0, dot) as TextEntity;
|
|
|
|
|
return STRUCTURE_ENTITY[id] ?? null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 09:55:24 +07:00
|
|
|
export const PROXY_BASE = '/api/content/';
|
|
|
|
|
export const TYPES_FILE = 'src/types/index.ts';
|
|
|
|
|
|
|
|
|
|
export function proxyUrl(file: string, ref: string): string {
|
|
|
|
|
return `${PROXY_BASE}${file}?ref=${encodeURIComponent(ref)}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- JSON paths -----------------------------------------------------------------
|
|
|
|
|
// A path is a dot-separated chain of object keys and [n] array indices, e.g.
|
|
|
|
|
// `projects.iot-dws-integration.sections.tldr.content` or
|
|
|
|
|
// `profile.tagline[2].text` — the same shape the EditBar and validator print.
|
|
|
|
|
|
|
|
|
|
export type PathSeg = string | number;
|
|
|
|
|
|
|
|
|
|
export function parsePath(path: string): PathSeg[] {
|
|
|
|
|
const out: PathSeg[] = [];
|
|
|
|
|
for (const m of path.matchAll(/([^.[\]]+)|\[(\d+)\]/g)) {
|
|
|
|
|
out.push(m[2] !== undefined ? Number(m[2]) : m[1]);
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function getPath(root: unknown, segs: PathSeg[]): unknown {
|
|
|
|
|
let cur: unknown = root;
|
|
|
|
|
for (const seg of segs) {
|
|
|
|
|
if (cur === undefined || cur === null) return undefined;
|
|
|
|
|
cur = (cur as Record<PathSeg, unknown>)[seg];
|
|
|
|
|
}
|
|
|
|
|
return cur;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function setPath(root: unknown, segs: PathSeg[], value: unknown): unknown {
|
|
|
|
|
if (segs.length === 0) return value;
|
|
|
|
|
const [head, ...rest] = segs;
|
2026-10-23 09:31:45 +07:00
|
|
|
// A missing container under a numeric segment is an array. A text document
|
|
|
|
|
// that does not hold the field yet (an older target branch, e.g.
|
|
|
|
|
// `profile.currentInterests` still living in the old structure document)
|
|
|
|
|
// must not gain an object-keyed pseudo-array — that shape crashed every
|
|
|
|
|
// consumer doing items.map on the re-render after the first commit.
|
2026-10-22 09:55:24 +07:00
|
|
|
const copy = (
|
2026-10-23 09:31:45 +07:00
|
|
|
Array.isArray(root)
|
|
|
|
|
? [...(root as unknown[])]
|
|
|
|
|
: root === undefined && typeof head === 'number'
|
|
|
|
|
? []
|
|
|
|
|
: { ...(root as Record<PathSeg, unknown>) }
|
2026-10-22 09:55:24 +07:00
|
|
|
) as Record<PathSeg, unknown>;
|
|
|
|
|
copy[head] = rest.length === 0 ? value : setPath(copy[head], rest, value);
|
|
|
|
|
return copy;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function deletePath(root: unknown, segs: PathSeg[]): unknown {
|
|
|
|
|
if (segs.length === 0) return undefined;
|
|
|
|
|
const [head, ...rest] = segs;
|
|
|
|
|
if (rest.length === 0) {
|
|
|
|
|
if (Array.isArray(root)) {
|
|
|
|
|
const copy = [...root];
|
|
|
|
|
copy.splice(Number(head), 1);
|
|
|
|
|
return copy;
|
|
|
|
|
}
|
|
|
|
|
const copy = { ...(root as Record<PathSeg, unknown>) };
|
|
|
|
|
delete copy[head as string];
|
|
|
|
|
return copy;
|
|
|
|
|
}
|
|
|
|
|
const copy = (
|
|
|
|
|
Array.isArray(root) ? [...(root as unknown[])] : { ...(root as Record<PathSeg, unknown>) }
|
|
|
|
|
) as Record<PathSeg, unknown>;
|
|
|
|
|
copy[head] = deletePath(copy[head], rest);
|
|
|
|
|
return copy;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isPlainObject = (v: unknown): v is Record<string, unknown> =>
|
|
|
|
|
typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
|
|
|
|
|
|
|
|
// Leaf-level diff between a baseline document and its draft copy: object keys
|
|
|
|
|
// added or removed report the key itself, arrays whose length changed report
|
|
|
|
|
// the array path, everything else recurses to the differing leaf.
|
|
|
|
|
export function diffPaths(a: unknown, b: unknown, prefix = ''): string[] {
|
|
|
|
|
if (isPlainObject(a) && isPlainObject(b)) {
|
|
|
|
|
const out: string[] = [];
|
|
|
|
|
for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
|
|
|
|
const child = prefix ? `${prefix}.${key}` : key;
|
|
|
|
|
if (a[key] === undefined || b[key] === undefined) {
|
|
|
|
|
out.push(child);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
out.push(...diffPaths(a[key], b[key], child));
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
if (Array.isArray(a) && Array.isArray(b)) {
|
|
|
|
|
if (a.length !== b.length) return prefix ? [prefix] : [];
|
|
|
|
|
const out: string[] = [];
|
|
|
|
|
for (let i = 0; i < a.length; i++) {
|
|
|
|
|
out.push(...diffPaths(a[i], b[i], `${prefix}[${i}]`));
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
if (a === b) return [];
|
|
|
|
|
return prefix ? [prefix] : [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- proxy transport -------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
export type DocBase = { data: unknown; sha: string };
|
|
|
|
|
|
|
|
|
|
function decodeBase64(b64: string): string {
|
|
|
|
|
const bin = atob(b64.replace(/\s+/g, ''));
|
|
|
|
|
const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
|
|
|
|
|
return new TextDecoder('utf-8').decode(bytes);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function encodeBase64(text: string): string {
|
|
|
|
|
const bytes = new TextEncoder().encode(text);
|
|
|
|
|
let bin = '';
|
|
|
|
|
for (const b of bytes) bin += String.fromCharCode(b);
|
|
|
|
|
return btoa(bin);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function fetchDoc(file: string, branch: string): Promise<DocBase> {
|
|
|
|
|
const res = await fetch(proxyUrl(file, branch));
|
|
|
|
|
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
|
2026-10-23 09:51:28 +07:00
|
|
|
// The contents response carries both the blob sha (`sha`) and the last
|
|
|
|
|
// commit that touched the file (`last_commit_sha`). Gitea 28's UpdateFile
|
|
|
|
|
// concurrency field is the blob sha — that is the value the draft keeps.
|
|
|
|
|
const json = (await res.json()) as { content?: string; sha?: string };
|
2026-10-22 09:55:24 +07:00
|
|
|
return {
|
|
|
|
|
data: JSON.parse(decodeBase64(json.content ?? '')),
|
2026-10-23 09:51:28 +07:00
|
|
|
sha: String(json.sha ?? ''),
|
2026-10-22 09:55:24 +07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function fetchTextFile(file: string, branch: string): Promise<{ text: string; sha: string }> {
|
|
|
|
|
const res = await fetch(proxyUrl(file, branch));
|
|
|
|
|
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
|
2026-10-23 09:51:28 +07:00
|
|
|
const json = (await res.json()) as { content?: string; sha?: string };
|
|
|
|
|
return { text: decodeBase64(json.content ?? ''), sha: String(json.sha ?? '') };
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
2026-10-23 09:51:28 +07:00
|
|
|
export type PutResult =
|
|
|
|
|
| { ok: true; sha: string }
|
|
|
|
|
| { ok: false; status: number; message: string };
|
2026-10-22 09:55:24 +07:00
|
|
|
|
|
|
|
|
async function putBase64(
|
|
|
|
|
file: string,
|
|
|
|
|
encoded: string,
|
|
|
|
|
message: string,
|
2026-10-23 09:51:28 +07:00
|
|
|
blobSha: string,
|
2026-10-22 09:55:24 +07:00
|
|
|
branch: string,
|
|
|
|
|
): Promise<PutResult> {
|
2026-10-23 09:51:28 +07:00
|
|
|
// Gitea 28 UpdateFileOptions: `sha` is the blob ID of the file to update —
|
|
|
|
|
// empty means create (an existing file then answers 422 "repository file
|
|
|
|
|
// already exists"), a stale one means a concurrency mismatch. The FileResponse
|
|
|
|
|
// returns the new blob sha at `content.sha`.
|
2026-10-22 09:55:24 +07:00
|
|
|
const res = await fetch(proxyUrl(file, branch), {
|
|
|
|
|
method: 'PUT',
|
|
|
|
|
headers: { 'content-type': 'application/json' },
|
|
|
|
|
body: JSON.stringify({
|
|
|
|
|
content: encoded,
|
|
|
|
|
message,
|
|
|
|
|
branch,
|
2026-10-23 09:51:28 +07:00
|
|
|
sha: blobSha,
|
2026-10-22 09:55:24 +07:00
|
|
|
}),
|
|
|
|
|
});
|
2026-10-23 09:51:28 +07:00
|
|
|
if (!res.ok) {
|
|
|
|
|
let detail = '';
|
|
|
|
|
try {
|
|
|
|
|
const json = (await res.json()) as { message?: string };
|
|
|
|
|
detail = String(json.message ?? '');
|
|
|
|
|
} catch {
|
|
|
|
|
// non-JSON body — the status code alone still drives the caller
|
|
|
|
|
}
|
|
|
|
|
return { ok: false, status: res.status, message: detail };
|
|
|
|
|
}
|
|
|
|
|
const json = (await res.json()) as { content?: { sha?: string } };
|
|
|
|
|
return { ok: true, sha: String(json.content?.sha ?? '') };
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Serialize exactly as the repository file is formatted (2-space indent, key
|
|
|
|
|
// order preserved from the parsed document) so Gitea diffs stay reviewable
|
|
|
|
|
// (§6.1).
|
|
|
|
|
export function putDoc(
|
|
|
|
|
file: string,
|
|
|
|
|
data: unknown,
|
|
|
|
|
message: string,
|
|
|
|
|
lastCommitSha: string,
|
|
|
|
|
branch: string,
|
|
|
|
|
): Promise<PutResult> {
|
|
|
|
|
return putBase64(file, encodeBase64(`${JSON.stringify(data, null, 2)}\n`), message, lastCommitSha, branch);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function putTextFile(
|
|
|
|
|
file: string,
|
|
|
|
|
text: string,
|
|
|
|
|
message: string,
|
|
|
|
|
lastCommitSha: string,
|
|
|
|
|
branch: string,
|
|
|
|
|
): Promise<PutResult> {
|
|
|
|
|
return putBase64(file, encodeBase64(text), message, lastCommitSha, branch);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Offline fallback (§5.1): the bundled build-time documents, flagged stale in
|
|
|
|
|
// the UI, save disabled — the draft is never initialized from a bundle that
|
|
|
|
|
// might be older than master when the proxy is reachable.
|
|
|
|
|
export function bundledBase(): Record<DraftDocId, DocBase> {
|
|
|
|
|
return {
|
|
|
|
|
profile: { data: structuredClone(profileJson), sha: '' },
|
|
|
|
|
skills: { data: structuredClone(skillsJson), sha: '' },
|
|
|
|
|
experience: { data: structuredClone(experienceJson), sha: '' },
|
|
|
|
|
projects: { data: structuredClone(projectsJson), sha: '' },
|
2026-10-23 10:55:29 +07:00
|
|
|
'profile.vi': { data: structuredClone(profileViTextJson), sha: '' },
|
|
|
|
|
'profile.en': { data: structuredClone(profileEnTextJson), sha: '' },
|
|
|
|
|
'skills.vi': { data: structuredClone(skillsViTextJson), sha: '' },
|
|
|
|
|
'skills.en': { data: structuredClone(skillsEnTextJson), sha: '' },
|
|
|
|
|
'experience.vi': { data: structuredClone(experienceViTextJson), sha: '' },
|
|
|
|
|
'experience.en': { data: structuredClone(experienceEnTextJson), sha: '' },
|
|
|
|
|
'projects.vi': { data: structuredClone(projectsViTextJson), sha: '' },
|
|
|
|
|
'projects.en': { data: structuredClone(projectsEnTextJson), sha: '' },
|
2026-10-22 09:55:24 +07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- id unions (§3.1) ------------------------------------------------------------
|
|
|
|
|
// Adding a content item is three edits: a union member, a structure record,
|
2026-10-24 10:08:58 +07:00
|
|
|
// its Vietnamese text. Deleting one is the mirror image: the record and its
|
|
|
|
|
// text go, and the union member must go with them. The editor does every leg
|
|
|
|
|
// — once the content documents land, saveIdUnions brings each union in
|
|
|
|
|
// src/types/index.ts to exactly the ids its document carries.
|
2026-10-22 09:55:24 +07:00
|
|
|
|
|
|
|
|
const UNION_SPECS: ReadonlyArray<{ union: string; ids: (s: ContentStructures) => string[] }> = [
|
|
|
|
|
{ union: 'ProjectId', ids: (s) => s.projects.map((p) => p.id) },
|
|
|
|
|
{ union: 'ExperienceId', ids: (s) => s.experience.map((e) => e.id) },
|
|
|
|
|
{ union: 'SkillGroupId', ids: (s) => s.skills.map((g) => g.id) },
|
|
|
|
|
{ union: 'PhilosophyId', ids: (s) => s.profile.philosophy.map((p) => p.id) },
|
|
|
|
|
];
|
|
|
|
|
|
2026-10-24 10:08:58 +07:00
|
|
|
// A union is read as a block — `export type X =` followed by its ` | 'id'`
|
|
|
|
|
// member lines — never as a substring search: an id slug can legitimately
|
|
|
|
|
// appear elsewhere in the same file (ProjectCategory carries slugs that also
|
|
|
|
|
// read as project ids), and a substring test would silently skip that leg. An
|
|
|
|
|
// emptied union (`never`, the state an emptied document leaves) reads as an
|
|
|
|
|
// empty member list, so a record added on top of it is appended back. Any
|
|
|
|
|
// other shape (a one-line union) is reported as unpatchable, never corrupted.
|
|
|
|
|
type UnionBlock = { union: string; members: string[]; from: number; to: number };
|
|
|
|
|
|
|
|
|
|
const MEMBER_LINE = /^[ \t]*\| '([^']+)'[ \t]*;?[ \t]*\r?\n?$/;
|
|
|
|
|
const CLOSING_LINE = /^[ \t]*;[ \t]*\r?\n?$/;
|
|
|
|
|
|
|
|
|
|
// One line of the source including its terminator, or null at end of file.
|
|
|
|
|
function nextLine(source: string, from: number): { text: string; end: number } | null {
|
|
|
|
|
if (from >= source.length) return null;
|
|
|
|
|
const at = source.indexOf('\n', from);
|
|
|
|
|
const end = at < 0 ? source.length : at + 1;
|
|
|
|
|
return { text: source.slice(from, end), end };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// `from`/`to` are the exact span of the declaration, so nothing else in the
|
|
|
|
|
// file is ever rewritten.
|
|
|
|
|
function readUnionBlock(source: string, union: string): UnionBlock | null {
|
|
|
|
|
const never = new RegExp(`^export type ${union} = never;\\r?\\n?`, 'm').exec(source);
|
|
|
|
|
if (never) return { union, members: [], from: never.index, to: never.index + never[0].length };
|
|
|
|
|
const header = new RegExp(`^export type ${union} =\\r?\\n`, 'm').exec(source);
|
|
|
|
|
if (!header) return null;
|
|
|
|
|
const from = header.index;
|
|
|
|
|
let pos = from + header[0].length;
|
|
|
|
|
const members: string[] = [];
|
|
|
|
|
for (;;) {
|
|
|
|
|
const line = nextLine(source, pos);
|
|
|
|
|
if (!line) break;
|
|
|
|
|
const member = MEMBER_LINE.exec(line.text);
|
|
|
|
|
if (!member) break;
|
|
|
|
|
members.push(member[1]);
|
|
|
|
|
pos = line.end;
|
|
|
|
|
}
|
|
|
|
|
if (members.length === 0) return null;
|
|
|
|
|
const closing = nextLine(source, pos);
|
|
|
|
|
if (closing && CLOSING_LINE.test(closing.text)) pos = closing.end;
|
|
|
|
|
return { union, members, from, to: pos };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// An emptied union is `never`, which keeps `Record<never, T>` valid against an
|
|
|
|
|
// empty document.
|
|
|
|
|
function renderUnion(union: string, members: readonly string[], eol: string): string {
|
|
|
|
|
if (members.length === 0) return `export type ${union} = never;${eol}`;
|
|
|
|
|
const body = members.map((id) => ` | '${id}'`).join(eol);
|
|
|
|
|
return `export type ${union} =${eol}${body};${eol}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// One pass per union: surviving members keep their order, removed ids are
|
|
|
|
|
// dropped, added ids follow the document order. Null when a union's shape is
|
|
|
|
|
// not the one the editor writes.
|
|
|
|
|
export function applyUnionChanges(
|
|
|
|
|
source: string,
|
|
|
|
|
changes: { union: string; add: string[]; remove: string[] }[],
|
|
|
|
|
): string | null {
|
|
|
|
|
// git stores LF; a Windows checkout reads CRLF. A patch keeps the line
|
|
|
|
|
// ending the file already uses, so the commit the owner reviews is one line.
|
|
|
|
|
const eol = source.includes('\r\n') ? '\r\n' : '\n';
|
|
|
|
|
let out = source;
|
|
|
|
|
for (const change of changes) {
|
|
|
|
|
const block = readUnionBlock(out, change.union);
|
|
|
|
|
if (!block) return null;
|
|
|
|
|
const removed = new Set(change.remove);
|
|
|
|
|
const members = block.members.filter((id) => !removed.has(id));
|
|
|
|
|
for (const id of change.add) if (!members.includes(id)) members.push(id);
|
|
|
|
|
out = `${out.slice(0, block.from)}${renderUnion(change.union, members, eol)}${out.slice(block.to)}`;
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-24 10:08:58 +07:00
|
|
|
// Ids whose documents have landed but whose union does not match them:
|
|
|
|
|
// missing members to append, stale members to drop. committedStructures() reads
|
|
|
|
|
// the post-PUT base, so a document that has not landed keeps the branch's ids
|
|
|
|
|
// and never reads as stale.
|
|
|
|
|
export function diffIdsWithUnions(
|
|
|
|
|
store: DraftStore,
|
|
|
|
|
typesSource: string,
|
|
|
|
|
): { added: { union: string; id: string }[]; removed: { union: string; id: string }[] } {
|
|
|
|
|
const structures = store.committedStructures();
|
|
|
|
|
const added: { union: string; id: string }[] = [];
|
|
|
|
|
const removed: { union: string; id: string }[] = [];
|
|
|
|
|
for (const spec of UNION_SPECS) {
|
|
|
|
|
const block = readUnionBlock(typesSource, spec.union);
|
|
|
|
|
if (!block) continue;
|
|
|
|
|
const live = new Set(spec.ids(structures));
|
|
|
|
|
for (const id of live) if (!block.members.includes(id)) added.push({ union: spec.union, id });
|
|
|
|
|
for (const id of block.members) if (!live.has(id)) removed.push({ union: spec.union, id });
|
|
|
|
|
}
|
|
|
|
|
return { added, removed };
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- the store ---------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
export type SavedDraft = {
|
|
|
|
|
docs: Record<string, unknown>;
|
|
|
|
|
baseShas: Record<string, string>;
|
2026-10-23 09:31:45 +07:00
|
|
|
// Record ids created inside this draft session — their ids follow the title
|
|
|
|
|
// until the record is saved (spec-v4-inline-editing E3). Optional so a
|
|
|
|
|
// persisted draft from before this existed still restores.
|
|
|
|
|
created?: string[];
|
2026-10-22 09:55:24 +07:00
|
|
|
};
|
|
|
|
|
|
2026-10-23 09:31:45 +07:00
|
|
|
export type RecordKind = 'project' | 'experience' | 'skill-group' | 'philosophy' | 'section';
|
|
|
|
|
export type RecordIds = { id: string; projectId?: string };
|
|
|
|
|
|
|
|
|
|
// Where a field physically lives (spec-v4-inline-editing E7): `doc` is the
|
|
|
|
|
// short form a developer searches, `pointer` the path inside it, `repoPath`
|
|
|
|
|
// the full project path — what the provenance chip copies to the clipboard.
|
|
|
|
|
export type FieldInfo = { doc: string; pointer: string; repoPath: string };
|
|
|
|
|
|
|
|
|
|
// One field where my draft and the moved branch both changed, to different
|
|
|
|
|
// values (E8) — the store never resolves it by itself.
|
|
|
|
|
export type ConflictField = { path: string; mine: unknown; theirs: unknown };
|
|
|
|
|
|
2026-10-22 09:55:24 +07:00
|
|
|
function uniqueId(base: string, taken: readonly string[]): string {
|
|
|
|
|
let id = base;
|
|
|
|
|
let n = 2;
|
|
|
|
|
while (taken.includes(id)) id = `${base}-${n++}`;
|
|
|
|
|
return id;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 09:31:45 +07:00
|
|
|
// Ids are born from titles (spec-v4-inline-editing E3): lowercase, hyphen-
|
|
|
|
|
// joined ASCII. Vietnamese diacritics fold through NFD; đ folds separately.
|
|
|
|
|
export function slugify(title: string): string {
|
|
|
|
|
return title
|
|
|
|
|
.normalize('NFD')
|
|
|
|
|
.replace(/[\u0300-\u036f]/g, '')
|
|
|
|
|
.toLowerCase()
|
|
|
|
|
.replace(/đ/g, 'd')
|
|
|
|
|
.replace(/[^a-z0-9]+/g, '-')
|
|
|
|
|
.replace(/^-+|-+$/g, '');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const recordKey = (kind: RecordKind, ids: RecordIds): string =>
|
|
|
|
|
ids.projectId ? `${kind}:${ids.projectId}:${ids.id}` : `${kind}:${ids.id}`;
|
|
|
|
|
|
|
|
|
|
// A committed text path naming a record title — the trigger for id re-sluging
|
|
|
|
|
// while the record is still draft-only (E3).
|
|
|
|
|
export function recordForTitlePath(
|
|
|
|
|
path: string,
|
|
|
|
|
): { kind: RecordKind; ids: RecordIds } | null {
|
|
|
|
|
const section = /^projects\.([^.[\]]+)\.sections\.([^.[\]]+)\.title$/.exec(path);
|
|
|
|
|
if (section) return { kind: 'section', ids: { id: section[2], projectId: section[1] } };
|
|
|
|
|
const project = /^projects\.([^.[\]]+)\.title$/.exec(path);
|
|
|
|
|
if (project) return { kind: 'project', ids: { id: project[1] } };
|
|
|
|
|
const experience = /^experience\.([^.[\]]+)\.title$/.exec(path);
|
|
|
|
|
if (experience) return { kind: 'experience', ids: { id: experience[1] } };
|
|
|
|
|
const group = /^skills\.([^.[\]]+)\.title$/.exec(path);
|
|
|
|
|
if (group) return { kind: 'skill-group', ids: { id: group[1] } };
|
|
|
|
|
const point = /^profile\.philosophy\.([^.[\]]+)\.title$/.exec(path);
|
|
|
|
|
if (point) return { kind: 'philosophy', ids: { id: point[1] } };
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 09:55:24 +07:00
|
|
|
export class DraftStore {
|
|
|
|
|
private base = new Map<DraftDocId, DocBase>();
|
|
|
|
|
// The baseline the draft was taken against. `base` may be refreshed by a
|
2026-10-23 09:51:28 +07:00
|
|
|
// 422/412 conflict; `origin` never moves until a document lands, so a rebase
|
2026-10-22 09:55:24 +07:00
|
|
|
// can always tell my changes from theirs (§5.6).
|
|
|
|
|
private origin = new Map<DraftDocId, unknown>();
|
|
|
|
|
private working = new Map<DraftDocId, unknown>();
|
|
|
|
|
private changes = new Map<DraftDocId, string[]>;
|
2026-10-23 09:31:45 +07:00
|
|
|
// Ids of records created in this draft session (recordKey form). A created
|
|
|
|
|
// id follows its title while the record is draft-only; after a save the id
|
|
|
|
|
// is published and fixed (E3).
|
|
|
|
|
private created = new Set<string>();
|
2026-10-22 09:55:24 +07:00
|
|
|
|
|
|
|
|
constructor(bases: Record<DraftDocId, DocBase>) {
|
|
|
|
|
for (const meta of DRAFT_DOCS) {
|
|
|
|
|
this.base.set(meta.id, bases[meta.id]);
|
|
|
|
|
this.origin.set(meta.id, bases[meta.id].data);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
dataOf(id: DraftDocId): unknown {
|
|
|
|
|
return this.working.has(id) ? this.working.get(id) : this.base.get(id)!.data;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
shaOf(id: DraftDocId): string {
|
|
|
|
|
return this.base.get(id)!.sha;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
touched(): DraftDocId[] {
|
|
|
|
|
return [...this.working.keys()];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
changedPaths(id: DraftDocId): string[] {
|
|
|
|
|
return this.changes.get(id) ?? [];
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isDirty(): boolean {
|
|
|
|
|
return this.working.size > 0;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
changedDocs(): { id: DraftDocId; paths: { path: string; before: unknown; after: unknown }[] }[] {
|
|
|
|
|
return this.touched().map((id) => ({
|
|
|
|
|
id,
|
|
|
|
|
paths: this.changedPaths(id).map((p) => ({
|
|
|
|
|
path: p,
|
|
|
|
|
before: getPath(this.base.get(id)!.data, parsePath(p)),
|
|
|
|
|
after: getPath(this.dataOf(id), parsePath(p)),
|
|
|
|
|
})),
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
draftStructures(): ContentStructures {
|
|
|
|
|
return {
|
|
|
|
|
profile: this.dataOf('profile'),
|
|
|
|
|
skills: this.dataOf('skills'),
|
|
|
|
|
experience: this.dataOf('experience'),
|
|
|
|
|
projects: this.dataOf('projects'),
|
|
|
|
|
} as unknown as ContentStructures;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
baseDataOf(id: DraftDocId): unknown {
|
|
|
|
|
return this.base.get(id)!.data;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Structures as they would exist in master after the already-written PUTs —
|
|
|
|
|
// the union patch only covers ids whose documents actually landed.
|
|
|
|
|
committedStructures(): ContentStructures {
|
|
|
|
|
const baseData = (id: DraftDocId) => this.base.get(id)!.data;
|
|
|
|
|
return {
|
|
|
|
|
profile: baseData('profile'),
|
|
|
|
|
skills: baseData('skills'),
|
|
|
|
|
experience: baseData('experience'),
|
|
|
|
|
projects: baseData('projects'),
|
|
|
|
|
} as unknown as ContentStructures;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
draftTexts(): { vi: ContentVi; en: ContentEn } {
|
|
|
|
|
return {
|
2026-10-23 10:55:29 +07:00
|
|
|
vi: {
|
|
|
|
|
profile: this.dataOf('profile.vi') as ContentVi['profile'],
|
|
|
|
|
skills: this.dataOf('skills.vi') as ContentVi['skills'],
|
|
|
|
|
experience: this.dataOf('experience.vi') as ContentVi['experience'],
|
|
|
|
|
projects: this.dataOf('projects.vi') as ContentVi['projects'],
|
|
|
|
|
},
|
|
|
|
|
en: {
|
|
|
|
|
profile: this.dataOf('profile.en') as ContentEn['profile'],
|
|
|
|
|
skills: this.dataOf('skills.en') as ContentEn['skills'],
|
|
|
|
|
experience: this.dataOf('experience.en') as ContentEn['experience'],
|
|
|
|
|
projects: this.dataOf('projects.en') as ContentEn['projects'],
|
|
|
|
|
},
|
2026-10-22 09:55:24 +07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
validate(): ContentIssue[] {
|
|
|
|
|
const texts = this.draftTexts();
|
|
|
|
|
return collectContentIssues(this.draftStructures(), texts.vi, texts.en);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// --- text documents -----------------------------------------------------------
|
|
|
|
|
// A text path carries its entity as the first segment; the target document
|
|
|
|
|
// is that entity's text file in the language being edited, and the pointer
|
|
|
|
|
// inside it is the rest (spec-v4-data-organization §3, E7). Missing en
|
|
|
|
|
// entries are created, vi paths always exist (§5.3). Invalid candidates
|
|
|
|
|
// return the validator issues and leave the store untouched.
|
|
|
|
|
|
|
|
|
|
private textTarget(
|
|
|
|
|
lang: Language,
|
|
|
|
|
path: string,
|
|
|
|
|
): { id: DraftDocId; segs: PathSeg[]; rest: string } | null {
|
|
|
|
|
const split = splitTextPath(path);
|
|
|
|
|
if (!split) return null;
|
|
|
|
|
return { id: textDocId(split.entity, lang), segs: parsePath(split.rest), rest: split.rest };
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 09:55:24 +07:00
|
|
|
setValue(lang: Language, path: string, value: string): ContentIssue[] | null {
|
2026-10-23 10:55:29 +07:00
|
|
|
return this.setText(lang, path, value);
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Write any value at a text path — a string leaf, a tag array, a tagline
|
|
|
|
|
// segment object. One write surface for every text shape (E1/E5).
|
|
|
|
|
setText(lang: Language, path: string, value: unknown): ContentIssue[] | null {
|
|
|
|
|
const t = this.textTarget(lang, path);
|
|
|
|
|
if (!t) return [{ path, message: 'not a text path' }];
|
|
|
|
|
return this.tryApply(new Map([[t.id, setPath(this.dataOf(t.id), t.segs, value)]]));
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
deleteText(lang: Language, path: string): ContentIssue[] | null {
|
|
|
|
|
const t = this.textTarget(lang, path);
|
|
|
|
|
if (!t) return [{ path, message: 'not a text path' }];
|
|
|
|
|
return this.tryApply(new Map([[t.id, deletePath(this.dataOf(t.id), t.segs)]]));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
moveText(lang: Language, path: string, from: number, to: number): ContentIssue[] | null {
|
|
|
|
|
const t = this.textTarget(lang, path);
|
|
|
|
|
if (!t) return [{ path, message: 'not a text path' }];
|
|
|
|
|
const arr = getPath(this.dataOf(t.id), t.segs);
|
|
|
|
|
if (!Array.isArray(arr) || from < 0 || to < 0 || from >= arr.length || to >= arr.length) {
|
|
|
|
|
return null;
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
2026-10-23 10:55:29 +07:00
|
|
|
const next = [...arr];
|
|
|
|
|
const [moved] = next.splice(from, 1);
|
|
|
|
|
next.splice(to, 0, moved);
|
|
|
|
|
return this.tryApply(new Map([[t.id, setPath(this.dataOf(t.id), t.segs, next)]]));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isTextDirty(lang: Language, path: string): boolean {
|
|
|
|
|
const t = this.textTarget(lang, path);
|
|
|
|
|
return t !== null && this.changedPaths(t.id).includes(t.rest);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Per-field revert (§5.3): restore the baseline value at this document-
|
|
|
|
|
// relative path in this document; a path that was newly created is removed.
|
|
|
|
|
revertIn(id: DraftDocId, path: string): ContentIssue[] | null {
|
|
|
|
|
if (!this.changedPaths(id).includes(path)) return null;
|
|
|
|
|
const segs = parsePath(path);
|
|
|
|
|
const original = getPath(this.base.get(id)!.data, segs);
|
|
|
|
|
const next =
|
|
|
|
|
original === undefined
|
|
|
|
|
? deletePath(this.dataOf(id), segs)
|
|
|
|
|
: setPath(this.dataOf(id), segs, original);
|
|
|
|
|
return this.tryApply(new Map([[id, next]]));
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
discardDocument(id: DraftDocId): void {
|
|
|
|
|
this.working.delete(id);
|
|
|
|
|
this.changes.delete(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Templates and record deletes (§5.4): structure record and text entries
|
|
|
|
|
// are created or removed in one action — orphan text is never produced.
|
2026-10-23 09:31:45 +07:00
|
|
|
addRecord(kind: RecordKind, options: { projectId?: string } = {}): ContentIssue[] | null {
|
2026-10-22 09:55:24 +07:00
|
|
|
const candidates = new Map<DraftDocId, unknown>();
|
2026-10-23 09:31:45 +07:00
|
|
|
let createdIds: RecordIds | null = null;
|
2026-10-22 09:55:24 +07:00
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Structure record and text entries are created in one action — orphan
|
|
|
|
|
// text is never produced (§5.4). The text lives in the entity's own
|
|
|
|
|
// document in both languages.
|
|
|
|
|
const withTexts = (entity: TextEntity, mutate: (doc: Record<string, any>) => void) => {
|
|
|
|
|
for (const lang of ['vi', 'en'] as const) {
|
|
|
|
|
const id = textDocId(entity, lang);
|
|
|
|
|
const doc = structuredClone(this.dataOf(id)) as Record<string, any>;
|
|
|
|
|
mutate(doc);
|
|
|
|
|
candidates.set(id, doc);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-22 09:55:24 +07:00
|
|
|
if (kind === 'project') {
|
|
|
|
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
|
|
|
|
const id = uniqueId('new-project', projects.map((p) => p.id));
|
2026-10-23 09:31:45 +07:00
|
|
|
createdIds = { id };
|
2026-10-22 22:53:26 +07:00
|
|
|
projects.push({ id, category: 'experiment', technologies: [], featured: false, sections: [] });
|
2026-10-22 09:55:24 +07:00
|
|
|
candidates.set('projects', projects);
|
2026-10-22 22:53:26 +07:00
|
|
|
const stub = { title: 'New project', summary: 'Write the summary here.', role: 'Owner', sections: {} };
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
doc[id] = structuredClone(stub);
|
|
|
|
|
});
|
2026-10-22 09:55:24 +07:00
|
|
|
} else if (kind === 'experience') {
|
|
|
|
|
const experiences = structuredClone(this.dataOf('experience')) as Record<string, any>[];
|
|
|
|
|
const id = uniqueId('new-experience', experiences.map((e) => e.id));
|
2026-10-23 09:31:45 +07:00
|
|
|
createdIds = { id };
|
2026-10-22 22:53:26 +07:00
|
|
|
experiences.push({ id });
|
2026-10-22 09:55:24 +07:00
|
|
|
candidates.set('experience', experiences);
|
2026-10-22 22:53:26 +07:00
|
|
|
const stub = { title: 'New role', company: 'New company', duration: 'present', responsibilities: ['Write a responsibility here.'] };
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('experience', (doc) => {
|
|
|
|
|
doc[id] = structuredClone(stub);
|
|
|
|
|
});
|
2026-10-22 09:55:24 +07:00
|
|
|
} else if (kind === 'skill-group') {
|
|
|
|
|
const groups = structuredClone(this.dataOf('skills')) as Record<string, any>[];
|
|
|
|
|
const id = uniqueId('new-skill-group', groups.map((g) => g.id));
|
2026-10-23 09:31:45 +07:00
|
|
|
createdIds = { id };
|
2026-10-22 09:55:24 +07:00
|
|
|
groups.push({ id, skills: ['New skill'] });
|
|
|
|
|
candidates.set('skills', groups);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('skills', (doc) => {
|
|
|
|
|
doc[id] = { title: 'New skill group' };
|
|
|
|
|
});
|
2026-10-22 09:55:24 +07:00
|
|
|
} else if (kind === 'philosophy') {
|
|
|
|
|
const profile = structuredClone(this.dataOf('profile')) as Record<string, any>;
|
|
|
|
|
const points = profile.philosophy as Record<string, any>[];
|
|
|
|
|
const id = uniqueId('new-philosophy-point', points.map((p) => p.id));
|
2026-10-23 09:31:45 +07:00
|
|
|
createdIds = { id };
|
2026-10-22 22:53:26 +07:00
|
|
|
points.push({ id });
|
2026-10-22 09:55:24 +07:00
|
|
|
candidates.set('profile', profile);
|
2026-10-22 22:53:26 +07:00
|
|
|
const stub = { title: 'New principle', description: 'Write the principle here.', keywords: ['new-keyword'] };
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('profile', (doc) => {
|
|
|
|
|
doc.philosophy = { ...doc.philosophy, [id]: structuredClone(stub) };
|
|
|
|
|
});
|
2026-10-22 09:55:24 +07:00
|
|
|
} else {
|
|
|
|
|
const projectId = options.projectId;
|
|
|
|
|
if (!projectId) return [{ path: 'projects.json', message: 'pick a project first' }];
|
|
|
|
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
|
|
|
|
const project = projects.find((p) => p.id === projectId);
|
|
|
|
|
if (!project) return [{ path: 'projects.json', message: `no project ${projectId}` }];
|
|
|
|
|
const sectionId = uniqueId('new-section', (project.sections as Record<string, any>[]).map((s) => s.id));
|
2026-10-23 09:31:45 +07:00
|
|
|
createdIds = { id: sectionId, projectId };
|
2026-10-22 09:55:24 +07:00
|
|
|
project.sections = [...project.sections, { id: sectionId, type: 'text' }];
|
|
|
|
|
candidates.set('projects', projects);
|
|
|
|
|
const stub = { title: 'New section', content: 'Write the section here.' };
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
const text = doc[projectId] as Record<string, any>;
|
|
|
|
|
doc[projectId] = { ...text, sections: { ...text.sections, [sectionId]: structuredClone(stub) } };
|
|
|
|
|
});
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
2026-10-23 09:31:45 +07:00
|
|
|
const issues = this.tryApply(candidates);
|
|
|
|
|
if (issues === null && createdIds) this.created.add(recordKey(kind, createdIds));
|
|
|
|
|
return issues;
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Delete removes the structure record and the record's text entries from
|
|
|
|
|
// both language documents in the same action — the validator can never see
|
|
|
|
|
// orphan text (§5.4).
|
2026-10-23 09:31:45 +07:00
|
|
|
deleteRecord(kind: RecordKind, ids: RecordIds): ContentIssue[] | null {
|
2026-10-22 09:55:24 +07:00
|
|
|
const candidates = new Map<DraftDocId, unknown>();
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
const withTexts = (entity: TextEntity, mutate: (doc: Record<string, any>) => void) => {
|
|
|
|
|
for (const lang of ['vi', 'en'] as const) {
|
|
|
|
|
const id = textDocId(entity, lang);
|
2026-10-22 09:55:24 +07:00
|
|
|
const doc = structuredClone(this.dataOf(id)) as Record<string, any>;
|
|
|
|
|
mutate(doc);
|
|
|
|
|
candidates.set(id, doc);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (kind === 'project') {
|
2026-10-23 10:55:29 +07:00
|
|
|
candidates.set('projects', (this.dataOf('projects') as Record<string, any>[]).filter((p) => p.id !== ids.id));
|
|
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
delete doc[ids.id];
|
2026-10-22 09:55:24 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'experience') {
|
|
|
|
|
candidates.set('experience', (this.dataOf('experience') as Record<string, any>[]).filter((e) => e.id !== ids.id));
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('experience', (doc) => {
|
|
|
|
|
delete doc[ids.id];
|
2026-10-22 09:55:24 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'skill-group') {
|
|
|
|
|
candidates.set('skills', (this.dataOf('skills') as Record<string, any>[]).filter((g) => g.id !== ids.id));
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('skills', (doc) => {
|
|
|
|
|
delete doc[ids.id];
|
2026-10-22 09:55:24 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'philosophy') {
|
|
|
|
|
const profile = structuredClone(this.dataOf('profile')) as Record<string, any>;
|
|
|
|
|
profile.philosophy = (profile.philosophy as Record<string, any>[]).filter((p) => p.id !== ids.id);
|
|
|
|
|
candidates.set('profile', profile);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('profile', (doc) => {
|
|
|
|
|
delete doc.philosophy[ids.id];
|
2026-10-22 09:55:24 +07:00
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
const projectId = ids.projectId;
|
|
|
|
|
if (!projectId || !ids.id) return [{ path: 'projects.json', message: 'pick a project and section first' }];
|
|
|
|
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
|
|
|
|
const project = projects.find((p) => p.id === projectId);
|
|
|
|
|
if (!project) return [{ path: 'projects.json', message: `no project ${projectId}` }];
|
|
|
|
|
project.sections = (project.sections as Record<string, any>[]).filter((s) => s.id !== ids.id);
|
|
|
|
|
candidates.set('projects', projects);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
const text = doc[projectId];
|
2026-10-22 09:55:24 +07:00
|
|
|
if (text) text.sections = { ...text.sections };
|
|
|
|
|
delete text?.sections[ids.id];
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-10-23 09:31:45 +07:00
|
|
|
const issues = this.tryApply(candidates);
|
|
|
|
|
if (issues === null) this.created.delete(recordKey(kind, ids));
|
|
|
|
|
return issues;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- provenance (spec-v4-inline-editing E7) ---------------------------------
|
|
|
|
|
|
|
|
|
|
describeField(id: DraftDocId, path: string): FieldInfo {
|
|
|
|
|
const file = DRAFT_DOCS.find((d) => d.id === id)?.file ?? id;
|
|
|
|
|
return { doc: file.replace(/^src\//, ''), pointer: path, repoPath: file };
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Provenance for a text path (E7): resolves the entity document for the
|
|
|
|
|
// language being edited — the chip reads `locales/vi/content/profile.json → bio`.
|
|
|
|
|
describeText(lang: Language, path: string): FieldInfo {
|
|
|
|
|
const split = splitTextPath(path);
|
|
|
|
|
if (!split) return { doc: 'content', pointer: path, repoPath: path };
|
|
|
|
|
return this.describeField(textDocId(split.entity, lang), split.rest);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 09:31:45 +07:00
|
|
|
// --- generic document writes (E4/E5): structure fields and text arrays ----
|
|
|
|
|
|
|
|
|
|
apply(id: DraftDocId, next: unknown): ContentIssue[] | null {
|
|
|
|
|
return this.tryApply(new Map([[id, next]]));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setStructured(id: DraftDocId, path: string, value: unknown): ContentIssue[] | null {
|
|
|
|
|
return this.apply(id, setPath(this.dataOf(id), parsePath(path), value));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
deleteStructured(id: DraftDocId, path: string): ContentIssue[] | null {
|
|
|
|
|
return this.apply(id, deletePath(this.dataOf(id), parsePath(path)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Move one element inside an array the path names (a document root array
|
|
|
|
|
// included) — record order and tag order share this single primitive.
|
|
|
|
|
moveItem(id: DraftDocId, path: string, from: number, to: number): ContentIssue[] | null {
|
|
|
|
|
const segs = parsePath(path);
|
|
|
|
|
const arr = getPath(this.dataOf(id), segs);
|
|
|
|
|
if (!Array.isArray(arr) || from < 0 || to < 0 || from >= arr.length || to >= arr.length) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
const next = [...arr];
|
|
|
|
|
const [moved] = next.splice(from, 1);
|
|
|
|
|
next.splice(to, 0, moved);
|
|
|
|
|
return this.apply(id, setPath(this.dataOf(id), segs, next));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
isCreated(kind: RecordKind, ids: RecordIds): boolean {
|
|
|
|
|
return this.created.has(recordKey(kind, ids));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// E3: a draft-only id follows its title. Once the record has been saved the
|
|
|
|
|
// id is published — it is the URL — and never changes again.
|
|
|
|
|
renameRecord(kind: RecordKind, ids: RecordIds, rawId: string): ContentIssue[] | null {
|
|
|
|
|
if (!this.isCreated(kind, ids)) return null;
|
|
|
|
|
const slug = slugify(rawId);
|
|
|
|
|
if (!slug) return null;
|
|
|
|
|
|
|
|
|
|
const candidates = new Map<DraftDocId, unknown>();
|
|
|
|
|
let newId = slug;
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
const withTexts = (entity: TextEntity, mutate: (doc: Record<string, any>) => void) => {
|
|
|
|
|
for (const lang of ['vi', 'en'] as const) {
|
|
|
|
|
const id = textDocId(entity, lang);
|
2026-10-23 09:31:45 +07:00
|
|
|
const doc = structuredClone(this.dataOf(id)) as Record<string, any>;
|
|
|
|
|
mutate(doc);
|
|
|
|
|
candidates.set(id, doc);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-23 10:55:29 +07:00
|
|
|
// Rename a record key in place, keeping the document's key order so the
|
|
|
|
|
// committed file stays reviewable.
|
|
|
|
|
const renameKey = (doc: Record<string, any>, from: string, to: string) => {
|
|
|
|
|
if (doc[from] === undefined) return;
|
|
|
|
|
const entries = Object.entries(doc).map(([k, v]) => (k === from ? [to, v] : [k, v]));
|
|
|
|
|
for (const k of Object.keys(doc)) delete doc[k];
|
|
|
|
|
Object.assign(doc, Object.fromEntries(entries));
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-23 09:31:45 +07:00
|
|
|
if (kind === 'project') {
|
|
|
|
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
|
|
|
|
newId = uniqueId(slug, projects.map((p) => p.id));
|
|
|
|
|
if (newId === ids.id) return null;
|
|
|
|
|
projects.forEach((p, i) => {
|
|
|
|
|
if (p.id === ids.id) projects[i] = { ...p, id: newId };
|
|
|
|
|
});
|
|
|
|
|
candidates.set('projects', projects);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
renameKey(doc, ids.id, newId);
|
2026-10-23 09:31:45 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'experience') {
|
|
|
|
|
const experiences = structuredClone(this.dataOf('experience')) as Record<string, any>[];
|
|
|
|
|
newId = uniqueId(slug, experiences.map((e) => e.id));
|
|
|
|
|
if (newId === ids.id) return null;
|
|
|
|
|
experiences.forEach((e, i) => {
|
|
|
|
|
if (e.id === ids.id) experiences[i] = { ...e, id: newId };
|
|
|
|
|
});
|
|
|
|
|
candidates.set('experience', experiences);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('experience', (doc) => {
|
|
|
|
|
renameKey(doc, ids.id, newId);
|
2026-10-23 09:31:45 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'skill-group') {
|
|
|
|
|
const groups = structuredClone(this.dataOf('skills')) as Record<string, any>[];
|
|
|
|
|
newId = uniqueId(slug, groups.map((g) => g.id));
|
|
|
|
|
if (newId === ids.id) return null;
|
|
|
|
|
groups.forEach((g, i) => {
|
|
|
|
|
if (g.id === ids.id) groups[i] = { ...g, id: newId };
|
|
|
|
|
});
|
|
|
|
|
candidates.set('skills', groups);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('skills', (doc) => {
|
|
|
|
|
renameKey(doc, ids.id, newId);
|
2026-10-23 09:31:45 +07:00
|
|
|
});
|
|
|
|
|
} else if (kind === 'philosophy') {
|
|
|
|
|
const profile = structuredClone(this.dataOf('profile')) as Record<string, any>;
|
|
|
|
|
const points = profile.philosophy as Record<string, any>[];
|
|
|
|
|
newId = uniqueId(slug, points.map((p) => p.id));
|
|
|
|
|
if (newId === ids.id) return null;
|
|
|
|
|
points.forEach((p, i) => {
|
|
|
|
|
if (p.id === ids.id) points[i] = { ...p, id: newId };
|
|
|
|
|
});
|
|
|
|
|
candidates.set('profile', profile);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('profile', (doc) => {
|
|
|
|
|
renameKey(doc.philosophy, ids.id, newId);
|
2026-10-23 09:31:45 +07:00
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
const projectId = ids.projectId;
|
|
|
|
|
if (!projectId) return null;
|
|
|
|
|
const projects = structuredClone(this.dataOf('projects')) as Record<string, any>[];
|
|
|
|
|
const project = projects.find((p) => p.id === projectId);
|
|
|
|
|
if (!project) return null;
|
|
|
|
|
const sections = project.sections as Record<string, any>[];
|
|
|
|
|
newId = uniqueId(slug, sections.map((s) => s.id));
|
|
|
|
|
if (newId === ids.id) return null;
|
|
|
|
|
sections.forEach((s, i) => {
|
|
|
|
|
if (s.id === ids.id) sections[i] = { ...s, id: newId };
|
|
|
|
|
});
|
|
|
|
|
candidates.set('projects', projects);
|
2026-10-23 10:55:29 +07:00
|
|
|
withTexts('projects', (doc) => {
|
|
|
|
|
const text = doc[projectId];
|
|
|
|
|
if (text?.sections) renameKey(text.sections, ids.id, newId);
|
2026-10-23 09:31:45 +07:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const issues = this.tryApply(candidates);
|
|
|
|
|
if (issues === null) {
|
|
|
|
|
this.created.delete(recordKey(kind, ids));
|
|
|
|
|
this.created.add(recordKey(kind, { ...ids, id: newId }));
|
|
|
|
|
}
|
|
|
|
|
return issues;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- conflicts, field by field (E8) -------------------------------------------
|
|
|
|
|
|
|
|
|
|
conflictFields(id: DraftDocId): ConflictField[] {
|
|
|
|
|
const origin = this.origin.get(id);
|
|
|
|
|
const theirs = this.base.get(id)?.data;
|
|
|
|
|
if (origin === undefined || theirs === undefined) return [];
|
|
|
|
|
const mine = this.dataOf(id);
|
|
|
|
|
const theirPaths = new Set(diffPaths(origin, theirs));
|
|
|
|
|
const out: ConflictField[] = [];
|
|
|
|
|
for (const path of diffPaths(origin, mine)) {
|
|
|
|
|
if (!theirPaths.has(path)) continue;
|
|
|
|
|
const segs = parsePath(path);
|
|
|
|
|
const myValue = getPath(mine, segs);
|
|
|
|
|
const theirValue = getPath(theirs, segs);
|
|
|
|
|
if (JSON.stringify(myValue) === JSON.stringify(theirValue)) continue;
|
|
|
|
|
out.push({ path, mine: myValue, theirs: theirValue });
|
|
|
|
|
}
|
|
|
|
|
return out;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Keep one side for one field, then retry the rebase. 'theirs': the working
|
|
|
|
|
// copy adopts the branch value, so my edit at that path is dropped. 'mine':
|
|
|
|
|
// the origin snapshot adopts the branch value, so the rebase replays my
|
|
|
|
|
// value over theirs — my edit wins at that path, every other replay is
|
|
|
|
|
// untouched.
|
|
|
|
|
resolveConflictField(
|
|
|
|
|
id: DraftDocId,
|
|
|
|
|
path: string,
|
|
|
|
|
side: 'mine' | 'theirs',
|
|
|
|
|
): ContentIssue[] | null {
|
|
|
|
|
const origin = this.origin.get(id);
|
|
|
|
|
const theirs = this.base.get(id)?.data;
|
|
|
|
|
if (origin === undefined || theirs === undefined) return null;
|
|
|
|
|
const segs = parsePath(path);
|
|
|
|
|
if (side === 'mine') {
|
|
|
|
|
this.origin.set(id, setPath(origin, segs, getPath(theirs, segs)));
|
|
|
|
|
} else {
|
|
|
|
|
const issues = this.apply(id, setPath(this.dataOf(id), segs, getPath(theirs, segs)));
|
|
|
|
|
if (issues) return issues;
|
|
|
|
|
}
|
|
|
|
|
return this.rebase(id);
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Apply candidate documents atomically: replace, recompute changed paths,
|
|
|
|
|
// run the full cross-document validator, roll every document back when the
|
|
|
|
|
// candidate draft is invalid (§5.4 — an invalid draft never reaches the
|
|
|
|
|
// preview). A document that ends up equal to its baseline stops being
|
|
|
|
|
// touched, so save only ever PUTs documents that actually differ.
|
|
|
|
|
private tryApply(candidates: Map<DraftDocId, unknown>): ContentIssue[] | null {
|
|
|
|
|
const undo: [DraftDocId, boolean, unknown, string[] | undefined][] = [];
|
|
|
|
|
for (const [id, data] of candidates) {
|
|
|
|
|
undo.push([id, this.working.has(id), this.working.get(id), this.changes.get(id)]);
|
|
|
|
|
this.working.set(id, data);
|
|
|
|
|
this.refreshChanges(id);
|
|
|
|
|
}
|
|
|
|
|
const issues = this.validate();
|
|
|
|
|
if (issues.length > 0) {
|
|
|
|
|
for (const [id, had, prev, prevChanges] of undo) {
|
|
|
|
|
if (had) {
|
|
|
|
|
this.working.set(id, prev);
|
|
|
|
|
if (prevChanges) this.changes.set(id, prevChanges);
|
|
|
|
|
} else {
|
|
|
|
|
this.working.delete(id);
|
|
|
|
|
this.changes.delete(id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return issues;
|
|
|
|
|
}
|
|
|
|
|
for (const id of candidates.keys()) {
|
|
|
|
|
if (JSON.stringify(this.dataOf(id)) === JSON.stringify(this.base.get(id)!.data)) {
|
|
|
|
|
this.working.delete(id);
|
|
|
|
|
this.changes.delete(id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private refreshChanges(id: DraftDocId): void {
|
|
|
|
|
const diff = diffPaths(this.base.get(id)!.data, this.working.get(id));
|
|
|
|
|
if (diff.length > 0) this.changes.set(id, diff);
|
|
|
|
|
else this.changes.delete(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- persistence (§5.2) ---
|
|
|
|
|
|
|
|
|
|
snapshot(): SavedDraft {
|
|
|
|
|
const docs: Record<string, unknown> = {};
|
|
|
|
|
for (const [id, data] of this.working) docs[id] = data;
|
|
|
|
|
const baseShas: Record<string, string> = {};
|
|
|
|
|
for (const [id, meta] of this.base) baseShas[id] = meta.sha;
|
2026-10-23 09:31:45 +07:00
|
|
|
return { docs, baseShas, created: [...this.created] };
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Re-apply a persisted draft onto freshly fetched baselines. A document
|
2026-10-23 09:51:28 +07:00
|
|
|
// whose blob sha moved since the draft was taken is returned as
|
2026-10-22 09:55:24 +07:00
|
|
|
// drifted → the conflict flow (§5.6) owns it from here.
|
|
|
|
|
applySaved(saved: SavedDraft): DraftDocId[] {
|
2026-10-23 09:31:45 +07:00
|
|
|
this.created = new Set(saved.created ?? []);
|
2026-10-22 09:55:24 +07:00
|
|
|
const drifted: DraftDocId[] = [];
|
|
|
|
|
for (const [idStr, data] of Object.entries(saved.docs)) {
|
|
|
|
|
const id = idStr as DraftDocId;
|
|
|
|
|
if (!DRAFT_DOCS.some((d) => d.id === id)) continue;
|
|
|
|
|
const savedSha = saved.baseShas[id] ?? '';
|
|
|
|
|
const liveSha = this.shaOf(id);
|
|
|
|
|
if (savedSha && savedSha !== liveSha) drifted.push(id);
|
|
|
|
|
this.working.set(id, data);
|
|
|
|
|
this.refreshChanges(id);
|
|
|
|
|
}
|
|
|
|
|
return drifted;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- save pipeline (§5.6, §6.1) ---
|
|
|
|
|
|
|
|
|
|
markWritten(id: DraftDocId, newSha: string): void {
|
|
|
|
|
const data = this.dataOf(id);
|
|
|
|
|
this.base.set(id, { data, sha: newSha });
|
|
|
|
|
this.origin.set(id, data);
|
|
|
|
|
this.working.delete(id);
|
|
|
|
|
this.changes.delete(id);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
resetBase(id: DraftDocId, fresh: DocBase): void {
|
|
|
|
|
this.base.set(id, fresh);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Rebase (§5.6): a real three-way merge of origin → mine against origin →
|
|
|
|
|
// theirs. Paths only I touched replay onto the refreshed base; a path both
|
|
|
|
|
// sides changed differently is a conflict the store refuses to resolve —
|
2026-10-23 09:31:45 +07:00
|
|
|
// resolveConflictField (spec-v4-inline-editing E8) settles it field by
|
|
|
|
|
// field, take-theirs still owns the whole document.
|
2026-10-22 09:55:24 +07:00
|
|
|
rebase(id: DraftDocId): ContentIssue[] | null {
|
|
|
|
|
const origin = this.origin.get(id)!;
|
|
|
|
|
const theirs = this.base.get(id)!.data;
|
|
|
|
|
const mine = this.dataOf(id);
|
|
|
|
|
const myPaths = diffPaths(origin, mine);
|
|
|
|
|
const theirPaths = new Set(diffPaths(origin, theirs));
|
|
|
|
|
const clashes = myPaths.filter(
|
|
|
|
|
(p) =>
|
|
|
|
|
theirPaths.has(p) &&
|
|
|
|
|
JSON.stringify(getPath(mine, parsePath(p))) !== JSON.stringify(getPath(theirs, parsePath(p))),
|
|
|
|
|
);
|
|
|
|
|
if (clashes.length > 0) {
|
|
|
|
|
return clashes.map((p) => ({
|
|
|
|
|
path: p,
|
2026-10-23 09:31:45 +07:00
|
|
|
message: 'changed both locally and in the branch — resolve the field or take theirs',
|
2026-10-22 09:55:24 +07:00
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
let data = theirs;
|
|
|
|
|
for (const p of myPaths) {
|
|
|
|
|
const value = getPath(mine, parsePath(p));
|
|
|
|
|
if (value !== undefined) data = setPath(data, parsePath(p), value);
|
|
|
|
|
}
|
|
|
|
|
const issues = this.tryApply(new Map([[id, data]]));
|
|
|
|
|
if (issues === null) this.origin.set(id, theirs);
|
|
|
|
|
return issues;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// --- save pipeline -----------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
export type DocSaveResult = {
|
|
|
|
|
id: DraftDocId;
|
|
|
|
|
status: 'written' | 'conflict' | 'failed';
|
|
|
|
|
http?: number;
|
|
|
|
|
};
|
|
|
|
|
|
2026-10-23 09:51:28 +07:00
|
|
|
// Sequential PUTs, one commit per touched document (§6.1). A blob-sha
|
|
|
|
|
// mismatch — Gitea 28 answers 422 with a "does not match" message, older
|
|
|
|
|
// deployments answered 412 — refreshes that document's base and reports a
|
|
|
|
|
// conflict without stopping the sequence; any other failure stops so a retry
|
|
|
|
|
// resumes from the first unwritten document — landed documents are never
|
|
|
|
|
// rewritten (§5.6).
|
2026-10-22 09:55:24 +07:00
|
|
|
export async function saveDraft(
|
|
|
|
|
store: DraftStore,
|
|
|
|
|
onResult: (result: DocSaveResult) => void,
|
|
|
|
|
branch: string,
|
|
|
|
|
): Promise<{ results: DocSaveResult[]; stoppedEarly: boolean }> {
|
|
|
|
|
const results: DocSaveResult[] = [];
|
|
|
|
|
for (const id of store.touched()) {
|
|
|
|
|
const meta = DRAFT_DOCS.find((d) => d.id === id)!;
|
|
|
|
|
const paths = store.changedPaths(id);
|
2026-10-23 10:55:29 +07:00
|
|
|
const message = `content: ${meta.file} (${paths.length} path${paths.length === 1 ? '' : 's'})`;
|
2026-10-22 09:55:24 +07:00
|
|
|
const res = await putDoc(meta.file, store.dataOf(id), message, store.shaOf(id), branch);
|
|
|
|
|
if (res.ok) {
|
|
|
|
|
store.markWritten(id, res.sha);
|
|
|
|
|
const result: DocSaveResult = { id, status: 'written' };
|
|
|
|
|
results.push(result);
|
|
|
|
|
onResult(result);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2026-10-23 09:51:28 +07:00
|
|
|
if (res.status === 412 || (res.status === 422 && /does not match/i.test(res.message))) {
|
2026-10-22 09:55:24 +07:00
|
|
|
try {
|
|
|
|
|
store.resetBase(id, await fetchDoc(meta.file, branch));
|
|
|
|
|
} catch {
|
|
|
|
|
// keep the old base; the conflict UI still offers take-theirs
|
|
|
|
|
}
|
2026-10-23 09:51:28 +07:00
|
|
|
const result: DocSaveResult = { id, status: 'conflict', http: res.status };
|
2026-10-22 09:55:24 +07:00
|
|
|
results.push(result);
|
|
|
|
|
onResult(result);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
const result: DocSaveResult = { id, status: 'failed', http: res.status };
|
|
|
|
|
results.push(result);
|
|
|
|
|
onResult(result);
|
|
|
|
|
return { results, stoppedEarly: true };
|
|
|
|
|
}
|
|
|
|
|
return { results, stoppedEarly: false };
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-24 10:08:58 +07:00
|
|
|
// The third leg of §3.1: once the documents that add or drop ids have landed,
|
|
|
|
|
// bring their unions in src/types/index.ts to exactly those ids so the next CI
|
|
|
|
|
// build compiles. Returns the updated source/sha, or null when nothing needs
|
|
|
|
|
// changing (an unpatchable shape or a rejected PUT is reported to the EditBar,
|
|
|
|
|
// and the owner finishes that edit in Gitea).
|
2026-10-22 09:55:24 +07:00
|
|
|
export async function saveIdUnions(
|
|
|
|
|
store: DraftStore,
|
|
|
|
|
types: { source: string; sha: string },
|
|
|
|
|
branch: string,
|
2026-10-24 10:08:58 +07:00
|
|
|
): Promise<{
|
|
|
|
|
added: { union: string; id: string }[];
|
|
|
|
|
removed: { union: string; id: string }[];
|
|
|
|
|
source?: string;
|
|
|
|
|
sha?: string;
|
|
|
|
|
failed?: number;
|
|
|
|
|
} | null> {
|
|
|
|
|
const { added, removed } = diffIdsWithUnions(store, types.source);
|
|
|
|
|
if (added.length === 0 && removed.length === 0) return null;
|
|
|
|
|
const grouped = new Map<string, { add: string[]; remove: string[] }>();
|
|
|
|
|
const bucket = (union: string) => {
|
|
|
|
|
const existing = grouped.get(union);
|
|
|
|
|
if (existing) return existing;
|
|
|
|
|
const fresh = { add: [] as string[], remove: [] as string[] };
|
|
|
|
|
grouped.set(union, fresh);
|
|
|
|
|
return fresh;
|
|
|
|
|
};
|
|
|
|
|
for (const { union, id } of added) bucket(union).add.push(id);
|
|
|
|
|
for (const { union, id } of removed) bucket(union).remove.push(id);
|
|
|
|
|
const source = applyUnionChanges(
|
|
|
|
|
types.source,
|
|
|
|
|
[...grouped].map(([union, change]) => ({ union, ...change })),
|
|
|
|
|
);
|
|
|
|
|
if (source === null) return { added, removed, failed: 0 };
|
|
|
|
|
const summary = [...added.map((a) => `+${a.id}`), ...removed.map((r) => `-${r.id}`)].join(', ');
|
|
|
|
|
const message = `content: update id union members (${summary})`;
|
2026-10-22 09:55:24 +07:00
|
|
|
const res = await putTextFile(TYPES_FILE, source, message, types.sha, branch);
|
2026-10-24 10:08:58 +07:00
|
|
|
if (!res.ok) return { added, removed, failed: res.status };
|
|
|
|
|
return { added, removed, source, sha: res.sha };
|
2026-10-22 09:55:24 +07:00
|
|
|
}
|