@resumekit/schema 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The contract between the API that builds an export and the browser that draws
3
+ * it — declared here, in the library that owns the document, so the two sides
4
+ * cannot describe it differently.
5
+ *
6
+ * It lives in `libs/core` — not beside the bundle — precisely so both sides can
7
+ * hold it without either depending on the other. `apps/api` builds the document
8
+ * and ships the bundle as an opaque asset; it imports no template, no component
9
+ * and no React, so no `scope:api → scope:templates` edge exists.
10
+ */
11
+ import type { Letter } from './letter.js';
12
+ import type { ResumeObject } from './resume.js';
13
+ import type { ResumePresentation } from './template.js';
14
+
15
+ /** The global the shell writes and the bundle reads. */
16
+ export const EXPORT_PAYLOAD_GLOBAL = '__CVGS_EXPORT__';
17
+
18
+ /** The global the bundle writes and the renderer waits on. */
19
+ export const EXPORT_STATE_GLOBAL = '__CVGS_EXPORT_STATE__';
20
+
21
+ /** The global carrying the page count, once the document has settled. */
22
+ export const EXPORT_PAGES_GLOBAL = '__CVGS_EXPORT_PAGES__';
23
+
24
+ /**
25
+ * What the renderer waits for.
26
+ *
27
+ * `waitForExpression` is given `ready`; `failed` exists so a document that
28
+ * cannot be drawn ends the wait immediately with a diagnosable state rather
29
+ * than burning the full timeout and reporting only that it expired.
30
+ */
31
+ export type ExportState = 'pending' | 'ready' | 'failed';
32
+
33
+ /** Everything the browser needs to draw a resume, and nothing else. */
34
+ export interface ResumeExportPayload {
35
+ resume: ResumeObject;
36
+ presentation?: ResumePresentation;
37
+ }
38
+
39
+ /**
40
+ * Everything the browser needs to draw a cover letter. The date line arrives
41
+ * already written, so the file does not depend on the renderer's locale or
42
+ * clock.
43
+ */
44
+ export interface LetterExportPayload {
45
+ letter: Letter;
46
+ date: string;
47
+ }
48
+
49
+ export type ExportPayload = ResumeExportPayload | LetterExportPayload;
50
+
51
+ export function isLetterPayload(
52
+ payload: ExportPayload,
53
+ ): payload is LetterExportPayload {
54
+ return 'letter' in payload;
55
+ }
56
+
57
+ /**
58
+ * Paper has no gap between its pages.
59
+ *
60
+ * The single parameter separating the exported document from the one on screen.
61
+ * Named here rather than written as a bare `0` at the call site, so the reason
62
+ * travels with the value.
63
+ */
64
+ export const PRINT_SHEET_GAP = 0;
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ export * from './locale.js';
2
+ export * from './resume.js';
3
+ export * from './resume-dates.js';
4
+ export * from './collections.js';
5
+ export * from './template.js';
6
+ export * from './library.js';
7
+ export * from './letter.js';
8
+ export * from './export-contract.js';
package/src/letter.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The content a letter document draws: who it is addressed to, its body and its
3
+ * sign-off. A shape, not a schema — whoever produces the letter validates it,
4
+ * and anything wider (a generator's notes, say) is still a `Letter`.
5
+ */
6
+ export interface Letter {
7
+ recipient?: string;
8
+ greeting: string;
9
+ paragraphs: string[];
10
+ closing: string;
11
+ signature: string;
12
+ }
package/src/library.ts ADDED
@@ -0,0 +1,179 @@
1
+ import type { ResumeObject } from './resume.js';
2
+ import type { APPENDABLE_SECTIONS } from './template.js';
3
+
4
+ /**
5
+ * Taking entries from the career profile into the resume being edited.
6
+ *
7
+ * The profile is the candidate's whole history; a resume carries the part
8
+ * chosen for it. These functions answer which of the profile's entries a
9
+ * resume does not carry yet, and how to name one in a list — pure, so the
10
+ * editor, its tests and any later surface agree on both. See
11
+ * `add-from-career-profile`.
12
+ */
13
+
14
+ export type LibrarySection = (typeof APPENDABLE_SECTIONS)[number];
15
+
16
+ const norm = (value: unknown) =>
17
+ String(value ?? '')
18
+ .toLowerCase()
19
+ .replace(/[^a-z0-9]/g, '');
20
+
21
+ type Item = Record<string, unknown>;
22
+
23
+ /**
24
+ * What makes two entries the SAME entry, per section.
25
+ *
26
+ * A role is its employer and when it began — not its title or bullets, which a
27
+ * tailored resume rewrites, so a reworded role is still recognised as the one
28
+ * already on the page. Everything else is recognised by the name it is listed
29
+ * under.
30
+ */
31
+ export function entryIdentity(section: LibrarySection, item: unknown): string {
32
+ if (typeof item === 'string') return norm(item);
33
+ const it = (item ?? {}) as Item;
34
+ switch (section) {
35
+ case 'experience':
36
+ return `${norm(it['company'])}|${String(it['start'] ?? '').slice(0, 7)}`;
37
+ case 'education':
38
+ return `${norm(it['school'])}|${norm(it['degree'])}`;
39
+ case 'skills':
40
+ return norm(it['category']);
41
+ case 'links':
42
+ return norm(String(it['url'] ?? '').replace(/^https?:\/\/(www\.)?/i, ''));
43
+ case 'languages':
44
+ return norm(it['name']);
45
+ case 'achievements':
46
+ case 'courses':
47
+ case 'passions':
48
+ return norm(it['title']);
49
+ case 'certifications':
50
+ return norm(item);
51
+ }
52
+ }
53
+
54
+ /** The profile's entries of `section` that `present` does not already carry. */
55
+ export function libraryCandidates(
56
+ section: LibrarySection,
57
+ present: readonly unknown[],
58
+ library: ResumeObject | null | undefined,
59
+ ): unknown[] {
60
+ const available = (library?.[section] ?? []) as readonly unknown[];
61
+ if (available.length === 0) return [];
62
+ const have = new Set(present.map((item) => entryIdentity(section, item)));
63
+ return available.filter((item) => {
64
+ const key = entryIdentity(section, item);
65
+ return key.length > 0 && key !== '|' && !have.has(key);
66
+ });
67
+ }
68
+
69
+ /** How an entry is named in a list: a title and, when there is one, a detail line. */
70
+ export function describeLibraryEntry(
71
+ section: LibrarySection,
72
+ item: unknown,
73
+ ): { title: string; detail?: string } {
74
+ if (typeof item === 'string') return { title: item };
75
+ const it = (item ?? {}) as Item;
76
+ const s = (key: string) =>
77
+ typeof it[key] === 'string' ? (it[key] as string) : '';
78
+ const joined = (...parts: string[]) =>
79
+ parts.filter(Boolean).join(' · ') || undefined;
80
+ switch (section) {
81
+ case 'experience':
82
+ return {
83
+ title: s('title') || s('company'),
84
+ detail: joined(
85
+ s('company'),
86
+ [s('start'), s('end')].filter(Boolean).join(' – '),
87
+ ),
88
+ };
89
+ case 'education':
90
+ return {
91
+ title: s('school'),
92
+ detail: joined(
93
+ [s('degree'), s('field')].filter(Boolean).join(', '),
94
+ s('end'),
95
+ ),
96
+ };
97
+ case 'skills': {
98
+ const items = Array.isArray(it['items']) ? (it['items'] as string[]) : [];
99
+ return {
100
+ title: s('category') || 'Skills',
101
+ detail: items.slice(0, 6).join(', ') || undefined,
102
+ };
103
+ }
104
+ case 'links':
105
+ return {
106
+ title: s('label') || s('url'),
107
+ detail: s('label') ? s('url') : undefined,
108
+ };
109
+ case 'languages':
110
+ return { title: s('name'), detail: s('level') || undefined };
111
+ default:
112
+ return { title: s('title'), detail: s('description') || undefined };
113
+ }
114
+ }
115
+
116
+ const sameText = (text: string) =>
117
+ text
118
+ .toLowerCase()
119
+ .replace(/[^a-z0-9]+/g, ' ')
120
+ .trim();
121
+
122
+ /** The profile's version of a role on the resume: same employer, same start. */
123
+ export function libraryRole(
124
+ role: { company?: unknown; start?: unknown },
125
+ library: ResumeObject | null | undefined,
126
+ ): ResumeObject['experience'][number] | undefined {
127
+ const key = entryIdentity('experience', role);
128
+ if (key === '|') return undefined;
129
+ return library?.experience.find(
130
+ (entry) => entryIdentity('experience', entry) === key,
131
+ );
132
+ }
133
+
134
+ /**
135
+ * The bullets the profile holds for this role that the resume's version of it
136
+ * does not — compared by their words, so a bullet that differs only in
137
+ * punctuation or case is not offered twice.
138
+ */
139
+ export function libraryBullets(
140
+ role: { company?: unknown; start?: unknown },
141
+ present: readonly string[],
142
+ library: ResumeObject | null | undefined,
143
+ ): string[] {
144
+ const match = libraryRole(role, library);
145
+ if (!match) return [];
146
+ const have = new Set(present.map(sameText));
147
+ return match.bullets.filter((bullet) => {
148
+ const key = sameText(bullet);
149
+ return key.length > 0 && !have.has(key);
150
+ });
151
+ }
152
+
153
+ /** What the profile can add from a role on the resume. */
154
+ export interface ExperienceOffer {
155
+ /** The profile's bullets for THIS role that the resume's version lacks. */
156
+ bullets: string[];
157
+ /** The profile's roles the resume does not carry at all. */
158
+ roles: ResumeObject['experience'];
159
+ }
160
+
161
+ /**
162
+ * Everything the profile can add, seen from one role: more of this role, and
163
+ * other roles. One answer for both, so a role already on the page never hides
164
+ * the bullets the resume left out of it.
165
+ */
166
+ export function experienceOffer(
167
+ role: { company?: unknown; start?: unknown; bullets?: readonly string[] },
168
+ present: readonly unknown[],
169
+ library: ResumeObject | null | undefined,
170
+ ): ExperienceOffer {
171
+ return {
172
+ bullets: libraryBullets(role, role.bullets ?? [], library),
173
+ roles: libraryCandidates(
174
+ 'experience',
175
+ present,
176
+ library,
177
+ ) as ResumeObject['experience'],
178
+ };
179
+ }
package/src/locale.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * The languages a document can be drawn in. A closed set: adding a language is
5
+ * adding it here and a catalog in `@resumekit/react`.
6
+ */
7
+ export const LocaleSchema = z.enum(['en', 'es']);
8
+ export type Locale = z.infer<typeof LocaleSchema>;
@@ -0,0 +1,252 @@
1
+ import type { ResumeObject } from './resume.js';
2
+
3
+ /**
4
+ * Whether a résumé's dates read the way a recruiter expects them to.
5
+ *
6
+ * The rules are NOT invented here. Both are already in the knowledge base, and
7
+ * both already bind the writer through `GUIDE`:
8
+ *
9
+ * - `reverse-chronological` — "List experience and education in reverse
10
+ * chronological order", because "recruiters expect the most recent, most
11
+ * relevant role first within a six-second scan".
12
+ * - `date-format` — "YYYY-MM, and 'Present' for the current role".
13
+ *
14
+ * What was missing is that neither bound the CANDIDATE. The editor lets them add
15
+ * a role, drag it anywhere and type any date into it, so a résumé could be
16
+ * exported with 2019 above 2024, or with a role that ends before it starts, and
17
+ * the first reader to notice was the recruiter doing the six-second scan.
18
+ *
19
+ * Pure and framework-free: no I/O, no model call, no clock. Comparing two dates
20
+ * is arithmetic, and a check the product can make itself must not become a
21
+ * billable request.
22
+ *
23
+ * @pii Reads employment dates and returns PATHS and an enum — never a date, and
24
+ * never anything that identifies the candidate.
25
+ */
26
+
27
+ /** What was noticed about a date. */
28
+ export type DateIssueKind =
29
+ /** The range ends before it starts. */
30
+ | 'ends-before-start'
31
+ /** This entry is more recent than the one above it. */
32
+ | 'out-of-order';
33
+
34
+ export interface DateIssue {
35
+ kind: DateIssueKind;
36
+ /** The entry this is about, e.g. `experience.1`. */
37
+ entryPath: string;
38
+ /** The fields to mark, e.g. `['experience.1.start', 'experience.1.end']`. */
39
+ fields: string[];
40
+ }
41
+
42
+ /**
43
+ * The word for a role that has not ended, in each language a resume can be
44
+ * translated to. Stored `Present` in English; a translation writes the target
45
+ * language's word instead, from this table rather than the model, so it costs
46
+ * nothing and reads the same in every resume.
47
+ */
48
+ export const PRESENT_WORDS = {
49
+ en: 'Present',
50
+ es: 'Actualidad',
51
+ fr: "Aujourd'hui",
52
+ de: 'Heute',
53
+ pt: 'Atual',
54
+ it: 'Presente',
55
+ nl: 'Heden',
56
+ pl: 'Obecnie',
57
+ ro: 'Prezent',
58
+ ru: 'Настоящее время',
59
+ uk: 'Дотепер',
60
+ tr: 'Günümüz',
61
+ sv: 'Nu',
62
+ zh: '至今',
63
+ ja: '現在',
64
+ ko: '현재',
65
+ hi: 'वर्तमान',
66
+ id: 'Sekarang',
67
+ } as const;
68
+
69
+ const PRESENT = new Set(
70
+ Object.values(PRESENT_WORDS).map((word) => word.toLocaleLowerCase()),
71
+ );
72
+
73
+ /** Whether an end date says the role has not ended, in any language. */
74
+ export function isPresentDate(value: string | undefined): boolean {
75
+ return PRESENT.has((value ?? '').trim().toLocaleLowerCase());
76
+ }
77
+
78
+ /**
79
+ * A date reduced to a number that sorts, or `null` when it cannot be read.
80
+ *
81
+ * `null` is the important return. A candidate mid-keystroke has `20`, and a
82
+ * résumé written like the reference one has `Feb 2024` — neither is wrong, and
83
+ * reporting either as an error would be the editor refusing a document that is
84
+ * perfectly good. Only what can be READ is judged; everything else is left
85
+ * alone. That is why this returns `null` rather than `0` or `NaN`.
86
+ *
87
+ * `Present` is the LARGEST value rather than today's date, deliberately: it
88
+ * means "has not ended", which outranks any month a candidate could type, and
89
+ * using a clock here would make the same résumé report differently tomorrow.
90
+ */
91
+ export function dateOrder(value: string | undefined): number | null {
92
+ const text = (value ?? '').trim();
93
+ if (!text) return null;
94
+ if (isPresentDate(text)) return Number.POSITIVE_INFINITY;
95
+
96
+ /* `YYYY-MM`, and `YYYY` alone — a degree is routinely dated by year, and a
97
+ year is perfectly comparable against a month in another entry. */
98
+ const iso = /^(\d{4})(?:-(\d{1,2}))?$/.exec(text);
99
+ if (iso) {
100
+ const year = Number(iso[1]);
101
+ const month = iso[2] ? Number(iso[2]) : 1;
102
+ if (month < 1 || month > 12) return null;
103
+ return year * 12 + (month - 1);
104
+ }
105
+ return null;
106
+ }
107
+
108
+ /** One dated entry, whichever section it came from. */
109
+ interface Dated {
110
+ start?: string;
111
+ end?: string;
112
+ }
113
+
114
+ /**
115
+ * The issues in one section's entries.
116
+ *
117
+ * Ordering is judged on the START date, which is what "reverse chronological"
118
+ * orders by: two roles that both ended in 2024 are ordered by which began more
119
+ * recently, and a current role has no end to order by at all.
120
+ *
121
+ * An entry whose start cannot be read is SKIPPED rather than treated as zero —
122
+ * and skipped without breaking the chain, so a half-typed row in the middle does
123
+ * not make every row beneath it look out of order. The comparison is against the
124
+ * last entry that could be read.
125
+ */
126
+ function sectionIssues(entries: readonly Dated[], path: string): DateIssue[] {
127
+ const issues: DateIssue[] = [];
128
+ let previousStart: number | null = null;
129
+
130
+ entries.forEach((entry, i) => {
131
+ const entryPath = `${path}.${i}`;
132
+ const start = dateOrder(entry.start);
133
+ const end = dateOrder(entry.end);
134
+
135
+ if (start !== null && end !== null && end < start) {
136
+ issues.push({
137
+ kind: 'ends-before-start',
138
+ entryPath,
139
+ fields: [`${entryPath}.start`, `${entryPath}.end`],
140
+ });
141
+ }
142
+
143
+ if (start === null) return;
144
+ if (previousStart !== null && start > previousStart) {
145
+ issues.push({
146
+ kind: 'out-of-order',
147
+ entryPath,
148
+ fields: [`${entryPath}.start`],
149
+ });
150
+ }
151
+ previousStart = start;
152
+ });
153
+
154
+ return issues;
155
+ }
156
+
157
+ /**
158
+ * Every date in a résumé that disagrees with the chronological rules.
159
+ *
160
+ * Sections are checked INDEPENDENTLY: experience running most-recent-first says
161
+ * nothing about education, and a section nobody has dated yet must not suppress
162
+ * the check on one that is complete.
163
+ */
164
+ export function resumeDateIssues(resume: ResumeObject): DateIssue[] {
165
+ return [
166
+ ...sectionIssues(resume.experience ?? [], 'experience'),
167
+ ...sectionIssues(resume.education ?? [], 'education'),
168
+ ];
169
+ }
170
+
171
+ /**
172
+ * The same check, over the order the document is actually DRAWN in.
173
+ *
174
+ * This replaces a version that scanned `experience.<n>.start` keys and walked
175
+ * them by `n`, and that was wrong in the one case the feature exists for.
176
+ *
177
+ * A path follows the JOB, not the position: a résumé the candidate has
178
+ * reordered renders `experience.2` in first place, and its fields keep saying
179
+ * `experience.2.*` so a stored edit follows the role rather than the slot. So
180
+ * the path index says where an entry STARTED, and reverse-chronological order
181
+ * is a claim about where it is NOW. Walking by index compared entries in an
182
+ * order nobody was looking at — and reported nothing on the very document a
183
+ * candidate had just dragged into the wrong order, which is exactly when they
184
+ * need telling.
185
+ *
186
+ * The caller passes the prefixes in drawn order, taken from the same
187
+ * `collectionOrder` the document lays itself out with, so the check and the
188
+ * page cannot disagree about which entry is above which.
189
+ *
190
+ * @param sections one array of entry path prefixes per section, each in the
191
+ * order the section is drawn — e.g. `[['experience.2', 'experience.0']]`.
192
+ * @param valueAt reads a field's current value, live from the editor.
193
+ */
194
+ export function dateIssuesInDrawnOrder(
195
+ sections: readonly (readonly string[])[],
196
+ valueAt: (path: string) => string | undefined,
197
+ ): Map<string, DateIssueKind> {
198
+ const byField = new Map<string, DateIssueKind>();
199
+
200
+ for (const prefixes of sections) {
201
+ let previousStart: number | null = null;
202
+
203
+ for (const prefix of prefixes) {
204
+ const start = dateOrder(valueAt(`${prefix}.start`));
205
+ const end = dateOrder(valueAt(`${prefix}.end`));
206
+
207
+ if (start !== null && end !== null && end < start) {
208
+ if (!byField.has(`${prefix}.start`))
209
+ byField.set(`${prefix}.start`, 'ends-before-start');
210
+ if (!byField.has(`${prefix}.end`))
211
+ byField.set(`${prefix}.end`, 'ends-before-start');
212
+ }
213
+
214
+ if (start === null) continue;
215
+ if (previousStart !== null && start > previousStart) {
216
+ if (!byField.has(`${prefix}.start`))
217
+ byField.set(`${prefix}.start`, 'out-of-order');
218
+ }
219
+ previousStart = start;
220
+ }
221
+ }
222
+
223
+ return byField;
224
+ }
225
+
226
+ /** What the editor says about each kind, in the candidate's terms. */
227
+ export const DATE_ISSUE_MESSAGE: Record<DateIssueKind, string> = {
228
+ 'ends-before-start': 'This ends before it starts — check the dates.',
229
+ 'out-of-order':
230
+ 'Recruiters expect the most recent first — this one starts later than the entry above it.',
231
+ };
232
+
233
+ /**
234
+ * The issues keyed by the FIELD path each one marks.
235
+ *
236
+ * Keyed by path because that is the address a field already knows itself by, so
237
+ * a field can ask "is there anything about me?" without knowing the résumé's
238
+ * shape — and every template gets this without being edited.
239
+ */
240
+ export function dateIssuesByField(
241
+ resume: ResumeObject,
242
+ ): Map<string, DateIssueKind> {
243
+ const byField = new Map<string, DateIssueKind>();
244
+ for (const issue of resumeDateIssues(resume)) {
245
+ for (const field of issue.fields) {
246
+ /* First wins. A range that is inverted AND out of order is more usefully
247
+ described by the thing wrong inside it than by its position. */
248
+ if (!byField.has(field)) byField.set(field, issue.kind);
249
+ }
250
+ }
251
+ return byField;
252
+ }