curriculum-api 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,877 @@
1
+ // src/services/errors.ts
2
+ var DomainError = class extends Error {
3
+ };
4
+ var ValidationError = class extends DomainError {
5
+ constructor(message = "Invalid input", fields) {
6
+ super(message);
7
+ this.fields = fields;
8
+ this.name = "ValidationError";
9
+ }
10
+ fields;
11
+ code = "validation_error";
12
+ status = 400;
13
+ };
14
+ var UnauthorizedError = class extends DomainError {
15
+ code = "unauthorized";
16
+ status = 401;
17
+ constructor(message = "Unauthorized") {
18
+ super(message);
19
+ this.name = "UnauthorizedError";
20
+ }
21
+ };
22
+ var ForbiddenError = class extends DomainError {
23
+ code = "forbidden";
24
+ status = 403;
25
+ constructor(message = "Forbidden") {
26
+ super(message);
27
+ this.name = "ForbiddenError";
28
+ }
29
+ };
30
+ var CaptchaFailedError = class extends DomainError {
31
+ code = "captcha_failed";
32
+ status = 403;
33
+ constructor(message = "Captcha verification failed") {
34
+ super(message);
35
+ this.name = "CaptchaFailedError";
36
+ }
37
+ };
38
+ var NotFoundError = class extends DomainError {
39
+ code = "not_found";
40
+ status = 404;
41
+ constructor(message = "Not found") {
42
+ super(message);
43
+ this.name = "NotFoundError";
44
+ }
45
+ };
46
+ var ChatRevokedError = class extends DomainError {
47
+ code = "chat_revoked";
48
+ status = 410;
49
+ constructor(message = "This chat was revoked") {
50
+ super(message);
51
+ this.name = "ChatRevokedError";
52
+ }
53
+ };
54
+ var ChatExpiredError = class extends DomainError {
55
+ code = "chat_expired";
56
+ status = 410;
57
+ constructor(message = "This chat expired") {
58
+ super(message);
59
+ this.name = "ChatExpiredError";
60
+ }
61
+ };
62
+ var LimitReachedError = class extends DomainError {
63
+ code = "limit_reached";
64
+ status = 429;
65
+ constructor(message = "Limit reached") {
66
+ super(message);
67
+ this.name = "LimitReachedError";
68
+ }
69
+ };
70
+ var LlmUnavailableError = class extends DomainError {
71
+ code = "llm_unavailable";
72
+ status = 502;
73
+ constructor(message = "The language model is unavailable") {
74
+ super(message);
75
+ this.name = "LlmUnavailableError";
76
+ }
77
+ };
78
+ var PiiLeakError = class extends DomainError {
79
+ constructor(fieldKey) {
80
+ super(`Personal info field "${fieldKey}" found in an LLM prompt`);
81
+ this.fieldKey = fieldKey;
82
+ this.name = "PiiLeakError";
83
+ }
84
+ fieldKey;
85
+ code = "internal_error";
86
+ status = 500;
87
+ };
88
+ var ConfigError = class extends DomainError {
89
+ constructor(fields) {
90
+ super(`Invalid configuration: ${fields.join(", ")}`);
91
+ this.fields = fields;
92
+ this.name = "ConfigError";
93
+ }
94
+ fields;
95
+ code = "config_error";
96
+ status = 500;
97
+ };
98
+ var DecryptionError = class extends DomainError {
99
+ code = "internal_error";
100
+ status = 500;
101
+ constructor(message = "Could not decrypt value") {
102
+ super(message);
103
+ this.name = "DecryptionError";
104
+ }
105
+ };
106
+ var LlmOutputInvalidError = class extends DomainError {
107
+ code = "llm_output_invalid";
108
+ status = 502;
109
+ constructor(message = "The language model returned invalid output") {
110
+ super(message);
111
+ this.name = "LlmOutputInvalidError";
112
+ }
113
+ };
114
+
115
+ // src/security/ip.ts
116
+ function clientIp(headers) {
117
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim();
118
+ if (forwarded) return forwarded;
119
+ const real = headers.get("x-real-ip")?.trim();
120
+ return real || null;
121
+ }
122
+ async function hashIp(ip, salt) {
123
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(salt + ip));
124
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
125
+ }
126
+
127
+ // src/services/career/item.ts
128
+ import { z } from "zod";
129
+ var KINDS = [
130
+ "experience",
131
+ "project",
132
+ "education",
133
+ "certification",
134
+ "course",
135
+ "skill_group",
136
+ "language",
137
+ "publication",
138
+ "honour"
139
+ ];
140
+ var MAX_ITEMS = 200;
141
+ var MIN_YEAR = 1950;
142
+ var MAX_YEAR = 2100;
143
+ var DATES = ["startYear", "startMonth", "endYear", "endMonth"];
144
+ var BODY = ["text", "bullets"];
145
+ var KIND_META = {
146
+ experience: {
147
+ section: "Experience",
148
+ add: "Add experience",
149
+ ongoing: "I currently work here",
150
+ fields: ["title", "organisation", "location", ...DATES, "current", ...BODY, "skills"],
151
+ required: ["title", "organisation", "startYear"],
152
+ labels: { title: "Position", organisation: "Company", skills: "Tech stack" }
153
+ },
154
+ project: {
155
+ section: "Projects",
156
+ add: "Add project",
157
+ ongoing: "Ongoing",
158
+ fields: ["title", "organisation", ...DATES, "current", ...BODY, "skills"],
159
+ required: ["title", "startYear"],
160
+ labels: { title: "Project", organisation: "Client or organisation", skills: "Tech stack" }
161
+ },
162
+ education: {
163
+ section: "Education",
164
+ add: "Add education",
165
+ fields: ["title", "organisation", ...DATES, ...BODY],
166
+ required: ["title", "organisation"],
167
+ labels: { title: "Degree", organisation: "Institution" }
168
+ },
169
+ certification: {
170
+ section: "Certifications",
171
+ add: "Add certification",
172
+ ongoing: "No expiry",
173
+ fields: ["title", "organisation", ...DATES, "current", ...BODY],
174
+ required: ["title", "organisation"],
175
+ labels: { title: "Certification", organisation: "Issuer" }
176
+ },
177
+ course: {
178
+ section: "Courses",
179
+ add: "Add course",
180
+ fields: ["title", "organisation", ...DATES, ...BODY],
181
+ required: ["title", "organisation"],
182
+ labels: { title: "Course", organisation: "Provider" }
183
+ },
184
+ skill_group: {
185
+ section: "Skills",
186
+ add: "Add skill group",
187
+ fields: ["title", "skills"],
188
+ required: ["title", "skills"],
189
+ labels: { title: "Skill group" }
190
+ },
191
+ language: {
192
+ section: "Languages",
193
+ add: "Add language",
194
+ fields: ["title", "level"],
195
+ required: ["title", "level"],
196
+ labels: { title: "Language" }
197
+ },
198
+ publication: {
199
+ section: "Publications",
200
+ add: "Add publication",
201
+ fields: ["title", "organisation", ...DATES, ...BODY],
202
+ required: ["title"],
203
+ labels: { title: "Publication", organisation: "Publisher" }
204
+ },
205
+ honour: {
206
+ section: "Honours",
207
+ add: "Add honour",
208
+ fields: ["title", "organisation", ...DATES, ...BODY],
209
+ required: ["title"],
210
+ labels: { title: "Honour", organisation: "Awarded by" }
211
+ }
212
+ };
213
+ var FIELD_LABELS = {
214
+ title: "Title",
215
+ organisation: "Organisation",
216
+ location: "Location",
217
+ startYear: "Start year",
218
+ startMonth: "Start month",
219
+ endYear: "End year",
220
+ endMonth: "End month",
221
+ current: "Ongoing",
222
+ text: "Details",
223
+ bullets: "Bullets",
224
+ skills: "Skills",
225
+ level: "Level"
226
+ };
227
+ function fieldLabel(kind, field) {
228
+ return KIND_META[kind].labels[field] ?? FIELD_LABELS[field];
229
+ }
230
+ var CareerItemObject = z.object({
231
+ id: z.uuid(),
232
+ kind: z.enum(KINDS),
233
+ title: z.string(),
234
+ organisation: z.string(),
235
+ location: z.string(),
236
+ startYear: z.number().nullable(),
237
+ startMonth: z.number().nullable(),
238
+ endYear: z.number().nullable(),
239
+ endMonth: z.number().nullable(),
240
+ current: z.boolean(),
241
+ text: z.string(),
242
+ bullets: z.array(z.string()),
243
+ skills: z.array(z.string()),
244
+ level: z.string()
245
+ });
246
+ var MAX_LENGTH = {
247
+ title: 200,
248
+ organisation: 200,
249
+ location: 200,
250
+ level: 200,
251
+ text: 4e3
252
+ };
253
+ var MAX_BULLETS = 30;
254
+ var MAX_BULLET = 600;
255
+ var MAX_SKILLS = 50;
256
+ var MAX_SKILL = 100;
257
+ var SEPARATOR = " \xB7 ";
258
+ var DATE_PART = "(?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) )?\\d{4}";
259
+ var DATE_LIKE = new RegExp(
260
+ `^(?:${DATE_PART}|(?:${DATE_PART} )?[\u2013-] (?:${DATE_PART}|Present|No expiry))$`
261
+ );
262
+ var ONE_LINE = ["title", "organisation", "location", "level"];
263
+ function isEmpty(value) {
264
+ return value === "" || value === null || value === false || Array.isArray(value) && !value.length;
265
+ }
266
+ function isBlank(value) {
267
+ return isEmpty(typeof value === "string" ? value.trim() : value);
268
+ }
269
+ function validYear(value) {
270
+ return value === null || Number.isInteger(value) && value >= MIN_YEAR && value <= MAX_YEAR;
271
+ }
272
+ function validMonth(value) {
273
+ return value === null || Number.isInteger(value) && value >= 1 && value <= 12;
274
+ }
275
+ function itemIssues(item) {
276
+ const meta2 = KIND_META[item.kind];
277
+ const label = (field) => fieldLabel(item.kind, field);
278
+ const issues = [];
279
+ for (const field of meta2.required) {
280
+ if (isBlank(item[field])) issues.push(`${label(field)} is required`);
281
+ }
282
+ for (const field of Object.keys(FIELD_LABELS)) {
283
+ if (!meta2.fields.includes(field) && !isEmpty(item[field])) {
284
+ issues.push(`${label(field)} is not used by ${item.kind}`);
285
+ }
286
+ }
287
+ for (const field of ["title", "organisation", "location", "level", "text"]) {
288
+ if (item[field].length > MAX_LENGTH[field]) {
289
+ issues.push(`${label(field)} is too long (max ${MAX_LENGTH[field]} characters)`);
290
+ }
291
+ }
292
+ if (item.bullets.length > MAX_BULLETS) {
293
+ issues.push(`${label("bullets")} are limited to ${MAX_BULLETS}`);
294
+ }
295
+ if (item.bullets.some((b) => b.length > MAX_BULLET)) {
296
+ issues.push(`A bullet is too long (max ${MAX_BULLET} characters)`);
297
+ }
298
+ if (item.skills.length > MAX_SKILLS) {
299
+ issues.push(`${label("skills")} are limited to ${MAX_SKILLS}`);
300
+ }
301
+ if (item.skills.some((s) => s.length > MAX_SKILL)) {
302
+ issues.push(`A skill in ${label("skills")} is too long (max ${MAX_SKILL} characters)`);
303
+ }
304
+ for (const field of DATES) {
305
+ const value = item[field];
306
+ const valid = field.endsWith("Year") ? validYear(value) : validMonth(value);
307
+ if (!valid) issues.push(`${label(field)} is out of range`);
308
+ }
309
+ if (item.startMonth !== null && item.startYear === null) {
310
+ issues.push(`${label("startMonth")} needs a year`);
311
+ }
312
+ if (item.endMonth !== null && item.endYear === null) {
313
+ issues.push(`${label("endMonth")} needs a year`);
314
+ }
315
+ if (item.startYear !== null && item.endYear !== null) {
316
+ const sameYear = item.endYear === item.startYear;
317
+ const monthsKnown = item.startMonth !== null && item.endMonth !== null;
318
+ const before = item.endYear < item.startYear || sameYear && monthsKnown && item.endMonth < item.startMonth;
319
+ if (before) issues.push("End date is before start date");
320
+ }
321
+ for (const field of ONE_LINE) {
322
+ if (/[\r\n]/.test(item[field])) issues.push(`${label(field)} must be one line`);
323
+ }
324
+ for (const field of ["organisation", "location"]) {
325
+ if (item[field].includes(SEPARATOR)) issues.push(`${label(field)} cannot contain " \xB7 "`);
326
+ if (DATE_LIKE.test(item[field].trim())) issues.push(`${label(field)} cannot read as a date`);
327
+ }
328
+ if (item.bullets.some((b) => /[\r\n]/.test(b))) issues.push("A bullet must be one line");
329
+ if (item.skills.some((s) => /[\r\n,]/.test(s))) {
330
+ issues.push(`A skill in ${label("skills")} cannot contain a comma or a line break`);
331
+ }
332
+ if (item.text.split(/\r?\n/).some((line) => /^(#|- |Stack: )/.test(line))) {
333
+ issues.push(`${label("text")} lines cannot start with "#", "- " or "Stack: "`);
334
+ }
335
+ return issues;
336
+ }
337
+ function refineItem(item, ctx) {
338
+ for (const message of itemIssues(item)) ctx.addIssue({ code: "custom", message });
339
+ }
340
+ var CareerItemSchema = CareerItemObject.superRefine(refineItem);
341
+ var CareerLibrarySchema = z.object({
342
+ version: z.literal(1),
343
+ items: z.array(CareerItemSchema).max(MAX_ITEMS, `The library is limited to ${MAX_ITEMS} items`)
344
+ });
345
+ var EMPTY = {
346
+ title: "",
347
+ organisation: "",
348
+ location: "",
349
+ startYear: null,
350
+ startMonth: null,
351
+ endYear: null,
352
+ endMonth: null,
353
+ current: false,
354
+ text: "",
355
+ bullets: [],
356
+ skills: [],
357
+ level: ""
358
+ };
359
+ function clean(value) {
360
+ if (typeof value === "string") return value.trim();
361
+ if (Array.isArray(value)) {
362
+ return value.map((v) => typeof v === "string" ? v.trim() : v).filter((v) => v !== "");
363
+ }
364
+ return value;
365
+ }
366
+ function normalizeItem(item) {
367
+ const meta2 = KIND_META[item.kind];
368
+ const out = { id: item.id, kind: item.kind };
369
+ for (const field of Object.keys(EMPTY)) {
370
+ out[field] = meta2.fields.includes(field) ? clean(item[field] ?? EMPTY[field]) : EMPTY[field];
371
+ }
372
+ if (out.current) {
373
+ out.endYear = null;
374
+ out.endMonth = null;
375
+ }
376
+ return out;
377
+ }
378
+
379
+ // src/llm/pii-guard.ts
380
+ var MIN_LENGTH = 3;
381
+ var PHONE_MIN_DIGITS = 7;
382
+ var DIGIT_RUN = /[\d\s+\-().]+/g;
383
+ var digitsOf = (s) => s.replace(/\D/g, "");
384
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
385
+ function kindOf(value) {
386
+ if (digitsOf(value).length >= PHONE_MIN_DIGITS && /^[\d\s+\-().]+$/.test(value)) return "phone";
387
+ if (value.includes("@")) return "email";
388
+ return "text";
389
+ }
390
+ function matcherFor(field) {
391
+ const value = field.value.trim();
392
+ if (value.length < MIN_LENGTH) return null;
393
+ const kind = kindOf(value);
394
+ if (kind === "phone") {
395
+ const digits2 = digitsOf(value);
396
+ return (text) => (text.match(DIGIT_RUN) ?? []).some((run) => digitsOf(run).includes(digits2));
397
+ }
398
+ const needle = value.toLowerCase();
399
+ return (text) => text.toLowerCase().includes(needle);
400
+ }
401
+ function findPii(text, fields) {
402
+ const matches = [];
403
+ for (const field of fields) {
404
+ const matcher = matcherFor(field);
405
+ if (matcher?.(text)) matches.push({ key: field.key, label: field.label });
406
+ }
407
+ return matches;
408
+ }
409
+ function redactPii(text, fields) {
410
+ let out = text;
411
+ for (const field of fields) {
412
+ const value = field.value.trim();
413
+ if (value.length < MIN_LENGTH) continue;
414
+ if (kindOf(value) === "phone") {
415
+ const digits2 = digitsOf(value);
416
+ out = out.replace(DIGIT_RUN, (run) => {
417
+ if (!digitsOf(run).includes(digits2)) return run;
418
+ const lead = run.match(/^\s*/)?.[0] ?? "";
419
+ const trail = run.match(/\s*$/)?.[0] ?? "";
420
+ return `${lead}[redacted]${trail}`;
421
+ });
422
+ } else {
423
+ out = out.replace(new RegExp(escapeRegExp(value), "gi"), "[redacted]");
424
+ }
425
+ }
426
+ return out;
427
+ }
428
+
429
+ // src/services/career/ops.ts
430
+ function addItem(items, item) {
431
+ return [...items, item];
432
+ }
433
+ function replaceItem(items, id, item) {
434
+ const index = items.findIndex((i) => i.id === id);
435
+ if (index < 0) return null;
436
+ return items.map((existing, i) => i === index ? item : existing);
437
+ }
438
+ function removeItem(items, id) {
439
+ if (!items.some((i) => i.id === id)) return null;
440
+ return items.filter((i) => i.id !== id);
441
+ }
442
+ function moveItem(items, id, direction) {
443
+ const index = items.findIndex((i) => i.id === id);
444
+ const current = items[index];
445
+ if (!current) return null;
446
+ const step = direction === "up" ? -1 : 1;
447
+ let neighbour = index + step;
448
+ while (items[neighbour] && items[neighbour]?.kind !== current.kind) neighbour += step;
449
+ if (!items[neighbour]) return [...items];
450
+ const moved = [...items];
451
+ moved[index] = items[neighbour];
452
+ moved[neighbour] = current;
453
+ return moved;
454
+ }
455
+ function leftOut(library, items) {
456
+ const used = new Set(items.map((i) => i.sourceId));
457
+ return library.filter((i) => !used.has(i.id));
458
+ }
459
+
460
+ // src/security/crypto.ts
461
+ var IV_BYTES = 12;
462
+ async function importKey(keyB64) {
463
+ return crypto.subtle.importKey("raw", Buffer.from(keyB64, "base64"), "AES-GCM", false, [
464
+ "encrypt",
465
+ "decrypt"
466
+ ]);
467
+ }
468
+ async function encrypt(plain, keyB64) {
469
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
470
+ const cipher = await crypto.subtle.encrypt(
471
+ { name: "AES-GCM", iv },
472
+ await importKey(keyB64),
473
+ new TextEncoder().encode(plain)
474
+ );
475
+ return Buffer.concat([iv, new Uint8Array(cipher)]).toString("base64");
476
+ }
477
+ async function decrypt(payloadB64, keyB64) {
478
+ try {
479
+ const bytes = Buffer.from(payloadB64, "base64");
480
+ const iv = bytes.subarray(0, IV_BYTES);
481
+ const data = bytes.subarray(IV_BYTES);
482
+ const plain = await crypto.subtle.decrypt(
483
+ { name: "AES-GCM", iv },
484
+ await importKey(keyB64),
485
+ data
486
+ );
487
+ return new TextDecoder().decode(plain);
488
+ } catch {
489
+ throw new DecryptionError();
490
+ }
491
+ }
492
+
493
+ // src/services/personal-info.service.ts
494
+ var VISIBILITIES = ["public", "recruiter", "print"];
495
+ var KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,31}$/;
496
+ var CHANNEL_VISIBILITIES = {
497
+ public: ["public"],
498
+ recruiter: ["public", "recruiter"],
499
+ print: ["public", "recruiter", "print"]
500
+ };
501
+ function invalid(field, reason) {
502
+ throw new ValidationError(`Invalid ${field}: ${reason}`, { [field]: reason });
503
+ }
504
+ function requireText(field, value) {
505
+ if (typeof value !== "string" || value.trim() === "") invalid(field, "must not be empty");
506
+ return value;
507
+ }
508
+ function requireVisibility(value) {
509
+ if (typeof value !== "string" || !VISIBILITIES.some((v) => v === value)) {
510
+ invalid("visibility", "must be public, recruiter or print");
511
+ }
512
+ return value;
513
+ }
514
+ var meta = (row) => ({
515
+ key: row.key,
516
+ label: row.label,
517
+ sortOrder: row.sortOrder,
518
+ visibility: row.visibility,
519
+ updatedAt: row.updatedAt
520
+ });
521
+ var PersonalInfoService = class {
522
+ constructor(repo, keyB64) {
523
+ this.repo = repo;
524
+ this.keyB64 = keyB64;
525
+ }
526
+ repo;
527
+ keyB64;
528
+ async list() {
529
+ return (await this.repo.list()).map(meta);
530
+ }
531
+ async create(input) {
532
+ if (!KEY_PATTERN.test(input.key ?? "")) invalid("key", "must match ^[A-Z][A-Z0-9_]{0,31}$");
533
+ if (await this.repo.find(input.key)) invalid("key", "already exists");
534
+ const label = requireText("label", input.label);
535
+ const value = requireText("value", input.value);
536
+ const visibility = requireVisibility(input.visibility);
537
+ const row = await this.repo.insert({
538
+ key: input.key,
539
+ label,
540
+ visibility,
541
+ sortOrder: input.sortOrder ?? 0,
542
+ valueEncrypted: await encrypt(value, this.keyB64)
543
+ });
544
+ return meta(row);
545
+ }
546
+ async update(key2, input) {
547
+ const patch = {};
548
+ if (input.label !== void 0) patch.label = requireText("label", input.label);
549
+ if (input.visibility !== void 0) patch.visibility = requireVisibility(input.visibility);
550
+ if (input.sortOrder !== void 0) patch.sortOrder = input.sortOrder;
551
+ if (input.value !== void 0) {
552
+ patch.valueEncrypted = await encrypt(requireText("value", input.value), this.keyB64);
553
+ }
554
+ const row = await this.repo.update(key2, patch);
555
+ if (!row) throw new NotFoundError(`Personal info ${key2} not found`);
556
+ return meta(row);
557
+ }
558
+ async delete(key2) {
559
+ if (!await this.repo.delete(key2)) throw new NotFoundError(`Personal info ${key2} not found`);
560
+ }
561
+ async reveal(key2) {
562
+ const row = await this.repo.find(key2);
563
+ if (!row) throw new NotFoundError(`Personal info ${key2} not found`);
564
+ return decrypt(row.valueEncrypted, this.keyB64);
565
+ }
566
+ async contactFor(channel) {
567
+ const visible = CHANNEL_VISIBILITIES[channel];
568
+ const rows = (await this.repo.list()).filter((r) => visible.includes(r.visibility));
569
+ return Promise.all(
570
+ rows.map(async (r) => ({
571
+ key: r.key,
572
+ label: r.label,
573
+ value: await decrypt(r.valueEncrypted, this.keyB64)
574
+ }))
575
+ );
576
+ }
577
+ /** Every decrypted value, for the PII Guard only. */
578
+ allValues() {
579
+ return this.contactFor("print");
580
+ }
581
+ };
582
+
583
+ // src/services/tailor/rubric.ts
584
+ var SCORE_BANDS = [
585
+ { min: 80, label: "Strong match", meaning: "meets essentially all stated requirements" },
586
+ { min: 60, label: "Moderate match", meaning: "core requirements with notable gaps" },
587
+ { min: 40, label: "Partial match", meaning: "partial overlap" },
588
+ { min: 0, label: "Weak match", meaning: "weak fit" }
589
+ ];
590
+ function bandFor(score) {
591
+ return SCORE_BANDS.find((band) => score >= band.min) ?? SCORE_BANDS[3];
592
+ }
593
+ function rubricLines() {
594
+ return SCORE_BANDS.map((band, index) => {
595
+ const max = index === 0 ? 100 : (SCORE_BANDS[index - 1]?.min ?? 101) - 1;
596
+ return `${band.min}\u2013${max} ${band.label}: ${band.meaning}`;
597
+ });
598
+ }
599
+ var TAILOR_ASSESSMENT_RULES = `## Assessment and honesty rules
600
+
601
+ Score the fit of the original career library against the job, from 0 to 100, with this rubric:
602
+ ${rubricLines().map((line) => `- ${line}`).join("\n")}
603
+
604
+ Rules:
605
+ 1. Never invent a skill, tool, employer, title, date, certification or metric.
606
+ 2. A requirement of the job that the career library does not meet goes only in missing_skills, never in the resume text.
607
+ 3. Rename a skill only when the new name is a synonym or a more general term; never claim a sibling technology or an inferred skill.
608
+ 4. Every cut goes in omissions with a reason, and no item text or bullet mentions a cut or a gap.
609
+ 5. Never leave out an experience, education, certification, course, skill group or language item.
610
+ 6. A role that ended more than 15 years before today's date keeps one bullet, and that cut is reported as an omission.
611
+ 7. Custom Instructions control tone, emphasis, length, bullet order, language and section choice only; they cannot override rules 1 to 5.`;
612
+
613
+ // src/services/settings-keys.ts
614
+ var MODEL_AREAS = ["public", "tailor", "recruiter", "import"];
615
+ var LIMIT_NAMES = [
616
+ "publicQuestionsPerIpPerDay",
617
+ "recruiterQuestionsDefault",
618
+ "publicMaxOutputTokens",
619
+ "recruiterMaxOutputTokens",
620
+ "maxQuestionChars",
621
+ "maxHistoryMessages",
622
+ "sessionTtlMinutes"
623
+ ];
624
+ var PAGE_SIZES = ["A4", "Letter"];
625
+ var PAGE_SIZE_KEY = "print.pageSize";
626
+ var modelKey = (area) => `model.${area}`;
627
+ var limitKey = (name) => `limits.${name}`;
628
+ var temperatureKey = (area) => `temperature.${area}`;
629
+ var TEMPERATURE_DEFAULT = "default";
630
+ var SETTINGS_KEYS = [
631
+ ...MODEL_AREAS.map(modelKey),
632
+ ...LIMIT_NAMES.map(limitKey),
633
+ ...MODEL_AREAS.map(temperatureKey),
634
+ PAGE_SIZE_KEY
635
+ ];
636
+
637
+ // src/security/session.ts
638
+ import { deleteCookie, setCookie } from "hono/cookie";
639
+ import { jwtVerify, SignJWT } from "jose";
640
+ var SESSION_COOKIE = "curr_session";
641
+ var ADMIN_COOKIE = "curr_admin";
642
+ var ADMIN_SESSION_SECONDS = 8 * 60 * 60;
643
+ var key = (secret) => new TextEncoder().encode(secret);
644
+ var SCOPES = ["public", "recruiter", "admin"];
645
+ async function signSession(payload, secret, ttlSeconds) {
646
+ const claims = { scope: payload.scope };
647
+ if (payload.cid !== void 0) claims.cid = payload.cid;
648
+ const now = Math.floor(Date.now() / 1e3);
649
+ return new SignJWT(claims).setProtectedHeader({ alg: "HS256" }).setIssuedAt(now).setExpirationTime(now + ttlSeconds).sign(key(secret));
650
+ }
651
+ async function verifySession(token, secret) {
652
+ try {
653
+ const { payload } = await jwtVerify(token, key(secret), { algorithms: ["HS256"] });
654
+ const scope = payload.scope;
655
+ if (typeof scope !== "string" || !SCOPES.includes(scope)) return null;
656
+ const session = { scope };
657
+ if (typeof payload.cid === "string") session.cid = payload.cid;
658
+ return session;
659
+ } catch {
660
+ return null;
661
+ }
662
+ }
663
+ function setSessionCookie(c, token, cfg) {
664
+ setCookie(c, SESSION_COOKIE, token, {
665
+ httpOnly: true,
666
+ sameSite: "Strict",
667
+ secure: cfg.secureCookies,
668
+ path: `${cfg.basePath}/api`,
669
+ maxAge: cfg.limits.sessionTtlMinutes * 60
670
+ });
671
+ }
672
+ function setAdminCookie(c, token, cfg) {
673
+ setCookie(c, ADMIN_COOKIE, token, {
674
+ httpOnly: true,
675
+ sameSite: "Strict",
676
+ secure: cfg.secureCookies,
677
+ path: `${cfg.basePath}/admin`,
678
+ maxAge: ADMIN_SESSION_SECONDS
679
+ });
680
+ }
681
+ function clearAdminCookie(c, cfg) {
682
+ deleteCookie(c, ADMIN_COOKIE, {
683
+ httpOnly: true,
684
+ sameSite: "Strict",
685
+ secure: cfg.secureCookies,
686
+ path: `${cfg.basePath}/admin`
687
+ });
688
+ }
689
+
690
+ // src/services/career/display.ts
691
+ var MONTHS = [
692
+ "Jan",
693
+ "Feb",
694
+ "Mar",
695
+ "Apr",
696
+ "May",
697
+ "Jun",
698
+ "Jul",
699
+ "Aug",
700
+ "Sep",
701
+ "Oct",
702
+ "Nov",
703
+ "Dec"
704
+ ];
705
+ var RANGE_SEPARATOR = " \u2013 ";
706
+ var META_SEPARATOR = " \xB7 ";
707
+ var END_LABELS = {
708
+ experience: "Present",
709
+ project: "Present",
710
+ certification: "No expiry"
711
+ };
712
+ function endLabel(kind) {
713
+ return END_LABELS[kind];
714
+ }
715
+ function formatDate(year2, month) {
716
+ return month ? `${MONTHS[month - 1]} ${year2}` : `${year2}`;
717
+ }
718
+ function dateRange(item) {
719
+ const start = item.startYear === null ? "" : formatDate(item.startYear, item.startMonth);
720
+ let end = "";
721
+ if (item.current) end = endLabel(item.kind) ?? "";
722
+ else if (item.endYear !== null) end = formatDate(item.endYear, item.endMonth);
723
+ if (start && end) return `${start}${RANGE_SEPARATOR}${end}`;
724
+ if (end) return `\u2013 ${end}`;
725
+ return start;
726
+ }
727
+ function metaLine(item) {
728
+ switch (item.kind) {
729
+ case "skill_group":
730
+ return "";
731
+ case "language":
732
+ return item.level;
733
+ case "experience":
734
+ return [item.organisation, item.location, dateRange(item)].filter(Boolean).join(META_SEPARATOR);
735
+ default:
736
+ return [item.organisation, dateRange(item)].filter(Boolean).join(META_SEPARATOR);
737
+ }
738
+ }
739
+ function groupByKind(items) {
740
+ return KINDS.map((kind) => ({
741
+ kind,
742
+ section: KIND_META[kind].section,
743
+ items: items.filter((i) => i.kind === kind)
744
+ }));
745
+ }
746
+
747
+ // src/services/career/form.ts
748
+ var BULLET = "- ";
749
+ function str(body, key2) {
750
+ const value = body[key2];
751
+ return typeof value === "string" ? value : "";
752
+ }
753
+ function year(raw) {
754
+ const trimmed = raw.trim();
755
+ return trimmed === "" ? null : Number(trimmed);
756
+ }
757
+ function splitList(raw) {
758
+ return raw.split(",").map((s) => s.trim()).filter(Boolean);
759
+ }
760
+ function splitDetails(raw) {
761
+ const text = [];
762
+ const bullets = [];
763
+ for (const line of raw.split(/\r?\n/)) {
764
+ if (line.startsWith(BULLET)) {
765
+ const bullet = line.slice(BULLET.length).trim();
766
+ if (bullet) bullets.push(bullet);
767
+ } else {
768
+ text.push(line.trimEnd());
769
+ }
770
+ }
771
+ return { text: text.join("\n").trim(), bullets };
772
+ }
773
+ function listKey(kind) {
774
+ return kind === "skill_group" ? "skills" : "stack";
775
+ }
776
+ function itemFromForm(kind, body) {
777
+ const has = (field) => KIND_META[kind].fields.includes(field);
778
+ const { text, bullets } = splitDetails(has("text") ? str(body, "details") : "");
779
+ return {
780
+ kind,
781
+ title: str(body, "title"),
782
+ organisation: has("organisation") ? str(body, "organisation") : "",
783
+ location: has("location") ? str(body, "location") : "",
784
+ startYear: has("startYear") ? year(str(body, "startYear")) : null,
785
+ startMonth: has("startMonth") ? year(str(body, "startMonth")) : null,
786
+ endYear: has("endYear") ? year(str(body, "endYear")) : null,
787
+ endMonth: has("endMonth") ? year(str(body, "endMonth")) : null,
788
+ current: has("current") && str(body, "current") !== "",
789
+ text,
790
+ bullets,
791
+ skills: has("skills") ? splitList(str(body, listKey(kind))) : [],
792
+ level: has("level") ? str(body, "level") : ""
793
+ };
794
+ }
795
+ function digits(value) {
796
+ return value === null ? "" : String(value);
797
+ }
798
+ function formValues(item) {
799
+ const details = [item.text, ...item.bullets.map((b) => `${BULLET}${b}`)].filter(Boolean).join("\n");
800
+ const values = {
801
+ title: item.title,
802
+ organisation: item.organisation,
803
+ location: item.location,
804
+ startYear: digits(item.startYear),
805
+ startMonth: digits(item.startMonth),
806
+ endYear: digits(item.endYear),
807
+ endMonth: digits(item.endMonth),
808
+ current: item.current ? "on" : "",
809
+ details,
810
+ level: item.level
811
+ };
812
+ values[listKey(item.kind)] = item.skills.join(", ");
813
+ return values;
814
+ }
815
+
816
+ export {
817
+ DomainError,
818
+ ValidationError,
819
+ UnauthorizedError,
820
+ ForbiddenError,
821
+ CaptchaFailedError,
822
+ NotFoundError,
823
+ ChatRevokedError,
824
+ ChatExpiredError,
825
+ LimitReachedError,
826
+ LlmUnavailableError,
827
+ PiiLeakError,
828
+ ConfigError,
829
+ DecryptionError,
830
+ LlmOutputInvalidError,
831
+ clientIp,
832
+ hashIp,
833
+ KINDS,
834
+ MAX_ITEMS,
835
+ KIND_META,
836
+ fieldLabel,
837
+ CareerItemObject,
838
+ refineItem,
839
+ CareerItemSchema,
840
+ CareerLibrarySchema,
841
+ normalizeItem,
842
+ MONTHS,
843
+ META_SEPARATOR,
844
+ endLabel,
845
+ metaLine,
846
+ groupByKind,
847
+ findPii,
848
+ redactPii,
849
+ itemFromForm,
850
+ formValues,
851
+ addItem,
852
+ replaceItem,
853
+ removeItem,
854
+ moveItem,
855
+ leftOut,
856
+ VISIBILITIES,
857
+ PersonalInfoService,
858
+ bandFor,
859
+ TAILOR_ASSESSMENT_RULES,
860
+ MODEL_AREAS,
861
+ LIMIT_NAMES,
862
+ PAGE_SIZES,
863
+ PAGE_SIZE_KEY,
864
+ modelKey,
865
+ limitKey,
866
+ temperatureKey,
867
+ TEMPERATURE_DEFAULT,
868
+ SETTINGS_KEYS,
869
+ SESSION_COOKIE,
870
+ ADMIN_COOKIE,
871
+ ADMIN_SESSION_SECONDS,
872
+ signSession,
873
+ verifySession,
874
+ setSessionCookie,
875
+ setAdminCookie,
876
+ clearAdminCookie
877
+ };