@hadoku/resume-bot 3.15.116 → 3.15.118

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.
Files changed (39) hide show
  1. package/dist/{index-D6Xd4aSy.js → index-DTz0YFfl.js} +1189 -201
  2. package/dist/{node.browser-CP5wfAdg.js → node.browser-B0AdQysu.js} +1 -1
  3. package/dist/{node.browser-Bk9bty0A.js → node.browser-iYPBhOfA.js} +2 -2
  4. package/dist/worker/application-extras.d.ts +4 -1
  5. package/dist/worker/application-extras.d.ts.map +1 -1
  6. package/dist/worker/blocks.d.ts +6 -1
  7. package/dist/worker/blocks.d.ts.map +1 -1
  8. package/dist/worker/builder.d.ts +20 -6
  9. package/dist/worker/builder.d.ts.map +1 -1
  10. package/dist/worker/contact.d.ts +21 -1
  11. package/dist/worker/contact.d.ts.map +1 -1
  12. package/dist/worker/cover-letter.d.ts +4 -1
  13. package/dist/worker/cover-letter.d.ts.map +1 -1
  14. package/dist/worker/erase.d.ts +31 -0
  15. package/dist/worker/erase.d.ts.map +1 -0
  16. package/dist/worker/fit.d.ts +32 -0
  17. package/dist/worker/fit.d.ts.map +1 -0
  18. package/dist/worker/form-answers.d.ts +4 -1
  19. package/dist/worker/form-answers.d.ts.map +1 -1
  20. package/dist/worker/index.d.ts +18 -5
  21. package/dist/worker/index.d.ts.map +1 -1
  22. package/dist/worker/paper.d.ts +16 -0
  23. package/dist/worker/paper.d.ts.map +1 -0
  24. package/dist/worker/pdf.d.ts +25 -0
  25. package/dist/worker/pdf.d.ts.map +1 -1
  26. package/dist/worker/resume-import.d.ts +33 -0
  27. package/dist/worker/resume-import.d.ts.map +1 -0
  28. package/dist/worker/resume.d.ts +2 -1
  29. package/dist/worker/resume.d.ts.map +1 -1
  30. package/dist/worker/scope.d.ts +105 -0
  31. package/dist/worker/scope.d.ts.map +1 -0
  32. package/dist/worker/skeleton.d.ts +31 -2
  33. package/dist/worker/skeleton.d.ts.map +1 -1
  34. package/dist/worker/tailored-resume.d.ts +8 -1
  35. package/dist/worker/tailored-resume.d.ts.map +1 -1
  36. package/dist/worker/variants.d.ts +49 -5
  37. package/dist/worker/variants.d.ts.map +1 -1
  38. package/dist/worker.js +1 -1
  39. package/package.json +2 -2
@@ -15141,13 +15141,108 @@ async function recordRequest(kv, ip) {
15141
15141
  expirationTtl: RATE_LIMIT_CONFIG.KV_TTL_SECONDS
15142
15142
  });
15143
15143
  }
