@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,2360 @@
1
+ import { z } from 'zod';
2
+ import {
3
+ COLLECTIONS,
4
+ PresentedResumeSchema,
5
+ TOP_LEVEL_COLLECTIONS,
6
+ isUnfilled,
7
+ type CollectionId,
8
+ type PresentedResume,
9
+ } from './collections.js';
10
+ import {
11
+ ContentAuthorSchema,
12
+ LinkTargetSchema,
13
+ CustomEntrySchema,
14
+ type ResumeObject,
15
+ } from './resume.js';
16
+ import { LocaleSchema } from './locale.js';
17
+
18
+ /**
19
+ * Resume templates — the renderers that turn a {@link ResumeObject} into a
20
+ * document — plus the **presentation overlay** that records a candidate's own
21
+ * corrections to one.
22
+ *
23
+ * Framework-free on purpose. A template is data here and a renderer in whichever
24
+ * surface draws it, so the same catalog is readable by the API, the web app, and
25
+ * any future render service, and switching template stays a data operation
26
+ * costing zero LLM tokens.
27
+ */
28
+
29
+ /**
30
+ * The template catalog. Data — add an entry plus a renderer and a new template
31
+ * exists; nothing about the editor changes.
32
+ *
33
+ * `ats` states what a template guarantees against the knowledge base's format
34
+ * rules. It is not marketing copy: every line must be true of the rendered
35
+ * document, because it is the reason a candidate can trust this output in a
36
+ * screening system.
37
+ *
38
+ * `columns` states the same fact as a NUMBER, because the chooser draws a badge
39
+ * from it and a badge cannot be produced by reading English. The `ats` lines are
40
+ * sentences written for a candidate, and matching `/two columns/i` against one
41
+ * would make the badge silently wrong the first time somebody reworded it — in
42
+ * the one property a screening system reads differently. Structured here, and
43
+ * `template.spec.ts` asserts the two AGREE rather than deriving one from the
44
+ * other. See `editor-tabbed-rail` (#48), design decision 3.
45
+ */
46
+ export const TEMPLATES = {
47
+ harvard: {
48
+ name: 'Harvard',
49
+ description:
50
+ 'The classic single-column resume: centred name block, rule-underlined ' +
51
+ 'section headings, and two-column experience entries.',
52
+ page: 'letter',
53
+ columns: 1,
54
+ ats: [
55
+ 'Single column — no sidebar, no text boxes',
56
+ 'No tables, images, or icon fonts carrying meaning',
57
+ 'Real selectable text, standard system typefaces',
58
+ 'Reverse-chronological sections with YYYY-MM dates',
59
+ ],
60
+ },
61
+ ivy: {
62
+ name: 'Ivy League',
63
+ description:
64
+ 'A centred academic page: the name over one contact line, section ' +
65
+ 'headings ruled across the column, and every entry set as four corners ' +
66
+ '— organisation and place over role and dates.',
67
+ page: 'letter',
68
+ columns: 1,
69
+ ats: [
70
+ 'Single column — no sidebar, no text boxes',
71
+ 'Skills as a list, one keyword per item, under their categories',
72
+ 'No tables, images, or icon fonts carrying meaning',
73
+ 'Real selectable text, standard system typefaces',
74
+ 'Reverse-chronological sections with YYYY-MM dates',
75
+ ],
76
+ },
77
+ classic: {
78
+ name: 'Classic',
79
+ description:
80
+ 'A plain left-aligned page whose only ornament is the accent on the ' +
81
+ 'line that names the employer: small uppercase headings, the role over ' +
82
+ 'the employer, and place and dates kept in a quiet column.',
83
+ page: 'letter',
84
+ columns: 1,
85
+ ats: [
86
+ 'Single column — no sidebar, no text boxes',
87
+ 'Headings in plain text, with no rules or bands to parse around',
88
+ 'No tables, images, or icon fonts carrying meaning',
89
+ 'Real selectable text, standard system typefaces',
90
+ 'Reverse-chronological sections with YYYY-MM dates',
91
+ ],
92
+ },
93
+ compact: {
94
+ name: 'Compact',
95
+ description:
96
+ 'Two dense columns with the resume in the wide one: the role on its ' +
97
+ 'own line over employer, dates and place, and a rail carrying skills ' +
98
+ 'as chips beside the candidate’s own sections.',
99
+ page: 'letter',
100
+ columns: 2,
101
+ ats: [
102
+ 'Two columns — the resume is written first, so extracted text reads the work history through before the rail',
103
+ 'Skills are chips by appearance and a list by structure — one skill per extracted line',
104
+ 'No tables, images, or icon fonts carrying meaning',
105
+ 'Real selectable text, standard system typefaces',
106
+ 'Reverse-chronological sections with YYYY-MM dates',
107
+ ],
108
+ },
109
+ timeline: {
110
+ name: 'Timeline',
111
+ description:
112
+ 'One column with every entry hung off a dated spine: the dates and the ' +
113
+ 'place at the left, a ruled line with a dot, then the role over the ' +
114
+ 'employer in the accent.',
115
+ page: 'letter',
116
+ columns: 1,
117
+ ats: [
118
+ 'Single column — the spine is a border, not a layout',
119
+ 'Each entry extracts as its dates, its place, then the role and employer',
120
+ 'Skills are chips by appearance and a list by structure — one skill per extracted line',
121
+ 'No tables, images, or icon fonts carrying meaning',
122
+ 'Reverse-chronological sections with YYYY-MM dates',
123
+ ],
124
+ },
125
+ modern: {
126
+ name: 'Modern',
127
+ description:
128
+ 'A navy name over an accented headline with the candidate’s initials ' +
129
+ 'beside it, and two columns whose headings are ruled across their own ' +
130
+ 'column rather than divided by a line.',
131
+ page: 'letter',
132
+ columns: 2,
133
+ ats: [
134
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
135
+ 'The initials are decoration with no text of their own to extract',
136
+ 'Skills are chips by appearance and a list by structure — one skill per extracted line',
137
+ 'No tables, images, or icon fonts carrying meaning',
138
+ 'Reverse-chronological sections with YYYY-MM dates',
139
+ ],
140
+ },
141
+ stylish: {
142
+ name: 'Stylish',
143
+ description:
144
+ 'Two columns with the highlights rail on the left and the work history ' +
145
+ 'beside it, headings ruled across their own column, and the ' +
146
+ 'candidate’s initials beside the name.',
147
+ page: 'letter',
148
+ columns: 2,
149
+ ats: [
150
+ 'Two columns, written in the order they are read — the rail is on the left, so extracted text gives the highlights and skills before the work history',
151
+ 'The initials are decoration with no text of their own to extract',
152
+ 'Skills are chips by appearance and a list by structure — one skill per extracted line',
153
+ 'No tables, images, or icon fonts carrying meaning',
154
+ 'Reverse-chronological sections with YYYY-MM dates',
155
+ ],
156
+ },
157
+ creative: {
158
+ name: 'Creative',
159
+ description:
160
+ 'A full-width band carrying the name, the headline, the contact details ' +
161
+ 'and the candidate’s initials, over two columns with the work history ' +
162
+ 'in the wide one.',
163
+ page: 'letter',
164
+ columns: 2,
165
+ ats: [
166
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
167
+ 'Band colour is forced to print, so white-on-navy never vanishes',
168
+ 'Skills are chips by appearance and a list by structure — one skill per extracted line',
169
+ 'No tables, images, or icon fonts carrying meaning',
170
+ 'Reverse-chronological sections with YYYY-MM dates',
171
+ ],
172
+ },
173
+ contemporary: {
174
+ name: 'Contemporary',
175
+ description:
176
+ 'The candidate’s initials at the head of a left rail that carries the ' +
177
+ 'contact details as a section of their own, beside the name and a ' +
178
+ 'headline set in a tinted pill.',
179
+ page: 'letter',
180
+ columns: 2,
181
+ ats: [
182
+ 'Two columns, written in the order they are read — the rail is on the left, so extracted text gives the contact details and highlights before the work history',
183
+ 'The headline’s pill is a background behind ordinary text — nothing is lost when the colour is not printed',
184
+ 'Skills as a list, one keyword per item, under their categories',
185
+ 'No tables, images, or icon fonts carrying meaning',
186
+ 'Reverse-chronological sections with YYYY-MM dates',
187
+ ],
188
+ },
189
+ 'double-column': {
190
+ name: 'Double Column',
191
+ description:
192
+ 'The plainest two-column page in the catalog: bold uppercase headings ' +
193
+ 'over a heavy rule, with the work history in the wide column and the ' +
194
+ 'highlights in a rail.',
195
+ page: 'letter',
196
+ columns: 2,
197
+ ats: [
198
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
199
+ 'Skills are filled chips by appearance and a list by structure — one skill per extracted line',
200
+ 'Nothing on the page depends on a printed background',
201
+ 'No tables, images, or icon fonts carrying meaning',
202
+ 'Reverse-chronological sections with YYYY-MM dates',
203
+ ],
204
+ },
205
+ 'double-column-logos': {
206
+ name: 'Double Column with Logos',
207
+ description:
208
+ 'Double Column’s page with a mark beside every employer, drawn from ' +
209
+ 'the employer’s own initials — a resume stores no logos, and the ' +
210
+ 'renderer fetches nothing.',
211
+ page: 'letter',
212
+ columns: 2,
213
+ ats: [
214
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
215
+ 'The marks are initials with no text of their own to extract, and no image is fetched',
216
+ 'Skills are filled chips by appearance and a list by structure — one skill per extracted line',
217
+ 'No tables, images, or icon fonts carrying meaning',
218
+ 'Reverse-chronological sections with YYYY-MM dates',
219
+ ],
220
+ },
221
+ elegant: {
222
+ name: 'Elegant',
223
+ description:
224
+ 'A painted rail down the right of every sheet, reversed out in white, ' +
225
+ 'beside a work history that is written first — the highlights, the ' +
226
+ 'skills and the candidate’s own sections ride the rail.',
227
+ page: 'letter',
228
+ columns: 2,
229
+ ats: [
230
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
231
+ 'Rail colour is forced to print, so white-on-navy never vanishes',
232
+ 'The rail is a column with a background, not a box the text is placed inside',
233
+ 'No tables, images, or icon fonts carrying meaning',
234
+ 'Reverse-chronological sections with YYYY-MM dates',
235
+ ],
236
+ },
237
+ 'elegant-logos': {
238
+ name: 'Elegant with Logos',
239
+ description:
240
+ 'Elegant’s painted rail with a mark beside every employer, drawn from ' +
241
+ 'the employer’s own initials — a resume stores no logos, and the ' +
242
+ 'renderer fetches nothing.',
243
+ page: 'letter',
244
+ columns: 2,
245
+ ats: [
246
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
247
+ 'Rail colour is forced to print, so white-on-navy never vanishes',
248
+ 'The marks are initials with no text of their own to extract, and no image is fetched',
249
+ 'No tables, images, or icon fonts carrying meaning',
250
+ 'Reverse-chronological sections with YYYY-MM dates',
251
+ ],
252
+ },
253
+ polished: {
254
+ name: 'Polished',
255
+ description:
256
+ 'A painted rail down the left of every sheet carrying the name at its ' +
257
+ 'head, with the headline, the contact details and the work history in ' +
258
+ 'the wide column beside it.',
259
+ page: 'letter',
260
+ columns: 2,
261
+ ats: [
262
+ 'Two columns, written in the order they are read — the rail is on the left, so extracted text opens with the name and the highlights',
263
+ 'Rail colour is forced to print, so white-on-teal never vanishes',
264
+ 'The rail is a column with a background, not a box the text is placed inside',
265
+ 'No tables, images, or icon fonts carrying meaning',
266
+ 'Reverse-chronological sections with YYYY-MM dates',
267
+ ],
268
+ },
269
+ executive: {
270
+ name: 'Executive',
271
+ description:
272
+ 'A coloured header band with a monogram, small-capital section ' +
273
+ 'headings, and a two-column skills list.',
274
+ page: 'letter',
275
+ /*
276
+ * ONE, and the description's "two-column skills list" is not a
277
+ * contradiction: those are CSS `columns` over a single list, so the body is
278
+ * one column and the extracted text is linear. This is the number a
279
+ * screening system cares about, which is why it is not read off the prose.
280
+ */
281
+ columns: 1,
282
+ /*
283
+ * Deliberately NOT Harvard's list. This template's skills run in two
284
+ * columns, so it must not claim a single one — the honest guarantee is that
285
+ * the columns are visual: CSS columns over ONE list, leaving the text a
286
+ * parser extracts in document order.
287
+ */
288
+ ats: [
289
+ 'Skills in visual columns over a single list — extracted text stays linear',
290
+ 'No tables, images, or icon fonts carrying meaning',
291
+ 'Real selectable text, standard system typefaces',
292
+ 'Header colour is forced to print, so white-on-navy never vanishes',
293
+ 'Reverse-chronological sections with YYYY-MM dates',
294
+ ],
295
+ },
296
+ meridian: {
297
+ name: 'Meridian',
298
+ description:
299
+ 'A charcoal crown band with a rule-flanked monogram over a terracotta ' +
300
+ 'contact rule, and a body split by a full-height hairline into a main ' +
301
+ 'column and a keyword sidebar. Its headings are set in the template’s ' +
302
+ 'own serif; the typeface you choose sets everything else.',
303
+ page: 'letter',
304
+ columns: 2,
305
+ /*
306
+ * A DISCLOSURE, not a reassurance — and the difference is the whole reason
307
+ * this list is separate from Executive's.
308
+ *
309
+ * Executive can say its extracted text stays linear because its columns are
310
+ * CSS `columns` over ONE list: the DOM order and the read order are the same
311
+ * order. These columns are grid tracks holding different sections, so that
312
+ * property does not hold and borrowing the phrasing would put the product's
313
+ * central claim behind a sentence somebody typed. What IS true is the
314
+ * reading order, and `meridian.spec.tsx` holds the renderer to it.
315
+ */
316
+ ats: [
317
+ 'Two columns — the resume is written first, so extracted text reads it through before the sidebar',
318
+ 'No tables, images, or icon fonts carrying meaning',
319
+ 'Real selectable text, standard system typefaces',
320
+ 'Both bands are forced to print, so white-on-charcoal never vanishes',
321
+ 'Reverse-chronological sections with YYYY-MM dates',
322
+ ],
323
+ },
324
+ cobalt: {
325
+ name: 'Cobalt',
326
+ description:
327
+ 'A cobalt hexagonal crest beside the name in serif, section headings ' +
328
+ 'underlined across their own column, and a body of two columns with the ' +
329
+ 'keyword rail on the left. Its headings are set in the template’s own ' +
330
+ 'serif; the typeface you choose sets everything else.',
331
+ page: 'letter',
332
+ columns: 2,
333
+ /*
334
+ * Two guarantees here are this template's alone.
335
+ *
336
+ * The FIRST names sections rather than a column. "The main column is read
337
+ * first" is what Meridian can say, because its main column is also its left
338
+ * one; this template's rail is on the left, so the honest statement is the
339
+ * order a parser actually gets — and a column name tells a candidate
340
+ * nothing about their own résumé anyway.
341
+ *
342
+ * The FOURTH is the one no other template in this catalog can make. Both
343
+ * Executive and Meridian force a background colour to print, which is a
344
+ * promise about a browser setting: when it is declined, reversed type on an
345
+ * unpainted band does not degrade, it disappears. This template draws no
346
+ * band at all — every mark it makes is a glyph, a border, or a stroked
347
+ * outline — so the claim is about paper rather than about a hint, and
348
+ * `cobalt.spec.tsx` holds the stylesheet to it.
349
+ */
350
+ ats: [
351
+ 'Two columns, written in the order they are read — extracted text runs summary, skills and education, then the work history',
352
+ 'No tables, images, or icon fonts carrying meaning',
353
+ 'Real selectable text, standard system typefaces',
354
+ 'No printed band — every mark is foreground ink, so it prints complete with background graphics off',
355
+ 'Reverse-chronological sections with YYYY-MM dates',
356
+ ],
357
+ },
358
+ /*
359
+ * The ten below reproduce widely used LaTeX designs (`ten-new-templates`,
360
+ * #116; origins and licences in `docs/template-references/README.md`). Their
361
+ * references are A4 or Letter, but the paginator and the export are Letter
362
+ * only, so each states the page it is actually rendered on.
363
+ */
364
+ crimson: {
365
+ name: 'Crimson',
366
+ description:
367
+ 'A centred name set light then bold over a job line in crimson and the ' +
368
+ 'contact details behind small icons, then section headings that open in ' +
369
+ 'crimson beside a rule running to the margin. Each entry puts the ' +
370
+ 'employer and place over the role and dates.',
371
+ page: 'letter',
372
+ columns: 1,
373
+ ats: [
374
+ 'Single column — no sidebar, no text boxes',
375
+ 'Skills under their categories, one keyword per extracted unit — never a comma run',
376
+ 'Contact icons are drawn marks with no text of their own to extract',
377
+ 'Real selectable text, set in typefaces embedded in the file',
378
+ 'Reverse-chronological sections with YYYY-MM dates',
379
+ ],
380
+ },
381
+ engineer: {
382
+ name: 'Engineer',
383
+ description:
384
+ 'A dense one-page layout for a first technical job: a large serif name ' +
385
+ 'over a single contact line, small-capital headings over a hairline, and ' +
386
+ 'every entry set as four corners, its title and place over the detail and dates.',
387
+ page: 'letter',
388
+ columns: 1,
389
+ ats: [
390
+ 'Single column — no sidebar, no text boxes',
391
+ 'Skills under their categories, one keyword per extracted unit — never a comma run',
392
+ 'No tables, images, or icon fonts carrying meaning',
393
+ 'Real selectable text, set in typefaces embedded in the file',
394
+ 'Reverse-chronological sections with YYYY-MM dates',
395
+ ],
396
+ },
397
+ split: {
398
+ name: 'Split',
399
+ description:
400
+ 'An oversized light name over the contact lines and a full-width ' +
401
+ 'hairline, then two columns under large light uppercase headings: a ' +
402
+ 'narrow one on the left for education, skills and links, and a wide one ' +
403
+ 'for the work history.',
404
+ page: 'letter',
405
+ columns: 2,
406
+ ats: [
407
+ 'Two columns, written in the order they are read — the narrow column is on the left, so extracted text gives education, skills and links before the work history',
408
+ 'Skills under their categories, one keyword per extracted unit — never a comma run',
409
+ 'No tables, images, or icon fonts carrying meaning',
410
+ 'Real selectable text, set in typefaces embedded in the file',
411
+ 'Reverse-chronological sections with YYYY-MM dates',
412
+ ],
413
+ },
414
+ academic: {
415
+ name: 'Academic',
416
+ description:
417
+ 'A traditional European curriculum vitae: a large serif name and an ' +
418
+ 'italic title beside a right-aligned contact block and the candidate’s ' +
419
+ 'initials, headings led by a green bar, and every entry hung off its ' +
420
+ 'dates in a margin of their own.',
421
+ page: 'letter',
422
+ columns: 1,
423
+ ats: [
424
+ 'Single column — the date margin is part of each entry, not a layout',
425
+ 'Each entry extracts as its dates first, then the role, the organisation and the details',
426
+ 'Skills under their categories, one keyword per extracted unit — never a comma run',
427
+ 'No tables, images, or icon fonts carrying meaning',
428
+ 'Reverse-chronological sections with YYYY-MM dates',
429
+ ],
430
+ },
431
+ alta: {
432
+ name: 'Alta',
433
+ description:
434
+ 'A bold slab-serif name over a coloured tagline and a band of contact ' +
435
+ 'icons, the initials in a disc at the right, and two columns under ' +
436
+ 'headings ruled in gold: the work history in the wide one, highlights, ' +
437
+ 'skills and languages with level dots in the other.',
438
+ page: 'letter',
439
+ columns: 2,
440
+ ats: [
441
+ 'Two columns — the work history is written first, so extracted text reads it through before the rail',
442
+ 'Language levels print as words; the dots beside them are decoration',
443
+ 'Contact icons are drawn marks with no text of their own to extract',
444
+ 'Real selectable text, set in typefaces embedded in the file',
445
+ 'Reverse-chronological sections with YYYY-MM dates',
446
+ ],
447
+ },
448
+ prism: {
449
+ name: 'Prism',
450
+ description:
451
+ 'A charcoal band across the top with the name set light then bold, a ' +
452
+ 'narrow right-aligned column of contact details and skills at the left, ' +
453
+ 'and section headings whose opening letters change colour from one ' +
454
+ 'section to the next.',
455
+ page: 'letter',
456
+ columns: 2,
457
+ /*
458
+ * A disclosure first: this is a design for a reader, and saying so plainly
459
+ * is the honest guarantee. What is still true of it follows.
460
+ */
461
+ ats: [
462
+ 'Two columns, written in the order they are read — the label column is on the left, so extracted text gives the contact details and skills before the work history',
463
+ 'Not built for screening systems — a design to hand to a reader, not to upload to a job portal',
464
+ 'The header band is forced to print, so white-on-charcoal never vanishes',
465
+ 'Reverse-chronological sections with YYYY-MM dates',
466
+ ],
467
+ },
468
+ hipster: {
469
+ name: 'Hipster',
470
+ description:
471
+ 'A charcoal name band over a grey sidebar carrying the candidate’s ' +
472
+ 'initials in a circle and short notes under small coloured labels, ' +
473
+ 'beside a work history hung off a dated spine under small-capital ' +
474
+ 'headings.',
475
+ page: 'letter',
476
+ columns: 2,
477
+ ats: [
478
+ 'Two columns, written in the order they are read — the sidebar is on the left, so extracted text gives the summary and skills before the work history',
479
+ 'Not built for screening systems — a design to hand to a reader, not to upload to a job portal',
480
+ 'The header band is forced to print, so white-on-charcoal never vanishes',
481
+ 'The rail is a column with a background, not a box the text is placed inside',
482
+ 'The initials are decoration with no text of their own to extract',
483
+ ],
484
+ },
485
+ scholar: {
486
+ name: 'Scholar',
487
+ description:
488
+ 'A formal serif page: the name in bold blue italics centred over the ' +
489
+ 'contact details, italic blue section headings over a full-width rule, ' +
490
+ 'and each entry set as four corners with its details in italics.',
491
+ page: 'letter',
492
+ columns: 1,
493
+ ats: [
494
+ 'Single column — no sidebar, no text boxes',
495
+ 'Skills under their categories, one keyword per extracted unit — never a comma run',
496
+ 'Contact details in one centred block of plain text, with no icons',
497
+ 'Real selectable text, set in typefaces embedded in the file',
498
+ 'Reverse-chronological sections with YYYY-MM dates',
499
+ ],
500
+ },
501
+ portrait: {
502
+ name: 'Portrait',
503
+ description:
504
+ 'A grey sidebar down the left with the candidate’s initials in a large ' +
505
+ 'circle, the name in blue, the contact details beside round icons, the ' +
506
+ 'summary and the skills, next to a body whose headings set their opening ' +
507
+ 'letters in a filled tab.',
508
+ page: 'letter',
509
+ columns: 2,
510
+ ats: [
511
+ 'Two columns, written in the order they are read — the sidebar is on the left, so extracted text opens with the name, the contact details and the skills',
512
+ 'Not built for screening systems — a design to hand to a reader, not to upload to a job portal',
513
+ 'The rail is a column with a background, not a box the text is placed inside',
514
+ 'The initials are decoration with no text of their own to extract',
515
+ ],
516
+ },
517
+ curve: {
518
+ name: 'Curve',
519
+ description:
520
+ 'One column for a research record: bold headings over a fading green ' +
521
+ 'rule, and every entry hung off its dates at the left beside a small ' +
522
+ 'crimson marker — a layout that suits publications kept as a section of ' +
523
+ 'their own.',
524
+ page: 'letter',
525
+ columns: 1,
526
+ ats: [
527
+ 'Single column — the date margin is part of each entry, not a layout',
528
+ 'Each entry extracts as its dates first, then the role, the organisation and the details',
529
+ 'Entry markers are drawn shapes with no text of their own to extract',
530
+ 'No tables, images, or icon fonts carrying meaning',
531
+ 'Reverse-chronological sections with YYYY-MM dates',
532
+ ],
533
+ },
534
+ } as const;
535
+
536
+ export type TemplateId = keyof typeof TEMPLATES;
537
+ export type TemplateDetails = (typeof TEMPLATES)[TemplateId];
538
+
539
+ /**
540
+ * Derived from the catalog keys rather than declared a second time: a template
541
+ * that exists but cannot be requested (or the reverse) is exactly the drift this
542
+ * avoids.
543
+ */
544
+ export const TemplateIdSchema = z.enum(
545
+ Object.keys(TEMPLATES) as [TemplateId, ...TemplateId[]],
546
+ );
547
+
548
+ /** What a resume is presented in when nobody has chosen. */
549
+ export const DEFAULT_TEMPLATE_ID: TemplateId = 'harvard';
550
+
551
+ export function templateDetails(id: TemplateId): TemplateDetails {
552
+ return TEMPLATES[id];
553
+ }
554
+
555
+ /** The catalog paired with the ids that address it, in declaration order. */
556
+ export function orderedTemplates(): {
557
+ id: TemplateId;
558
+ details: TemplateDetails;
559
+ }[] {
560
+ return (Object.keys(TEMPLATES) as TemplateId[]).map((id) => ({
561
+ id,
562
+ details: TEMPLATES[id],
563
+ }));
564
+ }
565
+
566
+ /**
567
+ * Operator configuration for one template.
568
+ *
569
+ * Deliberately NOT the whole catalog. Two kinds of fact get called "template
570
+ * metadata" and they have opposite requirements:
571
+ *
572
+ * - **Renderer-bound facts** — id, page size, ATS guarantees — describe what
573
+ * the code DOES. `harvard` is single-column at US Letter because
574
+ * `HarvardDocument` and `harvard.css` say so. In a database the two can
575
+ * disagree, and the product's central claim becomes a string somebody typed.
576
+ * They stay in {@link TEMPLATES}, where a test can hold them to it.
577
+ * - **Operator decisions** — offered or not, in what order, emphasised,
578
+ * badged — describe what the business wants this week and change without
579
+ * any code changing. Needing a deploy for those is the actual complaint.
580
+ *
581
+ * This is the second kind. Every field but the id is optional, so a document
582
+ * that sets only `enabled` is valid configuration.
583
+ */
584
+ export const TemplateConfigSchema = z.object({
585
+ template_id: z.string(),
586
+ enabled: z.boolean().optional(),
587
+ order: z.number().optional(),
588
+ featured: z.boolean().optional(),
589
+ badge: z.string().max(24).optional(),
590
+ });
591
+ export type TemplateConfig = z.infer<typeof TemplateConfigSchema>;
592
+
593
+ /** A template as offered to a candidate: catalog facts plus operator emphasis. */
594
+ export const OfferedTemplateSchema = z.object({
595
+ id: TemplateIdSchema,
596
+ name: z.string(),
597
+ description: z.string(),
598
+ page: z.string(),
599
+ /** How many columns the body is. Drawn as the chooser's badge. */
600
+ columns: z.number(),
601
+ ats: z.array(z.string()),
602
+ featured: z.boolean().optional(),
603
+ badge: z.string().optional(),
604
+ });
605
+ export type OfferedTemplate = z.infer<typeof OfferedTemplateSchema>;
606
+
607
+ function isTemplateId(id: string): id is TemplateId {
608
+ return Object.prototype.hasOwnProperty.call(TEMPLATES, id);
609
+ }
610
+
611
+ /**
612
+ * The templates a candidate is offered: the catalog, layered with operator
613
+ * configuration. Pure — no I/O, no model call.
614
+ *
615
+ * Configuration can hide a template, order it, and emphasise it. It can NEVER
616
+ * introduce one: an id the catalog does not contain is ignored, because a
617
+ * template without a renderer is a row that draws nothing.
618
+ *
619
+ * The result is never empty. If configuration would leave nothing offered — a
620
+ * bad seed, a typo, a half-finished migration — the default is offered anyway.
621
+ * An editor with no template to choose is not a degraded screen but a broken
622
+ * one, and that failure would arrive through data, where no test would catch it.
623
+ */
624
+ export function resolveTemplates(
625
+ configs?: readonly TemplateConfig[],
626
+ ): OfferedTemplate[] {
627
+ const byId = new Map(
628
+ (configs ?? [])
629
+ .filter((c) => isTemplateId(c.template_id))
630
+ .map((c) => [c.template_id as TemplateId, c]),
631
+ );
632
+
633
+ const offered = (Object.keys(TEMPLATES) as TemplateId[])
634
+ .filter((id) => byId.get(id)?.enabled !== false)
635
+ .map((id, index) => ({
636
+ id,
637
+ ...TEMPLATES[id],
638
+ ats: [...TEMPLATES[id].ats],
639
+ // Catalog order is the tiebreak, so an unordered template keeps its place
640
+ // rather than jumping to the front on a zero default.
641
+ _order: byId.get(id)?.order ?? index,
642
+ featured: byId.get(id)?.featured,
643
+ badge: byId.get(id)?.badge,
644
+ }))
645
+ .sort((a, b) => a._order - b._order)
646
+ .map(({ _order: _drop, ...rest }) => rest);
647
+
648
+ if (offered.length > 0) return offered;
649
+ return [
650
+ {
651
+ id: DEFAULT_TEMPLATE_ID,
652
+ ...TEMPLATES[DEFAULT_TEMPLATE_ID],
653
+ ats: [...TEMPLATES[DEFAULT_TEMPLATE_ID].ats],
654
+ },
655
+ ];
656
+ }
657
+
658
+ /**
659
+ * Segments that would climb out of the object being edited. Checked by name
660
+ * rather than relying on the final schema parse, because assignment to
661
+ * `__proto__` mutates a shared prototype *before* anything gets validated.
662
+ */
663
+ const FORBIDDEN_SEGMENTS: readonly string[] = [
664
+ '__proto__',
665
+ 'constructor',
666
+ 'prototype',
667
+ ];
668
+
669
+ /** A field name (`summary`, `still_missing`) or an array index (`0`, `12`). */
670
+ const SEGMENT = /^(?:[a-z][a-z0-9_]*|\d+)$/;
671
+
672
+ /**
673
+ * Whether a string addresses a location in a {@link ResumeObject} —
674
+ * `summary`, `contact.email`, `experience.2.bullets`.
675
+ *
676
+ * Grammar only. Whether the path *resolves* against a particular resume is a
677
+ * separate question, answered at apply time, because an overlay outlives the
678
+ * resume it was written against.
679
+ */
680
+ export function isResumeFieldPath(path: string): boolean {
681
+ if (path.length === 0) return false;
682
+ const segments = path.split('.');
683
+ return segments.every(
684
+ (s) => SEGMENT.test(s) && !FORBIDDEN_SEGMENTS.includes(s),
685
+ );
686
+ }
687
+
688
+ export const ResumeFieldPathSchema = z
689
+ .string()
690
+ .refine(isResumeFieldPath, {
691
+ message:
692
+ 'Not a resume field path (expected e.g. "summary" or "experience.0.bullets").',
693
+ })
694
+ .describe('A dotted path naming a location in the structured resume.');
695
+
696
+ /**
697
+ * One edited value: a single field, or a whole list.
698
+ *
699
+ * A list is stored whole rather than as a patch. Resume bullets are bare
700
+ * strings with no stable identity, so any per-item merge would need synthetic
701
+ * ids invented purely to serve the editor — see `design.md`, decision 2.
702
+ */
703
+ export const EditValueSchema = z.union([z.string(), z.array(z.string())]);
704
+ export type EditValue = z.infer<typeof EditValueSchema>;
705
+
706
+ /** One replaced field: where, and what it now says. */
707
+ export const SetEditSchema = z.object({
708
+ kind: z.literal('set'),
709
+ path: ResumeFieldPathSchema,
710
+ value: EditValueSchema,
711
+ });
712
+ export type SetEdit = z.infer<typeof SetEditSchema>;
713
+
714
+ /**
715
+ * A section that takes appended entries.
716
+ *
717
+ * An allowlist rather than any array path: appending is only meaningful for the
718
+ * listed sections a template draws as repeated entries, and naming them keeps
719
+ * `experience.0.bullets` — which has its own add/remove control — out of a
720
+ * second, structural route to the same thing.
721
+ */
722
+ export const APPENDABLE_SECTIONS = [
723
+ 'experience',
724
+ 'education',
725
+ 'skills',
726
+ 'certifications',
727
+ 'links',
728
+ 'achievements',
729
+ 'courses',
730
+ 'passions',
731
+ 'languages',
732
+ ] as const;
733
+
734
+ /**
735
+ * The same set, derived from {@link COLLECTIONS}.
736
+ *
737
+ * `template.spec.ts` asserts the two agree, so a collection cannot be addable
738
+ * here and unknown there — the check `registry.spec.ts` already performs for
739
+ * templates and their renderers. A tuple is kept above because `z.enum` needs
740
+ * one; the derivation is what makes it a projection rather than a second list.
741
+ *
742
+ * `custom_sections` is excluded: a section carries a heading, so declaring one
743
+ * is a different act from appending an entry, and it has its own operation.
744
+ */
745
+ export const APPENDABLE_FROM_COLLECTIONS: readonly CollectionId[] =
746
+ TOP_LEVEL_COLLECTIONS.filter((id) => id !== 'custom_sections');
747
+ export type AppendableSection = (typeof APPENDABLE_SECTIONS)[number];
748
+ export const AppendableSectionSchema = z.enum(APPENDABLE_SECTIONS);
749
+
750
+ /**
751
+ * An entry the candidate added to a listed section.
752
+ *
753
+ * `ref` is minted when the entry is created and is how a later `drop` names it.
754
+ * NOT an index: an index is a claim about the base the overlay was written
755
+ * against, and the base changes every time the writer runs again.
756
+ *
757
+ * `entry` is validated against the section's own schema at apply time, so an
758
+ * appended role is the same shape as a written one and is edited through the
759
+ * same locked nodes.
760
+ */
761
+ export const AppendEditSchema = z.object({
762
+ kind: z.literal('append'),
763
+ ref: z.string().min(1),
764
+ section: AppendableSectionSchema,
765
+ entry: z.unknown(),
766
+ author: ContentAuthorSchema,
767
+ });
768
+ export type AppendEdit = z.infer<typeof AppendEditSchema>;
769
+
770
+ /**
771
+ * Removal of an addition THIS overlay made.
772
+ *
773
+ * There is deliberately no way to express the removal of writer-produced
774
+ * content. The match score, the requirement audit and `still_missing[]` are all
775
+ * derived against what the writer produced; a document that can silently lose a
776
+ * grounded role is one those derivations no longer describe. Correcting such a
777
+ * role is the `set` path, which already exists.
778
+ */
779
+ export const DropEditSchema = z.object({
780
+ kind: z.literal('drop'),
781
+ ref: z.string().min(1),
782
+ });
783
+ export type DropEdit = z.infer<typeof DropEditSchema>;
784
+
785
+ /** A section the schema has no concept of, declared by the candidate. */
786
+ export const SectionEditSchema = z.object({
787
+ kind: z.literal('section'),
788
+ ref: z.string().min(1),
789
+ heading: z.string().min(1),
790
+ entries: z.array(CustomEntrySchema).default([]),
791
+ author: ContentAuthorSchema,
792
+ });
793
+ export type SectionEdit = z.infer<typeof SectionEditSchema>;
794
+
795
+ /**
796
+ * The schema an appended entry is validated against, per section.
797
+ *
798
+ * An appended role is the SAME shape as a written one — that is what lets it be
799
+ * edited through the same locked nodes and rendered by the same template code.
800
+ * A candidate fills fields; they never compose a layout.
801
+ */
802
+ const APPEND_SCHEMAS = {
803
+ experience: COLLECTIONS.experience.item,
804
+ education: COLLECTIONS.education.item,
805
+ skills: COLLECTIONS.skills.item,
806
+ certifications: COLLECTIONS.certifications.item,
807
+ links: COLLECTIONS.links.item,
808
+ achievements: COLLECTIONS.achievements.item,
809
+ courses: COLLECTIONS.courses.item,
810
+ passions: COLLECTIONS.passions.item,
811
+ languages: COLLECTIONS.languages.item,
812
+ } satisfies Record<AppendableSection, z.ZodTypeAny>;
813
+
814
+ /**
815
+ * One position in a collection, named by WHAT it is rather than by where it sits.
816
+ *
817
+ * A base index names an entry the writer produced; a `ref` names an addition
818
+ * this overlay made. Naming an addition by its ref rather than by its index is
819
+ * what stops dropping one addition from silently re-pointing the slots after it,
820
+ * which a bare list of numbers would.
821
+ *
822
+ * When `document-composition` (#37) mints server-side entry ids, both arms
823
+ * collapse into `{ id }` and the resolution below loses its stale-index branch.
824
+ */
825
+ export const SlotSchema = z.union([
826
+ z.object({ base: z.number().int().nonnegative() }),
827
+ z.object({ ref: z.string().min(1) }),
828
+ ]);
829
+ export type Slot = z.infer<typeof SlotSchema>;
830
+
831
+ /** Stable text for a slot, so two slots can be compared without a type test. */
832
+ export const slotKey = (slot: Slot): string =>
833
+ 'base' in slot ? `b${slot.base}` : `r${slot.ref}`;
834
+
835
+ /**
836
+ * The order the candidate put a collection in.
837
+ *
838
+ * Stored as an ORDERING rather than applied by renumbering the overlay's paths.
839
+ * A renumbering is a claim about the base an overlay was written against, and
840
+ * that base changes every time the writer runs again; an ordering is a claim
841
+ * about nothing but itself. Applied last — see `applyPresentation` — so every
842
+ * replacement has already landed on the position it was written against.
843
+ */
844
+ export const ReorderEditSchema = z.object({
845
+ kind: z.literal('reorder'),
846
+ section: AppendableSectionSchema,
847
+ order: z.array(SlotSchema),
848
+ });
849
+ export type ReorderEdit = z.infer<typeof ReorderEditSchema>;
850
+
851
+ /**
852
+ * A writer-produced entry the candidate does not want on this document.
853
+ *
854
+ * HIDDEN, not deleted, and the distinction is not softness. `match_score`, the
855
+ * requirement audit and `still_missing[]` are all derived against what the
856
+ * writer produced; deleting a role would leave those figures describing a
857
+ * document that no longer exists. A hidden entry is absent from the render and
858
+ * from every export, restorable by the candidate, and still visible as a hidden
859
+ * entry to anything that reads the overlay.
860
+ */
861
+ export const HideEditSchema = z.object({
862
+ kind: z.literal('hide'),
863
+ section: AppendableSectionSchema,
864
+ base: z.number().int().nonnegative(),
865
+ });
866
+ export type HideEdit = z.infer<typeof HideEditSchema>;
867
+
868
+ /**
869
+ * One operation in the overlay.
870
+ *
871
+ * `kind` is INJECTED as `'set'` when absent, which is what makes this change
872
+ * additive rather than a migration: every overlay stored before structural
873
+ * operations existed is a list of bare `{path, value}` objects, and each one
874
+ * parses here as the replacement it has always been, with exactly its previous
875
+ * meaning.
876
+ */
877
+ export const ResumeEditSchema = z.preprocess(
878
+ (raw) =>
879
+ raw && typeof raw === 'object' && !('kind' in raw)
880
+ ? { ...(raw as Record<string, unknown>), kind: 'set' }
881
+ : raw,
882
+ z.discriminatedUnion('kind', [
883
+ SetEditSchema,
884
+ AppendEditSchema,
885
+ DropEditSchema,
886
+ SectionEditSchema,
887
+ ReorderEditSchema,
888
+ HideEditSchema,
889
+ ]),
890
+ );
891
+ export type ResumeEdit = z.infer<typeof ResumeEditSchema>;
892
+
893
+ /**
894
+ * Narrowing helpers, so callers never re-derive the discriminant by hand.
895
+ *
896
+ * `isSetEdit` treats a MISSING `kind` as a replacement, and that is not
897
+ * belt-and-braces: the schema injects the default only for values that pass
898
+ * through it, and an overlay read straight out of storage and handed to
899
+ * `applyPresentation` never does. Without this, every edit written before
900
+ * structural operations existed would be silently skipped — the whole document
901
+ * reverting to the writer's wording with nothing reported. Backward
902
+ * compatibility has to hold at runtime, not only at the parse boundary.
903
+ */
904
+ export const isSetEdit = (edit: ResumeEdit): edit is SetEdit =>
905
+ (edit as { kind?: unknown }).kind === undefined || edit.kind === 'set';
906
+ export const isAppendEdit = (edit: ResumeEdit): edit is AppendEdit =>
907
+ edit.kind === 'append';
908
+ export const isDropEdit = (edit: ResumeEdit): edit is DropEdit =>
909
+ edit.kind === 'drop';
910
+ export const isSectionEdit = (edit: ResumeEdit): edit is SectionEdit =>
911
+ edit.kind === 'section';
912
+ export const isReorderEdit = (edit: ResumeEdit): edit is ReorderEdit =>
913
+ edit.kind === 'reorder';
914
+ export const isHideEdit = (edit: ResumeEdit): edit is HideEdit =>
915
+ edit.kind === 'hide';
916
+
917
+ /**
918
+ * The overlay with additions nobody ever typed into taken out of it.
919
+ *
920
+ * An overlay records what the candidate DECIDED. An addition whose entry is
921
+ * still entirely empty records no decision: there is nothing in it, `renderText`
922
+ * already omits it from the text export, and the document being read draws no
923
+ * item for it. What it does do is persist — so pressing add and walking away
924
+ * leaves a permanent, invisible entry behind, and a control that appeared not to
925
+ * work left one per press.
926
+ *
927
+ * Applied when a stored overlay is ADOPTED, and deliberately nowhere else. As a
928
+ * filter on the projection it would delete the entry the candidate has this
929
+ * second pressed add for, before they could type a character into it; as a rule
930
+ * of the save it would race the typing. At load the question is unambiguous:
931
+ * this addition survived a reload with nothing in it, so nothing is lost by
932
+ * dropping it, and one press brings back an identical one.
933
+ *
934
+ * `drop` edits naming a removed addition go with it — there is nothing left to
935
+ * drop — and the refs are taken out of any ordering, since a slot pointing at an
936
+ * addition that no longer exists is a slot `collectionOrder` would skip anyway.
937
+ *
938
+ * Additions the candidate has typed into are untouched: `presentationEdits`
939
+ * folds typed values INTO the addition's own entry, so an entry with a word in
940
+ * it is not unfilled.
941
+ */
942
+ export function withoutUnfilledAdditions(edits: ResumeEdits): ResumeEdits {
943
+ const empty = new Set(
944
+ edits
945
+ .filter((edit) => isAppendEdit(edit) && isUnfilled(edit.entry))
946
+ .map((edit) => (edit as AppendEdit).ref),
947
+ );
948
+ if (empty.size === 0) return edits;
949
+
950
+ const kept: ResumeEdits = [];
951
+ for (const edit of edits) {
952
+ if (
953
+ (isAppendEdit(edit) || isDropEdit(edit)) &&
954
+ empty.has((edit as AppendEdit | DropEdit).ref)
955
+ ) {
956
+ continue;
957
+ }
958
+ if (isReorderEdit(edit)) {
959
+ kept.push({
960
+ ...edit,
961
+ order: edit.order.filter(
962
+ (slot) => !('ref' in slot && empty.has(slot.ref)),
963
+ ),
964
+ });
965
+ continue;
966
+ }
967
+ kept.push(edit);
968
+ }
969
+ return kept;
970
+ }
971
+
972
+ /**
973
+ * The overlay: only what actually changed.
974
+ *
975
+ * A **list**, not a `path → value` map, and the reason is the storage layer.
976
+ * `RunStore.update` writes with Firestore's `set(…, { merge: true })`, which
977
+ * DEEP-merges maps: a candidate who reverted a bullet to the writer's wording
978
+ * would drop that key from the overlay and Firestore would faithfully keep the
979
+ * old one, so the edit could never be undone. Merge replaces an array wholesale,
980
+ * so the overlay says what it means. (It also sidesteps the question of dots in
981
+ * Firestore map keys, which every path would have had.)
982
+ *
983
+ * Paths are unique — two replacements of one field is an ambiguity, not an
984
+ * ordering question.
985
+ */
986
+ export const ResumeEditsSchema = z
987
+ .array(ResumeEditSchema)
988
+ .refine(
989
+ (edits) => {
990
+ const paths = edits.filter(isSetEdit).map((e) => e.path);
991
+ return new Set(paths).size === paths.length;
992
+ },
993
+ { message: 'Each resume field path may be edited at most once.' },
994
+ )
995
+ /*
996
+ * Additions are identified by `ref`, so two additions sharing one is the same
997
+ * ambiguity a duplicated path is — and it would make a `drop` name two things.
998
+ */
999
+ .refine(
1000
+ (edits) => {
1001
+ const refs = edits
1002
+ .filter((e) => isAppendEdit(e) || isSectionEdit(e))
1003
+ .map((e) => (e as AppendEdit | SectionEdit).ref);
1004
+ return new Set(refs).size === refs.length;
1005
+ },
1006
+ { message: 'Each added entry may be declared at most once.' },
1007
+ )
1008
+ /*
1009
+ * A `drop` may only name an addition this same overlay made. This is where
1010
+ * "the candidate may not remove what the writer produced" is actually
1011
+ * enforced — the operation is simply not expressible against anything else.
1012
+ */
1013
+ .refine(
1014
+ (edits) => {
1015
+ const added = new Set(
1016
+ edits
1017
+ .filter((e) => isAppendEdit(e) || isSectionEdit(e))
1018
+ .map((e) => (e as AppendEdit | SectionEdit).ref),
1019
+ );
1020
+ return edits.filter(isDropEdit).every((drop) => added.has(drop.ref));
1021
+ },
1022
+ {
1023
+ message:
1024
+ 'A removal may only name an entry the same overlay added; writer-produced content cannot be removed.',
1025
+ },
1026
+ );
1027
+ export type ResumeEdits = z.infer<typeof ResumeEditsSchema>;
1028
+
1029
+ /**
1030
+ * Typefaces the document may use.
1031
+ *
1032
+ * A curated set, and the curation is the point: every entry is metrically
1033
+ * common and extracts cleanly in a screening system. That is what lets a
1034
+ * template keep advertising ATS safety while the candidate chooses — a free
1035
+ * font field could not.
1036
+ *
1037
+ * Each entry has two parts. `supplied` is the face the **product ships**, in
1038
+ * `libs/resume-templates/src/fonts`, and it leads `stack` so it is what the
1039
+ * document is actually drawn in; every supplied face is metrically compatible
1040
+ * with the typeface the entry names, wherever such a face exists. `stack` keeps
1041
+ * the system families behind it as the declared fallback, so a font file that
1042
+ * fails to load degrades to the previous behaviour rather than to nothing.
1043
+ *
1044
+ * Supplying the faces is what makes the document the same everywhere. A résumé
1045
+ * set in "Calibri" used to reach a Mac with no Calibri, Candara, Segoe or Optima
1046
+ * installed, fall through the whole stack, and be drawn in Arial — so no two
1047
+ * readers saw the same document and no server could match either of them.
1048
+ *
1049
+ * Data here rather than in the toolbar because two surfaces read it: the editor
1050
+ * and the PDF renderer. A font list maintained inside a React component is a
1051
+ * list the server renderer silently disagrees with.
1052
+ */
1053
+ export const DOCUMENT_FONTS = {
1054
+ helvetica: {
1055
+ name: 'Helvetica',
1056
+ supplied: 'TeX Gyre Heros',
1057
+ stack:
1058
+ "'TeX Gyre Heros', 'Helvetica Neue', Helvetica, Arial, 'Liberation Sans', sans-serif",
1059
+ },
1060
+ arial: {
1061
+ name: 'Arial',
1062
+ supplied: 'Arimo',
1063
+ stack:
1064
+ "Arimo, Arial, 'Helvetica Neue', Helvetica, 'Liberation Sans', sans-serif",
1065
+ },
1066
+ calibri: {
1067
+ name: 'Calibri',
1068
+ supplied: 'Carlito',
1069
+ stack:
1070
+ "Carlito, Calibri, Candara, Segoe, 'Segoe UI', Optima, Arial, sans-serif",
1071
+ },
1072
+ georgia: {
1073
+ name: 'Georgia',
1074
+ supplied: 'Gelasio',
1075
+ stack: "Gelasio, Georgia, Cambria, 'Times New Roman', Times, serif",
1076
+ },
1077
+ garamond: {
1078
+ name: 'Garamond',
1079
+ supplied: 'EB Garamond',
1080
+ stack:
1081
+ "'EB Garamond', Garamond, Baskerville, 'Baskerville Old Face', 'Times New Roman', serif",
1082
+ },
1083
+ times: {
1084
+ name: 'Times',
1085
+ supplied: 'Tinos',
1086
+ stack: "Tinos, 'Times New Roman', Times, Georgia, serif",
1087
+ },
1088
+ /*
1089
+ * The four below are the product's OWN choices rather than stand-ins for a
1090
+ * typeface a reader might have installed.
1091
+ *
1092
+ * The six above answer "the candidate asked for Calibri": each is metrically
1093
+ * compatible with a named face, so a résumé keeps the line breaks that face
1094
+ * would have produced. These answer a different question — the six cover two
1095
+ * registers, a neo-grotesque sans and a transitional serif, three times each,
1096
+ * so "more fonts" was really "more than two ways for a résumé to look".
1097
+ *
1098
+ * `supplied` is the face's own name here, because there is nothing to stand
1099
+ * in for. Each still leads a stack that degrades to something of its own
1100
+ * register if the file fails to load.
1101
+ */
1102
+ lato: {
1103
+ name: 'Lato',
1104
+ supplied: 'Lato',
1105
+ stack: "Lato, 'Segoe UI', Candara, Optima, Calibri, sans-serif",
1106
+ },
1107
+ condensed: {
1108
+ name: 'Roboto Condensed',
1109
+ supplied: 'Roboto Condensed',
1110
+ stack:
1111
+ "'Roboto Condensed', 'Arial Narrow', 'Helvetica Neue Condensed', 'Liberation Sans Narrow', sans-serif",
1112
+ },
1113
+ ptserif: {
1114
+ name: 'PT Serif',
1115
+ supplied: 'PT Serif',
1116
+ stack: "'PT Serif', Charter, Cambria, Georgia, 'Times New Roman', serif",
1117
+ },
1118
+ bitter: {
1119
+ name: 'Bitter',
1120
+ supplied: 'Bitter',
1121
+ stack:
1122
+ "Bitter, 'Roboto Slab', Rockwell, 'Courier New', Cambria, Georgia, serif",
1123
+ },
1124
+ } as const;
1125
+
1126
+ export type DocumentFontId = keyof typeof DOCUMENT_FONTS;
1127
+ export const DocumentFontIdSchema = z.enum(
1128
+ Object.keys(DOCUMENT_FONTS) as [DocumentFontId, ...DocumentFontId[]],
1129
+ );
1130
+
1131
+ /**
1132
+ * Inks a document (or one line of it) may be set in.
1133
+ *
1134
+ * Document colours, deliberately dark and low-chroma: a resume is read on paper
1135
+ * and in an ATS, and a palette is what keeps "readable when printed in
1136
+ * greyscale" true without asking the candidate to know that.
1137
+ */
1138
+ export const INK_COLORS = {
1139
+ ink: { name: 'Ink', hex: '#111111' },
1140
+ slate: { name: 'Slate', hex: '#33414f' },
1141
+ navy: { name: 'Navy', hex: '#1c3a63' },
1142
+ maroon: { name: 'Maroon', hex: '#6b2434' },
1143
+ forest: { name: 'Forest', hex: '#1f4433' },
1144
+ grey: { name: 'Grey', hex: '#5a5a5a' },
1145
+ /*
1146
+ * The wider palette. Same rule as the first six: every ink holds at least
1147
+ * 4.5:1 against white (WCAG AA for body text; these all clear 8:1), so a
1148
+ * document set in any of them stays readable on paper, in greyscale and in
1149
+ * an ATS preview. `template.spec.ts` asserts the contrast, so a lighter ink
1150
+ * cannot be added.
1151
+ */
1152
+ charcoal: { name: 'Charcoal', hex: '#2e3236' },
1153
+ cobalt: { name: 'Cobalt', hex: '#1d4a91' },
1154
+ indigo: { name: 'Indigo', hex: '#2f3878' },
1155
+ teal: { name: 'Teal', hex: '#0f5257' },
1156
+ olive: { name: 'Olive', hex: '#404a1c' },
1157
+ plum: { name: 'Plum', hex: '#4e2a5a' },
1158
+ rust: { name: 'Rust', hex: '#7c3416' },
1159
+ brown: { name: 'Brown', hex: '#57382a' },
1160
+ } as const;
1161
+
1162
+ export type InkId = keyof typeof INK_COLORS;
1163
+ export const InkIdSchema = z.enum(
1164
+ Object.keys(INK_COLORS) as [InkId, ...InkId[]],
1165
+ );
1166
+
1167
+ /**
1168
+ * How open the document's vertical rhythm is — a MULTIPLIER on the template's
1169
+ * own spacing, for the same reason `scale` multiplies its type scale rather than
1170
+ * setting a point size.
1171
+ *
1172
+ * A template's spacing is a set of relationships: the gap under a section
1173
+ * heading is smaller than the gap between two sections, and that is a
1174
+ * typographic decision the template made. A multiplier preserves those
1175
+ * relationships; a set of measurements would let a candidate put more air
1176
+ * between a heading and its own body than between two sections.
1177
+ *
1178
+ * Named rather than continuous because the useful positions are three —
1179
+ * "tighter", "as designed", "more open" — and three named values are three test
1180
+ * cases in the guarantee suite.
1181
+ */
1182
+ export const DENSITIES = {
1183
+ tight: { name: 'Tight', factor: 0.85 },
1184
+ normal: { name: 'Normal', factor: 1 },
1185
+ roomy: { name: 'Roomy', factor: 1.15 },
1186
+ } as const;
1187
+
1188
+ export type DensityId = keyof typeof DENSITIES;
1189
+ export const DensityIdSchema = z.enum(
1190
+ Object.keys(DENSITIES) as [DensityId, ...DensityId[]],
1191
+ );
1192
+
1193
+ /** What a document is spaced at before anybody chooses. */
1194
+ export const DENSITY_DEFAULT: DensityId = 'normal';
1195
+
1196
+ /**
1197
+ * Extra space above one section, or one field.
1198
+ *
1199
+ * The `steps` are counted in the template's OWN spacing unit, not in any
1200
+ * absolute measure — `s2` is two of whatever a section gap is in that template,
1201
+ * so Harvard's `s2` and Executive's `s2` are both "noticeably more air" in their
1202
+ * respective rhythms rather than the same number of millimetres in both.
1203
+ *
1204
+ * This is the control a candidate actually reaches for when a section feels
1205
+ * cramped. Without it the only way to close a gap is the type scale, which
1206
+ * makes every word smaller to fix a margin.
1207
+ *
1208
+ * A SCALE, not a set of presets, and that is a consequence of what the control
1209
+ * turned out to be. The catalog began as `sm` / `md` / `lg` — three names for a
1210
+ * picker in a panel. The control is the gap itself now, dragged where the space
1211
+ * will appear, and a drag with three stops reads as a switch: somebody closing
1212
+ * up a header is adjusting a distance, not choosing an adjective.
1213
+ *
1214
+ * So it is a fine scale with a ceiling: fifths of a unit, up to 200. Fine
1215
+ * enough that the drag tracks the hand and a gap can be nudged rather than
1216
+ * jumped, bounded so that the whole product of styling combinations is still
1217
+ * enumerable — which is what the ATS guarantee test walks, and the condition on
1218
+ * having a drag at all. Nothing here is a measurement: the number counts the
1219
+ * template's unit, and the template decides what that is.
1220
+ */
1221
+ /** The finest adjustment the scale can express, in template units. */
1222
+ export const SPACE_QUANTUM = 0.2;
1223
+ /** The most space a gap can hold, in template units. */
1224
+ export const SPACE_LIMIT = 200;
1225
+
1226
+ /**
1227
+ * Built rather than written out, because 1,000 named constants is a table
1228
+ * nobody reads and one that cannot drift from its own arithmetic. The id keeps
1229
+ * the number legible in a stored document — `s3_4` is three and two fifths of
1230
+ * the template's unit — and the tenths are underscored because a dot is a path
1231
+ * separator everywhere else in this file.
1232
+ */
1233
+ export const SECTION_SPACES: Record<string, { name: string; steps: number }> =
1234
+ Object.fromEntries([
1235
+ ['none', { name: 'None', steps: 0 }],
1236
+ ...Array.from(
1237
+ { length: Math.round(SPACE_LIMIT / SPACE_QUANTUM) },
1238
+ (_, i) => {
1239
+ const steps = Number(((i + 1) * SPACE_QUANTUM).toFixed(1));
1240
+ const id = `s${String(steps).replace('.', '_')}`;
1241
+ return [id, { name: `${steps}`, steps }] as const;
1242
+ },
1243
+ ),
1244
+ ]);
1245
+
1246
+ export type SectionSpaceId = keyof typeof SECTION_SPACES;
1247
+ export const SectionSpaceIdSchema = z.enum(
1248
+ Object.keys(SECTION_SPACES) as [SectionSpaceId, ...SectionSpaceId[]],
1249
+ );
1250
+
1251
+ /** The scale in order, shallowest first. `none` is the first step, not a gap. */
1252
+ export const SPACE_SCALE = (
1253
+ Object.keys(SECTION_SPACES) as SectionSpaceId[]
1254
+ ).sort((a, b) => SECTION_SPACES[a].steps - SECTION_SPACES[b].steps);
1255
+
1256
+ /** The most steps this catalog can express. */
1257
+ export const SPACE_MAX_STEPS = SPACE_LIMIT;
1258
+
1259
+ /**
1260
+ * How many steps a token is worth. `undefined` is none, which is what an
1261
+ * absent record means.
1262
+ */
1263
+ export function spaceSteps(id: SectionSpaceId | undefined): number {
1264
+ return id ? SECTION_SPACES[id].steps : 0;
1265
+ }
1266
+
1267
+ /**
1268
+ * The token for a number of steps, clamped to the scale.
1269
+ *
1270
+ * The one place a number becomes a token, so a drag — which is arithmetic on a
1271
+ * pointer — cannot express a value the catalog does not hold. Anything off the
1272
+ * scale lands on its nearest end rather than being refused: a candidate who
1273
+ * drags past the bottom has asked for no space, and a control that stopped
1274
+ * responding would read as broken.
1275
+ */
1276
+ export function spaceAtStep(steps: number): SectionSpaceId {
1277
+ // Quantised first, so a pointer position lands on the scale rather than
1278
+ // between two of its values.
1279
+ const wanted = Number(
1280
+ (Math.round(steps / SPACE_QUANTUM) * SPACE_QUANTUM).toFixed(1),
1281
+ );
1282
+ if (wanted <= 0) return 'none' as SectionSpaceId;
1283
+ const found = SPACE_SCALE.find((id) => SECTION_SPACES[id]?.steps === wanted);
1284
+ return found ?? (SPACE_SCALE[SPACE_SCALE.length - 1] as SectionSpaceId);
1285
+ }
1286
+
1287
+ /**
1288
+ * The sections spacing can be keyed by.
1289
+ *
1290
+ * A fixed enum of the sections a `ResumeObject` already has — deliberately NOT a
1291
+ * composition model. "Space above Experience" is answerable today, and making it
1292
+ * wait for sections to become addable, removable and orderable would hold a small
1293
+ * control hostage to a much larger change.
1294
+ */
1295
+ export const RESUME_SECTIONS = [
1296
+ 'summary',
1297
+ 'skills',
1298
+ 'experience',
1299
+ 'education',
1300
+ 'certifications',
1301
+ /*
1302
+ * The supporting sections. Members here rather than anywhere else because
1303
+ * that is what gives each one the rail, the adjustable gap and the stored
1304
+ * spacing record the five above already have — by construction, rather than
1305
+ * by seventeen templates each remembering to wire four more.
1306
+ *
1307
+ * Still not a composition model: these are four more sections a `ResumeObject`
1308
+ * HAS. Making sections addable, removable and orderable remains the larger
1309
+ * change this enum has always declined to start.
1310
+ */
1311
+ 'achievements',
1312
+ 'courses',
1313
+ 'passions',
1314
+ 'languages',
1315
+ ] as const;
1316
+
1317
+ export type ResumeSectionId = (typeof RESUME_SECTIONS)[number];
1318
+ export const ResumeSectionIdSchema = z.enum(RESUME_SECTIONS);
1319
+
1320
+ /**
1321
+ * The document size scale — a MULTIPLIER on the template's own type scale, not a
1322
+ * point size.
1323
+ *
1324
+ * The template's sizes are a set of relationships (name over heading over body);
1325
+ * a multiplier preserves them, whereas a point size would let a candidate set
1326
+ * body text larger than the headings above it. Bounded because the useful range
1327
+ * is "fit it on one page" / "fill the page", and everything past that is a worse
1328
+ * resume.
1329
+ */
1330
+ export const SCALE_MIN = 0.85;
1331
+ export const SCALE_MAX = 1.2;
1332
+ export const SCALE_STEP = 0.05;
1333
+ export const SCALE_DEFAULT = 1;
1334
+
1335
+ /** Round to the nearest representable scale, clamped to the bounds. */
1336
+ export function normalizeScale(value: number): number {
1337
+ const stepped = Math.round(value / SCALE_STEP) * SCALE_STEP;
1338
+ const clamped = Math.min(SCALE_MAX, Math.max(SCALE_MIN, stepped));
1339
+ // Steps of 0.05 are not exact in binary; two decimals is the domain's precision.
1340
+ return Number(clamped.toFixed(2));
1341
+ }
1342
+
1343
+ /**
1344
+ * How far apart the letters of the document's text sit — an override of the
1345
+ * template's tracking, chosen from presets, never a free number.
1346
+ *
1347
+ * Absent means the template's own tracking, which is what every stored
1348
+ * document has. Headings keep the template's tracking either way: it is part of
1349
+ * how a heading is drawn (an uppercase rule is tracked open on purpose), and
1350
+ * {@link HEADING_CASES} owns it when the candidate changes the heading's case.
1351
+ */
1352
+ export const LETTER_SPACINGS = {
1353
+ tight: { name: 'Tight', em: -0.01 },
1354
+ wide: { name: 'Wide', em: 0.02 },
1355
+ } as const;
1356
+ export type LetterSpacingId = keyof typeof LETTER_SPACINGS;
1357
+ export const LetterSpacingIdSchema = z.enum(
1358
+ Object.keys(LETTER_SPACINGS) as [LetterSpacingId, ...LetterSpacingId[]],
1359
+ );
1360
+
1361
+ /**
1362
+ * The distance between lines of the document's text, as a unitless line height
1363
+ * from presets. Absent means the template's own leading. Headings keep theirs.
1364
+ */
1365
+ export const LINE_HEIGHTS = {
1366
+ compact: { name: 'Compact', value: 1.15 },
1367
+ relaxed: { name: 'Relaxed', value: 1.4 },
1368
+ airy: { name: 'Airy', value: 1.55 },
1369
+ } as const;
1370
+ export type LineHeightId = keyof typeof LINE_HEIGHTS;
1371
+ export const LineHeightIdSchema = z.enum(
1372
+ Object.keys(LINE_HEIGHTS) as [LineHeightId, ...LineHeightId[]],
1373
+ );
1374
+
1375
+ /**
1376
+ * How section headings are cased. A presentation of the heading, never its
1377
+ * text: the stored heading is unchanged, so copy-out and ATS extraction read
1378
+ * what the candidate wrote. Absent means the template's own casing.
1379
+ */
1380
+ export const HEADING_CASES = {
1381
+ normal: { name: 'As written' },
1382
+ upper: { name: 'Uppercase' },
1383
+ smallcaps: { name: 'Small caps' },
1384
+ } as const;
1385
+ export type HeadingCaseId = keyof typeof HEADING_CASES;
1386
+ export const HeadingCaseIdSchema = z.enum(
1387
+ Object.keys(HEADING_CASES) as [HeadingCaseId, ...HeadingCaseId[]],
1388
+ );
1389
+
1390
+ /**
1391
+ * How heavy section headings are. Two weights, because every font in
1392
+ * {@link DOCUMENT_FONTS} ships both, so no choice falls back to a synthesised
1393
+ * weight. Absent means the template's own weight.
1394
+ */
1395
+ export const HEADING_WEIGHTS = {
1396
+ regular: { name: 'Regular', weight: 400 },
1397
+ bold: { name: 'Bold', weight: 700 },
1398
+ } as const;
1399
+ export type HeadingWeightId = keyof typeof HEADING_WEIGHTS;
1400
+ export const HeadingWeightIdSchema = z.enum(
1401
+ Object.keys(HEADING_WEIGHTS) as [HeadingWeightId, ...HeadingWeightId[]],
1402
+ );
1403
+
1404
+ /**
1405
+ * How the whole document is set. Absent means the template's own defaults — a
1406
+ * resume nobody has styled renders exactly as the template defines it.
1407
+ */
1408
+ export const DocumentStyleSchema = z.object({
1409
+ font: DocumentFontIdSchema,
1410
+ ink: InkIdSchema,
1411
+ scale: z
1412
+ .number()
1413
+ .min(SCALE_MIN)
1414
+ .max(SCALE_MAX)
1415
+ .describe('Multiplier on the template type scale.'),
1416
+ /*
1417
+ * The colour a template rules its headings, hairlines and header band with.
1418
+ *
1419
+ * Typed `InkIdSchema` on purpose: an accent IS a document colour, and the
1420
+ * product already has one vetted palette for those — low-chroma and dark
1421
+ * enough to survive greyscale printing. A second palette would be a second
1422
+ * answer to the same question and a second thing to keep honest.
1423
+ *
1424
+ * Optional, because absent means the template's own accent, which is what
1425
+ * every stored document has.
1426
+ */
1427
+ accent: InkIdSchema.optional(),
1428
+ /** Absent means the template's own rhythm — see {@link DENSITIES}. */
1429
+ density: DensityIdSchema.optional(),
1430
+ /*
1431
+ * The typographic controls a word processor offers, each as a preset over
1432
+ * the template rather than a free value, and each absent unless chosen — so
1433
+ * a document that sets none renders exactly as the template defines it.
1434
+ */
1435
+ /** Letter spacing of the text — see {@link LETTER_SPACINGS}. */
1436
+ tracking: LetterSpacingIdSchema.optional(),
1437
+ /** Line height of the text — see {@link LINE_HEIGHTS}. */
1438
+ leading: LineHeightIdSchema.optional(),
1439
+ /** The typeface of the name and section headings, from the same vetted set. */
1440
+ headingFont: DocumentFontIdSchema.optional(),
1441
+ /** How section headings are cased — see {@link HEADING_CASES}. */
1442
+ headingCase: HeadingCaseIdSchema.optional(),
1443
+ /** How heavy section headings are — see {@link HEADING_WEIGHTS}. */
1444
+ headingWeight: HeadingWeightIdSchema.optional(),
1445
+ });
1446
+ export type DocumentStyle = z.infer<typeof DocumentStyleSchema>;
1447
+
1448
+ /** How one line is set, over and above the document's own style. */
1449
+ export const FieldAlignSchema = z.enum(['left', 'center', 'right']);
1450
+ export type FieldAlign = z.infer<typeof FieldAlignSchema>;
1451
+
1452
+ /**
1453
+ * One step smaller or larger than the template sets the line. A step, not a
1454
+ * size: the template's proportions hold, so a stepped-up bullet still reads
1455
+ * smaller than a heading.
1456
+ */
1457
+ export const FIELD_STEPS = {
1458
+ smaller: { name: 'Smaller', factor: 0.9 },
1459
+ larger: { name: 'Larger', factor: 1.12 },
1460
+ } as const;
1461
+ export type FieldStepId = keyof typeof FIELD_STEPS;
1462
+ export const FieldStepSchema = z.enum(
1463
+ Object.keys(FIELD_STEPS) as [FieldStepId, ...FieldStepId[]],
1464
+ );
1465
+
1466
+ export const FieldFormatSchema = z.object({
1467
+ path: ResumeFieldPathSchema,
1468
+ bold: z.boolean().optional(),
1469
+ italic: z.boolean().optional(),
1470
+ underline: z.boolean().optional(),
1471
+ /** One step smaller or larger — see {@link FIELD_STEPS}. */
1472
+ step: FieldStepSchema.optional(),
1473
+ align: FieldAlignSchema.optional(),
1474
+ ink: InkIdSchema.optional(),
1475
+ /** Extra space above this field — the one place a section rule cannot reach. */
1476
+ space: SectionSpaceIdSchema.optional(),
1477
+ /*
1478
+ * Where this field points, if anywhere.
1479
+ *
1480
+ * CONTENT carried on the per-path record, not formatting — the distinction
1481
+ * that matters is `BOUNDED_NODE_PROPS`, which admits `href` as a validated
1482
+ * domain type rather than as a free string. It rides here because this is
1483
+ * already the per-path channel that travels the save path and is addressed by
1484
+ * the same paths the edits use; a second parallel map keyed the same way
1485
+ * would be a second thing to keep in step.
1486
+ *
1487
+ * Validated by `LinkTargetSchema`, so a `javascript:` target cannot reach a
1488
+ * stored document, let alone an exported one.
1489
+ */
1490
+ href: LinkTargetSchema.optional(),
1491
+ });
1492
+ export type FieldFormat = z.infer<typeof FieldFormatSchema>;
1493
+
1494
+ /** A format carrying no flags says nothing; it is dropped rather than stored. */
1495
+ export function formatIsEmpty(format: FieldFormat): boolean {
1496
+ return (
1497
+ format.bold === undefined &&
1498
+ format.italic === undefined &&
1499
+ format.underline === undefined &&
1500
+ format.step === undefined &&
1501
+ format.align === undefined &&
1502
+ format.ink === undefined &&
1503
+ format.href === undefined &&
1504
+ // `none` is the absence of space, not a spacing — storing it would leave a
1505
+ // record of a control being returned to where it started.
1506
+ (format.space === undefined || format.space === 'none')
1507
+ );
1508
+ }
1509
+
1510
+ /**
1511
+ * Per-field formatting.
1512
+ *
1513
+ * A **list** for the same reason `edits` is one: `RunStore.update` writes through
1514
+ * Firestore's `set(…, { merge: true })`, which deep-merges maps, so formatting a
1515
+ * candidate cleared would survive its own clearing.
1516
+ */
1517
+ export const ResumeFormatsSchema = z
1518
+ .array(FieldFormatSchema)
1519
+ .refine((f) => new Set(f.map((x) => x.path)).size === f.length, {
1520
+ message: 'Each resume field path may be formatted at most once.',
1521
+ })
1522
+ .refine((f) => f.every((x) => !formatIsEmpty(x)), {
1523
+ message: 'A format with no emphasis, alignment or ink is not stored.',
1524
+ });
1525
+ export type ResumeFormats = z.infer<typeof ResumeFormatsSchema>;
1526
+
1527
+ /** The format for one path, or undefined when the field carries none. */
1528
+ export function formatFor(
1529
+ formats: ResumeFormats | undefined,
1530
+ path: string,
1531
+ ): FieldFormat | undefined {
1532
+ return formats?.find((f) => f.path === path);
1533
+ }
1534
+
1535
+ /**
1536
+ * Named presets over the document style.
1537
+ *
1538
+ * A theme is a STARTING POINT, not a mode: applying one writes concrete values
1539
+ * and nothing records that a theme was used. Storing a theme id instead would
1540
+ * make a saved document's appearance depend on a definition that can change
1541
+ * after it was saved — the same class of defect as an unversioned renderer,
1542
+ * reintroduced for no benefit. Concrete values keep rendering a pure function of
1543
+ * stored data, which is what a server-side render requires.
1544
+ *
1545
+ * The cost is that the editor cannot say "you are on Classic" afterwards. That
1546
+ * is a label, and it is not worth a second source of truth about how a document
1547
+ * looks.
1548
+ */
1549
+ export const THEMES = {
1550
+ classic: {
1551
+ name: 'Classic',
1552
+ description: 'Serif and restrained',
1553
+ style: {
1554
+ font: 'times',
1555
+ ink: 'ink',
1556
+ accent: 'ink',
1557
+ density: 'normal',
1558
+ },
1559
+ },
1560
+ modern: {
1561
+ name: 'Modern',
1562
+ description: 'Open and current',
1563
+ style: {
1564
+ font: 'helvetica',
1565
+ ink: 'slate',
1566
+ accent: 'navy',
1567
+ density: 'roomy',
1568
+ },
1569
+ },
1570
+ compact: {
1571
+ name: 'Compact',
1572
+ description: 'Tight, fits more',
1573
+ style: {
1574
+ font: 'arial',
1575
+ ink: 'ink',
1576
+ accent: 'grey',
1577
+ density: 'tight',
1578
+ },
1579
+ },
1580
+ academic: {
1581
+ name: 'Academic',
1582
+ description: 'Formal and sober',
1583
+ style: {
1584
+ font: 'georgia',
1585
+ ink: 'ink',
1586
+ accent: 'maroon',
1587
+ density: 'normal',
1588
+ },
1589
+ },
1590
+ } as const satisfies Record<
1591
+ string,
1592
+ {
1593
+ name: string;
1594
+ /** One line telling a candidate what it looks like, not what it sets. */
1595
+ description: string;
1596
+ style: {
1597
+ font: DocumentFontId;
1598
+ ink: InkId;
1599
+ accent: InkId;
1600
+ density: DensityId;
1601
+ };
1602
+ }
1603
+ >;
1604
+
1605
+ export type ThemeId = keyof typeof THEMES;
1606
+
1607
+ /**
1608
+ * Apply a theme, preserving what the theme does not speak to.
1609
+ *
1610
+ * The size scale survives: it is how a candidate fits their resume on one page,
1611
+ * which is a decision about THEIR document rather than about its styling, and
1612
+ * silently resetting it would undo work a theme has no opinion about.
1613
+ */
1614
+ export function applyTheme(style: DocumentStyle, id: ThemeId): DocumentStyle {
1615
+ return { ...style, ...THEMES[id].style };
1616
+ }
1617
+
1618
+ /** Extra space above one named section. */
1619
+ export const SectionSpacingSchema = z.object({
1620
+ section: ResumeSectionIdSchema,
1621
+ space: SectionSpaceIdSchema,
1622
+ });
1623
+ export type SectionSpacing = z.infer<typeof SectionSpacingSchema>;
1624
+
1625
+ /**
1626
+ * Space above the document's sections.
1627
+ *
1628
+ * A **list**, for exactly the reason `edits` and `formats` are lists:
1629
+ * `RunStore.update` writes through Firestore's `set(…, { merge: true })`, which
1630
+ * deep-merges maps — so a spacing the candidate cleared would survive its own
1631
+ * clearing if this were keyed.
1632
+ *
1633
+ * `none` is refused rather than stored for the same reason `formatIsEmpty`
1634
+ * drops an empty format: returning a control to where it started should leave no
1635
+ * trace, so an untouched document stores nothing.
1636
+ */
1637
+ export const ResumeSectionSpacingSchema = z
1638
+ .array(SectionSpacingSchema)
1639
+ .refine((s) => new Set(s.map((x) => x.section)).size === s.length, {
1640
+ message: 'Each section may be spaced at most once.',
1641
+ })
1642
+ .refine((s) => s.every((x) => x.space !== 'none'), {
1643
+ message: 'A section spaced by nothing is not stored.',
1644
+ });
1645
+ export type ResumeSectionSpacing = z.infer<typeof ResumeSectionSpacingSchema>;
1646
+
1647
+ /** The spacing for one section, or undefined when it carries none. */
1648
+ export function spacingFor(
1649
+ spacing: ResumeSectionSpacing | undefined,
1650
+ section: string,
1651
+ ): SectionSpacing | undefined {
1652
+ return spacing?.find((s) => s.section === section);
1653
+ }
1654
+
1655
+ /**
1656
+ * How a run's resume is presented: which template, and the candidate's own
1657
+ * corrections on top of what the writer produced.
1658
+ *
1659
+ * Deliberately NOT the editor's serialized node tree. The tree is
1660
+ * template-shaped and library-shaped; this is neither, so switching template
1661
+ * loses nothing, `ResumeObjectSchema` still governs the result, and renaming a
1662
+ * React component cannot invalidate a stored document.
1663
+ *
1664
+ * @pii `edits` holds resume text. It lives on the run record beside the result
1665
+ * it corrects, so it shares that run's owner scope, retention, and deletion.
1666
+ */
1667
+ export const ResumePresentationSchema = z.object({
1668
+ template_id: TemplateIdSchema,
1669
+ edits: ResumeEditsSchema.default([]),
1670
+ /** Absent means the template's own typography (`resume-document-formatting`). */
1671
+ style: DocumentStyleSchema.optional(),
1672
+ /** Absent means no line carries formatting of its own. */
1673
+ formats: ResumeFormatsSchema.optional(),
1674
+ /** Absent means every section sits where the template puts it. */
1675
+ section_spacing: ResumeSectionSpacingSchema.optional(),
1676
+ /** The language the document prints in. Absent means English. */
1677
+ language: LocaleSchema.optional(),
1678
+ updated_at: z.string(),
1679
+ });
1680
+ export type ResumePresentation = z.infer<typeof ResumePresentationSchema>;
1681
+
1682
+ /** `PUT /runs/:id/presentation` request. The server owns `updated_at`. */
1683
+ export const PutPresentationRequestSchema = z.object({
1684
+ template_id: TemplateIdSchema,
1685
+ edits: ResumeEditsSchema.default([]),
1686
+ style: DocumentStyleSchema.optional(),
1687
+ formats: ResumeFormatsSchema.optional(),
1688
+ section_spacing: ResumeSectionSpacingSchema.optional(),
1689
+ language: LocaleSchema.optional(),
1690
+ });
1691
+ export type PutPresentationRequest = z.infer<
1692
+ typeof PutPresentationRequestSchema
1693
+ >;
1694
+
1695
+ type Container = Record<string, unknown> | unknown[];
1696
+
1697
+ function isContainer(value: unknown): value is Container {
1698
+ return typeof value === 'object' && value !== null;
1699
+ }
1700
+
1701
+ /** Walk to the container that holds `path`'s last segment, or `undefined`. */
1702
+ function resolveParent(
1703
+ root: Container,
1704
+ segments: string[],
1705
+ ): Container | undefined {
1706
+ let node: unknown = root;
1707
+ for (const segment of segments) {
1708
+ if (!isContainer(node)) return undefined;
1709
+ node = Array.isArray(node)
1710
+ ? node[Number(segment)]
1711
+ : (node as Record<string, unknown>)[segment];
1712
+ }
1713
+ return isContainer(node) ? node : undefined;
1714
+ }
1715
+
1716
+ /** The value a path addresses, or `undefined` when it does not resolve. */
1717
+ export function readAtPath(resume: ResumeObject, path: string): unknown {
1718
+ if (!isResumeFieldPath(path)) return undefined;
1719
+ const segments = path.split('.');
1720
+ const leaf = segments.pop() as string;
1721
+ const parent = resolveParent(resume as unknown as Container, segments);
1722
+ if (parent === undefined) return undefined;
1723
+ return Array.isArray(parent)
1724
+ ? parent[Number(leaf)]
1725
+ : (parent as Record<string, unknown>)[leaf];
1726
+ }
1727
+
1728
+ /**
1729
+ * The order a collection is actually drawn in, as slots.
1730
+ *
1731
+ * THE single definition of "which entries exist here, and in what order" —
1732
+ * `applyPresentation` builds the rendered array from it and the editor builds
1733
+ * its field paths from it, so the document and the paths into it can never
1734
+ * disagree. The same reasoning `appendedEntryRefs` records: a renderer that
1735
+ * recomputed this would be a second definition, free to drift.
1736
+ *
1737
+ * Total by construction. A slot that does not resolve is dropped, an entry no
1738
+ * slot names keeps its natural order after the ones that are named, and a
1739
+ * duplicated slot keeps its first occurrence — so an ordering written against a
1740
+ * résumé the writer has since replaced degrades to the writer's own order
1741
+ * rather than to a document that will not open.
1742
+ */
1743
+ export function collectionOrder(
1744
+ base: ResumeObject,
1745
+ edits: ResumeEdits,
1746
+ section: AppendableSection,
1747
+ ): Slot[] {
1748
+ const hidden = new Set(
1749
+ edits
1750
+ .filter(isHideEdit)
1751
+ .filter((e) => e.section === section)
1752
+ .map((e) => e.base),
1753
+ );
1754
+ const dropped = new Set(edits.filter(isDropEdit).map((e) => e.ref));
1755
+
1756
+ const natural: Slot[] = [];
1757
+ const baseLength = (base[section] as unknown[] | undefined)?.length ?? 0;
1758
+ for (let i = 0; i < baseLength; i += 1) {
1759
+ if (!hidden.has(i)) natural.push({ base: i });
1760
+ }
1761
+ for (const edit of edits) {
1762
+ if (!isAppendEdit(edit) || edit.section !== section) continue;
1763
+ if (dropped.has(edit.ref)) continue;
1764
+ if (!APPEND_SCHEMAS[section].safeParse(edit.entry).success) continue;
1765
+ natural.push({ ref: edit.ref });
1766
+ }
1767
+
1768
+ // The last ordering wins: two orderings of one collection is not an
1769
+ // ambiguity to resolve, it is a stale one and a current one.
1770
+ const reorder = edits
1771
+ .filter(isReorderEdit)
1772
+ .filter((e) => e.section === section)
1773
+ .at(-1);
1774
+ if (!reorder) return natural;
1775
+
1776
+ const available = new Map(natural.map((slot) => [slotKey(slot), slot]));
1777
+ const ordered: Slot[] = [];
1778
+ for (const slot of reorder.order) {
1779
+ const key = slotKey(slot);
1780
+ const found = available.get(key);
1781
+ if (!found) continue;
1782
+ available.delete(key);
1783
+ ordered.push(found);
1784
+ }
1785
+ ordered.push(...available.values());
1786
+ return ordered;
1787
+ }
1788
+
1789
+ /**
1790
+ * Apply a presentation's edits to the writer's resume and validate the result.
1791
+ *
1792
+ * Pure: no I/O, no model call, and the input is never mutated — the run's
1793
+ * `result.resume_object` stays exactly what the model produced, so an edit is
1794
+ * reversible by dropping the overlay and the grounding record survives.
1795
+ *
1796
+ * A path that does not resolve is **skipped**, not thrown. A stored overlay is
1797
+ * data at rest that outlives the code that wrote it; a retired field must
1798
+ * degrade to a dropped edit, never to a resume that will not open.
1799
+ *
1800
+ * @throws if the edits would produce a resume the schema refuses.
1801
+ */
1802
+ export function applyPresentation(
1803
+ resume: ResumeObject,
1804
+ edits: ResumeEdits,
1805
+ ): PresentedResume {
1806
+ const draft = structuredClone(resume) as unknown as Container;
1807
+
1808
+ /*
1809
+ * `section_headings` is the one MAP a `set` edit writes into, and it has to
1810
+ * exist before the replacements run.
1811
+ *
1812
+ * Every other path a `set` addresses lands in an array or an object the
1813
+ * writer always emits. This one may be genuinely absent: the field was added
1814
+ * after résumés were already stored, and `ResumeObjectSchema` only defaults it
1815
+ * at the PARSE below — which happens after the replacements, not before. So a
1816
+ * résumé written before the field existed would resolve no parent, every
1817
+ * rename would be skipped as a stale path, and the candidate's headings would
1818
+ * quietly stop saving.
1819
+ *
1820
+ * Seeded rather than defaulted, because the alternative is parsing the base
1821
+ * here, which would refuse a draft entry the candidate has added and not yet
1822
+ * filled in — the exact thing the presented schema exists to allow.
1823
+ */
1824
+ const headings = (draft as Record<string, unknown>)['section_headings'];
1825
+ if (
1826
+ typeof headings !== 'object' ||
1827
+ headings === null ||
1828
+ Array.isArray(headings)
1829
+ ) {
1830
+ (draft as Record<string, unknown>)['section_headings'] = {};
1831
+ }
1832
+
1833
+ /*
1834
+ * Structural operations run FIRST, and replacements second.
1835
+ *
1836
+ * The order is load-bearing: an appended entry becomes an ordinary member of
1837
+ * its section, so a `set` naming `experience.4.title` can address it. Running
1838
+ * replacements first would make an edit to an added entry depend on whether
1839
+ * the entry happened to exist yet, which is exactly the ordering ambiguity
1840
+ * the unique-path rule exists to avoid.
1841
+ */
1842
+ const dropped = new Set(edits.filter(isDropEdit).map((e) => e.ref));
1843
+
1844
+ for (const edit of edits) {
1845
+ if (isAppendEdit(edit)) {
1846
+ if (dropped.has(edit.ref)) continue;
1847
+ const target = (draft as Record<string, unknown>)[edit.section];
1848
+ if (!Array.isArray(target)) continue;
1849
+ /*
1850
+ * Parsed against the section's own schema. An entry that does not fit is
1851
+ * skipped rather than thrown, for the same reason a stale path is: a
1852
+ * stored overlay outlives the code that wrote it, and a résumé that will
1853
+ * not open is a worse failure than an addition that does not show.
1854
+ */
1855
+ const schema = APPEND_SCHEMAS[edit.section];
1856
+ const parsed = schema.safeParse(edit.entry);
1857
+ if (!parsed.success) continue;
1858
+ /*
1859
+ * No `ref` is written into the résumé. The entry keeps its section's own
1860
+ * shape, so `ResumeObject` stays exactly what a template already renders
1861
+ * and the writer's entry schemas gain nothing. Which entries a candidate
1862
+ * added is DERIVED instead — appends land after the base entries in
1863
+ * overlay order, so the boundary is `base[section].length`. See
1864
+ * `appendedRefs` below.
1865
+ */
1866
+ target.push(parsed.data);
1867
+ continue;
1868
+ }
1869
+
1870
+ if (isSectionEdit(edit)) {
1871
+ if (dropped.has(edit.ref)) continue;
1872
+ const sections = (draft as Record<string, unknown>)['custom_sections'];
1873
+ if (!Array.isArray(sections)) continue;
1874
+ sections.push({
1875
+ id: edit.ref,
1876
+ heading: edit.heading,
1877
+ entries: edit.entries,
1878
+ author: edit.author,
1879
+ });
1880
+ }
1881
+ }
1882
+
1883
+ for (const edit of edits) {
1884
+ if (!isSetEdit(edit)) continue;
1885
+ const { path, value } = edit;
1886
+ if (!isResumeFieldPath(path)) continue;
1887
+ const segments = path.split('.');
1888
+ const leaf = segments.pop() as string;
1889
+ const parent = resolveParent(draft, segments);
1890
+ if (parent === undefined) continue;
1891
+
1892
+ if (Array.isArray(parent)) {
1893
+ const index = Number(leaf);
1894
+ // Replacing past the end would leave holes the schema then rejects; an
1895
+ // out-of-range edit is a stale path, which is the skip case.
1896
+ if (!Number.isInteger(index) || index < 0 || index >= parent.length)
1897
+ continue;
1898
+ parent[index] = value;
1899
+ } else {
1900
+ // An unknown key is left to `ResumeObjectSchema`, which strips it.
1901
+ (parent as Record<string, unknown>)[leaf] = value;
1902
+ }
1903
+ }
1904
+
1905
+ /*
1906
+ * Hides and orderings LAST, once every replacement has landed.
1907
+ *
1908
+ * This is what lets an ordering coexist with positional paths: at the moment
1909
+ * a `set` is applied nothing has moved, so `experience.1.title` addresses the
1910
+ * entry it addressed when it was written. Only then is the array permuted.
1911
+ */
1912
+ for (const section of APPENDABLE_SECTIONS) {
1913
+ const touched = edits.some(
1914
+ (edit) =>
1915
+ (isReorderEdit(edit) || isHideEdit(edit)) && edit.section === section,
1916
+ );
1917
+ if (!touched) continue;
1918
+ const current = (draft as Record<string, unknown>)[section];
1919
+ if (!Array.isArray(current)) continue;
1920
+
1921
+ // Where each slot sits in the draft right now: base entries kept their
1922
+ // indices, and appends landed after them in overlay order.
1923
+ const refIndex = new Map(
1924
+ [...appendedEntryRefs(resume, edits, section)].map(([i, ref]) => [
1925
+ ref,
1926
+ i,
1927
+ ]),
1928
+ );
1929
+ (draft as Record<string, unknown>)[section] = collectionOrder(
1930
+ resume,
1931
+ edits,
1932
+ section,
1933
+ )
1934
+ .map((slot) =>
1935
+ 'base' in slot
1936
+ ? current[slot.base]
1937
+ : current[refIndex.get(slot.ref) ?? -1],
1938
+ )
1939
+ .filter((entry) => entry !== undefined);
1940
+ }
1941
+
1942
+ /*
1943
+ * Parsed as a PRESENTED résumé, not as the writer's.
1944
+ *
1945
+ * The difference is exactly one thing: an entry the candidate has added and
1946
+ * not yet filled in has empty fields, and the writer's schema refuses those —
1947
+ * correctly, for the writer. Refusing them here would mean an added entry
1948
+ * could not appear on the page until it was already complete.
1949
+ */
1950
+ return PresentedResumeSchema.parse(draft) as PresentedResume;
1951
+ }
1952
+
1953
+ function sameValue(a: unknown, b: EditValue): boolean {
1954
+ if (Array.isArray(b)) {
1955
+ return (
1956
+ Array.isArray(a) && a.length === b.length && a.every((x, i) => x === b[i])
1957
+ );
1958
+ }
1959
+ /*
1960
+ * Nothing where there was nothing.
1961
+ *
1962
+ * A field the writer's résumé never carried, still blank, is not an edit —
1963
+ * it is the absence it always was. This matters because a template may OFFER
1964
+ * a field the résumé has no value for: the header's phone number is drawn
1965
+ * whether or not there is one, so the candidate has somewhere to type it.
1966
+ * Without this, `undefined !== ''` and merely opening the editor wrote an
1967
+ * overlay full of empty strings — a document nobody had touched was dirty,
1968
+ * and autosave stored it.
1969
+ *
1970
+ * Clearing a field that DID have a value is still an edit, and still records
1971
+ * the empty string: `a` is the old text, not nothing.
1972
+ */
1973
+ if (b === '' && (a === undefined || a === null)) return true;
1974
+ return a === b;
1975
+ }
1976
+
1977
+ /**
1978
+ * Where each addition's fields are ADDRESSED, as a path prefix.
1979
+ *
1980
+ * Past the end of the writer's own array, never among it: an addition to a
1981
+ * section of two roles is `experience.2`, whatever position it is drawn in.
1982
+ * That is where `applyPresentation` actually puts it — appends are pushed onto
1983
+ * the end of the section — so the prefix names the entry in the presented
1984
+ * résumé, and it is the scheme `custom_sections` has always used.
1985
+ *
1986
+ * It used to be the RENDER index, which collided. A candidate who added a role
1987
+ * above their second one gave the addition `experience.1`, which is also the
1988
+ * writer's second role's own address: the editor built two fields claiming to
1989
+ * edit the same path, Craft.js resolved both to one node, and the writer's role
1990
+ * was blanked off the page. The `claimed` filter below then swallowed its text
1991
+ * as belonging to the addition. Ordering is expressed by a `reorder` edit and
1992
+ * by nothing else; an address must not move when a document is rearranged.
1993
+ *
1994
+ * Used three times, which is the point: to fold an addition's own text into it,
1995
+ * to keep those paths out of the replacements, and — through `additionPaths` —
1996
+ * by the editor that emits them, so there is one definition rather than two
1997
+ * free to drift.
1998
+ */
1999
+ function additionSlots(
2000
+ base: ResumeObject,
2001
+ structural: ResumeEdits,
2002
+ ): Map<string, string> {
2003
+ const slots = new Map<string, string>();
2004
+ const dropped = new Set(structural.filter(isDropEdit).map((e) => e.ref));
2005
+
2006
+ for (const section of APPENDABLE_SECTIONS) {
2007
+ const written = (base[section] as unknown[] | undefined)?.length ?? 0;
2008
+ let ordinal = 0;
2009
+ for (const edit of structural) {
2010
+ if (!isAppendEdit(edit) || edit.section !== section) continue;
2011
+ if (dropped.has(edit.ref)) continue;
2012
+ // The same admission test `applyPresentation` applies, so the ordinal
2013
+ // counts exactly the entries that reach the résumé.
2014
+ if (!APPEND_SCHEMAS[section].safeParse(edit.entry).success) continue;
2015
+ slots.set(edit.ref, `${section}.${written + ordinal}`);
2016
+ ordinal += 1;
2017
+ }
2018
+ }
2019
+
2020
+ const written = (base.custom_sections ?? []).length;
2021
+ structural
2022
+ .filter(isSectionEdit)
2023
+ .filter((edit) => !dropped.has(edit.ref))
2024
+ .forEach((edit, i) => {
2025
+ slots.set(edit.ref, `custom_sections.${written + i}`);
2026
+ });
2027
+ return slots;
2028
+ }
2029
+
2030
+ /**
2031
+ * Where each addition's fields are addressed, for the editor that draws them.
2032
+ *
2033
+ * Exported so the document emits the paths this module reads back, from this
2034
+ * module's own arithmetic. The two were computed separately and disagreed —
2035
+ * see `additionSlots` — which is the kind of bug that only shows up as text
2036
+ * appearing in the wrong job.
2037
+ */
2038
+ export function additionPaths(
2039
+ base: ResumeObject,
2040
+ edits: ResumeEdits,
2041
+ ): Map<string, string> {
2042
+ return additionSlots(
2043
+ base,
2044
+ edits.filter((edit) => !isSetEdit(edit)),
2045
+ );
2046
+ }
2047
+
2048
+ /**
2049
+ * What decides which FIELDS the document has, as opposed to what they say.
2050
+ *
2051
+ * The editor rebuilds its node tree when this changes, and must not when only
2052
+ * the text does. An addition's words live inside its own `append` edit — that
2053
+ * is what `foldAdditions` is for — so serializing the overlay whole made every
2054
+ * character typed into a newly added role look like a structural change: the
2055
+ * tree was rebuilt mid-word and the field the candidate was typing in was
2056
+ * unmounted from under them. What a `ref` SAYS is not part of the document's
2057
+ * shape; that it exists, and where it sits, is.
2058
+ *
2059
+ * A custom section's entry COUNT is shape — one more entry is one more set of
2060
+ * fields — while its heading and its entries' text are not.
2061
+ */
2062
+ export function documentShapeKey(edits: ResumeEdits): string {
2063
+ const shape = edits.flatMap((edit) => {
2064
+ if (isAppendEdit(edit)) return [`a:${edit.section}:${edit.ref}`];
2065
+ if (isDropEdit(edit)) return [`d:${edit.ref}`];
2066
+ if (isHideEdit(edit)) return [`h:${edit.section}:${edit.base}`];
2067
+ if (isReorderEdit(edit)) {
2068
+ return [`o:${edit.section}:${edit.order.map(slotKey).join(',')}`];
2069
+ }
2070
+ if (isSectionEdit(edit)) return [`s:${edit.ref}:${edit.entries.length}`];
2071
+ return [];
2072
+ });
2073
+ return shape.join('|');
2074
+ }
2075
+
2076
+ /** Write `value` at `segments` inside `target`, creating nothing that is absent. */
2077
+ function writeInto(
2078
+ target: Record<string, unknown>,
2079
+ segments: string[],
2080
+ value: EditValue,
2081
+ ): void {
2082
+ let node: unknown = target;
2083
+ for (const segment of segments.slice(0, -1)) {
2084
+ if (!isContainer(node)) return;
2085
+ node = Array.isArray(node)
2086
+ ? node[Number(segment)]
2087
+ : (node as Record<string, unknown>)[segment];
2088
+ }
2089
+ if (!isContainer(node)) return;
2090
+ const leaf = segments[segments.length - 1] as string;
2091
+ if (Array.isArray(node)) {
2092
+ const index = Number(leaf);
2093
+ if (!Number.isInteger(index) || index < 0 || index >= node.length) return;
2094
+ node[index] = value;
2095
+ } else {
2096
+ (node as Record<string, unknown>)[leaf] = value;
2097
+ }
2098
+ }
2099
+
2100
+ /**
2101
+ * Fold the text a candidate typed into an entry THEY added back into that
2102
+ * addition.
2103
+ *
2104
+ * This is the branch that was missing beside `addressesBase`. An appended entry
2105
+ * lives at an index past the end of the writer's array, so every field of it
2106
+ * fails that test and is refused as a replacement — correctly, because an
2107
+ * out-of-range `set` would retarget the next time the writer produced a résumé
2108
+ * of a different length. What was never written was where the value goes
2109
+ * instead. It goes here: into the addition that owns it, addressed by `ref`,
2110
+ * where no change to the base can move it.
2111
+ *
2112
+ * Without this, a candidate who adds a role and types into it saves the
2113
+ * placeholder the entry was minted with, and exports it.
2114
+ */
2115
+ function foldAdditions(
2116
+ base: ResumeObject,
2117
+ values: Record<string, EditValue>,
2118
+ structural: ResumeEdits,
2119
+ ): ResumeEdits {
2120
+ const slotOf = additionSlots(base, structural);
2121
+
2122
+ return structural.map((edit) => {
2123
+ if (!isAppendEdit(edit) && !isSectionEdit(edit)) return edit;
2124
+ const prefix = slotOf.get(edit.ref);
2125
+ if (prefix === undefined) return edit;
2126
+
2127
+ const patch = Object.entries(values).filter(([path]) =>
2128
+ path.startsWith(`${prefix}.`),
2129
+ );
2130
+ if (patch.length === 0) return edit;
2131
+
2132
+ if (isSectionEdit(edit)) {
2133
+ const draft = {
2134
+ heading: edit.heading,
2135
+ entries: structuredClone(edit.entries),
2136
+ };
2137
+ for (const [path, value] of patch) {
2138
+ writeInto(
2139
+ draft as unknown as Record<string, unknown>,
2140
+ path.slice(prefix.length + 1).split('.'),
2141
+ value,
2142
+ );
2143
+ }
2144
+ return { ...edit, heading: draft.heading, entries: draft.entries };
2145
+ }
2146
+
2147
+ const entry = structuredClone(edit.entry);
2148
+ if (!isContainer(entry)) return edit;
2149
+ for (const [path, value] of patch) {
2150
+ writeInto(
2151
+ entry as Record<string, unknown>,
2152
+ path.slice(prefix.length + 1).split('.'),
2153
+ value,
2154
+ );
2155
+ }
2156
+ return { ...edit, entry };
2157
+ });
2158
+ }
2159
+
2160
+ /**
2161
+ * The inverse projection: given the values a surface currently holds, keep only
2162
+ * those that differ from the writer's resume.
2163
+ *
2164
+ * This is what makes an untouched document store nothing, and what keeps the
2165
+ * overlay a record of the candidate's corrections rather than a second copy of
2166
+ * the whole resume.
2167
+ *
2168
+ * Sorted by path so that saving the same document twice produces the same
2169
+ * overlay — a diff of two saves should show what the candidate changed, not what
2170
+ * order a node tree happened to be walked in.
2171
+ */
2172
+ export function presentationEdits(
2173
+ base: ResumeObject,
2174
+ values: Record<string, EditValue>,
2175
+ /*
2176
+ * The structural operations the document already carries, passed through
2177
+ * untouched.
2178
+ *
2179
+ * They are not derivable from `values`: an append is a decision the candidate
2180
+ * made, not a difference between two texts, and diffing cannot recover it.
2181
+ * Defaulted so every existing caller keeps its current behaviour.
2182
+ */
2183
+ structural: ResumeEdits = [],
2184
+ /*
2185
+ * The value a field holds because the TEMPLATE supplied it, by path.
2186
+ *
2187
+ * A section heading prints "Experience" on a résumé nobody has renamed, so
2188
+ * the field's value is not blank and the base's `section_headings` is empty —
2189
+ * which made merely opening a document look like nine edits and marked it
2190
+ * dirty before the candidate touched anything. `sameValue` already refuses the
2191
+ * blank case for exactly this reason ("a field the writer's résumé never
2192
+ * carried, still blank, is not an edit"); this is the same rule where the
2193
+ * template's own word, rather than emptiness, is what stands there.
2194
+ *
2195
+ * Equality with the default is enough on its own: typing a heading back to
2196
+ * the template's word is how a candidate undoes a rename, and it must leave
2197
+ * no trace, exactly as returning a space control to where it started does.
2198
+ */
2199
+ defaults: Readonly<Record<string, string>> = {},
2200
+ ): ResumeEdits {
2201
+ /*
2202
+ * The positions an addition occupies. Any value under one of these belongs to
2203
+ * the addition and is folded into it below; emitting it as a replacement as
2204
+ * well would write the candidate's new entry over whatever the writer's
2205
+ * résumé happens to hold at the same index.
2206
+ */
2207
+ const claimed = [
2208
+ ...additionSlots(
2209
+ base,
2210
+ structural.filter((edit) => !isSetEdit(edit)),
2211
+ ).values(),
2212
+ ];
2213
+
2214
+ const sets = Object.entries(values)
2215
+ .filter(
2216
+ ([path, value]) =>
2217
+ isResumeFieldPath(path) &&
2218
+ !claimed.some(
2219
+ (prefix) => path === prefix || path.startsWith(`${prefix}.`),
2220
+ ) &&
2221
+ /*
2222
+ * Only paths that ADDRESS the writer's résumé become replacements.
2223
+ *
2224
+ * Without this, the fields of an appended entry — which live at indices
2225
+ * past the end of the base array — would each be emitted as a `set` on
2226
+ * an out-of-range path. They would even apply, since appends run first,
2227
+ * and then silently retarget the wrong entry the next time the writer
2228
+ * produced a résumé of a different length. An addition's text belongs to
2229
+ * the addition, addressed by `ref`; only the base's own fields are
2230
+ * addressed by path.
2231
+ */
2232
+ addressesBase(base, path) &&
2233
+ !(typeof value === 'string' && value === defaults[path]) &&
2234
+ !sameValue(readAtPath(base, path), value),
2235
+ )
2236
+ .map(([path, value]) => ({ kind: 'set' as const, path, value }))
2237
+ .sort((a, b) => a.path.localeCompare(b.path));
2238
+
2239
+ /*
2240
+ * Structural first, then replacements sorted by path — the same order
2241
+ * `applyPresentation` resolves them in, so a saved overlay reads in the order
2242
+ * it is applied and saving twice produces the same bytes.
2243
+ */
2244
+ const additions = foldAdditions(
2245
+ base,
2246
+ values,
2247
+ structural.filter((edit) => !isSetEdit(edit)),
2248
+ );
2249
+ return [...additions, ...sets];
2250
+ }
2251
+
2252
+ /**
2253
+ * A surface's new overlay, keeping the replacements it could not see.
2254
+ *
2255
+ * An editing surface reports its overlay from the fields it DRAWS. A template
2256
+ * that draws no location for a role therefore reported no replacement for one,
2257
+ * and a location the candidate typed under another template was deleted by
2258
+ * merely switching to this one and back. The résumé's data must not depend on
2259
+ * which template happens to be drawing it.
2260
+ *
2261
+ * So a replacement in `previous` survives when its field is not among `shown`
2262
+ * and `next` says nothing about it. A field that IS shown is reported by the
2263
+ * surface, so its absence from `next` is a real revert and is respected.
2264
+ *
2265
+ * Safe to carry because a replacement only ever addresses the writer's own
2266
+ * entries, and those are hidden rather than deleted. A hidden entry keeps its
2267
+ * corrections for when it is shown again. An addition's words live inside its
2268
+ * own `append` edit and never arrive here.
2269
+ */
2270
+ export function withUnshownReplacements(
2271
+ previous: ResumeEdits,
2272
+ next: ResumeEdits,
2273
+ shown: ReadonlySet<string>,
2274
+ ): ResumeEdits {
2275
+ const overlaps = (path: string) => {
2276
+ if (shown.has(path)) return true;
2277
+ for (const field of shown) {
2278
+ if (field.startsWith(`${path}.`) || path.startsWith(`${field}.`)) {
2279
+ return true;
2280
+ }
2281
+ }
2282
+ return false;
2283
+ };
2284
+ const reported = new Set(next.filter(isSetEdit).map((edit) => edit.path));
2285
+ const carried = previous
2286
+ .filter(isSetEdit)
2287
+ .filter((edit) => !reported.has(edit.path) && !overlaps(edit.path));
2288
+ if (carried.length === 0) return next;
2289
+
2290
+ // Same order `presentationEdits` writes: structural first, then
2291
+ // replacements by path, so the same document still saves the same bytes.
2292
+ const sets = [...next.filter(isSetEdit), ...carried]
2293
+ .map((edit) => ({
2294
+ kind: 'set' as const,
2295
+ path: edit.path,
2296
+ value: edit.value,
2297
+ }))
2298
+ .sort((a, b) => a.path.localeCompare(b.path));
2299
+ return [...next.filter((edit) => !isSetEdit(edit)), ...sets];
2300
+ }
2301
+
2302
+ /**
2303
+ * Whether a path addresses a location in the WRITER's résumé.
2304
+ *
2305
+ * Distinguishes an out-of-range array index (not addressable — that entry does
2306
+ * not exist in the base) from an absent optional field (addressable — a résumé
2307
+ * with no `headline` can still have one typed into it). `readAtPath` returns
2308
+ * `undefined` for both, which is why this cannot be expressed as a null check.
2309
+ */
2310
+ function addressesBase(base: ResumeObject, path: string): boolean {
2311
+ let node: unknown = base;
2312
+ for (const segment of path.split('.')) {
2313
+ if (Array.isArray(node)) {
2314
+ const index = Number(segment);
2315
+ if (!Number.isInteger(index) || index < 0 || index >= node.length) {
2316
+ return false;
2317
+ }
2318
+ node = node[index];
2319
+ } else if (node !== null && typeof node === 'object') {
2320
+ node = (node as Record<string, unknown>)[segment];
2321
+ } else {
2322
+ // A leaf was reached before the path was consumed.
2323
+ return false;
2324
+ }
2325
+ }
2326
+ return true;
2327
+ }
2328
+
2329
+ /**
2330
+ * Which entries of a section the candidate added, by their index in the
2331
+ * PRESENTED résumé, paired with the `ref` that names them.
2332
+ *
2333
+ * Derived rather than stored in the document: appends land after the base
2334
+ * entries in overlay order, so the boundary is `base[section].length` and the
2335
+ * order is the overlay's. That is what lets `ResumeObject` stay exactly the
2336
+ * shape a template already renders, with no editor bookkeeping written into it.
2337
+ *
2338
+ * This is the one place the derivation lives — an editor that recomputed it
2339
+ * would be a second definition of "which of these did I add", free to disagree.
2340
+ */
2341
+ export function appendedEntryRefs(
2342
+ base: ResumeObject,
2343
+ edits: ResumeEdits,
2344
+ section: AppendableSection,
2345
+ ): Map<number, string> {
2346
+ const dropped = new Set(edits.filter(isDropEdit).map((e) => e.ref));
2347
+ const baseLength = (base[section] as unknown[]).length;
2348
+ const refs = new Map<number, string>();
2349
+
2350
+ let index = baseLength;
2351
+ for (const edit of edits) {
2352
+ if (!isAppendEdit(edit) || edit.section !== section) continue;
2353
+ if (dropped.has(edit.ref)) continue;
2354
+ // Only entries the schema accepts are appended, so only those take a slot.
2355
+ if (!APPEND_SCHEMAS[section].safeParse(edit.entry).success) continue;
2356
+ refs.set(index, edit.ref);
2357
+ index += 1;
2358
+ }
2359
+ return refs;
2360
+ }