15144
- async function getAllBlocks(kv) {
15145
- const indexJson = await kv.get("resume:blocks:index");
15144
+ const OWNER_SCOPE = { kind: "owner" };
15145
+ class NoResumeBlocksError extends Error {
15146
+ code = "NO_RESUME_BLOCKS";
15147
+ constructor(scope) {
15148
+ super(
15149
+ scope.kind === "owner" ? "No resume blocks found in KV storage" : "No resume blocks for this user. Import a resume first (POST /blocks/import)."
15150
+ );
15151
+ this.name = "NoResumeBlocksError";
15152
+ }
15153
+ }
15154
+ const USER_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
15155
+ function isUserId(id2) {
15156
+ return USER_ID_PATTERN.test(id2);
15157
+ }
15158
+ function listed(csv, id2) {
15159
+ return (csv ?? "").split(",").map((s) => s.trim()).filter(Boolean).includes(id2);
15160
+ }
15161
+ function resolveScope(auth, env, onBehalfOf2) {
15162
+ if (onBehalfOf2 !== void 0 && onBehalfOf2 !== null && typeof onBehalfOf2 !== "string") {
15163
+ return { status: 400, error: "on_behalf_of_user_id must be a string" };
15164
+ }
15165
+ const named = typeof onBehalfOf2 === "string" ? onBehalfOf2.trim() : "";
15166
+ let userId;
15167
+ if (named) {
15168
+ const callerId = auth?.userId ?? null;
15169
+ const allowed = tierAtLeast(auth, "admin") || tierAtLeast(auth, "service") && !!callerId && listed(env.ON_BEHALF_CALLER_USER_IDS, callerId);
15170
+ if (!allowed) {
15171
+ return {
15172
+ status: 403,
15173
+ error: "Only admin, or a service caller listed in ON_BEHALF_CALLER_USER_IDS, may act on behalf of a user."
15174
+ };
15175
+ }
15176
+ if (!env.RESUME_OWNER_USER_ID?.trim()) {
15177
+ return {
15178
+ status: 503,
15179
+ error: "RESUME_OWNER_USER_ID is not configured, so on_behalf_of_user_id cannot be honoured."
15180
+ };
15181
+ }
15182
+ userId = named;
15183
+ } else if (tierAtLeast(auth, "admin")) {
15184
+ return { scope: OWNER_SCOPE };
15185
+ } else if (auth?.userType === "service") {
15186
+ return {
15187
+ status: 403,
15188
+ error: "A service caller must name the user it acts for (on_behalf_of_user_id)."
15189
+ };
15190
+ } else {
15191
+ userId = auth?.userId ?? null;
15192
+ }
15193
+ if (!userId) {
15194
+ return { status: 403, error: "No caller identity: reach this API through hadoku.me." };
15195
+ }
15196
+ if (!isUserId(userId)) {
15197
+ return { status: 400, error: "Malformed user id" };
15198
+ }
15199
+ const ownerId = env.RESUME_OWNER_USER_ID?.trim();
15200
+ if (ownerId && userId === ownerId) return { scope: OWNER_SCOPE };
15201
+ return { scope: { kind: "user", userId } };
15202
+ }
15203
+ function scopeKeys(scope) {
15204
+ if (scope.kind === "owner") {
15205
+ return {
15206
+ blockIndex: "resume:blocks:index",
15207
+ block: (id2) => `resume:blocks:${id2}`,
15208
+ feedback: "resume:blocks:feedback",
15209
+ contact: "resume:profile:contact",
15210
+ variant: (slug2) => `resume:variant:${slug2}`,
15211
+ variantListPrefix: "resume:variant:",
15212
+ cache: (kind) => `resume:${kind}`
15213
+ };
15214
+ }
15215
+ const u = scope.userId;
15216
+ return {
15217
+ blockIndex: `resume:blocks:${u}:index`,
15218
+ block: (id2) => `resume:blocks:${u}:${id2}`,
15219
+ feedback: `resume:blocks:${u}:feedback`,
15220
+ contact: `resume:profile:contact:${u}`,
15221
+ variant: (slug2) => `resume:variant:${u}:${slug2}`,
15222
+ variantListPrefix: `resume:variant:${u}:`,
15223
+ cache: (kind) => `resume:${kind}:${u}`
15224
+ };
15225
+ }
15226
+ const VARIANT_OWNER_PREFIX = "resume:variant-owner:";
15227
+ function variantOwnerKey(slug2) {
15228
+ return `${VARIANT_OWNER_PREFIX}${slug2}`;
15229
+ }
15230
+ const ERASED_POINTER = "!erased";
15231
+ function derivedCachePrefixes(scope) {
15232
+ const keys = scopeKeys(scope);
15233
+ return ["tailored", "coverletter", "extras"].map((kind) => `${keys.cache(kind)}:`);
15234
+ }
15235
+ function isUserScopedRemainder(remainder) {
15236
+ return remainder.includes(":");
15237
+ }
15238
+ async function getAllBlocks(kv, scope = OWNER_SCOPE) {
15239
+ const keys = scopeKeys(scope);
15240
+ const indexJson = await kv.get(keys.blockIndex);
15146
15241
  if (!indexJson) return [];
15147
15242
  const ids = JSON.parse(indexJson);
15148
15243
  const blocks = await Promise.all(
15149
15244
  ids.map(async (id2) => {
15150
- const json2 = await kv.get(`resume:blocks:${id2}`);
15245
+ const json2 = await kv.get(keys.block(id2));
15151
15246
  if (!json2) return null;
15152
15247
  return JSON.parse(json2);
15153
15248
  })
@@ -15173,7 +15268,6 @@ const SECTION_ORDER = [
15173
15268
  ];
15174
15269
  const PAGE_BREAK_BEFORE = /* @__PURE__ */ new Set(["projects", "skills"]);
15175
15270
  const PAGE_BREAK_MARKER = "<!-- page-break -->";
15176
- const SECTION_IDS = new Set(SECTION_ORDER);
15177
15271
  const SECTION_TAG_PREFIX = "section:";
15178
15272
  const SECTION_HEADINGS = {
15179
15273
  summary: "# Profile",
@@ -15189,6 +15283,41 @@ const CATEGORY_ORDER = [
15189
15283
  { id: "data-automation", heading: "### Data & Automation" },
15190
15284
  { id: "apps-games-tools", heading: "### Apps, Games & Tools" }
15191
15285
  ];
15286
+ const OWNER_LAYOUT = {
15287
+ order: SECTION_ORDER,
15288
+ headings: SECTION_HEADINGS,
15289
+ pageBreakBefore: PAGE_BREAK_BEFORE,
15290
+ projectCategories: CATEGORY_ORDER
15291
+ };
15292
+ const GENERIC_LAYOUT = {
15293
+ order: [
15294
+ "header",
15295
+ "summary",
15296
+ "experience-primary",
15297
+ "experience-secondary",
15298
+ "projects",
15299
+ "skills",
15300
+ "education",
15301
+ "languages",
15302
+ "certifications",
15303
+ "extra"
15304
+ ],
15305
+ headings: {
15306
+ summary: "# Summary",
15307
+ "experience-primary": "# Experience",
15308
+ "experience-secondary": "# Additional Experience",
15309
+ projects: "# Projects",
15310
+ skills: "# Skills",
15311
+ education: "# Education",
15312
+ languages: "# Languages",
15313
+ certifications: "# Certifications"
15314
+ },
15315
+ pageBreakBefore: /* @__PURE__ */ new Set(),
15316
+ projectCategories: null
15317
+ };
15318
+ function layoutFor(scope) {
15319
+ return scope.kind === "owner" ? OWNER_LAYOUT : GENERIC_LAYOUT;
15320
+ }
15192
15321
  function categoryOf(block) {
15193
15322
  const tag = block.tags.find((t) => t.startsWith(CATEGORY_TAG_PREFIX));
15194
15323
  return tag ? tag.slice(CATEGORY_TAG_PREFIX.length) : null;
@@ -15208,11 +15337,11 @@ function filterCanonical(blocks) {
15208
15337
  function stripPageBreaks(markdown) {
15209
15338
  return markdown.split("\n").filter((line) => line.trim() !== PAGE_BREAK_MARKER).join("\n").replace(/\n{3,}/g, "\n\n").trim();
15210
15339
  }
15211
- function sectionOf(block) {
15340
+ function sectionOf(block, layout = OWNER_LAYOUT) {
15212
15341
  const tag = block.tags.find((t) => t.startsWith(SECTION_TAG_PREFIX));
15213
15342
  if (tag) {
15214
15343
  const id2 = tag.slice(SECTION_TAG_PREFIX.length);
15215
- if (SECTION_IDS.has(id2)) return id2;
15344
+ if (layout.order.includes(id2)) return id2;
15216
15345
  }
15217
15346
  switch (block.type) {
15218
15347
  case "header":
@@ -15230,33 +15359,34 @@ function sectionOf(block) {
15230
15359
  return "experience-primary";
15231
15360
  }
15232
15361
  }
15233
- function assembleResume(blocks) {
15362
+ function assembleResume(blocks, layout = OWNER_LAYOUT) {
15234
15363
  const bySection = /* @__PURE__ */ new Map();
15235
15364
  for (const block of blocks) {
15236
- const section = sectionOf(block);
15365
+ const section = sectionOf(block, layout);
15237
15366
  const group = bySection.get(section);
15238
15367
  if (group) group.push(block);
15239
15368
  else bySection.set(section, [block]);
15240
15369
  }
15241
15370
  const parts = [];
15242
- for (const section of SECTION_ORDER) {
15371
+ for (const section of layout.order) {
15243
15372
  const group = bySection.get(section);
15244
15373
  if (!group || group.length === 0) continue;
15245
15374
  const ordered = group.map((block, i) => ({ block, i })).sort((a, b) => b.block.priority - a.block.priority || a.i - b.i).map((x) => x.block);
15246
- if (parts.length > 0 && PAGE_BREAK_BEFORE.has(section)) parts.push(PAGE_BREAK_MARKER);
15247
- const heading = SECTION_HEADINGS[section];
15375
+ if (parts.length > 0 && layout.pageBreakBefore.has(section)) parts.push(PAGE_BREAK_MARKER);
15376
+ const heading = layout.headings[section];
15248
15377
  if (heading) parts.push(heading);
15249
15378
  const emit = (block) => parts.push(heading ? stripLeadingHeading(block.content, heading) : block.content);
15250
- if (section === "projects") {
15379
+ const categories = layout.projectCategories;
15380
+ if (section === "projects" && categories) {
15251
15381
  const uncategorized = ordered.filter((b) => categoryOf(b) === null);
15252
15382
  for (const block of uncategorized) emit(block);
15253
- for (const { id: id2, heading: catHeading } of CATEGORY_ORDER) {
15383
+ for (const { id: id2, heading: catHeading } of categories) {
15254
15384
  const members = ordered.filter((b) => categoryOf(b) === id2);
15255
15385
  if (members.length === 0) continue;
15256
15386
  parts.push(catHeading);
15257
15387
  for (const block of members) emit(block);
15258
15388
  }
15259
- const known = new Set(CATEGORY_ORDER.map((c) => c.id));
15389
+ const known = new Set(categories.map((c) => c.id));
15260
15390
  for (const block of ordered) {
15261
15391
  const cat = categoryOf(block);
15262
15392
  if (cat !== null && !known.has(cat)) emit(block);
@@ -15295,9 +15425,14 @@ function countPageBreaks(markdown) {
15295
15425
  }
15296
15426
  return count2;
15297
15427
  }
15298
- async function getResumeContent(env) {
15299
- const blocks = await getAllBlocks(env.CONTENT_KV);
15428
+ async function getResumeContent(env, scope = OWNER_SCOPE) {
15429
+ const blocks = await getAllBlocks(env.CONTENT_KV, scope);
15300
15430
  const canonical = filterCanonical(blocks);
15431
+ if (scope.kind === "user") {
15432
+ const chosen = canonical.length > 0 ? canonical : blocks;
15433
+ if (chosen.length === 0) throw new NoResumeBlocksError(scope);
15434
+ return assembleResume(chosen, layoutFor(scope));
15435
+ }
15301
15436
  if (canonical.length > 0) return assembleResume(canonical);
15302
15437
  const content = await env.CONTENT_KV.get("resume:full") ?? await env.CONTENT_KV.get("resume");
15303
15438
  if (!content) {
@@ -34459,6 +34594,24 @@ var PDFButton = (
34459
34594
  return PDFButton2;
34460
34595
  })(PDFField)
34461
34596
  );
34597
+ const PAPER_SIZE = {
34598
+ a4: { width: 595.28, height: 841.89 },
34599
+ letter: { width: 612, height: 792 }
34600
+ };
34601
+ const LETTER_COUNTRY = /\b(usa|united states|canada)\b/i;
34602
+ const US_ABBREVIATION = /(^|[\s,(])(US|U\.S\.(A\.)?)(?=$|[\s,)])/;
34603
+ const LETTER_REGIONS = new Set(
34604
+ "AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY DC ON QC BC AB MB SK NS NB NL PE YT NT NU".split(" ")
34605
+ );
34606
+ function paperForLocation(location) {
34607
+ const text = (location ?? "").trim();
34608
+ if (!text) return "a4";
34609
+ if (LETTER_COUNTRY.test(text) || US_ABBREVIATION.test(text)) return "letter";
34610
+ for (const m of text.matchAll(/,\s*([A-Z]{2})\b/g)) {
34611
+ if (LETTER_REGIONS.has(m[1])) return "letter";
34612
+ }
34613
+ return "a4";
34614
+ }
34462
34615
  const INLINE_TOKEN = /(\*\*[^*]+\*\*|\[[^\]]+\]\(\S+\)|\*[^*\s][^*]*\*)/g;
34463
34616
  function parseInline(text) {
34464
34617
  const runs = [];
@@ -34506,7 +34659,11 @@ function parseBlocks(markdown) {
34506
34659
  blocks.push({ kind: "page-break" });
34507
34660
  } else if (/^#{1,3} /.test(line)) {
34508
34661
  flush();
34509
- blocks.push({ kind: "heading", runs: parseInline(line.replace(/^#{1,3} /, "")) });
34662
+ blocks.push({
34663
+ kind: "heading",
34664
+ level: line.indexOf(" "),
34665
+ runs: parseInline(line.replace(/^#{1,3} /, ""))
34666
+ });
34510
34667
  } else if (/^[-*] /.test(line)) {
34511
34668
  flush();
34512
34669
  blocks.push({ kind: "bullet", runs: parseInline(line.slice(2)) });
@@ -34520,17 +34677,49 @@ function parseBlocks(markdown) {
34520
34677
  flush();
34521
34678
  return blocks;
34522
34679
  }
34523
- const PAGE_WIDTH = 612;
34524
- const PAGE_HEIGHT = 792;
34525
- const MARGIN_X = 58;
34526
- const MARGIN_TOP = 64;
34527
- const MARGIN_BOTTOM = 58;
34528
- const CONTENT_WIDTH = PAGE_WIDTH - MARGIN_X * 2;
34529
- const BODY_SIZE = 10.5;
34530
- const BODY_LEADING = 15;
34531
- const HEADING_SIZE = 13.5;
34532
- const NAME_SIZE = 15;
34533
- const BULLET_INDENT = 18;
34680
+ const OWNER_TYPOGRAPHY = {
34681
+ pageWidth: 612,
34682
+ // US Letter
34683
+ pageHeight: 792,
34684
+ marginX: 58,
34685
+ marginTop: 64,
34686
+ marginBottom: 58,
34687
+ bodySize: 10.5,
34688
+ bodyLeading: 15,
34689
+ headingSize: 13.5,
34690
+ headingGap: 14,
34691
+ headingRuleGap: 7,
34692
+ headingAfterRule: 4,
34693
+ nameSize: 15,
34694
+ bulletIndent: 18,
34695
+ paragraphGap: 5,
34696
+ bulletGap: 2,
34697
+ entryHeading: null
34698
+ };
34699
+ const COMPACT_TYPOGRAPHY = {
34700
+ pageWidth: 612,
34701
+ pageHeight: 792,
34702
+ marginX: 46,
34703
+ marginTop: 42,
34704
+ marginBottom: 40,
34705
+ bodySize: 9.5,
34706
+ bodyLeading: 12.4,
34707
+ headingSize: 11.5,
34708
+ headingGap: 9,
34709
+ headingRuleGap: 4,
34710
+ headingAfterRule: 2,
34711
+ nameSize: 16,
34712
+ bulletIndent: 13,
34713
+ paragraphGap: 2.5,
34714
+ bulletGap: 0.6,
34715
+ entryHeading: { size: 10, gap: 6, after: 1 }
34716
+ };
34717
+ function typographyFor(style, paper = "letter") {
34718
+ const base = style === "compact" ? COMPACT_TYPOGRAPHY : OWNER_TYPOGRAPHY;
34719
+ if (paper === "letter") return base;
34720
+ const { width, height } = PAPER_SIZE[paper];
34721
+ return { ...base, pageWidth: width, pageHeight: height };
34722
+ }
34534
34723
  const TEXT_COLOR = rgb(0.13, 0.13, 0.13);
34535
34724
  const RULE_COLOR = rgb(0.75, 0.75, 0.75);
34536
34725
  const LINK_COLOR = rgb(0.1, 0.3, 0.65);
@@ -34608,24 +34797,32 @@ function wrapWords(words, fonts, size, maxWidth) {
34608
34797
  return lines;
34609
34798
  }
34610
34799
  class Typesetter {
34611
- constructor(doc, fonts) {
34800
+ constructor(doc, fonts, t, measureOnly = false) {
34612
34801
  this.doc = doc;
34613
34802
  this.fonts = fonts;
34803
+ this.t = t;
34804
+ this.measureOnly = measureOnly;
34614
34805
  this.newPage();
34615
34806
  }
34616
- page;
34807
+ page = null;
34617
34808
  y = 0;
34809
+ pages = 0;
34810
+ get contentWidth() {
34811
+ return this.t.pageWidth - this.t.marginX * 2;
34812
+ }
34618
34813
  newPage() {
34619
- this.page = this.doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
34620
- this.y = PAGE_HEIGHT - MARGIN_TOP;
34814
+ this.pages++;
34815
+ if (!this.measureOnly) this.page = this.doc.addPage([this.t.pageWidth, this.t.pageHeight]);
34816
+ this.y = this.t.pageHeight - this.t.marginTop;
34621
34817
  }
34622
34818
  ensureRoom(height) {
34623
- if (this.y - height < MARGIN_BOTTOM) this.newPage();
34819
+ if (this.y - height < this.t.marginBottom) this.newPage();
34624
34820
  }
34625
34821
  atTopOfPage() {
34626
- return this.y === PAGE_HEIGHT - MARGIN_TOP;
34822
+ return this.y === this.t.pageHeight - this.t.marginTop;
34627
34823
  }
34628
34824
  addLinkAnnotation(x, width, size, url2) {
34825
+ if (!this.page) return;
34629
34826
  const action = this.doc.context.obj({
34630
34827
  Type: PDFName.of("Action"),
34631
34828
  S: PDFName.of("URI"),
@@ -34649,6 +34846,7 @@ class Typesetter {
34649
34846
  }
34650
34847
  /** Draw one pre-wrapped line of words at the current cursor. */
34651
34848
  drawLine(line, size, x) {
34849
+ if (!this.page) return;
34652
34850
  const spaceWidth = this.fonts.regular.widthOfTextAtSize(" ", size);
34653
34851
  let cx2 = x;
34654
34852
  for (const [i, word] of line.entries()) {
@@ -34674,32 +34872,42 @@ class Typesetter {
34674
34872
  this.drawLine(line, size, x);
34675
34873
  }
34676
34874
  }
34677
- heading(runs) {
34678
- this.ensureRoom(HEADING_SIZE + 10 + BODY_LEADING * 2);
34679
- if (!this.atTopOfPage()) this.y -= 14;
34680
- this.y -= HEADING_SIZE;
34875
+ heading(runs, level = 1) {
34876
+ const t = this.t;
34681
34877
  const boldRuns = runs.map((r) => ({ ...r, bold: true }));
34682
- this.drawLine(toWords(boldRuns, this.fonts, HEADING_SIZE), HEADING_SIZE, MARGIN_X);
34683
- this.y -= 7;
34878
+ const entry = level > 1 ? t.entryHeading : null;
34879
+ if (entry) {
34880
+ this.ensureRoom(entry.size + entry.gap + t.bodyLeading * 2);
34881
+ if (!this.atTopOfPage()) this.y -= entry.gap;
34882
+ this.drawWrapped(boldRuns, entry.size, entry.size * 1.25, t.marginX, this.contentWidth);
34883
+ this.y -= entry.after;
34884
+ return;
34885
+ }
34886
+ this.ensureRoom(t.headingSize + 10 + t.bodyLeading * 2);
34887
+ if (!this.atTopOfPage()) this.y -= t.headingGap;
34888
+ this.y -= t.headingSize;
34889
+ this.drawLine(toWords(boldRuns, this.fonts, t.headingSize), t.headingSize, t.marginX);
34890
+ this.y -= t.headingRuleGap;
34684
34891
  this.rule();
34685
- this.y -= 4;
34892
+ this.y -= t.headingAfterRule;
34686
34893
  }
34687
34894
  rule() {
34688
34895
  this.ensureRoom(2);
34896
+ if (!this.page) return;
34689
34897
  this.page.drawLine({
34690
- start: { x: MARGIN_X, y: this.y },
34691
- end: { x: PAGE_WIDTH - MARGIN_X, y: this.y },
34898
+ start: { x: this.t.marginX, y: this.y },
34899
+ end: { x: this.t.pageWidth - this.t.marginX, y: this.y },
34692
34900
  thickness: 0.75,
34693
34901
  color: RULE_COLOR
34694
34902
  });
34695
34903
  }
34696
34904
  paragraph(lines, options = {}) {
34697
- const size = options.size ?? BODY_SIZE;
34698
- const leading = options.leading ?? BODY_LEADING;
34905
+ const size = options.size ?? this.t.bodySize;
34906
+ const leading = options.leading ?? this.t.bodyLeading;
34699
34907
  for (const lineRuns of lines) {
34700
- this.drawWrapped(lineRuns, size, leading, MARGIN_X, CONTENT_WIDTH);
34908
+ this.drawWrapped(lineRuns, size, leading, this.t.marginX, this.contentWidth);
34701
34909
  }
34702
- this.y -= 5;
34910
+ this.y -= this.t.paragraphGap;
34703
34911
  }
34704
34912
  /** Render a parsed document. The first paragraph before any heading is the
34705
34913
  * name/contact block and gets display sizing on its first line. */
@@ -34710,16 +34918,16 @@ class Typesetter {
34710
34918
  switch (block.kind) {
34711
34919
  case "heading":
34712
34920
  seenHeading = true;
34713
- this.heading(block.runs);
34921
+ this.heading(block.runs, block.level);
34714
34922
  break;
34715
34923
  case "paragraph":
34716
34924
  if (isFirstBlock && !seenHeading && block.lines.length > 0) {
34717
34925
  const [nameLine, ...rest] = block.lines;
34718
34926
  this.paragraph([nameLine.map((r) => ({ ...r, bold: true }))], {
34719
- size: NAME_SIZE,
34720
- leading: NAME_SIZE * 1.4
34927
+ size: this.t.nameSize,
34928
+ leading: this.t.nameSize * 1.4
34721
34929
  });
34722
- this.y += 5;
34930
+ this.y += this.t.paragraphGap;
34723
34931
  if (rest.length > 0) this.paragraph(rest);
34724
34932
  } else {
34725
34933
  this.paragraph(block.lines);
@@ -34741,43 +34949,57 @@ class Typesetter {
34741
34949
  }
34742
34950
  }
34743
34951
  drawBullet(runs) {
34744
- const words = toWords(runs, this.fonts, BODY_SIZE);
34745
- const lines = wrapWords(words, this.fonts, BODY_SIZE, CONTENT_WIDTH - BULLET_INDENT);
34952
+ const t = this.t;
34953
+ const words = toWords(runs, this.fonts, t.bodySize);
34954
+ const lines = wrapWords(words, this.fonts, t.bodySize, this.contentWidth - t.bulletIndent);
34746
34955
  for (const [i, line] of lines.entries()) {
34747
- this.ensureRoom(BODY_LEADING);
34748
- this.y -= BODY_LEADING;
34749
- if (i === 0) {
34956
+ this.ensureRoom(t.bodyLeading);
34957
+ this.y -= t.bodyLeading;
34958
+ if (i === 0 && this.page) {
34750
34959
  this.page.drawText("•", {
34751
- x: MARGIN_X + 6,
34960
+ x: t.marginX + t.bulletIndent / 3,
34752
34961
  y: this.y,
34753
- size: BODY_SIZE,
34962
+ size: t.bodySize,
34754
34963
  font: this.fonts.regular,
34755
34964
  color: TEXT_COLOR
34756
34965
  });
34757
34966
  }
34758
- this.drawLine(line, BODY_SIZE, MARGIN_X + BULLET_INDENT);
34967
+ this.drawLine(line, t.bodySize, t.marginX + t.bulletIndent);
34759
34968
  }
34760
- this.y -= 2;
34969
+ this.y -= t.bulletGap;
34761
34970
  }
34762
34971
  }
34763
- async function renderResumePdf(input) {
34764
- const doc = await PDFDocument.create();
34765
- doc.setTitle(`${input.ownerName} — Résumé`);
34766
- doc.setAuthor(input.ownerName);
34972
+ async function embedFonts(doc) {
34767
34973
  const regular = await doc.embedFont(StandardFonts.Helvetica);
34768
- const fonts = {
34974
+ return {
34769
34975
  regular,
34770
34976
  bold: await doc.embedFont(StandardFonts.HelveticaBold),
34771
34977
  italic: await doc.embedFont(StandardFonts.HelveticaOblique),
34772
34978
  boldItalic: await doc.embedFont(StandardFonts.HelveticaBoldOblique),
34773
34979
  charset: new Set(regular.getCharacterSet())
34774
34980
  };
34775
- const typesetter = new Typesetter(doc, fonts);
34981
+ }
34982
+ async function createPageCounter(style, paper = "letter") {
34983
+ const doc = await PDFDocument.create();
34984
+ const fonts = await embedFonts(doc);
34985
+ const t = typographyFor(style, paper);
34986
+ return (markdown) => {
34987
+ const typesetter = new Typesetter(doc, fonts, t, true);
34988
+ typesetter.render(parseBlocks(markdown));
34989
+ return typesetter.pages;
34990
+ };
34991
+ }
34992
+ async function renderResumePdf(input) {
34993
+ const doc = await PDFDocument.create();
34994
+ doc.setTitle(input.title ?? `${input.ownerName} — Résumé`);
34995
+ doc.setAuthor(input.ownerName);
34996
+ const fonts = await embedFonts(doc);
34997
+ const typesetter = new Typesetter(doc, fonts, typographyFor(input.style, input.paper));
34776
34998
  typesetter.render(parseBlocks(input.resume));
34777
34999
  if (input.coverLetter && input.coverLetter.length > 0) {
34778
35000
  typesetter.newPage();
34779
35001
  typesetter.render([
34780
- { kind: "heading", runs: [{ text: "Cover Letter", bold: true, italic: false }] },
35002
+ { kind: "heading", level: 1, runs: [{ text: "Cover Letter", bold: true, italic: false }] },
34781
35003
  ...parseBlocks(input.coverLetter)
34782
35004
  ]);
34783
35005
  }
@@ -48516,7 +48738,7 @@ var EnvironmentWorker = /* @__PURE__ */ (() => {
48516
48738
  const ctrl = new AbortController();
48517
48739
  const detachExternal = linkAbort(externalSignal, ctrl);
48518
48740
  const lease = new Lease(ctrl);
48519
- const agentToolset = await import("./node.browser-Bk9bty0A.js");
48741
+ const agentToolset = await import("./node.browser-iYPBhOfA.js");
48520
48742
  let leaseTtlMs;
48521
48743
  let runner;
48522
48744
  const heartbeatPromise = heartbeatLoop(sessionClient, work, lease, log, this.requestOptions, (ttlMs) => {
@@ -65145,7 +65367,7 @@ function redactSensitive(body) {
65145
65367
  async function checkCredentialsFileSafety(path2, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) {
65146
65368
  if (typeof process === "undefined" || process.platform === "win32")
65147
65369
  return;
65148
- const { fs } = await import("./node.browser-CP5wfAdg.js");
65370
+ const { fs } = await import("./node.browser-B0AdQysu.js");
65149
65371
  let resolved = path2;
65150
65372
  let st;
65151
65373
  try {
@@ -65166,7 +65388,7 @@ async function checkCredentialsFileSafety(path2, onWarn = (m) => console.warn(`a
65166
65388
  }
65167
65389
  }
65168
65390
  async function writeCredentialsFileAtomic(targetPath, data) {
65169
- const { fs, path: path2 } = await import("./node.browser-CP5wfAdg.js");
65391
+ const { fs, path: path2 } = await import("./node.browser-B0AdQysu.js");
65170
65392
  const dir = path2.dirname(targetPath);
65171
65393
  await fs.promises.mkdir(dir, { recursive: true, mode: 448 });
65172
65394
  const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
@@ -65385,7 +65607,7 @@ const loadConfigWithSource = async (profile) => {
65385
65607
  return null;
65386
65608
  }
65387
65609
  validateProfileName(profileName);
65388
- const { fs, path: path2 } = await import("./node.browser-CP5wfAdg.js");
65610
+ const { fs, path: path2 } = await import("./node.browser-B0AdQysu.js");
65389
65611
  const configPath = path2.join(rootConfigPath, "configs", `${profileName}.json`);
65390
65612
  let configRaw;
65391
65613
  try {
@@ -65446,14 +65668,14 @@ const getCredentialsPath = async (config2, profile) => {
65446
65668
  return null;
65447
65669
  }
65448
65670
  validateProfileName(profileName);
65449
- const { path: path2 } = await import("./node.browser-CP5wfAdg.js");
65671
+ const { path: path2 } = await import("./node.browser-B0AdQysu.js");
65450
65672
  return path2.join(rootConfigPath, "credentials", `${profileName}.json`);
65451
65673
  };
65452
65674
  const getRootConfigPath = async () => {
65453
65675
  if (!supportsLocalConfigFiles()) {
65454
65676
  return null;
65455
65677
  }
65456
- const { path: path2 } = await import("./node.browser-CP5wfAdg.js");
65678
+ const { path: path2 } = await import("./node.browser-B0AdQysu.js");
65457
65679
  const configDir = readEnv("ANTHROPIC_CONFIG_DIR");
65458
65680
  if (configDir) {
65459
65681
  return configDir;
@@ -65493,7 +65715,7 @@ const getActiveProfileName = async () => {
65493
65715
  if (profileName) {
65494
65716
  return profileName;
65495
65717
  }
65496
- const { fs, path: path2 } = await import("./node.browser-CP5wfAdg.js");
65718
+ const { fs, path: path2 } = await import("./node.browser-B0AdQysu.js");
65497
65719
  const filePath = path2.join(rootConfigPath, "active_config");
65498
65720
  try {
65499
65721
  return (await fs.promises.readFile(filePath, "utf-8")).trim() || "default";
@@ -65509,7 +65731,7 @@ function identityTokenFromFile(path2) {
65509
65731
  throw new AnthropicError("Identity token file path is empty");
65510
65732
  }
65511
65733
  return async () => {
65512
- const { fs } = await import("./node.browser-CP5wfAdg.js");
65734
+ const { fs } = await import("./node.browser-B0AdQysu.js");
65513
65735
  let content;
65514
65736
  try {
65515
65737
  content = await fs.promises.readFile(path2, "utf-8");
@@ -65588,7 +65810,7 @@ function oidcFederationProvider(config2) {
65588
65810
  }
65589
65811
  function userOAuthProvider(config2) {
65590
65812
  return async (opts) => {
65591
- const { fs } = await import("./node.browser-CP5wfAdg.js");
65813
+ const { fs } = await import("./node.browser-B0AdQysu.js");
65592
65814
  await checkCredentialsFileSafety(config2.credentialsPath, config2.onSafetyWarning);
65593
65815
  let raw;
65594
65816
  try {
@@ -65755,7 +65977,7 @@ function resolveIdentityTokenProvider(auth) {
65755
65977
  }
65756
65978
  function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) {
65757
65979
  return async (opts) => {
65758
- const { fs } = await import("./node.browser-CP5wfAdg.js");
65980
+ const { fs } = await import("./node.browser-B0AdQysu.js");
65759
65981
  await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);
65760
65982
  let existing;
65761
65983
  try {
@@ -67323,16 +67545,181 @@ function clip(posting, chars2) {
67323
67545
  return posting.length > chars2 ? `${posting.slice(0, chars2)}…` : posting;
67324
67546
  }
67325
67547
  const POSTING_INSTRUCTIONS_RULE = "If the posting asks applicants to do something specific in their application (mention a particular word or phrase, answer a question, follow a format), do it, naturally, in the cover letter and in the answers about why the candidate is applying.";
67548
+ class NoContactProfileError extends Error {
67549
+ code = "NO_CONTACT_PROFILE";
67550
+ constructor() {
67551
+ super("Contact profile not configured for this user. Store one first (PUT /contact-profile).");
67552
+ this.name = "NoContactProfileError";
67553
+ }
67554
+ }
67555
+ async function getContactProfile(kv, scope = OWNER_SCOPE) {
67556
+ const json2 = await kv.get(scopeKeys(scope).contact);
67557
+ return json2 ? JSON.parse(json2) : null;
67558
+ }
67559
+ async function paperFor(kv, scope) {
67560
+ if (scope.kind === "owner") return "letter";
67561
+ return paperForLocation((await getContactProfile(kv, scope))?.location);
67562
+ }
67563
+ async function putContactProfile(kv, profile, scope) {
67564
+ if (scope.kind === "owner") throw new Error("refusing to overwrite the owner's contact profile");
67565
+ await kv.put(scopeKeys(scope).contact, JSON.stringify(profile));
67566
+ }
67567
+ const CONTACT_FIELDS = [
67568
+ "name",
67569
+ "email",
67570
+ "phone",
67571
+ "linkedin",
67572
+ "github",
67573
+ "location",
67574
+ "work_auth",
67575
+ "relocation",
67576
+ "salary_line"
67577
+ ];
67578
+ const MAX_CONTACT_FIELD_CHARS = 300;
67579
+ function sanitizeContact(raw) {
67580
+ if (typeof raw !== "object" || raw === null) return null;
67581
+ const r = raw;
67582
+ const out = {};
67583
+ for (const f of CONTACT_FIELDS) {
67584
+ const v = r[f];
67585
+ out[f] = typeof v === "string" ? v.trim().slice(0, MAX_CONTACT_FIELD_CHARS) : "";
67586
+ }
67587
+ return out.name ? out : null;
67588
+ }
67589
+ function renderStandardFields(p) {
67590
+ return [
67591
+ `Name: ${p.name}`,
67592
+ `Email: ${p.email}`,
67593
+ `Phone: ${p.phone}`,
67594
+ `LinkedIn: ${p.linkedin}`,
67595
+ `GitHub: ${p.github}`,
67596
+ `Location: ${p.location}`,
67597
+ `Work authorization: ${p.work_auth}`,
67598
+ `Relocation: ${p.relocation}`
67599
+ ].join("\n");
67600
+ }
67601
+ const GENERIC_MAX_PAGES = 2;
67602
+ const EXPERIENCE_HEADINGS = /* @__PURE__ */ new Set(["experience", "additional experience", "work experience"]);
67603
+ const STANDARD_HEADINGS = /* @__PURE__ */ new Set([
67604
+ "summary",
67605
+ "experience",
67606
+ "additional experience",
67607
+ "work experience",
67608
+ "projects",
67609
+ "skills",
67610
+ "education",
67611
+ "languages",
67612
+ "certifications"
67613
+ ]);
67614
+ const NONE = {
67615
+ mergeSkills: false,
67616
+ roleCaps: null,
67617
+ extraCap: null,
67618
+ certCap: null,
67619
+ dropExtra: false
67620
+ };
67621
+ const LADDER = [
67622
+ NONE,
67623
+ { ...NONE, mergeSkills: true },
67624
+ { ...NONE, mergeSkills: true, roleCaps: [6, 5, 3, 2] },
67625
+ { ...NONE, mergeSkills: true, roleCaps: [6, 4, 3, 2], extraCap: 3 },
67626
+ { ...NONE, mergeSkills: true, roleCaps: [5, 4, 2, 1], extraCap: 3, certCap: 4 },
67627
+ { ...NONE, mergeSkills: true, roleCaps: [5, 3, 2, 1], extraCap: 2, certCap: 3 },
67628
+ { ...NONE, mergeSkills: true, roleCaps: [4, 3, 2, 1], extraCap: 2, certCap: 3 },
67629
+ { ...NONE, mergeSkills: true, roleCaps: [4, 3, 2, 1], certCap: 3, dropExtra: true },
67630
+ { ...NONE, mergeSkills: true, roleCaps: [3, 2, 1], certCap: 2, dropExtra: true },
67631
+ { ...NONE, mergeSkills: true, roleCaps: [2, 1], certCap: 2, dropExtra: true }
67632
+ ];
67633
+ const BULLET = /^[-*] /;
67634
+ const ENTRY_HEADING = /^#{2,3} /;
67635
+ function splitSections(markdown) {
67636
+ const sections = [{ name: "", lines: [] }];
67637
+ for (const line of markdown.split("\n")) {
67638
+ const h = /^# (.+)$/.exec(line);
67639
+ if (h) sections.push({ name: h[1].trim().toLowerCase(), lines: [line] });
67640
+ else sections[sections.length - 1].lines.push(line);
67641
+ }
67642
+ return sections;
67643
+ }
67644
+ function capBullets(lines, cap2) {
67645
+ const bulletIdx = lines.flatMap((l, i) => BULLET.test(l) ? [i] : []);
67646
+ if (bulletIdx.length <= cap2) return lines;
67647
+ let keep = new Set(bulletIdx.slice(0, cap2));
67648
+ const last2 = bulletIdx[cap2 - 1];
67649
+ if (cap2 > 0 && lines[last2].trimEnd().endsWith(":")) keep = new Set(bulletIdx.slice(0, cap2 - 1));
67650
+ return lines.filter((l, i) => !BULLET.test(l) || keep.has(i));
67651
+ }
67652
+ function capRoles(lines, caps, rank) {
67653
+ const out = [];
67654
+ let entry = [];
67655
+ let entryRank = null;
67656
+ const flush = () => {
67657
+ if (entryRank === null) out.push(...entry);
67658
+ else out.push(...capBullets(entry, caps[Math.min(entryRank, caps.length - 1)]));
67659
+ entry = [];
67660
+ };
67661
+ for (const line of lines) {
67662
+ if (ENTRY_HEADING.test(line)) {
67663
+ flush();
67664
+ entryRank = rank.n++;
67665
+ }
67666
+ entry.push(line);
67667
+ }
67668
+ flush();
67669
+ return out;
67670
+ }
67671
+ function mergeSkillBullets(lines) {
67672
+ const items = lines.filter((l) => BULLET.test(l)).map((l) => l.replace(BULLET, "").trim());
67673
+ if (items.length < 2) return lines;
67674
+ const out = [];
67675
+ let placed = false;
67676
+ for (const line of lines) {
67677
+ if (!BULLET.test(line)) out.push(line);
67678
+ else if (!placed) {
67679
+ out.push(items.join(" · "));
67680
+ placed = true;
67681
+ }
67682
+ }
67683
+ return out;
67684
+ }
67685
+ function applyStep(sections, step) {
67686
+ const rank = { n: 0 };
67687
+ const out = [];
67688
+ for (const { name, lines } of sections) {
67689
+ const optional2 = name !== "" && !STANDARD_HEADINGS.has(name);
67690
+ if (optional2 && step.dropExtra) continue;
67691
+ let next = lines;
67692
+ if (EXPERIENCE_HEADINGS.has(name) && step.roleCaps) next = capRoles(next, step.roleCaps, rank);
67693
+ if (name === "skills" && step.mergeSkills) next = mergeSkillBullets(next);
67694
+ if (name === "certifications" && step.certCap !== null) next = capBullets(next, step.certCap);
67695
+ if (optional2 && step.extraCap !== null) next = capBullets(next, step.extraCap);
67696
+ out.push(...next);
67697
+ }
67698
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();
67699
+ }
67700
+ function fitResumeToPages(markdown, maxPages, countPages) {
67701
+ const sections = splitSections(markdown);
67702
+ let candidate = markdown;
67703
+ let pages = countPages(markdown);
67704
+ if (pages <= maxPages) return { markdown, pages, condensed: false };
67705
+ for (const step of LADDER.slice(1)) {
67706
+ candidate = applyStep(sections, step);
67707
+ pages = countPages(candidate);
67708
+ if (pages <= maxPages) break;
67709
+ }
67710
+ return { markdown: candidate, pages, condensed: true };
67711
+ }
67326
67712
  const CACHE_TTL_SECONDS$3 = 2592e3;
67327
67713
  function stripCodeFence(text) {
67328
67714
  const trimmed = text.trim();
67329
67715
  const match2 = /^```[^\n]*\n([\s\S]*)\n```$/.exec(trimmed);
67330
67716
  return match2 ? match2[1].trim() : trimmed;
67331
67717
  }
67332
- async function generateTailoredResume(client, kv, req, deadline = Date.now() + OPERATION_BUDGET_MS) {
67718
+ async function generateTailoredResume(client, kv, req, deadline = Date.now() + OPERATION_BUDGET_MS, scope = OWNER_SCOPE) {
67333
67719
  const { job_title, company, description, profile_type, tailor = true } = req;
67720
+ const isOwner = scope.kind === "owner";
67334
67721
  const key = await cacheKey(
67335
- "resume:tailored",
67722
+ scopeKeys(scope).cache("tailored"),
67336
67723
  // Résumés cached before the whole posting was read were tailored to a
67337
67724
  // 1-2.5k-character slice of its HTML; a new key retires them.
67338
67725
  "full-posting",
@@ -67347,9 +67734,9 @@ async function generateTailoredResume(client, kv, req, deadline = Date.now() + O
67347
67734
  const result2 = JSON.parse(hit);
67348
67735
  return { ...result2, cached: true };
67349
67736
  }
67350
- const blocks = await getAllBlocks(kv);
67737
+ const blocks = await getAllBlocks(kv, scope);
67351
67738
  if (blocks.length === 0) {
67352
- throw new Error("No resume blocks found in KV storage");
67739
+ throw new NoResumeBlocksError(scope);
67353
67740
  }
67354
67741
  const truncate = (s, max) => s.length > max ? `${s.slice(0, max)}…` : s;
67355
67742
  const posting = jobText(description);
@@ -67364,6 +67751,7 @@ ${truncate(b.content, snippetChars)}` : "")
67364
67751
  ).join("\n\n");
67365
67752
  const profileHint = profile_type ? `
67366
67753
  Profile preference: "${profile_type}" — prefer blocks tagged with this, but include cross-tag blocks where genuinely relevant (e.g. a Staff ML role will usually want a leadership block too).` : "";
67754
+ if (!isOwner) return genericSelectionPrompt(job_title, company, jdForSelection, blockSummaries);
67367
67755
  return `You are assembling a tailored resume for a job application. Select the most relevant resume blocks and return their IDs in the order they should appear.${profileHint}
67368
67756
 
67369
67757
  Job: ${job_title} at ${company}
@@ -67385,14 +67773,14 @@ Rules:
67385
67773
  - Never select a rollup block AND its constituent detail blocks together; their bullets would duplicate.
67386
67774
  - Respond with ONLY a valid JSON array of block IDs, nothing else. Example: ["header", "exp_microsoft_se2", "skills_ml"]`;
67387
67775
  };
67388
- const { CHARS_PER_TOKEN, LADDER } = SELECTION_BUDGET;
67776
+ const { CHARS_PER_TOKEN, LADDER: LADDER2 } = SELECTION_BUDGET;
67389
67777
  const estimateTokens = (s) => Math.ceil(s.length / CHARS_PER_TOKEN);
67390
67778
  const selectionFor = (provider) => {
67391
67779
  const limit2 = provider.requestTokenLimit;
67392
67780
  if (limit2 === void 0)
67393
- return buildPrompt(LADDER[0][0], clip(posting, postingCharsFor(provider, 0, 0)));
67781
+ return buildPrompt(LADDER2[0][0], clip(posting, postingCharsFor(provider, 0, 0)));
67394
67782
  let prompt = "";
67395
- for (const [snippetChars, jdChars] of LADDER) {
67783
+ for (const [snippetChars, jdChars] of LADDER2) {
67396
67784
  prompt = buildPrompt(snippetChars, clip(posting, jdChars));
67397
67785
  if (estimateTokens(prompt) + TAILORED_RESUME_TOKENS.SELECTION <= limit2) return prompt;
67398
67786
  }
@@ -67400,18 +67788,23 @@ Rules:
67400
67788
  `selection prompt cannot fit the ${limit2}-token request ceiling even without snippets (${estimateTokens(prompt)} est. tokens; the palette has ${blocks.length} blocks)`
67401
67789
  );
67402
67790
  };
67403
- const selectionResponse = await sendChatCompletion(
67404
- client,
67405
- (provider) => [{ role: "user", content: selectionFor(provider) }],
67406
- { maxTokens: TAILORED_RESUME_TOKENS.SELECTION, temperature: 0.1, deadline }
67407
- );
67791
+ const nothingToSelect = !isOwner && blocks.every((b) => b.tags.includes(ALWAYS_TAG));
67408
67792
  let selectedIds;
67409
- try {
67410
- const parsed = JSON.parse(selectionResponse.message);
67411
- if (!Array.isArray(parsed)) throw new Error("Response was not a JSON array");
67412
- selectedIds = parsed.filter((id2) => typeof id2 === "string");
67413
- } catch {
67414
- throw new Error(`Block selection returned unparseable response: ${selectionResponse.message}`);
67793
+ if (nothingToSelect) {
67794
+ selectedIds = blocks.map((b) => b.id);
67795
+ } else {
67796
+ const selectionResponse = await sendChatCompletion(
67797
+ client,
67798
+ (provider) => [{ role: "user", content: selectionFor(provider) }],
67799
+ { maxTokens: TAILORED_RESUME_TOKENS.SELECTION, temperature: 0.1, deadline }
67800
+ );
67801
+ try {
67802
+ const parsed = JSON.parse(selectionResponse.message);
67803
+ if (!Array.isArray(parsed)) throw new Error("Response was not a JSON array");
67804
+ selectedIds = parsed.filter((id2) => typeof id2 === "string");
67805
+ } catch {
67806
+ throw new Error(`Block selection returned unparseable response: ${selectionResponse.message}`);
67807
+ }
67415
67808
  }
67416
67809
  const validIds = new Set(blocks.map((b) => b.id));
67417
67810
  selectedIds = selectedIds.filter((id2) => validIds.has(id2));
@@ -67440,7 +67833,7 @@ Rules:
67440
67833
  const pickedProjects = blocks.filter(
67441
67834
  (b) => selectedNow.has(b.id) && isProject(b) && !b.tags.includes(ALWAYS_TAG)
67442
67835
  );
67443
- if (pickedProjects.length < PROJECT_FLOOR) {
67836
+ if (isOwner && pickedProjects.length < PROJECT_FLOOR) {
67444
67837
  const topUp = blocks.filter((b) => !selectedNow.has(b.id) && isProject(b) && !b.tags.includes(ALWAYS_TAG)).sort((a, b) => tierOf(a) - tierOf(b) || b.priority - a.priority).slice(0, PROJECT_FLOOR - pickedProjects.length);
67445
67838
  for (const b of topUp) selectedIds.push(b.id);
67446
67839
  }
@@ -67454,7 +67847,7 @@ Rules:
67454
67847
  };
67455
67848
  const page1Len = (ids) => blocks.filter((b) => ids.has(b.id) && onPage1(b)).reduce((n, b) => n + b.content.length, 0);
67456
67849
  let page1Set = new Set(selectedIds);
67457
- if (page1Len(page1Set) > PAGE1_CHAR_BUDGET) {
67850
+ if (isOwner && page1Len(page1Set) > PAGE1_CHAR_BUDGET) {
67458
67851
  const trimmable = blocks.filter((b) => page1Set.has(b.id) && onPage1(b) && !b.tags.includes(ALWAYS_TAG)).sort((a, b) => a.priority - b.priority || b.content.length - a.content.length);
67459
67852
  for (const b of trimmable) {
67460
67853
  if (trimmable.filter((t) => page1Set.has(t.id)).length <= 1) break;
@@ -67469,10 +67862,10 @@ Rules:
67469
67862
  }
67470
67863
  const blockById = new Map(blocks.map((b) => [b.id, b]));
67471
67864
  const selectedBlocks = selectedIds.map((id2) => blockById.get(id2)).filter((b) => b !== void 0);
67472
- let resumeMarkdown = assembleResume(selectedBlocks);
67865
+ let resumeMarkdown = assembleResume(selectedBlocks, layoutFor(scope));
67473
67866
  const expectedBreaks = countPageBreaks(resumeMarkdown);
67474
67867
  if (tailor) {
67475
- const buildTailoringPrompt = (jd) => `You are tailoring a resume for a specific job application. Rewrite the bullet points in the experience and project sections to better emphasize skills and impact relevant to this role. Keep all facts strictly accurate — adjust emphasis and phrasing only, never invent achievements or change dates.
67868
+ const buildTailoringPrompt = (jd) => !isOwner ? genericTailoringPrompt(job_title, company, jd, resumeMarkdown, expectedBreaks) : `You are tailoring a resume for a specific job application. Rewrite the bullet points in the experience and project sections to better emphasize skills and impact relevant to this role. Keep all facts strictly accurate — adjust emphasis and phrasing only, never invent achievements or change dates.
67476
67869
 
67477
67870
  The resume contains \`${PAGE_BREAK_MARKER}\` marker lines that force page breaks. Keep every one of them, verbatim and on its own line, in the same position. Do not add, remove, or move content across them.
67478
67871
 
@@ -67504,12 +67897,20 @@ Return only the full rewritten resume markdown, no preamble or explanation.`;
67504
67897
  );
67505
67898
  const tailored = normalizeTypography(stripCodeFence(tailoredResponse.message));
67506
67899
  if (countPageBreaks(tailored) === expectedBreaks) {
67507
- resumeMarkdown = restoreProjectsAnchor(tailored, projectsAnchorText(selectedBlocks));
67900
+ resumeMarkdown = isOwner ? restoreProjectsAnchor(tailored, projectsAnchorText(selectedBlocks)) : tailored;
67508
67901
  }
67509
67902
  } catch {
67510
67903
  }
67511
67904
  }
67512
67905
  }
67906
+ if (!isOwner) {
67907
+ const countPages = await createPageCounter("compact", await paperFor(kv, scope));
67908
+ resumeMarkdown = fitResumeToPages(
67909
+ resumeMarkdown,
67910
+ GENERIC_MAX_PAGES,
67911
+ (md) => countPages(normalizeTypography(md))
67912
+ ).markdown;
67913
+ }
67513
67914
  const result = {
67514
67915
  resume_markdown: resumeMarkdown,
67515
67916
  blocks_used: selectedIds,
@@ -67518,10 +67919,54 @@ Return only the full rewritten resume markdown, no preamble or explanation.`;
67518
67919
  await kv.put(key, JSON.stringify(result), { expirationTtl: CACHE_TTL_SECONDS$3 });
67519
67920
  return result;
67520
67921
  }
67922
+ function genericSelectionPrompt(jobTitle, company, jd, blockSummaries) {
67923
+ return `You are assembling a tailored resume for a job application. Select the most relevant resume blocks and return their IDs in the order they should appear.
67924
+
67925
+ Job: ${jobTitle} at ${company}
67926
+ Description:
67927
+ ${jd}
67928
+
67929
+ Available blocks:
67930
+ ${blockSummaries}
67931
+
67932
+ Rules:
67933
+ - Always include the header block if present
67934
+ - Always include every experience block: employment history must stay complete, never tailored away
67935
+ - Always include the education, languages and certifications blocks if present
67936
+ - Include the skills blocks that matter for this role
67937
+ - Include a project block or an extra section (for example hackathons or awards) only when it supports this application
67938
+ - Select at most ONE block from each "variant:<group>" tag group (e.g. only one summary)
67939
+ - Respond with ONLY a valid JSON array of block IDs, nothing else. Example: ["header", "summary", "experience-1"]`;
67940
+ }
67941
+ function genericTailoringPrompt(jobTitle, company, jd, resumeMarkdown, pageBreaks) {
67942
+ const breakRule = pageBreaks > 0 ? `
67943
+ The resume contains \`${PAGE_BREAK_MARKER}\` marker lines that force page breaks. Keep every one of them, verbatim and on its own line, in the same position.
67944
+ ` : "";
67945
+ return `You are tailoring a resume for a specific job application. Rewrite the summary and the bullet points in the experience and project sections to better emphasize the skills and impact relevant to this role. Keep all facts strictly accurate: adjust emphasis and phrasing only, never invent achievements, employers, numbers or dates.
67946
+ ${breakRule}
67947
+ Keep the name and contact line, every heading, and every employer, job title, location and date exactly as written. Keep all number formatting exactly as written. Never use em dashes anywhere; use commas, colons, or hyphens instead.
67948
+
67949
+ The resume must fit on two pages. Within each job, order the bullets by relevance to this role, most relevant first, and keep them concise (one or two lines each). Give the most recent jobs the most bullets (at most five or six); condense the oldest jobs to one or two bullets. Keep every job, though: employment history stays complete.
67950
+
67951
+ Job: ${jobTitle} at ${company}
67952
+ Description:
67953
+ ${jd}
67954
+
67955
+ Resume to tailor:
67956
+ ${resumeMarkdown}
67957
+
67958
+ Return only the full rewritten resume markdown, no preamble or explanation.`;
67959
+ }
67521
67960
  const CACHE_TTL_SECONDS$2 = 2592e3;
67522
- async function generateCoverLetter(client, kv, resumeContent, req, deadline = Date.now() + OPERATION_BUDGET_MS) {
67961
+ async function generateCoverLetter(client, kv, resumeContent, req, deadline = Date.now() + OPERATION_BUDGET_MS, scope = OWNER_SCOPE) {
67523
67962
  const { job_title, company, description, tone = "conversational" } = req;
67524
- const key = await cacheKey("resume:coverletter", "full-posting", job_title, company, description);
67963
+ const key = await cacheKey(
67964
+ scopeKeys(scope).cache("coverletter"),
67965
+ "full-posting",
67966
+ job_title,
67967
+ company,
67968
+ description
67969
+ );
67525
67970
  const hit = await kv.get(key);
67526
67971
  if (hit) {
67527
67972
  const result2 = JSON.parse(hit);
@@ -67568,37 +68013,21 @@ Return only the cover letter in markdown, no preamble or explanation.`;
67568
68013
  await kv.put(key, JSON.stringify(result), { expirationTtl: CACHE_TTL_SECONDS$2 });
67569
68014
  return result;
67570
68015
  }
67571
- const CONTACT_KEY = "resume:profile:contact";
67572
- async function getContactProfile(kv) {
67573
- const json2 = await kv.get(CONTACT_KEY);
67574
- return json2 ? JSON.parse(json2) : null;
67575
- }
67576
- function renderStandardFields(p) {
67577
- return [
67578
- `Name: ${p.name}`,
67579
- `Email: ${p.email}`,
67580
- `Phone: ${p.phone}`,
67581
- `LinkedIn: ${p.linkedin}`,
67582
- `GitHub: ${p.github}`,
67583
- `Location: ${p.location}`,
67584
- `Work authorization: ${p.work_auth}`,
67585
- `Relocation: ${p.relocation}`
67586
- ].join("\n");
67587
- }
67588
68016
  const CACHE_TTL_SECONDS$1 = 2592e3;
67589
68017
  const RESUME_CHARS = 4e3;
67590
68018
  function cap(s, n) {
67591
68019
  return s.length > n ? `${s.slice(0, n)}…` : s;
67592
68020
  }
67593
- async function generateApplicationExtras(client, kv, req) {
68021
+ async function generateApplicationExtras(client, kv, req, scope = OWNER_SCOPE) {
67594
68022
  const { job_title, company, description, resume_markdown, job_location, workplace_type } = req;
67595
- const contact = await getContactProfile(kv);
68023
+ const contact = await getContactProfile(kv, scope);
67596
68024
  if (!contact) {
68025
+ if (scope.kind === "user") throw new NoContactProfileError();
67597
68026
  throw new Error("Contact profile not configured (resume:profile:contact missing from KV)");
67598
68027
  }
67599
68028
  const standard_fields = renderStandardFields(contact);
67600
68029
  const key = await cacheKey(
67601
- "resume:extras",
68030
+ scopeKeys(scope).cache("extras"),
67602
68031
  // Kits cached before the whole posting was read were written from its first
67603
68032
  // 3,000 characters; a new key retires them rather than serving them 30 days.
67604
68033
  "full-posting",
@@ -67699,10 +68128,10 @@ ${POSTING_INSTRUCTIONS_RULE}`;
67699
68128
  const MAX_FORM_QUESTIONS = 25;
67700
68129
  const MAX_QUESTION_CHARS = 500;
67701
68130
  const CACHE_TTL_SECONDS = 2592e3;
67702
- async function generateFormAnswers(client, kv, input, deadline = Date.now() + OPERATION_BUDGET_MS) {
68131
+ async function generateFormAnswers(client, kv, input, deadline = Date.now() + OPERATION_BUDGET_MS, scope = OWNER_SCOPE) {
67703
68132
  const { job_title, company, description, resume_markdown, contact, questions } = input;
67704
68133
  const key = await cacheKey(
67705
- "resume:form-answers",
68134
+ scopeKeys(scope).cache("form-answers"),
67706
68135
  job_title,
67707
68136
  company,
67708
68137
  description,
@@ -67781,17 +68210,43 @@ function readQuestions(value) {
67781
68210
  const questions = value.filter((q) => typeof q === "string" && q.trim() !== "").map((q) => q.trim().slice(0, MAX_QUESTION_CHARS)).slice(0, MAX_FORM_QUESTIONS);
67782
68211
  return questions.length ? questions : void 0;
67783
68212
  }
67784
- const VARIANT_PREFIX = "resume:variant:";
68213
+ const SLUG_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
68214
+ class SlugTakenError extends Error {
68215
+ constructor(slug2) {
68216
+ super(`Variant slug '${slug2}' is already taken`);
68217
+ this.name = "SlugTakenError";
68218
+ }
68219
+ }
67785
68220
  function randomSlug() {
67786
68221
  const bytes = new Uint8Array(9);
67787
68222
  crypto.getRandomValues(bytes);
67788
68223
  return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_");
67789
68224
  }
67790
- async function getVariant(kv, slug) {
67791
- const json2 = await kv.get(`${VARIANT_PREFIX}${slug}`);
68225
+ async function getVariant(kv, slug2, scope = OWNER_SCOPE) {
68226
+ const json2 = await kv.get(scopeKeys(scope).variant(slug2));
67792
68227
  return json2 ? JSON.parse(json2) : null;
67793
68228
  }
67794
- async function renderVariant(kv, variant) {
68229
+ async function findVariant(kv, slug2) {
68230
+ if (!slug2 || slug2.includes(":")) return null;
68231
+ const owned = await getVariant(kv, slug2, OWNER_SCOPE);
68232
+ if (owned) return { variant: owned, scope: OWNER_SCOPE };
68233
+ const userId = await kv.get(variantOwnerKey(slug2));
68234
+ if (!userId) return null;
68235
+ if (userId === ERASED_POINTER) return { gone: true };
68236
+ const scope = { kind: "user", userId };
68237
+ const variant = await getVariant(kv, slug2, scope);
68238
+ return variant ? { variant, scope } : { gone: true };
68239
+ }
68240
+ async function renderVariant(kv, variant, scope = OWNER_SCOPE) {
68241
+ if (scope.kind === "user") {
68242
+ if (variant.markdown) return variant.markdown;
68243
+ if (variant.block_ids?.length) {
68244
+ const byId = new Map((await getAllBlocks(kv, scope)).map((b) => [b.id, b]));
68245
+ const chosen = variant.block_ids.map((id2) => byId.get(id2)).filter((b) => b !== void 0);
68246
+ if (chosen.length > 0) return assembleResume(chosen, layoutFor(scope));
68247
+ }
68248
+ return null;
68249
+ }
67795
68250
  if (variant.markdown) {
67796
68251
  const blocks = await getAllBlocks(kv);
67797
68252
  return restoreProjectsAnchor(variant.markdown, projectsAnchorText(blocks));
@@ -67804,17 +68259,35 @@ async function renderVariant(kv, variant) {
67804
68259
  }
67805
68260
  return null;
67806
68261
  }
67807
- async function mintVariant(client, kv, req) {
67808
- const slug = req.slug ?? randomSlug();
68262
+ function nameFromMarkdown(markdown) {
68263
+ const line = markdown?.split("\n").find((l) => /^# \S/.test(l));
68264
+ const name = line?.slice(2).replace(/[*_`]/g, "").trim();
68265
+ return name ? name.slice(0, 120) : null;
68266
+ }
68267
+ async function assertSlugFree(kv, slug2, scope) {
68268
+ const pointer = await kv.get(variantOwnerKey(slug2));
68269
+ if (scope.kind === "owner") {
68270
+ if (pointer) throw new SlugTakenError(slug2);
68271
+ return;
68272
+ }
68273
+ if (!SLUG_PATTERN.test(slug2)) {
68274
+ throw new Error("slug must be 1-64 characters of A-Z, a-z, 0-9, hyphen or underscore");
68275
+ }
68276
+ if (pointer && pointer !== scope.userId) throw new SlugTakenError(slug2);
68277
+ if (await kv.get(scopeKeys(OWNER_SCOPE).variant(slug2))) throw new SlugTakenError(slug2);
68278
+ }
68279
+ async function mintVariant(client, kv, req, scope = OWNER_SCOPE) {
68280
+ const slug2 = req.slug ?? randomSlug();
68281
+ await assertSlugFree(kv, slug2, scope);
67809
68282
  const variant = {
67810
- slug,
68283
+ slug: slug2,
67811
68284
  label: req.label,
67812
68285
  created_at: (/* @__PURE__ */ new Date()).toISOString()
67813
68286
  };
67814
68287
  if (req.markdown) {
67815
68288
  variant.markdown = req.markdown;
67816
68289
  } else if (req.block_ids?.length) {
67817
- const blocks = await getAllBlocks(kv);
68290
+ const blocks = await getAllBlocks(kv, scope);
67818
68291
  const validIds = new Set(blocks.map((b) => b.id));
67819
68292
  const unknown2 = req.block_ids.filter((id2) => !validIds.has(id2));
67820
68293
  if (unknown2.length > 0) {
@@ -67833,7 +68306,8 @@ async function mintVariant(client, kv, req) {
67833
68306
  profile_type: req.profile_type,
67834
68307
  tailor: req.tailor
67835
68308
  },
67836
- deadline
68309
+ deadline,
68310
+ scope
67837
68311
  );
67838
68312
  variant.markdown = tailored.resume_markdown;
67839
68313
  variant.block_ids = tailored.blocks_used;
@@ -67848,7 +68322,8 @@ async function mintVariant(client, kv, req) {
67848
68322
  company: req.company,
67849
68323
  description: req.description
67850
68324
  },
67851
- deadline
68325
+ deadline,
68326
+ scope
67852
68327
  );
67853
68328
  variant.cover_letter_markdown = letter.cover_letter_markdown;
67854
68329
  } catch {
@@ -67862,16 +68337,26 @@ async function mintVariant(client, kv, req) {
67862
68337
  if (req.cover_letter_markdown) variant.cover_letter_markdown = req.cover_letter_markdown;
67863
68338
  if (req.job_title) variant.job_title = req.job_title;
67864
68339
  if (req.company) variant.company = req.company;
68340
+ if (scope.kind === "user") {
68341
+ const contact = await getContactProfile(kv, scope);
68342
+ const name = contact?.name || nameFromMarkdown(variant.markdown);
68343
+ if (name) variant.candidate_name = name;
68344
+ }
67865
68345
  const opts = req.ttl_days && req.ttl_days > 0 ? { expirationTtl: Math.round(req.ttl_days * 86400) } : void 0;
67866
- await kv.put(`${VARIANT_PREFIX}${slug}`, JSON.stringify(variant), opts);
68346
+ if (scope.kind === "user") {
68347
+ await kv.put(variantOwnerKey(slug2), scope.userId, { metadata: { userId: scope.userId } });
68348
+ }
68349
+ await kv.put(scopeKeys(scope).variant(slug2), JSON.stringify(variant), opts);
67867
68350
  return variant;
67868
68351
  }
67869
- async function listVariants(kv) {
68352
+ async function listVariants(kv, scope = OWNER_SCOPE) {
68353
+ const prefix = scopeKeys(scope).variantListPrefix;
67870
68354
  const summaries = [];
67871
68355
  let cursor;
67872
68356
  do {
67873
- const page = await kv.list({ prefix: VARIANT_PREFIX, cursor });
67874
- const variants = await Promise.all(page.keys.map((k) => kv.get(k.name)));
68357
+ const page = await kv.list({ prefix, cursor });
68358
+ const mine = scope.kind === "owner" ? page.keys.filter((k) => !isUserScopedRemainder(k.name.slice(prefix.length))) : page.keys;
68359
+ const variants = await Promise.all(mine.map((k) => kv.get(k.name)));
67875
68360
  for (const json2 of variants) {
67876
68361
  if (!json2) continue;
67877
68362
  const v = JSON.parse(json2);
@@ -67886,15 +68371,14 @@ async function listVariants(kv) {
67886
68371
  } while (cursor);
67887
68372
  return summaries.sort((a, b) => b.created_at.localeCompare(a.created_at));
67888
68373
  }
67889
- async function deleteVariant(kv, slug) {
67890
- const existing = await kv.get(`${VARIANT_PREFIX}${slug}`);
68374
+ async function deleteVariant(kv, slug2, scope = OWNER_SCOPE) {
68375
+ if (slug2.includes(":")) return false;
68376
+ const key = scopeKeys(scope).variant(slug2);
68377
+ const existing = await kv.get(key);
67891
68378
  if (!existing) return false;
67892
- await kv.delete(`${VARIANT_PREFIX}${slug}`);
68379
+ await kv.delete(key);
67893
68380
  return true;
67894
68381
  }
67895
- const BLOCK_PREFIX = "resume:blocks:";
67896
- const INDEX_KEY = "resume:blocks:index";
67897
- const FEEDBACK_KEY = "resume:blocks:feedback";
67898
68382
  const RESERVED_IDS = /* @__PURE__ */ new Set(["index", "feedback"]);
67899
68383
  const BLOCK_TYPES = /* @__PURE__ */ new Set([
67900
68384
  "experience",
@@ -67946,63 +68430,374 @@ function validateBlock(raw) {
67946
68430
  priority: b.priority
67947
68431
  };
67948
68432
  }
67949
- async function getIndex(kv) {
67950
- const json2 = await kv.get(INDEX_KEY);
68433
+ async function getIndex(kv, scope) {
68434
+ const json2 = await kv.get(scopeKeys(scope).blockIndex);
67951
68435
  return json2 ? JSON.parse(json2) : [];
67952
68436
  }
67953
- async function bustDerivedCaches(kv) {
67954
- for (const prefix of ["resume:tailored:", "resume:coverletter:", "resume:extras:"]) {
68437
+ async function bustDerivedCaches(kv, scope) {
68438
+ for (const prefix of derivedCachePrefixes(scope)) {
67955
68439
  let cursor;
67956
68440
  do {
67957
68441
  const page = await kv.list({ prefix, cursor });
67958
- await Promise.all(page.keys.map((k) => kv.delete(k.name)));
68442
+ const mine = scope.kind === "owner" ? page.keys.filter((k) => !isUserScopedRemainder(k.name.slice(prefix.length))) : page.keys;
68443
+ await Promise.all(mine.map((k) => kv.delete(k.name)));
67959
68444
  cursor = page.list_complete ? void 0 : page.cursor;
67960
68445
  } while (cursor);
67961
68446
  }
67962
68447
  }
67963
- async function upsertBlock(kv, block) {
67964
- await kv.put(`${BLOCK_PREFIX}${block.id}`, JSON.stringify(block));
67965
- const index2 = await getIndex(kv);
68448
+ async function upsertBlock(kv, block, scope = OWNER_SCOPE) {
68449
+ const keys = scopeKeys(scope);
68450
+ await kv.put(keys.block(block.id), JSON.stringify(block));
68451
+ const index2 = await getIndex(kv, scope);
67966
68452
  if (!index2.includes(block.id)) {
67967
68453
  index2.push(block.id);
67968
- await kv.put(INDEX_KEY, JSON.stringify(index2));
67969
- }
67970
- await bustDerivedCaches(kv);
67971
- }
67972
- async function deleteBlock(kv, id2) {
67973
- const index2 = await getIndex(kv);
68454
+ await kv.put(keys.blockIndex, JSON.stringify(index2));
68455
+ }
68456
+ await bustDerivedCaches(kv, scope);
68457
+ }
68458
+ async function replaceBlocks(kv, blocks, scope) {
68459
+ if (scope.kind === "owner") throw new Error("refusing to replace the owner's block set");
68460
+ const keys = scopeKeys(scope);
68461
+ const next = new Set(blocks.map((b) => b.id));
68462
+ const previous = await getIndex(kv, scope);
68463
+ await Promise.all(previous.filter((id2) => !next.has(id2)).map((id2) => kv.delete(keys.block(id2))));
68464
+ await Promise.all(blocks.map((b) => kv.put(keys.block(b.id), JSON.stringify(b))));
68465
+ await kv.put(keys.blockIndex, JSON.stringify(blocks.map((b) => b.id)));
68466
+ await bustDerivedCaches(kv, scope);
68467
+ }
68468
+ async function deleteBlock(kv, id2, scope = OWNER_SCOPE) {
68469
+ const keys = scopeKeys(scope);
68470
+ const index2 = await getIndex(kv, scope);
67974
68471
  if (!index2.includes(id2)) return false;
67975
- await kv.delete(`${BLOCK_PREFIX}${id2}`);
67976
- await kv.put(INDEX_KEY, JSON.stringify(index2.filter((x) => x !== id2)));
67977
- await bustDerivedCaches(kv);
68472
+ await kv.delete(keys.block(id2));
68473
+ await kv.put(keys.blockIndex, JSON.stringify(index2.filter((x) => x !== id2)));
68474
+ await bustDerivedCaches(kv, scope);
67978
68475
  return true;
67979
68476
  }
67980
- async function reorderBlocks(kv, ids) {
67981
- const current = await getIndex(kv);
68477
+ async function reorderBlocks(kv, ids, scope = OWNER_SCOPE) {
68478
+ const current = await getIndex(kv, scope);
67982
68479
  const currentSet = new Set(current);
67983
68480
  const nextSet = new Set(ids);
67984
68481
  if (ids.length !== current.length || [...currentSet].some((id2) => !nextSet.has(id2))) {
67985
68482
  throw new Error("reorder must be a permutation of the existing block ids");
67986
68483
  }
67987
- await kv.put(INDEX_KEY, JSON.stringify(ids));
67988
- await bustDerivedCaches(kv);
68484
+ await kv.put(scopeKeys(scope).blockIndex, JSON.stringify(ids));
68485
+ await bustDerivedCaches(kv, scope);
67989
68486
  }
67990
- async function getFeedback(kv) {
67991
- const json2 = await kv.get(FEEDBACK_KEY);
68487
+ async function getFeedback(kv, scope = OWNER_SCOPE) {
68488
+ const json2 = await kv.get(scopeKeys(scope).feedback);
67992
68489
  return json2 ? JSON.parse(json2) : {};
67993
68490
  }
67994
- async function setFeedback(kv, id2, text) {
67995
- const feedback = await getFeedback(kv);
68491
+ async function setFeedback(kv, id2, text, scope = OWNER_SCOPE) {
68492
+ const feedback = await getFeedback(kv, scope);
67996
68493
  if (text.trim()) {
67997
68494
  feedback[id2] = { text, updated: (/* @__PURE__ */ new Date()).toISOString() };
67998
68495
  } else {
67999
68496
  delete feedback[id2];
68000
68497
  }
68001
- await kv.put(FEEDBACK_KEY, JSON.stringify(feedback));
68498
+ await kv.put(scopeKeys(scope).feedback, JSON.stringify(feedback));
68002
68499
  return feedback;
68003
68500
  }
68004
- async function exportBlocks(kv) {
68005
- return getAllBlocks(kv);
68501
+ async function exportBlocks(kv, scope = OWNER_SCOPE) {
68502
+ return getAllBlocks(kv, scope);
68503
+ }
68504
+ const CACHE_KINDS = [
68505
+ "tailored",
68506
+ "coverletter",
68507
+ "extras",
68508
+ "form-answers"
68509
+ ];
68510
+ async function deletePrefix(kv, prefix) {
68511
+ const names = [];
68512
+ let cursor;
68513
+ do {
68514
+ const page = await kv.list({ prefix, cursor });
68515
+ names.push(...page.keys.map((k) => k.name));
68516
+ cursor = page.list_complete ? void 0 : page.cursor;
68517
+ } while (cursor);
68518
+ await Promise.all(names.map((n) => kv.delete(n)));
68519
+ return names.length;
68520
+ }
68521
+ async function tombstonePointers(kv, userId) {
68522
+ let erased = 0;
68523
+ let cursor;
68524
+ do {
68525
+ const page = await kv.list({ prefix: VARIANT_OWNER_PREFIX, cursor });
68526
+ const mine = await Promise.all(
68527
+ page.keys.map(
68528
+ async (k) => (
68529
+ // Every pointer carries its userId as metadata (variants.ts); one
68530
+ // without it is read, so nothing written some other way is missed.
68531
+ (k.metadata?.userId ?? await kv.get(k.name)) === userId ? k.name : null
68532
+ )
68533
+ )
68534
+ );
68535
+ const names = mine.filter((n) => n !== null);
68536
+ await Promise.all(names.map((n) => kv.put(n, ERASED_POINTER)));
68537
+ erased += names.length;
68538
+ cursor = page.list_complete ? void 0 : page.cursor;
68539
+ } while (cursor);
68540
+ return erased;
68541
+ }
68542
+ async function eraseUserData(kv, userId) {
68543
+ const keys = scopeKeys({ kind: "user", userId });
68544
+ const blocks = await deletePrefix(kv, `resume:blocks:${userId}:`);
68545
+ let contact_profile = 0;
68546
+ if (await kv.get(keys.contact)) {
68547
+ await kv.delete(keys.contact);
68548
+ contact_profile = 1;
68549
+ }
68550
+ const variants = await deletePrefix(kv, keys.variantListPrefix);
68551
+ let cached_outputs = 0;
68552
+ for (const kind of CACHE_KINDS) cached_outputs += await deletePrefix(kv, `${keys.cache(kind)}:`);
68553
+ const links_retired = await tombstonePointers(kv, userId);
68554
+ return { blocks, contact_profile, variants, cached_outputs, links_retired };
68555
+ }
68556
+ const MAX_RESUME_CHARS = 6e4;
68557
+ const MAX_BLOCKS = 60;
68558
+ const MAX_BLOCK_CHARS = 12e3;
68559
+ function classifyHeading(heading) {
68560
+ const h = heading.toLowerCase();
68561
+ if (/\blanguages?\b/.test(h) && !/programming/.test(h)) return "languages";
68562
+ if (/certif|licen[cs]e|courses|training/.test(h) && !/education/.test(h)) return "certifications";
68563
+ if (/summary|profile|about me|^about$|objective|overview/.test(h)) return "summary";
68564
+ if (/volunteer/.test(h)) return "extra";
68565
+ if (/experience|employment|work history|career history|positions held/.test(h)) {
68566
+ return "experience";
68567
+ }
68568
+ if (/project/.test(h)) return "projects";
68569
+ if (/skill|competenc|expertise|tools|technolog|software|tech stack|programming/.test(h)) {
68570
+ return "skills";
68571
+ }
68572
+ if (/education|academic|degree|qualification|studies/.test(h)) return "education";
68573
+ return "extra";
68574
+ }
68575
+ const KNOWN_HEADING = /^(professional |career |executive |personal )?(summary|profile|about me|objective|overview|(work |professional |relevant )?experience|employment( history)?|work history|career history|(key |selected |personal )?projects|(key |core |technical )?skills|(core )?competencies|expertise|tools|software|education|academic background|languages?|certifications?|licen[cs]es|courses|training|awards|honou?rs|publications|volunteering|volunteer experience|hackathons|interests|achievements)$/i;
68576
+ const MD_HEADING = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
68577
+ function cleanHeadingText(text) {
68578
+ return text.replace(/^\*\*(.*)\*\*$/, "$1").replace(/:$/, "").trim();
68579
+ }
68580
+ function displayHeading(text) {
68581
+ if (text !== text.toUpperCase() || !/[A-Z]/.test(text)) return text;
68582
+ return text.toLowerCase().replace(/(^|[\s/&(-])([a-z])/g, (_m, p, c) => {
68583
+ return p + c.toUpperCase();
68584
+ });
68585
+ }
68586
+ function plainHeading(line) {
68587
+ const t = cleanHeadingText(line.trim());
68588
+ if (!t || t.length > 50) return null;
68589
+ return KNOWN_HEADING.test(t) ? t : null;
68590
+ }
68591
+ function looksLikeName(line) {
68592
+ const t = line.trim();
68593
+ return t.length > 0 && t.length <= 60 && !/[@\d]|https?:|www\.|linkedin/i.test(t) && plainHeading(t) === null;
68594
+ }
68595
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/;
68596
+ const PHONE = /\+?\d[\d\s().-]{6,}\d/;
68597
+ const LINKEDIN = /(?:https?:\/\/)?(?:[a-z]{2,3}\.)?linkedin\.com\/[^\s|,;)]+/i;
68598
+ const GITHUB = /(?:https?:\/\/)?github\.com\/[^\s|,;)]+/i;
68599
+ function parseContact(name, preamble) {
68600
+ const text = preamble.join("\n");
68601
+ const contact = {
68602
+ name,
68603
+ email: EMAIL.exec(text)?.[0] ?? "",
68604
+ phone: PHONE.exec(text.replace(EMAIL, " "))?.[0].trim() ?? "",
68605
+ linkedin: LINKEDIN.exec(text)?.[0] ?? "",
68606
+ github: GITHUB.exec(text)?.[0] ?? "",
68607
+ location: "",
68608
+ work_auth: "",
68609
+ relocation: "",
68610
+ salary_line: ""
68611
+ };
68612
+ for (const line of preamble) {
68613
+ for (const raw of line.split(/\s+[-|•·–]\s+|\s{2,}|\s*\|\s*/)) {
68614
+ const part = raw.replace(/[*_]/g, "").trim();
68615
+ if (!part || EMAIL.test(part) || LINKEDIN.test(part) || GITHUB.test(part)) continue;
68616
+ if (/https?:|www\./i.test(part)) continue;
68617
+ if (PHONE.test(part) && part.replace(/\D/g, "").length >= 7) continue;
68618
+ if (/[A-Za-z]/.test(part) && part.length <= 60) {
68619
+ contact.location = part;
68620
+ return contact;
68621
+ }
68622
+ }
68623
+ }
68624
+ return contact;
68625
+ }
68626
+ const NESTED_BULLET = /^\s+[-*•]\s+/;
68627
+ function normalizeBody(lines) {
68628
+ const out = [];
68629
+ let leadIn = -1;
68630
+ for (const raw of lines.map((l) => l.replace(/\s+$/, ""))) {
68631
+ if (NESTED_BULLET.test(raw) && leadIn >= 0) {
68632
+ const item = raw.replace(NESTED_BULLET, "");
68633
+ out[leadIn] += out[leadIn].endsWith(":") ? ` ${item}` : `; ${item}`;
68634
+ continue;
68635
+ }
68636
+ const line = raw.replace(NESTED_BULLET, "- ").replace(/^[•]\s+/, "- ");
68637
+ leadIn = /^[-*] .*:$/.test(line) && !NESTED_BULLET.test(raw) ? out.length : -1;
68638
+ out.push(line);
68639
+ }
68640
+ return out.join("\n").replace(/\n{3,}/g, "\n\n").trim();
68641
+ }
68642
+ const DATE_RANGE = /((19|20)\d{2}|\d{1,2}\/(19|20)\d{2}).{0,20}(present|current|now|today|heute|(19|20)\d{2})/i;
68643
+ function splitEntries(lines, entryLevel) {
68644
+ const entries = [];
68645
+ let current = { heading: null, body: [] };
68646
+ const push = () => {
68647
+ if (current.heading !== null || current.body.some((l) => l.trim())) entries.push(current);
68648
+ };
68649
+ lines.forEach((line, i) => {
68650
+ const md = MD_HEADING.exec(line);
68651
+ const isMdEntry = md && entryLevel !== null && md[1].length === entryLevel;
68652
+ const prevBlank = i === 0 || lines[i - 1].trim() === "";
68653
+ const isPlainEntry = entryLevel === null && !md && prevBlank && !/^\s*[-*•]/.test(line) && DATE_RANGE.test(line);
68654
+ if (isMdEntry || isPlainEntry) {
68655
+ push();
68656
+ current = { heading: isMdEntry && md ? md[2].trim() : line.trim(), body: [] };
68657
+ } else {
68658
+ current.body.push(line);
68659
+ }
68660
+ });
68661
+ push();
68662
+ return entries;
68663
+ }
68664
+ function slug(text) {
68665
+ return text.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "section";
68666
+ }
68667
+ const STRUCTURAL = ["always", "canonical"];
68668
+ function parseResumeText(input) {
68669
+ const text = input.replace(/\r\n?/g, "\n").replace(/\t/g, " ");
68670
+ if (!text.trim()) throw new Error("resume text is empty");
68671
+ if (text.length > MAX_RESUME_CHARS) {
68672
+ throw new Error(`resume text is longer than ${MAX_RESUME_CHARS} characters`);
68673
+ }
68674
+ const lines = text.split("\n");
68675
+ let headings = [];
68676
+ lines.forEach((line, i) => {
68677
+ const m = MD_HEADING.exec(line);
68678
+ if (m) headings.push({ line: i, level: m[1].length, text: cleanHeadingText(m[2]) });
68679
+ });
68680
+ const markdown = headings.length > 0;
68681
+ if (!markdown) {
68682
+ lines.forEach((line, i) => {
68683
+ const t = plainHeading(line);
68684
+ if (t) headings.push({ line: i, level: 2, text: t });
68685
+ });
68686
+ }
68687
+ const firstContent = lines.findIndex((l) => l.trim() !== "");
68688
+ let name = "";
68689
+ let nameLine = -1;
68690
+ const top = headings[0];
68691
+ if (markdown && top && top.line === firstContent && classifyHeading(top.text) === "extra") {
68692
+ name = top.text;
68693
+ nameLine = top.line;
68694
+ headings = headings.slice(1);
68695
+ } else if (!markdown && firstContent >= 0 && looksLikeName(lines[firstContent])) {
68696
+ name = lines[firstContent].trim();
68697
+ nameLine = firstContent;
68698
+ }
68699
+ name = displayHeading(name.replace(/[*_]/g, ""));
68700
+ const sectionLevel = headings.length ? Math.min(...headings.map((h) => h.level)) : 2;
68701
+ const sections = headings.filter((h) => h.level === sectionLevel);
68702
+ let headerEnd = sections.length ? sections[0].line : lines.length;
68703
+ if (!sections.length) {
68704
+ let i = nameLine + 1;
68705
+ while (i < lines.length && lines[i].trim() === "") i++;
68706
+ while (i < lines.length && lines[i].trim() !== "" && i - nameLine <= 3) i++;
68707
+ headerEnd = i;
68708
+ }
68709
+ const preamble = lines.slice(nameLine + 1, headerEnd).filter((l) => l.trim() !== "");
68710
+ const contact = parseContact(name, preamble);
68711
+ const blocks = [];
68712
+ const used = /* @__PURE__ */ new Set();
68713
+ const uniqueId = (base) => {
68714
+ let id2 = base;
68715
+ for (let n = 2; used.has(id2); n++) id2 = `${base}-${n}`;
68716
+ used.add(id2);
68717
+ return id2;
68718
+ };
68719
+ const add = (base, type, section, title, content, always) => {
68720
+ if (!content.trim()) return;
68721
+ const tags = always ? [...STRUCTURAL, `section:${section}`] : ["canonical", `section:${section}`];
68722
+ blocks.push(
68723
+ validateBlock({
68724
+ id: uniqueId(base),
68725
+ type,
68726
+ tags,
68727
+ title: title.slice(0, 200),
68728
+ content: content.slice(0, MAX_BLOCK_CHARS),
68729
+ // Higher renders first within a section, so input order is kept.
68730
+ priority: 1e3 - blocks.length
68731
+ })
68732
+ );
68733
+ };
68734
+ if (name || preamble.length) {
68735
+ const header = [name ? `# ${name}` : "", preamble.join(" \n")].filter(Boolean).join("\n\n");
68736
+ add("header", "header", "header", "Header", header, true);
68737
+ }
68738
+ let languagesSeen = sections.some((s) => classifyHeading(s.text) === "languages");
68739
+ sections.forEach((section, idx) => {
68740
+ const end = idx + 1 < sections.length ? sections[idx + 1].line : lines.length;
68741
+ const bodyLines = lines.slice(section.line + 1, end);
68742
+ const kind = classifyHeading(section.text);
68743
+ const heading = displayHeading(section.text);
68744
+ if (kind === "experience" || kind === "projects") {
68745
+ const entries = splitEntries(bodyLines, markdown ? sectionLevel + 1 : null);
68746
+ const isExp = kind === "experience";
68747
+ for (const entry of entries) {
68748
+ const body2 = normalizeBody(entry.body);
68749
+ const content = entry.heading ? `### ${entry.heading}
68750
+ ${body2}`.trim() : body2;
68751
+ add(
68752
+ isExp ? "experience" : "project",
68753
+ isExp ? "experience" : "project",
68754
+ isExp ? "experience-primary" : "projects",
68755
+ entry.heading ?? heading,
68756
+ content,
68757
+ isExp
68758
+ );
68759
+ }
68760
+ return;
68761
+ }
68762
+ let body = normalizeBody(bodyLines);
68763
+ if (kind === "skills" && !languagesSeen) {
68764
+ const m = /^(?:\*\*)?languages?(?:\*\*)?\s*:\s*(?:\*\*)?\s*(.+)$/im.exec(body);
68765
+ if (m) {
68766
+ body = body.replace(m[0], "").replace(/\n{3,}/g, "\n\n").trim();
68767
+ add("languages", "skills", "languages", "Languages", m[1].trim(), true);
68768
+ languagesSeen = true;
68769
+ }
68770
+ }
68771
+ switch (kind) {
68772
+ case "summary":
68773
+ add("summary", "summary", "summary", heading, body, true);
68774
+ break;
68775
+ case "skills":
68776
+ add("skills", "skills", "skills", heading, body, true);
68777
+ break;
68778
+ case "education":
68779
+ add("education", "education", "education", heading, body, true);
68780
+ break;
68781
+ case "languages":
68782
+ add("languages", "skills", "languages", heading, body, true);
68783
+ break;
68784
+ case "certifications":
68785
+ add("certifications", "education", "certifications", heading, body, true);
68786
+ break;
68787
+ default:
68788
+ add(`extra-${slug(heading)}`, "project", "extra", heading, `# ${heading}
68789
+
68790
+ ${body}`, false);
68791
+ }
68792
+ });
68793
+ if (sections.length === 0) {
68794
+ const rest = normalizeBody(lines.slice(headerEnd));
68795
+ add("experience", "experience", "experience-primary", "Experience", rest, true);
68796
+ }
68797
+ if (blocks.length === 0) throw new Error("no résumé content found");
68798
+ if (blocks.length > MAX_BLOCKS)
68799
+ throw new Error(`résumé splits into more than ${MAX_BLOCKS} blocks`);
68800
+ return { blocks, contact };
68006
68801
  }
68007
68802
  function deferTo(c) {
68008
68803
  return (work) => {
@@ -68012,12 +68807,30 @@ function deferTo(c) {
68012
68807
  }
68013
68808
  };
68014
68809
  }
68810
+ function filenameStem(name) {
68811
+ const slug2 = (name ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
68812
+ return slug2 ? `${slug2}-resume` : "resume";
68813
+ }
68814
+ function missingContent(err) {
68815
+ if (err instanceof NoResumeBlocksError || err instanceof NoContactProfileError) {
68816
+ return { error: err.message, code: err.code };
68817
+ }
68818
+ return null;
68819
+ }
68820
+ const VARIANT_GONE = {
68821
+ error: "This application packet has expired or was removed.",
68822
+ code: "VARIANT_GONE"
68823
+ };
68824
+ function onBehalfOf(body) {
68825
+ return typeof body === "object" && body !== null ? body.on_behalf_of_user_id : void 0;
68826
+ }
68015
68827
  function createResumeHandler(basePath, options = {}) {
68016
68828
  const { ownerName = "the candidate" } = options;
68017
- const ownerSlug = (options.ownerName ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
68018
- const filenameBase = ownerSlug ? `${ownerSlug}-resume` : "resume";
68829
+ const makeClient = options.createClient ?? createLLMClient;
68830
+ const filenameBase = filenameStem(options.ownerName);
68019
68831
  const app = new Hono();
68020
68832
  const logger2 = createWorkerLogger({ service: "resume-api" });
68833
+ const scopeOf = (c, onBehalf) => resolveScope(c.get("authContext"), c.env, onBehalf);
68021
68834
  app.use("*", createEdgeAuth());
68022
68835
  app.get(`${basePath}/`, (c) => c.json({ status: "ok", service: "resume-api" }));
68023
68836
  app.get(`${basePath}/health`, (c) => c.json({ status: "ok", service: "resume-api" }));
@@ -68028,6 +68841,9 @@ function createResumeHandler(basePath, options = {}) {
68028
68841
  app.use(`${basePath}/application-extras`, friendAndUp);
68029
68842
  app.use(`${basePath}/variants`, friendAndUp);
68030
68843
  app.use(`${basePath}/variants/*`, friendAndUp);
68844
+ app.use(`${basePath}/blocks`, friendAndUp);
68845
+ app.use(`${basePath}/blocks/*`, friendAndUp);
68846
+ app.use(`${basePath}/contact-profile`, friendAndUp);
68031
68847
  const adminOnly = requireMinTier("admin");
68032
68848
  app.use(`${basePath}/builder/*`, adminOnly);
68033
68849
  app.get(`${basePath}/builder/blocks`, async (c) => {
@@ -68092,6 +68908,119 @@ function createResumeHandler(basePath, options = {}) {
68092
68908
  const feedback = await setFeedback(c.env.CONTENT_KV, c.req.param("id"), text);
68093
68909
  return c.json({ feedback });
68094
68910
  });
68911
+ const ownerSetRefusal = {
68912
+ error: "The owner's blocks are edited through /builder, not /blocks.",
68913
+ code: "OWNER_SET"
68914
+ };
68915
+ app.get(`${basePath}/blocks`, async (c) => {
68916
+ const r = scopeOf(c);
68917
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68918
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
68919
+ const [blocks, contact] = await Promise.all([
68920
+ getAllBlocks(c.env.CONTENT_KV, r.scope),
68921
+ getContactProfile(c.env.CONTENT_KV, r.scope)
68922
+ ]);
68923
+ return c.json({ blocks, contact });
68924
+ });
68925
+ app.put(`${basePath}/blocks/:id`, async (c) => {
68926
+ const r = scopeOf(c);
68927
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68928
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
68929
+ let body;
68930
+ try {
68931
+ body = await c.req.json();
68932
+ } catch {
68933
+ return c.json({ error: "Invalid JSON body" }, 400);
68934
+ }
68935
+ let block;
68936
+ try {
68937
+ block = validateBlock({ ...body, id: c.req.param("id") });
68938
+ } catch (err) {
68939
+ return c.json({ error: "Invalid block", message: err.message }, 400);
68940
+ }
68941
+ await upsertBlock(c.env.CONTENT_KV, block, r.scope);
68942
+ return c.json({ block });
68943
+ });
68944
+ app.delete(`${basePath}/blocks/:id`, async (c) => {
68945
+ const r = scopeOf(c);
68946
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68947
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
68948
+ const deleted = await deleteBlock(c.env.CONTENT_KV, c.req.param("id"), r.scope);
68949
+ if (!deleted) return c.json({ error: "Block not found" }, 404);
68950
+ return c.json({ deleted: true, id: c.req.param("id") });
68951
+ });
68952
+ app.post(`${basePath}/blocks/import`, async (c) => {
68953
+ let body;
68954
+ try {
68955
+ body = await c.req.json();
68956
+ } catch {
68957
+ return c.json({ error: "Invalid JSON body" }, 400);
68958
+ }
68959
+ const r = scopeOf(c, onBehalfOf(body));
68960
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68961
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
68962
+ if (typeof body.resume_text !== "string" || !body.resume_text.trim()) {
68963
+ return c.json({ error: "resume_text is required" }, 400);
68964
+ }
68965
+ const existing = await getAllBlocks(c.env.CONTENT_KV, r.scope);
68966
+ if (existing.length > 0 && body.replace !== true) {
68967
+ return c.json(
68968
+ { error: "This user already has blocks; send replace: true to overwrite them" },
68969
+ 409
68970
+ );
68971
+ }
68972
+ let parsed;
68973
+ try {
68974
+ parsed = parseResumeText(body.resume_text);
68975
+ } catch (err) {
68976
+ return c.json({ error: "Could not import resume", message: err.message }, 400);
68977
+ }
68978
+ const supplied = Object.entries(asObject(body.contact)).filter(
68979
+ ([, v]) => typeof v === "string" && v.trim() !== ""
68980
+ );
68981
+ const merged = sanitizeContact({ ...parsed.contact, ...Object.fromEntries(supplied) });
68982
+ await replaceBlocks(c.env.CONTENT_KV, parsed.blocks, r.scope);
68983
+ if (merged) await putContactProfile(c.env.CONTENT_KV, merged, r.scope);
68984
+ return c.json({ blocks: parsed.blocks, contact: merged });
68985
+ });
68986
+ app.get(`${basePath}/contact-profile`, async (c) => {
68987
+ const r = scopeOf(c);
68988
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68989
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
68990
+ return c.json({ contact: await getContactProfile(c.env.CONTENT_KV, r.scope) });
68991
+ });
68992
+ app.put(`${basePath}/contact-profile`, async (c) => {
68993
+ let body;
68994
+ try {
68995
+ body = await c.req.json();
68996
+ } catch {
68997
+ return c.json({ error: "Invalid JSON body" }, 400);
68998
+ }
68999
+ const r = scopeOf(c, onBehalfOf(body));
69000
+ if ("error" in r) return c.json({ error: r.error }, r.status);
69001
+ if (r.scope.kind === "owner") return c.json(ownerSetRefusal, 403);
69002
+ const contact = sanitizeContact(body.contact);
69003
+ if (!contact) return c.json({ error: "contact.name is required" }, 400);
69004
+ await putContactProfile(c.env.CONTENT_KV, contact, r.scope);
69005
+ await bustDerivedCaches(c.env.CONTENT_KV, r.scope);
69006
+ return c.json({ contact });
69007
+ });
69008
+ app.post(`${basePath}/_account/erase`, async (c) => {
69009
+ const auth = c.get("authContext");
69010
+ if (!tierAtLeast(auth, "member")) return c.json({ error: "Edge seal required" }, 401);
69011
+ const userId = auth?.userId?.trim();
69012
+ if (!userId) return c.json({ error: "No X-User-Id to erase" }, 401);
69013
+ if (!isUserId(userId)) return c.json({ error: "Malformed user id" }, 400);
69014
+ try {
69015
+ return c.json({ erased: await eraseUserData(c.env.CONTENT_KV, userId) });
69016
+ } catch (error2) {
69017
+ logger2.error("account erase failed", { error: error2.message });
69018
+ return c.json(
69019
+ { error: "Failed to erase account data", message: error2.message },
69020
+ 500
69021
+ );
69022
+ }
69023
+ });
68095
69024
  app.post(`${basePath}/chat`, async (c) => {
68096
69025
  const ip = c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "unknown";
68097
69026
  const rateLimitResult = await checkRateLimit(c.env.RATE_LIMIT_KV, ip);
@@ -68129,7 +69058,7 @@ function createResumeHandler(basePath, options = {}) {
68129
69058
  const systemPrompt = await getFullSystemPrompt(c.env, ownerName);
68130
69059
  messages2.unshift({ role: "system", content: systemPrompt });
68131
69060
  }
68132
- const client = createLLMClient(c.env, deferTo(c));
69061
+ const client = makeClient(c.env, deferTo(c));
68133
69062
  const response = await sendChatCompletion(client, messages2);
68134
69063
  return c.json(response);
68135
69064
  } catch (error2) {
@@ -68145,11 +69074,14 @@ function createResumeHandler(basePath, options = {}) {
68145
69074
  });
68146
69075
  app.get(`${basePath}/resume`, async (c) => {
68147
69076
  try {
68148
- const slug = c.req.query("v");
68149
- if (slug) {
68150
- const variant = await getVariant(c.env.CONTENT_KV, slug);
68151
- if (variant) {
68152
- const content2 = await renderVariant(c.env.CONTENT_KV, variant);
69077
+ const slug2 = c.req.query("v");
69078
+ if (slug2) {
69079
+ const found = await findVariant(c.env.CONTENT_KV, slug2);
69080
+ if (found && "gone" in found) return c.json(VARIANT_GONE, 404);
69081
+ if (found) {
69082
+ const { variant, scope } = found;
69083
+ const content2 = await renderVariant(c.env.CONTENT_KV, variant, scope);
69084
+ if (!content2 && scope.kind === "user") return c.json(VARIANT_GONE, 404);
68153
69085
  if (content2)
68154
69086
  return c.json({
68155
69087
  content: normalizeTypography(content2),
@@ -68157,7 +69089,10 @@ function createResumeHandler(basePath, options = {}) {
68157
69089
  label: variant.label,
68158
69090
  cover_letter: variant.cover_letter_markdown ? normalizeTypography(variant.cover_letter_markdown) : null,
68159
69091
  company: variant.company ?? null,
68160
- job_title: variant.job_title ?? null
69092
+ job_title: variant.job_title ?? null,
69093
+ // Whose packet this is, so a viewer can name its downloads. Only
69094
+ // on a user's packet; the owner's response is unchanged.
69095
+ ...scope.kind === "user" ? { candidate_name: candidateName(variant.candidate_name, content2) } : {}
68161
69096
  });
68162
69097
  }
68163
69098
  }
@@ -68170,17 +69105,26 @@ function createResumeHandler(basePath, options = {}) {
68170
69105
  });
68171
69106
  app.get(`${basePath}/resume.pdf`, async (c) => {
68172
69107
  try {
68173
- const slug = c.req.query("v");
69108
+ const slug2 = c.req.query("v");
68174
69109
  let content = null;
68175
69110
  let coverLetter = null;
68176
- const filename = `${filenameBase}.pdf`;
68177
- if (slug) {
68178
- const variant = await getVariant(c.env.CONTENT_KV, slug);
68179
- if (variant) {
68180
- const rendered = await renderVariant(c.env.CONTENT_KV, variant);
69111
+ let filename = `${filenameBase}.pdf`;
69112
+ let documentName = ownerName;
69113
+ let userPaper = null;
69114
+ if (slug2) {
69115
+ const found = await findVariant(c.env.CONTENT_KV, slug2);
69116
+ if (found && "gone" in found) return c.json(VARIANT_GONE, 404);
69117
+ if (found) {
69118
+ const rendered = await renderVariant(c.env.CONTENT_KV, found.variant, found.scope);
69119
+ if (!rendered && found.scope.kind === "user") return c.json(VARIANT_GONE, 404);
68181
69120
  if (rendered) {
68182
69121
  content = rendered;
68183
- coverLetter = variant.cover_letter_markdown ?? null;
69122
+ coverLetter = found.variant.cover_letter_markdown ?? null;
69123
+ if (found.scope.kind === "user") {
69124
+ documentName = candidateName(found.variant.candidate_name, rendered);
69125
+ filename = `${filenameStem(documentName)}.pdf`;
69126
+ userPaper = await paperFor(c.env.CONTENT_KV, found.scope);
69127
+ }
68184
69128
  }
68185
69129
  }
68186
69130
  }
@@ -68188,7 +69132,10 @@ function createResumeHandler(basePath, options = {}) {
68188
69132
  const bytes = await renderResumePdf({
68189
69133
  resume: normalizeTypography(content),
68190
69134
  coverLetter: coverLetter ? normalizeTypography(coverLetter) : null,
68191
- ownerName
69135
+ ownerName: documentName,
69136
+ // A user's packet: the compact two-page layout on A4 (Letter in the US
69137
+ // and Canada), and a plain title. The owner's PDF is unchanged.
69138
+ ...userPaper ? { style: "compact", paper: userPaper, title: `${documentName} - Resume` } : {}
68192
69139
  });
68193
69140
  return c.body(new Uint8Array(bytes).buffer, 200, {
68194
69141
  "Content-Type": "application/pdf",
@@ -68212,18 +69159,25 @@ function createResumeHandler(basePath, options = {}) {
68212
69159
  if (!body.label) {
68213
69160
  return c.json({ error: "Missing required field: label" }, 400);
68214
69161
  }
69162
+ const r = scopeOf(c, onBehalfOf(body));
69163
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68215
69164
  try {
68216
- const client = createLLMClient(c.env, deferTo(c));
68217
- const variant = await mintVariant(client, c.env.CONTENT_KV, body);
69165
+ const client = makeClient(c.env, deferTo(c));
69166
+ const variant = await mintVariant(client, c.env.CONTENT_KV, body, r.scope);
68218
69167
  return c.json(variant);
68219
69168
  } catch (error2) {
69169
+ if (error2 instanceof SlugTakenError) return c.json({ error: error2.message }, 409);
69170
+ const missing = r.scope.kind === "user" ? missingContent(error2) : null;
69171
+ if (missing) return c.json(missing, 409);
68220
69172
  logger2.error("variant mint failed", { error: error2.message });
68221
69173
  return c.json({ error: "Failed to mint variant", message: error2.message }, 400);
68222
69174
  }
68223
69175
  });
68224
69176
  app.get(`${basePath}/variants`, async (c) => {
68225
69177
  try {
68226
- const variants = await listVariants(c.env.CONTENT_KV);
69178
+ const r = scopeOf(c);
69179
+ if ("error" in r) return c.json({ error: r.error }, r.status);
69180
+ const variants = await listVariants(c.env.CONTENT_KV, r.scope);
68227
69181
  return c.json({ variants });
68228
69182
  } catch (error2) {
68229
69183
  logger2.error("variant list failed", { error: error2.message });
@@ -68232,7 +69186,9 @@ function createResumeHandler(basePath, options = {}) {
68232
69186
  });
68233
69187
  app.delete(`${basePath}/variants/:slug`, async (c) => {
68234
69188
  try {
68235
- const deleted = await deleteVariant(c.env.CONTENT_KV, c.req.param("slug"));
69189
+ const r = scopeOf(c);
69190
+ if ("error" in r) return c.json({ error: r.error }, r.status);
69191
+ const deleted = await deleteVariant(c.env.CONTENT_KV, c.req.param("slug"), r.scope);
68236
69192
  return deleted ? c.json({ deleted: true }) : c.json({ error: "Not found" }, 404);
68237
69193
  } catch (error2) {
68238
69194
  logger2.error("variant delete failed", { error: error2.message });
@@ -68261,11 +69217,21 @@ function createResumeHandler(basePath, options = {}) {
68261
69217
  if (!body.job_title || !body.company || !body.description) {
68262
69218
  return c.json({ error: "Missing required fields: job_title, company, description" }, 400);
68263
69219
  }
69220
+ const r = scopeOf(c, onBehalfOf(body));
69221
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68264
69222
  try {
68265
- const client = createLLMClient(c.env, deferTo(c));
68266
- const result = await generateTailoredResume(client, c.env.CONTENT_KV, body);
69223
+ const client = makeClient(c.env, deferTo(c));
69224
+ const result = await generateTailoredResume(
69225
+ client,
69226
+ c.env.CONTENT_KV,
69227
+ body,
69228
+ void 0,
69229
+ r.scope
69230
+ );
68267
69231
  return c.json(result);
68268
69232
  } catch (error2) {
69233
+ const missing = r.scope.kind === "user" ? missingContent(error2) : null;
69234
+ if (missing) return c.json(missing, 409);
68269
69235
  logger2.error("tailored-resume generation failed", {
68270
69236
  error: error2.message,
68271
69237
  company: body.company,
@@ -68287,12 +69253,23 @@ function createResumeHandler(basePath, options = {}) {
68287
69253
  if (!body.job_title || !body.company || !body.description) {
68288
69254
  return c.json({ error: "Missing required fields: job_title, company, description" }, 400);
68289
69255
  }
69256
+ const r = scopeOf(c, onBehalfOf(body));
69257
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68290
69258
  try {
68291
- const client = createLLMClient(c.env, deferTo(c));
68292
- const resumeContent = await getResumeContent(c.env);
68293
- const result = await generateCoverLetter(client, c.env.CONTENT_KV, resumeContent, body);
69259
+ const client = makeClient(c.env, deferTo(c));
69260
+ const resumeContent = await getResumeContent(c.env, r.scope);
69261
+ const result = await generateCoverLetter(
69262
+ client,
69263
+ c.env.CONTENT_KV,
69264
+ resumeContent,
69265
+ body,
69266
+ void 0,
69267
+ r.scope
69268
+ );
68294
69269
  return c.json(result);
68295
69270
  } catch (error2) {
69271
+ const missing = r.scope.kind === "user" ? missingContent(error2) : null;
69272
+ if (missing) return c.json(missing, 409);
68296
69273
  logger2.error("cover-letter generation failed", {
68297
69274
  error: error2.message,
68298
69275
  company: body.company,
@@ -68319,20 +69296,25 @@ function createResumeHandler(basePath, options = {}) {
68319
69296
  400
68320
69297
  );
68321
69298
  }
69299
+ const r = scopeOf(c, onBehalfOf(body));
69300
+ if ("error" in r) return c.json({ error: r.error }, r.status);
68322
69301
  try {
68323
- const client = createLLMClient(c.env, deferTo(c));
69302
+ const client = makeClient(c.env, deferTo(c));
68324
69303
  const deadline = Date.now() + OPERATION_BUDGET_MS;
68325
- const result = await generateApplicationExtras(client, c.env.CONTENT_KV, body);
69304
+ const result = await generateApplicationExtras(client, c.env.CONTENT_KV, body, r.scope);
68326
69305
  const questions = readQuestions(body.questions);
68327
69306
  if (!questions) return c.json(result);
68328
69307
  const form_answers = await generateFormAnswers(
68329
69308
  client,
68330
69309
  c.env.CONTENT_KV,
68331
69310
  { ...body, contact: result.contact, questions },
68332
- deadline
69311
+ deadline,
69312
+ r.scope
68333
69313
  );
68334
69314
  return c.json({ ...result, form_answers });
68335
69315
  } catch (error2) {
69316
+ const missing = r.scope.kind === "user" ? missingContent(error2) : null;
69317
+ if (missing) return c.json(missing, 409);
68336
69318
  logger2.error("application-extras generation failed", {
68337
69319
  error: error2.message,
68338
69320
  company: body.company,
@@ -68351,6 +69333,12 @@ function createResumeHandler(basePath, options = {}) {
68351
69333
  });
68352
69334
  return app;
68353
69335
  }
69336
+ function candidateName(stored, markdown) {
69337
+ return stored || nameFromMarkdown(markdown) || "Candidate";
69338
+ }
69339
+ function asObject(value) {
69340
+ return typeof value === "object" && value !== null ? value : {};
69341
+ }
68354
69342
  export {
68355
69343
  AnthropicError as A,
68356
69344
  DEFAULT_MEMORY_SYNC_INTERVAL_MS as D,