@heripo/research-radar 6.0.3 → 6.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.
package/dist/index.js CHANGED
@@ -200,7 +200,7 @@ function identityOf(candidate) {
200
200
  candidate.classification?.trim() ?? '',
201
201
  ];
202
202
  }
203
- function buildUserPrompt(candidates) {
203
+ function buildUserPrompt$2(candidates) {
204
204
  const lines = candidates.map((candidate, index) => {
205
205
  const [institution, title, classification] = identityOf(candidate);
206
206
  return (`${index}. [${institution}] ${title}` +
@@ -218,7 +218,7 @@ async function triageBatch(candidates, { model, onFallback }, signal) {
218
218
  model,
219
219
  output: Output.object({ schema: KEEP_SCHEMA }),
220
220
  system: SYSTEM_PROMPT,
221
- prompt: buildUserPrompt(candidates),
221
+ prompt: buildUserPrompt$2(candidates),
222
222
  abortSignal: signal,
223
223
  });
224
224
  const verdicts = new Array(candidates.length).fill(false);
@@ -302,483 +302,900 @@ const createHeritageBidTriage = (options) => {
302
302
  };
303
303
 
304
304
  /**
305
- * Reads what data.go.kr said when it refused a request.
306
- *
307
- * Its gateway answers a refusal with HTTP 400 and an XML envelope, whatever
308
- * format the service itself speaks. The envelope names the cause — a spent
309
- * daily quota, an unregistered key, a withdrawn service and a denied caller
310
- * are all different `returnReasonCode`s — but an adapter that reports only the
311
- * status throws that away.
312
- *
313
- * It cost a week to learn that. A nightly run failed at the same minute for
314
- * days with nothing in the log but `Request failed (status=502)`, and the
315
- * reason the gateway had supplied each time was discarded before anyone could
316
- * read it.
305
+ * Date service implementation
306
+ * - Provides newsletter publication date strings (ISO and localized display form)
307
+ * - Always returns Korea Standard Time (KST, Asia/Seoul) regardless of server timezone
308
+ * - Accepts optional publishDate to override "today" (e.g., generating today's run for tomorrow's publication)
317
309
  */
318
- function describeOpenDataError(body) {
319
- const read = (tag) => new RegExp(`<${tag}>\\s*([^<]*)</${tag}>`).exec(body)?.[1]?.trim();
320
- const parts = [
321
- read('errMsg'),
322
- read('returnReasonCode') && `code ${read('returnReasonCode')}`,
323
- read('returnAuthMsg'),
324
- ].filter((part) => Boolean(part));
325
- if (parts.length > 0) {
326
- return parts.join(' / ');
310
+ class DateService {
311
+ targetDate;
312
+ /**
313
+ * @param publishDate - Optional ISO date string (YYYY-MM-DD) representing the newsletter
314
+ * publication date. If omitted, the current wall-clock time (KST)
315
+ * is used. Pass tomorrow's date when building the issue the night before.
316
+ * @throws {Error} If publishDate is not in YYYY-MM-DD format or is not a real calendar date.
317
+ */
318
+ constructor(publishDate) {
319
+ if (publishDate !== undefined) {
320
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(publishDate)) {
321
+ throw new Error(`Invalid publishDate format: "${publishDate}". Expected YYYY-MM-DD (e.g., "2025-02-12").`);
322
+ }
323
+ const date = new Date(publishDate + 'T00:00:00+09:00');
324
+ // Round-trip check: format back to YYYY-MM-DD in KST and compare.
325
+ // Catches invalid dates like "2025-02-30" that JS silently normalizes to "2025-03-02".
326
+ const roundTrip = date.toLocaleDateString('en-CA', {
327
+ timeZone: 'Asia/Seoul',
328
+ });
329
+ if (roundTrip !== publishDate) {
330
+ throw new Error(`Invalid publishDate: "${publishDate}" is not a real calendar date.`);
331
+ }
332
+ this.targetDate = date;
333
+ }
334
+ else {
335
+ this.targetDate = new Date();
336
+ }
337
+ }
338
+ /**
339
+ * Get the newsletter publication date in ISO format (YYYY-MM-DD).
340
+ * - Always returns date in Korea Standard Time (UTC+9)
341
+ * @returns ISO date string (e.g., "2024-10-15")
342
+ */
343
+ getPublicationISODateString() {
344
+ // Use Intl.DateTimeFormat to get date in Korea timezone
345
+ // 'en-CA' locale returns YYYY-MM-DD format by default
346
+ const kstDate = this.targetDate.toLocaleDateString('en-CA', {
347
+ timeZone: 'Asia/Seoul',
348
+ });
349
+ return kstDate;
350
+ }
351
+ getCurrentISODateString() {
352
+ return this.getPublicationISODateString();
353
+ }
354
+ /**
355
+ * Get the newsletter publication date as a localized display string.
356
+ * - Always returns date in Korea Standard Time (UTC+9)
357
+ * @returns Korean formatted date (e.g., "2024년 10월 15일")
358
+ */
359
+ getPublicationDisplayDateString() {
360
+ const formatter = new Intl.DateTimeFormat('ko-KR', {
361
+ timeZone: 'Asia/Seoul',
362
+ year: 'numeric',
363
+ month: 'long',
364
+ day: 'numeric',
365
+ });
366
+ return formatter.format(this.targetDate);
367
+ }
368
+ getDisplayDateString() {
369
+ return this.getPublicationDisplayDateString();
327
370
  }
328
- // Not the documented envelope. A short body is still worth quoting; a long
329
- // one is a page rather than an error and only adds noise to the log.
330
- const trimmed = body.trim().replace(/\s+/g, ' ');
331
- return trimmed.length > 0 && trimmed.length <= 200 ? trimmed : null;
332
371
  }
333
372
 
334
- const API_BASE$2 = 'https://apis.data.go.kr/1051000/recruitment';
335
- const SITE_BASE$2 = 'https://job.alio.go.kr';
336
- /**
337
- * Public 알리오 board URL used as this target's list page.
338
- *
339
- * As with 나라일터, core fetches this URL and `createAlioFetch` answers it from
340
- * the 재정경제부 open API, keeping the service key out of the configuration.
341
- */
342
- const ALIO_LIST_URL = `${SITE_BASE$2}/recruit.do`;
343
- /** Public posting URL. */
344
- const buildAlioDetailUrl = (serial) => `${SITE_BASE$2}/recruitview.do?idx=${serial}`;
345
- /** `yyyymmdd` to ISO `yyyy-mm-dd`. */
346
- function toIsoDate$2(compact) {
347
- return /^\d{8}$/.test(compact)
348
- ? `${compact.slice(0, 4)}-${compact.slice(4, 6)}-${compact.slice(6, 8)}`
349
- : '';
373
+ /** Days before the date an action first becomes eligible (D-3 through D-day). */
374
+ const DEADLINE_REMINDER_LEAD_DAYS = 3;
375
+ /** Rows the unified deadline section displays. */
376
+ const DEADLINE_REMINDER_LIMIT = 10;
377
+ function escapeLabel(value) {
378
+ return value
379
+ .replace(/\s+/g, ' ')
380
+ .replace(/&/g, '&amp;')
381
+ .replace(/</g, '&lt;')
382
+ .replace(/>/g, '&gt;')
383
+ .replace(/[\\`*_{}[\]()|!#]/g, '\\$&');
350
384
  }
351
- /** `resultCode` this service returns on success. */
352
- const SUCCESS_RESULT_CODE$2 = 200;
353
- function parseResultCode(body) {
354
- try {
355
- const parsed = JSON.parse(body);
356
- return typeof parsed.resultCode === 'number' ? parsed.resultCode : null;
357
- }
358
- catch {
359
- return null;
360
- }
385
+ const clockPattern = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/;
386
+ const fullClock = (time) => (time.length === 5 ? `${time}:00` : time);
387
+ function calendarMs(date) {
388
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date))
389
+ return NaN;
390
+ const ms = Date.parse(`${date}T00:00:00Z`);
391
+ return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === date
392
+ ? ms
393
+ : NaN;
361
394
  }
362
395
  /**
363
- * Serves the 알리오 target from the 재정경제부 open API.
364
- *
365
- * This board only covers 공기업 and 준정부기관, so heritage postings are rare —
366
- * 국가유산청 and the national museums publish through 나라일터 instead. It is
367
- * collected anyway because a body like 국립농업박물관 does appear here, and the
368
- * NCS job codes make filtering cheap and precise.
396
+ * Every displayable reminder, deduplicated and in display order.
369
397
  *
370
- * Only postings still open (`ongoingYn=Y`) are requested.
398
+ * Eligibility stays deterministic: only verified, active actions from D-3
399
+ * through D-day, or events still running, with a safe link and a closing time
400
+ * that has not passed. Selection may choose among these but never adds to them.
371
401
  */
372
- const createAlioFetch = (baseFetch = fetch, options) => {
373
- const { apiKey, rowsPerPage = 3000, onError } = options;
374
- return async (input, init) => {
375
- const requestUrl = typeof input === 'string'
376
- ? input
377
- : input instanceof URL
378
- ? input.href
379
- : input.url;
402
+ function eligibleDeadlineReminders(reminders, publicationDate, now = new Date()) {
403
+ const date = new DateService(publicationDate).getPublicationISODateString();
404
+ const publicationMs = Date.parse(`${date}T00:00:00Z`);
405
+ const rows = reminders
406
+ .flatMap((reminder) => {
407
+ const { deadline } = reminder;
408
+ if (reminder.verificationStatus !== 'verified' ||
409
+ deadline.status !== 'active' ||
410
+ !deadline.date ||
411
+ !/^\d{4}-\d{2}-\d{2}$/.test(deadline.date))
412
+ return [];
413
+ const isEvent = deadline.type === 'event';
414
+ const ms = calendarMs(deadline.date);
415
+ const endDate = isEvent
416
+ ? (deadline.endDate ?? deadline.date)
417
+ : deadline.date;
418
+ const endMs = calendarMs(endDate);
419
+ if (!Number.isFinite(ms) || !Number.isFinite(endMs) || endMs < ms)
420
+ return [];
421
+ if ((!isEvent && (deadline.endDate || deadline.endTime)) ||
422
+ (deadline.endTime && !deadline.endDate))
423
+ return [];
424
+ if ((deadline.time && !clockPattern.test(deadline.time)) ||
425
+ (deadline.endTime && !clockPattern.test(deadline.endTime)))
426
+ return [];
427
+ if (isEvent &&
428
+ endDate === deadline.date &&
429
+ deadline.time &&
430
+ deadline.endTime &&
431
+ fullClock(deadline.endTime) < fullClock(deadline.time))
432
+ return [];
433
+ const days = (ms - publicationMs) / 86_400_000;
434
+ // Events remain eligible through a known end date; a start time is never
435
+ // treated as an application cutoff. Unknown endpoints stay unknown.
436
+ if (days > DEADLINE_REMINDER_LEAD_DAYS ||
437
+ endMs < publicationMs ||
438
+ !deadline.title.trim())
439
+ return [];
380
440
  let url;
381
441
  try {
382
- url = new URL(requestUrl);
383
- }
384
- catch {
385
- return baseFetch(input, init);
386
- }
387
- if (url.origin !== SITE_BASE$2) {
388
- return baseFetch(input, init);
389
- }
390
- if (!apiKey) {
391
- // Without a key the board is simply not collected. See gojobs.parser.ts.
392
- return Response.json({ result: [] });
393
- }
394
- if (url.pathname === '/recruit.do') {
395
- const response = await baseFetch(`${API_BASE$2}/list?serviceKey=${apiKey}&resultType=json` +
396
- `&numOfRows=${rowsPerPage}&pageNo=1&ongoingYn=Y`, init);
397
- if (!response.ok) {
398
- // See the 나라일터 adapter: keep the upstream status, report the reason.
399
- const body = await response.text();
400
- const detail = describeOpenDataError(body);
401
- onError?.(`알리오 list failed with HTTP ${response.status}` +
402
- (detail ? ` — ${detail}` : ''));
403
- return new Response(body, {
404
- status: response.status,
405
- statusText: response.statusText,
406
- });
407
- }
408
- // Same reasoning as the 나라일터 adapter: data.go.kr answers its own
409
- // errors with HTTP 200 and a result code, and passing one through turns a
410
- // rejected key or an outage into a board that simply has no postings.
411
- const body = await response.text();
412
- const resultCode = parseResultCode(body);
413
- if (resultCode !== null && resultCode !== SUCCESS_RESULT_CODE$2) {
414
- const reason = `알리오 list returned resultCode ${resultCode}`;
415
- onError?.(reason);
416
- return new Response(reason, { status: 502, statusText: 'Bad Gateway' });
442
+ url = new URL(reminder.url);
443
+ if (!['http:', 'https:'].includes(url.protocol) ||
444
+ url.username ||
445
+ url.password)
446
+ return [];
447
+ if (deadline.timeZone)
448
+ new Intl.DateTimeFormat('en', { timeZone: deadline.timeZone });
449
+ const closingTime = isEvent ? deadline.endTime : deadline.time;
450
+ if (closingTime) {
451
+ const parts = new Intl.DateTimeFormat('en', {
452
+ timeZone: deadline.timeZone ?? 'Asia/Seoul',
453
+ year: 'numeric',
454
+ month: '2-digit',
455
+ day: '2-digit',
456
+ hour: '2-digit',
457
+ minute: '2-digit',
458
+ second: '2-digit',
459
+ hourCycle: 'h23',
460
+ }).formatToParts(now);
461
+ const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
462
+ const localNow = `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}:${values.second}`;
463
+ const closes = `${endDate} ${fullClock(closingTime)}`;
464
+ if (closes <= localNow)
465
+ return [];
417
466
  }
418
- return new Response(body, {
419
- status: 200,
420
- headers: { 'content-type': 'application/json' },
421
- });
422
467
  }
423
- if (url.pathname === '/recruitview.do') {
424
- const serial = url.searchParams.get('idx');
425
- if (serial) {
426
- return baseFetch(`${API_BASE$2}/detail?serviceKey=${apiKey}&resultType=json&sn=${serial}`, init);
427
- }
468
+ catch {
469
+ return [];
428
470
  }
429
- return baseFetch(input, init);
430
- };
431
- };
432
- function parseJson$2(body) {
433
- try {
434
- return JSON.parse(body);
435
- }
436
- catch {
437
- return null;
438
- }
471
+ return [
472
+ {
473
+ reminder,
474
+ days,
475
+ ms,
476
+ url: url.href.replace(/[()]/g, (value) => encodeURIComponent(value)),
477
+ },
478
+ ];
479
+ })
480
+ .sort((a, b) =>
481
+ // The fallback limit must not let older ongoing events displace
482
+ // today's or upcoming deadlines/events. Ongoing events fill spare rows.
483
+ Number(a.days < 0) - Number(b.days < 0) ||
484
+ a.ms - b.ms ||
485
+ (a.reminder.deadline.time ?? '23:59:59').localeCompare(b.reminder.deadline.time ?? '23:59:59'));
486
+ const seen = new Set();
487
+ return rows.flatMap(({ reminder, days, url }) => {
488
+ const d = reminder.deadline;
489
+ const key = JSON.stringify([
490
+ url,
491
+ d.type ?? 'deadline',
492
+ d.title,
493
+ d.kind,
494
+ d.date,
495
+ d.time,
496
+ d.endDate ?? null,
497
+ d.endTime ?? null,
498
+ ]);
499
+ if (seen.has(key))
500
+ return [];
501
+ seen.add(key);
502
+ return [{ reminder, days, url }];
503
+ });
439
504
  }
440
- /** Renders a posting's fields as the article body. */
441
- function renderAlioContent(record) {
442
- const lines = [
443
- ['기관', record.instNm],
444
- ['직무분야', record.ncsCdNmLst],
445
- ['고용형태', record.hireTypeNmLst],
446
- ['채용구분', record.recrutSeNm],
447
- ['근무지역', record.workRgnNmLst],
448
- ['모집인원', record.recrutNope ? `${record.recrutNope}명` : ''],
449
- [
450
- '공고기간',
451
- [record.pbancBgngYmd, record.pbancEndYmd]
452
- .map((value) => toIsoDate$2(value ?? ''))
453
- .filter(Boolean)
454
- .join(' - '),
455
- ],
456
- ['원문', record.srcUrl],
457
- ]
458
- .filter(([, value]) => value)
459
- .map(([label, value]) => `- **${label}**: ${String(value).trim()}`);
460
- const sections = [
461
- ['지원자격', record.aplyQlfcCn],
462
- ['우대사항', record.prefCn],
463
- ['전형방법', record.scrnprcdrMthdExpln],
464
- ]
465
- .filter(([, value]) => value?.trim())
466
- .flatMap(([label, value]) => [
467
- '',
468
- `### ${label}`,
469
- '',
470
- String(value).trim(),
471
- ]);
472
- return [`## ${record.recrutPbancTtl ?? ''}`, '', ...lines, ...sections]
473
- .join('\n')
474
- .trim();
505
+ /** Renders already eligible rows in the order given, up to the display limit. */
506
+ function formatDeadlineReminders(rows) {
507
+ const lines = rows
508
+ .slice(0, DEADLINE_REMINDER_LIMIT)
509
+ .map(({ reminder, days, url }) => {
510
+ const d = reminder.deadline;
511
+ const isEvent = d.type === 'event';
512
+ const time = d.time ? ` ${d.time}` : '';
513
+ const end = isEvent && d.endDate
514
+ ? d.endDate !== d.date
515
+ ? ` ~ ${d.endDate}${d.endTime ? ` ${d.endTime}` : ''}`
516
+ : d.endTime
517
+ ? ` ~ ${d.endTime}`
518
+ : ''
519
+ : '';
520
+ const zone = (d.time || (isEvent && d.endTime)) && d.timeZone
521
+ ? ` (${escapeLabel(d.timeZone)})`
522
+ : '';
523
+ const timing = days > 0
524
+ ? `D-${days}`
525
+ : days < 0
526
+ ? '진행 중'
527
+ : isEvent
528
+ ? /공개/.test(d.kind)
529
+ ? '오늘 공개'
530
+ : '오늘 개최'
531
+ : '오늘 마감';
532
+ const label = d.title.includes(d.kind)
533
+ ? d.title
534
+ : `${d.title} · ${d.kind}`;
535
+ return `| [${escapeLabel(label)}](${url}) | **${d.date}${time}${end}${zone} · ${timing}** |`;
536
+ });
537
+ return lines.length
538
+ ? `## ⏰ 다가오는 일정·마감\n\n| 안내 | 일정 |\n| --- | --- |\n${lines.join('\n')}`
539
+ : '';
475
540
  }
476
- /** Parses the aggregated list response, keeping only heritage-related postings. */
477
- const parseAlioList = (body) => {
478
- const parsed = parseJson$2(body);
479
- const posts = [];
480
- for (const record of parsed?.result ?? []) {
481
- const title = record.recrutPbancTtl?.trim();
482
- if (!title || record.recrutPblntSn == null) {
483
- continue;
541
+ /** Deterministic deadlines/events, no LLM context: the first rows by date. */
542
+ function renderVerifiedDeadlineReminders(reminders, publicationDate, now = new Date()) {
543
+ return formatDeadlineReminders(eligibleDeadlineReminders(reminders, publicationDate, now));
544
+ }
545
+
546
+ /**
547
+ * Asks for the indices to display, never for titles, dates or links.
548
+ *
549
+ * Rendering stays on the verified rows, so the model can only leave a row out;
550
+ * it cannot invent an action or alter one. Indices out of range or repeated
551
+ * are discarded rather than trusted. Duplicates are named separately so a short
552
+ * selection can be filled without restoring an event the model merged.
553
+ */
554
+ const SELECT_SCHEMA$1 = jsonSchema({
555
+ type: 'object',
556
+ properties: {
557
+ select: {
558
+ type: 'array',
559
+ items: { type: 'integer' },
560
+ description: '뉴스레터에 안내할 일정·마감 후보의 번호',
561
+ },
562
+ duplicates: {
563
+ type: 'array',
564
+ items: { type: 'integer' },
565
+ description: '고른 후보와 같은 행사·마감이라 뺀 후보의 번호',
566
+ },
567
+ },
568
+ required: ['select', 'duplicates'],
569
+ additionalProperties: false,
570
+ });
571
+ const systemPrompt$1 = (limit) => `너는 한국 고고학·문화유산 뉴스레터의 "다가오는 일정·마감" 안내를 고른다.
572
+
573
+ 독자는 고고학·문화유산 연구자, 발굴·조사기관 종사자, 학예 인력, 관련 전공 학생이다.
574
+ 후보는 모두 원문에서 다시 확인한 일정이다. 날짜·제목은 바꿀 수 없고, 너는 번호만 고른다.
575
+
576
+ 고르는 규칙:
577
+ - 최대 ${limit}개를 고른다. 같은 행사 중복을 빼고도 후보가 ${limit}개 이상 남으면 반드시 ${limit}개를 채운다.
578
+ - 같은 행사 중복을 뺀 후보가 ${limit}개 미만이면 중복만 빼고 모두 고른다. 후순위 일정도 자리가 남으면 뺄 이유가 없다.
579
+ - 같은 행사나 같은 마감을 가리키는 후보는 하나만 고르고, 나머지 번호는 duplicates에 넣는다. 게시 기관이 달라 제목 표현이 조금 달라도 날짜·시각과 내용이 같으면 같은 행사다.
580
+ - 시각이 다른 회차, 링크의 공고번호가 다른 공고는 제목이 같아도 서로 다른 일정이다. duplicates에 넣지 않는다.
581
+ - 독자가 행동할 수 있는 일정을 우선한다: 학술대회·발표·논문 신청, 공모·지원사업 신청, 채용 접수, 발굴 현장 공개, 발굴·시굴·지표조사와 국가유산 수리·보존처리 입찰, 강연·답사 참가 신청.
582
+ - 문화유산과 관련이 약한 일반 시설·장비·전산 입찰, 행사 운영 대행은 후순위로 둔다.
583
+ - 오늘 마감·개최는 마지막 기회이므로 중요한 것을 우선 포함한다. 다만 오늘 일정만으로 채우지 말고 D-1~D-3 일정도 고르게 포함해 독자가 미리 준비할 수 있게 한다.
584
+ - "진행 중"인 장기 전시·행사는 남는 자리에만 넣는다. 최근 여러 번 안내된 일정은 더 뒤로 미룬다.
585
+ - 번호의 순서는 상관없다. 표시 순서는 날짜순으로 따로 정해진다.`;
586
+ function timingOf({ days, reminder }) {
587
+ if (days > 0)
588
+ return `D-${days}`;
589
+ if (days < 0)
590
+ return '진행 중';
591
+ return reminder.deadline.type === 'event' ? '오늘 개최' : '오늘 마감';
592
+ }
593
+ function clockOf(date, time) {
594
+ return time ? `${date} ${time}` : date;
595
+ }
596
+ function buildUserPrompt$1(rows, publicationDate, limit) {
597
+ const lines = rows.map((row, index) => {
598
+ const { deadline, recentReminderCount } = row.reminder;
599
+ const start = clockOf(deadline.date, deadline.time);
600
+ const end = deadline.type === 'event' && deadline.endDate
601
+ ? deadline.endDate !== deadline.date
602
+ ? ` ~ ${clockOf(deadline.endDate, deadline.endTime)}`
603
+ : deadline.endTime
604
+ ? ` ~ ${deadline.endTime}`
605
+ : ''
606
+ : '';
607
+ const zone = deadline.timeZone ? ` (${deadline.timeZone})` : '';
608
+ const recent = recentReminderCount
609
+ ? ` · 최근 7일 ${recentReminderCount}회 안내`
610
+ : '';
611
+ // The full link carries notice numbers, which tell same-titled bids apart.
612
+ return `${index}. [${timingOf(row)}] ${start}${end}${zone} · ${deadline.type === 'event' ? '행사' : '마감'} · ${deadline.kind} · ${deadline.title.replace(/\s+/g, ' ')} · ${row.url}${recent}`;
613
+ });
614
+ return `발행일 ${publicationDate}. 다음 ${rows.length}건 중 안내할 일정을 최대 ${limit}개 골라 번호로 답하라.\n\n${lines.join('\n')}`;
615
+ }
616
+ /**
617
+ * Builds the model selection that replaces "first rows by date".
618
+ *
619
+ * Several sources often announce the same 학술대회, and a busy day can hold
620
+ * fifteen same-day bids, so the earliest rows are a poor proxy for what readers
621
+ * need. The model judges relevance and duplicates; everything that decides
622
+ * whether a row may appear at all stays in {@link eligibleDeadlineReminders}.
623
+ *
624
+ * It never fails the newsletter: an error, a timeout, an empty answer or
625
+ * unusable indices fall back to the first rows by date. A selection shorter
626
+ * than the rows available is filled in date order, skipping named duplicates.
627
+ */
628
+ const createDeadlineReminderSelector = (options) => {
629
+ const limit = DEADLINE_REMINDER_LIMIT;
630
+ const fallback = (rows, reason) => {
631
+ options.onFallback?.(reason, rows.length);
632
+ return rows.slice(0, limit);
633
+ };
634
+ return async (rows, publicationDate) => {
635
+ // One row leaves nothing to choose or deduplicate.
636
+ if (rows.length <= 1)
637
+ return rows;
638
+ const timeoutMs = options.timeoutMs ?? 60_000;
639
+ const controller = new AbortController();
640
+ let timer;
641
+ try {
642
+ // Abort is only a request; a model that ignores it would otherwise hold
643
+ // the save forever, so the race is what bounds the wait.
644
+ const { output, usage } = await Promise.race([
645
+ generateText({
646
+ model: options.model,
647
+ output: Output.object({ schema: SELECT_SCHEMA$1 }),
648
+ system: systemPrompt$1(limit),
649
+ prompt: buildUserPrompt$1(rows, publicationDate, limit),
650
+ abortSignal: controller.signal,
651
+ }),
652
+ new Promise((_, reject) => {
653
+ timer = setTimeout(() => {
654
+ controller.abort();
655
+ reject(new Error(`selection timed out after ${timeoutMs}ms`));
656
+ }, timeoutMs);
657
+ }),
658
+ ]);
659
+ const usable = (index) => Number.isInteger(index) && index >= 0 && index < rows.length;
660
+ const chosen = new Set();
661
+ for (const index of output.select) {
662
+ if (chosen.size === limit)
663
+ break;
664
+ if (usable(index))
665
+ chosen.add(index);
666
+ }
667
+ // Every candidate is a verified, current action, so an empty section is
668
+ // a malformed answer rather than a judgement that nothing matters.
669
+ if (!chosen.size)
670
+ return fallback(rows, 'no usable index in the selection');
671
+ const duplicates = new Set((output.duplicates ?? []).filter((index) => usable(index) && !chosen.has(index)));
672
+ // The prompt asks for a full section; a short answer is filled by date
673
+ // rather than trusted, but never with a row the model called a repeat.
674
+ let filledCount = 0;
675
+ for (let index = 0; index < rows.length; index++) {
676
+ if (chosen.size === limit)
677
+ break;
678
+ if (chosen.has(index) || duplicates.has(index))
679
+ continue;
680
+ chosen.add(index);
681
+ filledCount++;
682
+ }
683
+ options.onSelected?.({
684
+ candidateCount: rows.length,
685
+ selectedCount: chosen.size,
686
+ filledCount,
687
+ usage,
688
+ });
689
+ return rows.filter((_, index) => chosen.has(index));
484
690
  }
485
- const heritage = isHeritageJobCandidate({
486
- institution: record.instNm ?? '',
487
- title,
488
- categoryCodes: (record.ncsCdLst ?? '').split(',').filter(Boolean),
489
- });
490
- if (!heritage) {
491
- continue;
691
+ catch (error) {
692
+ return fallback(rows, error instanceof Error ? error.message : String(error));
693
+ }
694
+ finally {
695
+ clearTimeout(timer);
492
696
  }
493
- posts.push({
494
- uniqId: String(record.recrutPblntSn),
495
- title,
496
- date: toIsoDate$2(record.pbancBgngYmd ?? ''),
497
- detailUrl: buildAlioDetailUrl(record.recrutPblntSn),
498
- dateType: DateType.REGISTERED,
499
- });
500
- }
501
- return posts;
502
- };
503
- /** Parses a `/detail` response into the article body. */
504
- const parseAlioDetail = (body) => {
505
- const parsed = parseJson$2(body);
506
- const record = parsed?.result;
507
- return {
508
- detailContent: record ? renderAlioContent(record) : '',
509
- hasAttachedFile: true,
510
- hasAttachedImage: false,
511
697
  };
512
698
  };
513
699
 
514
700
  /**
515
- * Formats a date string by replacing dots with dashes.
516
- * If the string contains a newline (indicating a date range),
517
- * it formats it as "start ~ end".
701
+ * Shares one call of the application's source between the crawl, which turns
702
+ * issues into articles, and generation, which renders them as tables.
518
703
  *
519
- * Examples:
520
- * - "2024.01.15" → "2024-01-15"
521
- * - "2024.01.15\n2024.01.20" → "2024-01-15 ~ 2024-01-20"
704
+ * A rejected call is forgotten, so a failure while crawling does not decide
705
+ * what generation sees: the next caller asks the source again. A call that
706
+ * does not settle within `timeoutMs` is rejected and forgotten the same way,
707
+ * so a stalled source cannot hold generation, which has no request timeout of
708
+ * its own.
522
709
  *
523
- * @param str The date string to format
524
- * @returns The formatted date string with dashes instead of dots
710
+ * @param timeoutMs - Milliseconds before a source call is given up
525
711
  */
526
- function getDate(str) {
527
- if (str.includes('\n')) {
528
- const textArr = str.split('\n');
529
- return `${textArr[0]} ~ ${textArr[1].trim()}`.replaceAll('.', '-');
530
- }
531
- return str.replaceAll('.', '-');
712
+ function createJournalIssueLoader(source, timeoutMs = 60_000) {
713
+ let pending = null;
714
+ return () => {
715
+ if (pending)
716
+ return pending;
717
+ let timer;
718
+ const call = Promise.race([
719
+ source(),
720
+ new Promise((_, reject) => {
721
+ timer = setTimeout(() => reject(new Error(`journal issue source timed out after ${timeoutMs}ms`)), timeoutMs);
722
+ }),
723
+ ])
724
+ .catch((error) => {
725
+ if (pending === call)
726
+ pending = null;
727
+ throw error;
728
+ })
729
+ .finally(() => clearTimeout(timer));
730
+ pending = call;
731
+ return call;
732
+ };
532
733
  }
734
+
533
735
  /**
534
- * Removes unnecessary parts from a URL such as session IDs and pagination parameters.
535
- * The following items are removed:
536
- * - Session IDs like ;jsessionid=xxx
537
- * - Query parameters: pageIndex, pageUnit, strWhere, searchWrd, sdate, edate
538
- *
539
- * Example: https://example.com/path;jsessionid=123456?id=123&pageIndex=1 → https://example.com/path?id=123
736
+ * Asks for paper indices, never for titles or authors.
540
737
  *
541
- * @param url The URL string to clean
542
- * @returns The cleaned URL with unnecessary parts removed
738
+ * Rendering stays on the injected papers, so the model can only choose and
739
+ * order them; it cannot rename one or alter its authors. The only text it
740
+ * supplies is the short topic label of a paper it left out of the table.
543
741
  */
544
- function cleanUrl(url) {
545
- if (!url) {
546
- return url;
547
- }
548
- try {
549
- // Remove all session ID information from semicolon (;) to before question mark (?) or hash (#)
550
- let cleaned = url.replace(/;[^?#]*/g, '');
551
- // Create URL object for parsing
552
- const urlObj = new URL(cleaned);
553
- // List of parameters to remove
554
- const paramsToRemove = [
555
- 'pageIndex',
556
- 'pageUnit',
557
- 'strWhere',
558
- 'searchWrd',
559
- 'sdate',
560
- 'edate',
561
- ];
562
- // Remove each unnecessary parameter
563
- paramsToRemove.forEach((param) => {
564
- urlObj.searchParams.delete(param);
565
- });
566
- // Return the cleaned URL string
567
- cleaned = urlObj.toString();
568
- return cleaned;
569
- }
570
- catch {
571
- return url; // Return original URL if an error occurs
572
- }
742
+ const SELECT_SCHEMA = jsonSchema({
743
+ type: 'object',
744
+ properties: {
745
+ featured: {
746
+ type: 'array',
747
+ items: { type: 'integer' },
748
+ description: '독자가 관심 가질 논문 번호. 관심이 클 것부터',
749
+ },
750
+ others: {
751
+ type: 'array',
752
+ items: {
753
+ type: 'object',
754
+ properties: {
755
+ index: { type: 'integer' },
756
+ topic: {
757
+ type: 'string',
758
+ description: '논문 주제를 2-12자로 요약한 명사구',
759
+ },
760
+ },
761
+ required: ['index', 'topic'],
762
+ additionalProperties: false,
763
+ },
764
+ description: '독자의 관심사에서 멀어 요약만 할 논문',
765
+ },
766
+ },
767
+ required: ['featured', 'others'],
768
+ additionalProperties: false,
769
+ });
770
+ const systemPrompt = (audience) => `너는 ${audience}에게 보내는 뉴스레터에서 학술지 신간 논문 중 무엇을 표로 소개할지 고른다.
771
+
772
+ 기준은 학문 분야가 아니라 **${audience}이(가) 이 논문을 찾아 읽어볼 만큼 관심을 가질까**다.
773
+ 제목·저자는 바꿀 수 없고, 너는 번호만 고른다. 모든 논문을 featured나 others 중 정확히 한 곳에 넣는다.
774
+
775
+ - featured: 독자가 관심을 가질 논문. 관심이 클 것부터 순서대로 넣는다.
776
+ - 고고학이 아니어도 독자의 연구·실무에 닿으면 넣는다. 예: 고대 환경·기후 복원, 연대측정·성분분석 같은 분석 기법,
777
+ 인골·동물 유존체, 고지도·지명 연구, 전통 건축·토목 기술, 유적·유물을 다루는 문헌사·미술사, 매장유산 제도·정책,
778
+ 문화유산 보존처리, 디지털 기록·GIS·AI의 유산 적용
779
+ - 다루는 대상이 독자의 관심 시대·지역·자료와 직접 맞닿는지 본다.
780
+ - others: 독자의 관심사에서 멀어 제목을 나열할 필요가 없는 논문. topic에 주제를 2-12자 명사구로 쓴다.
781
+ - 역사학·인문학이라도 독자와 거리가 멀면 여기에 넣는다. 예: 근현대 외교·정치사, 사상사·철학, 현대 문학 비평,
782
+ 현대 사회·경제·교육·관광 정책, 유산과 무관한 언어학
783
+ - 애매하면 featured에 넣는다. others는 독자가 거의 찾아보지 않을 논문만이다.`;
784
+ function buildUserPrompt(issue) {
785
+ const lines = issue.papers.map((paper, index) => {
786
+ const keywords = [
787
+ ...new Set(paper.keywords.map((k) => k.trim()).filter(Boolean)),
788
+ ].join(', ');
789
+ const abstract = [...(paper.abstract ?? '').replace(/\s+/g, ' ').trim()]
790
+ .slice(0, 200)
791
+ .join('');
792
+ return `${index}. ${paper.title.replace(/\s+/g, ' ').trim()}${keywords ? ` · 키워드: ${keywords}` : ''}${abstract ? ` · 초록: ${abstract}` : ''}`;
793
+ });
794
+ return `학술지 「${issue.journalName.trim()}」 ${issue.publishedYear}년 ${issue.publishedMonth}월 호의 논문 ${issue.papers.length}편을 나눠라.\n\n${lines.join('\n')}`;
573
795
  }
574
-
575
- const parseBuyeoMuseumList = (html, listId) => {
576
- const $ = cheerio.load(html);
577
- const posts = [];
578
- const baseUrl = 'https://buyeo.museum.go.kr';
579
- $('table.tableType1 tbody tr').each((index, element) => {
580
- const columns = $(element).find('td');
581
- if (columns.length === 0) {
582
- return;
796
+ function normalizeTopic(topic) {
797
+ const normalized = topic.replace(/\s+/g, ' ').trim();
798
+ return normalized && [...normalized].length <= 30 ? normalized : null;
799
+ }
800
+ /**
801
+ * Builds the selector that shows an issue's papers its readers would care
802
+ * about as a table, most interesting first, and collapses the rest into a
803
+ * topic summary.
804
+ *
805
+ * It never fails the newsletter: an error, a timeout or an answer with no
806
+ * usable index falls back to null, and the section lists every paper. A paper
807
+ * the model left out, named in both lists or summarized twice is shown in the
808
+ * table after the chosen ones rather than collapsed, so a malformed answer can
809
+ * only show more, never hide a paper.
810
+ */
811
+ const createJournalPaperSelector = (options) => {
812
+ const fallback = (issue, reason) => {
813
+ options.onFallback?.(reason, issue);
814
+ return null;
815
+ };
816
+ return async (issue) => {
817
+ if (issue.papers.length === 0)
818
+ return { featured: [], others: [] };
819
+ const timeoutMs = options.timeoutMs ?? 60_000;
820
+ const controller = new AbortController();
821
+ let timer;
822
+ try {
823
+ const { output } = await Promise.race([
824
+ generateText({
825
+ model: options.model,
826
+ output: Output.object({ schema: SELECT_SCHEMA }),
827
+ system: systemPrompt(options.audience),
828
+ prompt: buildUserPrompt(issue),
829
+ abortSignal: controller.signal,
830
+ }),
831
+ new Promise((_, reject) => {
832
+ timer = setTimeout(() => {
833
+ controller.abort();
834
+ reject(new Error(`selection timed out after ${timeoutMs}ms`));
835
+ }, timeoutMs);
836
+ }),
837
+ ]);
838
+ const count = issue.papers.length;
839
+ const usable = (index) => Number.isInteger(index) && index >= 0 && index < count;
840
+ const featured = [];
841
+ for (const index of output.featured ?? [])
842
+ if (usable(index) && !featured.includes(index))
843
+ featured.push(index);
844
+ const topics = new Map();
845
+ const repeated = new Set();
846
+ for (const { index, topic } of output.others ?? []) {
847
+ if (!usable(index) || featured.includes(index))
848
+ continue;
849
+ if (topics.has(index))
850
+ repeated.add(index);
851
+ else
852
+ topics.set(index, normalizeTopic(topic));
853
+ }
854
+ // A paper summarized twice is ambiguous, so it is shown rather than hidden.
855
+ for (const index of repeated)
856
+ topics.delete(index);
857
+ if (featured.length === 0 && topics.size === 0)
858
+ return fallback(issue, 'no usable index in the selection');
859
+ for (let index = 0; index < count; index++)
860
+ if (!featured.includes(index) && !topics.has(index))
861
+ featured.push(index);
862
+ return {
863
+ featured,
864
+ others: [...topics]
865
+ .map(([index, topic]) => ({ index, topic }))
866
+ .sort((a, b) => a.index - b.index),
867
+ };
583
868
  }
584
- const titleElement = columns.eq(1).find('a');
585
- const uniqId = getUniqIdFromBuyeoMuseum(columns.eq(1));
586
- const detailUrl = `${baseUrl}/bbs/view.do?pstSn=${uniqId}&key=${listId}`;
587
- const title = titleElement
588
- .clone() // 원본을 수정하지 않도록 복사
589
- .find('span, i') // span과 i 태그 선택
590
- .remove() // 제거
591
- .end() // 원래 요소로 돌아감
592
- .text() // 텍스트 추출
593
- .trim() ||
594
- titleElement.attr('title')?.trim() ||
595
- '';
596
- const date = getDate(columns.eq(4).text().trim());
597
- posts.push({
598
- uniqId,
599
- title,
600
- date,
601
- detailUrl: cleanUrl(detailUrl),
602
- dateType: DateType.REGISTERED,
603
- });
604
- });
605
- return posts;
606
- };
607
- const parseBuyeoMuseumDetail = (html) => {
608
- const $ = cheerio.load(html);
609
- const content = $('div.cont');
610
- return {
611
- detailContent: new TurndownService().turndown(content.html() ?? ''),
612
- hasAttachedFile: $('div.attachmentWrap ul.noList').length === 0,
613
- hasAttachedImage: content.find('img').length > 0,
614
- };
615
- };
616
- function getUniqIdFromBuyeoMuseum(element) {
617
- return (element.attr('onclick') ?? '').match(/goView\('(.*)'\)/)?.[1] ?? '';
618
- }
619
-
620
- const parseCheongjuMuseumList = (html) => {
621
- const $ = cheerio.load(html);
622
- const posts = [];
623
- const baseUrl = 'https://cheongju.museum.go.kr';
624
- $('table.bbs_default_list tbody tr').each((index, element) => {
625
- const columns = $(element).find('td');
626
- if (columns.length === 0) {
627
- return;
869
+ catch (error) {
870
+ return fallback(issue, error instanceof Error ? error.message : String(error));
628
871
  }
629
- const titleElement = columns.eq(1).find('a');
630
- const relativeHref = titleElement.attr('href');
631
- if (!relativeHref) {
632
- return;
872
+ finally {
873
+ clearTimeout(timer);
633
874
  }
634
- const fullUrl = new URL(relativeHref.replace('./', '/www/'), baseUrl);
635
- const detailUrl = fullUrl.href;
636
- const uniqId = fullUrl.searchParams.get('nttNo') ?? undefined;
637
- const title = titleElement.text()?.trim() ?? '';
638
- const date = getDate(columns.eq(4).text().trim());
639
- posts.push({
640
- uniqId,
641
- title,
642
- date,
643
- detailUrl: cleanUrl(detailUrl),
644
- dateType: DateType.REGISTERED,
645
- });
646
- });
647
- return posts;
648
- };
649
- const parseCheongjuMuseumDetail = (html) => {
650
- const $ = cheerio.load(html);
651
- const content = $('td.content');
652
- return {
653
- detailContent: new TurndownService().turndown(content.html() ?? ''),
654
- hasAttachedFile: $('tr.FILE td p').length > 0,
655
- hasAttachedImage: content.find('img').length > 0,
656
875
  };
657
876
  };
658
877
 
659
- const EXCAVATION_BASE_URL = 'https://www.e-minwon.go.kr';
660
- /** List page of the 국가유산청 발굴조사 보고서 board. */
661
- const EXCAVATION_REPORT_LIST_URL = `${EXCAVATION_BASE_URL}/ge/ee/getListEcexmRptp.do`;
662
- /** Public detail URL for one report, keyed by its board id (`ecexmRcno`). */
663
- const buildExcavationReportDetailUrl = (externalId) => `${EXCAVATION_BASE_URL}/ge/ee/getEcexmRptp.do?ecexmRcno=${externalId}`;
664
878
  /**
665
- * Marks a response body as injected report data rather than scraped HTML, so
666
- * the parsers below can tell the two apart without guessing.
879
+ * Reads what data.go.kr said when it refused a request.
880
+ *
881
+ * Its gateway answers a refusal with HTTP 400 and an XML envelope, whatever
882
+ * format the service itself speaks. The envelope names the cause — a spent
883
+ * daily quota, an unregistered key, a withdrawn service and a denied caller
884
+ * are all different `returnReasonCode`s — but an adapter that reports only the
885
+ * status throws that away.
886
+ *
887
+ * It cost a week to learn that. A nightly run failed at the same minute for
888
+ * days with nothing in the log but `Request failed (status=502)`, and the
889
+ * reason the gateway had supplied each time was discarded before anyone could
890
+ * read it.
667
891
  */
668
- const INJECTED_MARKER = '@heripo/research-radar:excavation-reports';
669
- function parseInjectedPayload(body) {
670
- if (!body.includes(INJECTED_MARKER)) {
671
- return null;
892
+ function describeOpenDataError(body) {
893
+ const read = (tag) => new RegExp(`<${tag}>\\s*([^<]*)</${tag}>`).exec(body)?.[1]?.trim();
894
+ const parts = [
895
+ read('errMsg'),
896
+ read('returnReasonCode') && `code ${read('returnReasonCode')}`,
897
+ read('returnAuthMsg'),
898
+ ].filter((part) => Boolean(part));
899
+ if (parts.length > 0) {
900
+ return parts.join(' / ');
672
901
  }
902
+ // Not the documented envelope. A short body is still worth quoting; a long
903
+ // one is a page rather than an error and only adds noise to the log.
904
+ const trimmed = body.trim().replace(/\s+/g, ' ');
905
+ return trimmed.length > 0 && trimmed.length <= 200 ? trimmed : null;
906
+ }
907
+
908
+ const API_BASE$2 = 'https://apis.data.go.kr/1051000/recruitment';
909
+ const SITE_BASE$2 = 'https://job.alio.go.kr';
910
+ /**
911
+ * Public 알리오 board URL used as this target's list page.
912
+ *
913
+ * As with 나라일터, core fetches this URL and `createAlioFetch` answers it from
914
+ * the 재정경제부 open API, keeping the service key out of the configuration.
915
+ */
916
+ const ALIO_LIST_URL = `${SITE_BASE$2}/recruit.do`;
917
+ /** Public posting URL. */
918
+ const buildAlioDetailUrl = (serial) => `${SITE_BASE$2}/recruitview.do?idx=${serial}`;
919
+ /** `yyyymmdd` to ISO `yyyy-mm-dd`. */
920
+ function toIsoDate$2(compact) {
921
+ return /^\d{8}$/.test(compact)
922
+ ? `${compact.slice(0, 4)}-${compact.slice(4, 6)}-${compact.slice(6, 8)}`
923
+ : '';
924
+ }
925
+ /** `resultCode` this service returns on success. */
926
+ const SUCCESS_RESULT_CODE$2 = 200;
927
+ function parseResultCode(body) {
673
928
  try {
674
929
  const parsed = JSON.parse(body);
675
- return parsed.marker === INJECTED_MARKER ? parsed : null;
930
+ return typeof parsed.resultCode === 'number' ? parsed.resultCode : null;
676
931
  }
677
932
  catch {
678
933
  return null;
679
934
  }
680
935
  }
681
- function jsonResponse$1(payload) {
682
- return new Response(JSON.stringify(payload), {
683
- status: 200,
684
- headers: { 'content-type': 'application/json' },
685
- });
686
- }
687
936
  /**
688
- * Serves the 발굴조사 보고서 board from an injected source instead of the live
689
- * site, leaving every other request untouched.
937
+ * Serves the 알리오 target from the 재정경제부 open API.
690
938
  *
691
- * Core's crawling chain always fetches a target's list URL and then each detail
692
- * URL, so the substitution happens at the fetch layer — the same seam
693
- * `createKrasFetch` uses. `source` is called once and its result reused for the
694
- * detail requests that follow.
939
+ * This board only covers 공기업 and 준정부기관, so heritage postings are rare —
940
+ * 국가유산청 and the national museums publish through 나라일터 instead. It is
941
+ * collected anyway because a body like 국립농업박물관 does appear here, and the
942
+ * NCS job codes make filtering cheap and precise.
695
943
  *
696
- * @param baseFetch - Fetch to delegate every other request to
697
- * @param source - Supplies the reports for this run
944
+ * Only postings still open (`ongoingYn=Y`) are requested.
698
945
  */
699
- const createExcavationReportFetch = (baseFetch = fetch, source) => {
700
- let pending = null;
701
- const loadReports = () => (pending ??= source());
946
+ const createAlioFetch = (baseFetch = fetch, options) => {
947
+ const { apiKey, rowsPerPage = 3000, onError } = options;
702
948
  return async (input, init) => {
703
949
  const requestUrl = typeof input === 'string'
704
950
  ? input
705
951
  : input instanceof URL
706
952
  ? input.href
707
953
  : input.url;
708
- const url = new URL(requestUrl, EXCAVATION_BASE_URL);
709
- if (url.origin !== new URL(EXCAVATION_BASE_URL).origin) {
954
+ let url;
955
+ try {
956
+ url = new URL(requestUrl);
957
+ }
958
+ catch {
710
959
  return baseFetch(input, init);
711
960
  }
712
- if (url.pathname === new URL(EXCAVATION_REPORT_LIST_URL).pathname) {
713
- const reports = await loadReports();
714
- return jsonResponse$1({
715
- marker: INJECTED_MARKER,
716
- reports,
717
- });
961
+ if (url.origin !== SITE_BASE$2) {
962
+ return baseFetch(input, init);
718
963
  }
719
- if (url.pathname === '/ge/ee/getEcexmRptp.do') {
720
- const externalId = url.searchParams.get('ecexmRcno');
721
- const report = (await loadReports()).find((candidate) => candidate.externalId === externalId);
722
- if (report) {
723
- return jsonResponse$1({
724
- marker: INJECTED_MARKER,
725
- report,
964
+ if (!apiKey) {
965
+ // Without a key the board is simply not collected. See gojobs.parser.ts.
966
+ return Response.json({ result: [] });
967
+ }
968
+ if (url.pathname === '/recruit.do') {
969
+ const response = await baseFetch(`${API_BASE$2}/list?serviceKey=${apiKey}&resultType=json` +
970
+ `&numOfRows=${rowsPerPage}&pageNo=1&ongoingYn=Y`, init);
971
+ if (!response.ok) {
972
+ // See the 나라일터 adapter: keep the upstream status, report the reason.
973
+ const body = await response.text();
974
+ const detail = describeOpenDataError(body);
975
+ onError?.(`알리오 list failed with HTTP ${response.status}` +
976
+ (detail ? ` — ${detail}` : ''));
977
+ return new Response(body, {
978
+ status: response.status,
979
+ statusText: response.statusText,
726
980
  });
727
981
  }
982
+ // Same reasoning as the 나라일터 adapter: data.go.kr answers its own
983
+ // errors with HTTP 200 and a result code, and passing one through turns a
984
+ // rejected key or an outage into a board that simply has no postings.
985
+ const body = await response.text();
986
+ const resultCode = parseResultCode(body);
987
+ if (resultCode !== null && resultCode !== SUCCESS_RESULT_CODE$2) {
988
+ const reason = `알리오 list returned resultCode ${resultCode}`;
989
+ onError?.(reason);
990
+ return new Response(reason, { status: 502, statusText: 'Bad Gateway' });
991
+ }
992
+ return new Response(body, {
993
+ status: 200,
994
+ headers: { 'content-type': 'application/json' },
995
+ });
996
+ }
997
+ if (url.pathname === '/recruitview.do') {
998
+ const serial = url.searchParams.get('idx');
999
+ if (serial) {
1000
+ return baseFetch(`${API_BASE$2}/detail?serviceKey=${apiKey}&resultType=json&sn=${serial}`, init);
1001
+ }
728
1002
  }
729
1003
  return baseFetch(input, init);
730
1004
  };
731
1005
  };
732
- /** Renders a report's fields as the article body. */
733
- function renderExcavationReportContent(report) {
734
- const lines = Object.entries(report.fields)
735
- .filter(([, value]) => value != null && String(value).trim() !== '')
1006
+ function parseJson$2(body) {
1007
+ try {
1008
+ return JSON.parse(body);
1009
+ }
1010
+ catch {
1011
+ return null;
1012
+ }
1013
+ }
1014
+ /** Renders a posting's fields as the article body. */
1015
+ function renderAlioContent(record) {
1016
+ const lines = [
1017
+ ['기관', record.instNm],
1018
+ ['직무분야', record.ncsCdNmLst],
1019
+ ['고용형태', record.hireTypeNmLst],
1020
+ ['채용구분', record.recrutSeNm],
1021
+ ['근무지역', record.workRgnNmLst],
1022
+ ['모집인원', record.recrutNope ? `${record.recrutNope}명` : ''],
1023
+ [
1024
+ '공고기간',
1025
+ [record.pbancBgngYmd, record.pbancEndYmd]
1026
+ .map((value) => toIsoDate$2(value ?? ''))
1027
+ .filter(Boolean)
1028
+ .join(' - '),
1029
+ ],
1030
+ ['원문', record.srcUrl],
1031
+ ]
1032
+ .filter(([, value]) => value)
736
1033
  .map(([label, value]) => `- **${label}**: ${String(value).trim()}`);
737
- return ['## 발굴조사 보고서 정보', '', ...lines].join('\n');
1034
+ const sections = [
1035
+ ['지원자격', record.aplyQlfcCn],
1036
+ ['우대사항', record.prefCn],
1037
+ ['전형방법', record.scrnprcdrMthdExpln],
1038
+ ]
1039
+ .filter(([, value]) => value?.trim())
1040
+ .flatMap(([label, value]) => [
1041
+ '',
1042
+ `### ${label}`,
1043
+ '',
1044
+ String(value).trim(),
1045
+ ]);
1046
+ return [`## ${record.recrutPbancTtl ?? ''}`, '', ...lines, ...sections]
1047
+ .join('\n')
1048
+ .trim();
738
1049
  }
739
- const parseExcavationReportList = (html) => {
740
- const injected = parseInjectedPayload(html);
741
- if (injected) {
742
- return injected.reports.map((report) => ({
743
- uniqId: report.externalId,
744
- title: report.title,
745
- date: report.submittedDate,
746
- detailUrl: buildExcavationReportDetailUrl(report.externalId),
1050
+ /** Parses the aggregated list response, keeping only heritage-related postings. */
1051
+ const parseAlioList = (body) => {
1052
+ const parsed = parseJson$2(body);
1053
+ const posts = [];
1054
+ for (const record of parsed?.result ?? []) {
1055
+ const title = record.recrutPbancTtl?.trim();
1056
+ if (!title || record.recrutPblntSn == null) {
1057
+ continue;
1058
+ }
1059
+ const heritage = isHeritageJobCandidate({
1060
+ institution: record.instNm ?? '',
1061
+ title,
1062
+ categoryCodes: (record.ncsCdLst ?? '').split(',').filter(Boolean),
1063
+ });
1064
+ if (!heritage) {
1065
+ continue;
1066
+ }
1067
+ posts.push({
1068
+ uniqId: String(record.recrutPblntSn),
1069
+ title,
1070
+ date: toIsoDate$2(record.pbancBgngYmd ?? ''),
1071
+ detailUrl: buildAlioDetailUrl(record.recrutPblntSn),
747
1072
  dateType: DateType.REGISTERED,
748
- }));
1073
+ });
1074
+ }
1075
+ return posts;
1076
+ };
1077
+ /** Parses a `/detail` response into the article body. */
1078
+ const parseAlioDetail = (body) => {
1079
+ const parsed = parseJson$2(body);
1080
+ const record = parsed?.result;
1081
+ return {
1082
+ detailContent: record ? renderAlioContent(record) : '',
1083
+ hasAttachedFile: true,
1084
+ hasAttachedImage: false,
1085
+ };
1086
+ };
1087
+
1088
+ /**
1089
+ * Formats a date string by replacing dots with dashes.
1090
+ * If the string contains a newline (indicating a date range),
1091
+ * it formats it as "start ~ end".
1092
+ *
1093
+ * Examples:
1094
+ * - "2024.01.15" → "2024-01-15"
1095
+ * - "2024.01.15\n2024.01.20" → "2024-01-15 ~ 2024-01-20"
1096
+ *
1097
+ * @param str The date string to format
1098
+ * @returns The formatted date string with dashes instead of dots
1099
+ */
1100
+ function getDate(str) {
1101
+ if (str.includes('\n')) {
1102
+ const textArr = str.split('\n');
1103
+ return `${textArr[0]} ~ ${textArr[1].trim()}`.replaceAll('.', '-');
1104
+ }
1105
+ return str.replaceAll('.', '-');
1106
+ }
1107
+ /**
1108
+ * Removes unnecessary parts from a URL such as session IDs and pagination parameters.
1109
+ * The following items are removed:
1110
+ * - Session IDs like ;jsessionid=xxx
1111
+ * - Query parameters: pageIndex, pageUnit, strWhere, searchWrd, sdate, edate
1112
+ *
1113
+ * Example: https://example.com/path;jsessionid=123456?id=123&pageIndex=1 → https://example.com/path?id=123
1114
+ *
1115
+ * @param url The URL string to clean
1116
+ * @returns The cleaned URL with unnecessary parts removed
1117
+ */
1118
+ function cleanUrl(url) {
1119
+ if (!url) {
1120
+ return url;
1121
+ }
1122
+ try {
1123
+ // Remove all session ID information from semicolon (;) to before question mark (?) or hash (#)
1124
+ let cleaned = url.replace(/;[^?#]*/g, '');
1125
+ // Create URL object for parsing
1126
+ const urlObj = new URL(cleaned);
1127
+ // List of parameters to remove
1128
+ const paramsToRemove = [
1129
+ 'pageIndex',
1130
+ 'pageUnit',
1131
+ 'strWhere',
1132
+ 'searchWrd',
1133
+ 'sdate',
1134
+ 'edate',
1135
+ ];
1136
+ // Remove each unnecessary parameter
1137
+ paramsToRemove.forEach((param) => {
1138
+ urlObj.searchParams.delete(param);
1139
+ });
1140
+ // Return the cleaned URL string
1141
+ cleaned = urlObj.toString();
1142
+ return cleaned;
749
1143
  }
1144
+ catch {
1145
+ return url; // Return original URL if an error occurs
1146
+ }
1147
+ }
1148
+
1149
+ const parseBuyeoMuseumList = (html, listId) => {
750
1150
  const $ = cheerio.load(html);
751
1151
  const posts = [];
752
- const baseUrl = 'https://www.e-minwon.go.kr';
753
- $('table.td_left tbody tr.list_tr').each((index, element) => {
1152
+ const baseUrl = 'https://buyeo.museum.go.kr';
1153
+ $('table.tableType1 tbody tr').each((index, element) => {
754
1154
  const columns = $(element).find('td');
755
1155
  if (columns.length === 0) {
756
1156
  return;
757
1157
  }
758
- const titleElement = columns.eq(2).find('a');
759
- const relativeHref = titleElement.attr('href');
760
- if (!relativeHref) {
761
- return;
762
- }
763
- const uniqId = getUniqIdFromExcavationItem(titleElement);
764
- const title = titleElement.attr('title')?.trim() ?? titleElement.text().trim() ?? '';
765
- const date = getDate(columns.eq(6).text().trim());
766
- const detailUrl = `${baseUrl}/ge/ee/getEcexmRptp.do?ecexmRcno=${uniqId}`;
1158
+ const titleElement = columns.eq(1).find('a');
1159
+ const uniqId = getUniqIdFromBuyeoMuseum(columns.eq(1));
1160
+ const detailUrl = `${baseUrl}/bbs/view.do?pstSn=${uniqId}&key=${listId}`;
1161
+ const title = titleElement
1162
+ .clone() // 원본을 수정하지 않도록 복사
1163
+ .find('span, i') // span과 i 태그 선택
1164
+ .remove() // 제거
1165
+ .end() // 원래 요소로 돌아감
1166
+ .text() // 텍스트 추출
1167
+ .trim() ||
1168
+ titleElement.attr('title')?.trim() ||
1169
+ '';
1170
+ const date = getDate(columns.eq(4).text().trim());
767
1171
  posts.push({
768
1172
  uniqId,
769
1173
  title,
770
1174
  date,
771
- detailUrl,
1175
+ detailUrl: cleanUrl(detailUrl),
772
1176
  dateType: DateType.REGISTERED,
773
1177
  });
774
1178
  });
775
1179
  return posts;
776
1180
  };
777
- const parseExcavationSiteList = (html) => {
1181
+ const parseBuyeoMuseumDetail = (html) => {
1182
+ const $ = cheerio.load(html);
1183
+ const content = $('div.cont');
1184
+ return {
1185
+ detailContent: new TurndownService().turndown(content.html() ?? ''),
1186
+ hasAttachedFile: $('div.attachmentWrap ul.noList').length === 0,
1187
+ hasAttachedImage: content.find('img').length > 0,
1188
+ };
1189
+ };
1190
+ function getUniqIdFromBuyeoMuseum(element) {
1191
+ return (element.attr('onclick') ?? '').match(/goView\('(.*)'\)/)?.[1] ?? '';
1192
+ }
1193
+
1194
+ const parseCheongjuMuseumList = (html) => {
778
1195
  const $ = cheerio.load(html);
779
1196
  const posts = [];
780
- const baseUrl = 'https://www.e-minwon.go.kr';
781
- $('table.td_left tbody tr.list_tr').each((index, element) => {
1197
+ const baseUrl = 'https://cheongju.museum.go.kr';
1198
+ $('table.bbs_default_list tbody tr').each((index, element) => {
782
1199
  const columns = $(element).find('td');
783
1200
  if (columns.length === 0) {
784
1201
  return;
@@ -788,106 +1205,263 @@ const parseExcavationSiteList = (html) => {
788
1205
  if (!relativeHref) {
789
1206
  return;
790
1207
  }
791
- const uniqId = getUniqIdFromExcavationItem(titleElement);
792
- const title = titleElement.attr('title')?.trim() ?? titleElement.text().trim() ?? '';
1208
+ const fullUrl = new URL(relativeHref.replace('./', '/www/'), baseUrl);
1209
+ const detailUrl = fullUrl.href;
1210
+ const uniqId = fullUrl.searchParams.get('nttNo') ?? undefined;
1211
+ const title = titleElement.text()?.trim() ?? '';
793
1212
  const date = getDate(columns.eq(4).text().trim());
794
- const detailUrl = `${baseUrl}/ge/ee/getLinkGrndsRls.do?grndsRlsSeqc=${uniqId}`;
795
1213
  posts.push({
796
1214
  uniqId,
797
1215
  title,
798
1216
  date,
799
- detailUrl,
800
- dateType: DateType.DURATION,
1217
+ detailUrl: cleanUrl(detailUrl),
1218
+ dateType: DateType.REGISTERED,
801
1219
  });
802
1220
  });
803
1221
  return posts;
804
1222
  };
805
- const parseExcavationReportDetail = (html) => {
806
- const injected = parseInjectedPayload(html);
807
- if (injected) {
808
- return {
809
- detailContent: renderExcavationReportContent(injected.report),
810
- hasAttachedFile: injected.report.hasAttachedFile ?? true,
811
- hasAttachedImage: false,
812
- };
813
- }
814
- const $ = cheerio.load(html);
815
- const content = $('table.td_left').parent();
816
- const trList = content.find('table tbody tr');
817
- trList.each((index, element) => {
818
- if (trList.length === index + 1) {
819
- $(element).remove();
820
- }
821
- });
822
- return {
823
- detailContent: new TurndownService().turndown(content.html() ?? ''),
824
- hasAttachedFile: true,
825
- hasAttachedImage: false,
826
- };
827
- };
828
- const parseExcavationSiteDetail = (html) => {
1223
+ const parseCheongjuMuseumDetail = (html) => {
829
1224
  const $ = cheerio.load(html);
830
- const content = $('div.board_view').parent();
831
- const dlList = content.find('div dl');
832
- dlList.each((index, element) => {
833
- if (dlList.length === index + 1) {
834
- $(element).remove();
835
- }
836
- });
1225
+ const content = $('td.content');
837
1226
  return {
838
1227
  detailContent: new TurndownService().turndown(content.html() ?? ''),
839
- hasAttachedFile: true,
840
- hasAttachedImage: false,
1228
+ hasAttachedFile: $('tr.FILE td p').length > 0,
1229
+ hasAttachedImage: content.find('img').length > 0,
841
1230
  };
842
1231
  };
843
- function getUniqIdFromExcavationItem(element) {
844
- return ((element.attr('onclick') ?? '').match(/dataSelected\('(.*)'\)/)?.[1] ?? '');
845
- }
846
1232
 
847
- const API_BASE$1 = 'https://apis.data.go.kr/1230000/ad/BidPublicInfoService';
848
- const SITE_BASE$1 = 'https://www.g2b.go.kr';
849
- /**
850
- * Public 나라장터 board URL used as this target's list page.
851
- *
852
- * Core fetches a target's `url` directly, so this stands in for the API calls:
853
- * `createG2bFetch` recognises it and queries the 조달청 open API instead, which
854
- * keeps the service key and the time window out of the configuration.
855
- */
856
- const G2B_LIST_URL = `${SITE_BASE$1}/co/co/ococ/CoOcOc.do`;
857
- /** Public notice URL, which is also what readers of the newsletter follow. */
858
- const buildG2bDetailUrl = (notice, order) => `${SITE_BASE$1}/link/PNPE027_01/single/?bidPbancNo=${notice}&bidPbancOrd=${order}`;
859
- /**
860
- * Business categories collected.
861
- *
862
- * 나라장터 splits its operations by 업무구분 and a notice only answers on the
863
- * matching one. Heritage work appears as 용역 (발굴조사, 학술연구, 보존처리) and
864
- * 공사 (수리, 정비); 물품 and 외자 carry none, so they are not requested.
865
- */
866
- const OPERATIONS = ['Servc', 'Cnstwk'];
867
- /** `resultCode` the service returns on success. */
868
- const SUCCESS_RESULT_CODE$1 = '00';
869
- /** Offset the service's wall clock runs on. */
870
- const KST_OFFSET_MS = 9 * 60 * 60 * 1000;
1233
+ const EXCAVATION_BASE_URL = 'https://www.e-minwon.go.kr';
1234
+ /** List page of the 국가유산청 발굴조사 보고서 board. */
1235
+ const EXCAVATION_REPORT_LIST_URL = `${EXCAVATION_BASE_URL}/ge/ee/getListEcexmRptp.do`;
1236
+ /** Public detail URL for one report, keyed by its board id (`ecexmRcno`). */
1237
+ const buildExcavationReportDetailUrl = (externalId) => `${EXCAVATION_BASE_URL}/ge/ee/getEcexmRptp.do?ecexmRcno=${externalId}`;
871
1238
  /**
872
- * `YYYYMMDDHHMM` in KST, the format `inqryBgnDt` and `inqryEndDt` expect.
873
- *
874
- * The parameters carry no timezone and the service reads them as Korean local
875
- * time, the same clock `bidNtceDt` is published on. Serialising UTC instead
876
- * shifts the whole window back nine hours: on a live seven-day query that was
877
- * 2,595 notices against 2,975, with the most recent 380 falling outside it.
1239
+ * Marks a response body as injected report data rather than scraped HTML, so
1240
+ * the parsers below can tell the two apart without guessing.
878
1241
  */
879
- function toApiDateTime(date) {
880
- return new Date(date.getTime() + KST_OFFSET_MS)
881
- .toISOString()
882
- .replace(/[-:T]/g, '')
883
- .slice(0, 12);
884
- }
885
- /** `2026-09-15 13:42:20` to ISO `2026-09-15`. */
886
- function toIsoDate$1(value) {
887
- const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value ?? '');
888
- return match ? `${match[1]}-${match[2]}-${match[3]}` : '';
1242
+ const INJECTED_MARKER$1 = '@heripo/research-radar:excavation-reports';
1243
+ function parseInjectedPayload$1(body) {
1244
+ if (!body.includes(INJECTED_MARKER$1)) {
1245
+ return null;
1246
+ }
1247
+ try {
1248
+ const parsed = JSON.parse(body);
1249
+ return parsed.marker === INJECTED_MARKER$1 ? parsed : null;
1250
+ }
1251
+ catch {
1252
+ return null;
1253
+ }
889
1254
  }
890
- function jsonResponse(payload) {
1255
+ function jsonResponse$2(payload) {
1256
+ return new Response(JSON.stringify(payload), {
1257
+ status: 200,
1258
+ headers: { 'content-type': 'application/json' },
1259
+ });
1260
+ }
1261
+ /**
1262
+ * Serves the 발굴조사 보고서 board from an injected source instead of the live
1263
+ * site, leaving every other request untouched.
1264
+ *
1265
+ * Core's crawling chain always fetches a target's list URL and then each detail
1266
+ * URL, so the substitution happens at the fetch layer — the same seam
1267
+ * `createKrasFetch` uses. `source` is called once and its result reused for the
1268
+ * detail requests that follow.
1269
+ *
1270
+ * @param baseFetch - Fetch to delegate every other request to
1271
+ * @param source - Supplies the reports for this run
1272
+ */
1273
+ const createExcavationReportFetch = (baseFetch = fetch, source) => {
1274
+ let pending = null;
1275
+ const loadReports = () => (pending ??= source());
1276
+ return async (input, init) => {
1277
+ const requestUrl = typeof input === 'string'
1278
+ ? input
1279
+ : input instanceof URL
1280
+ ? input.href
1281
+ : input.url;
1282
+ const url = new URL(requestUrl, EXCAVATION_BASE_URL);
1283
+ if (url.origin !== new URL(EXCAVATION_BASE_URL).origin) {
1284
+ return baseFetch(input, init);
1285
+ }
1286
+ if (url.pathname === new URL(EXCAVATION_REPORT_LIST_URL).pathname) {
1287
+ const reports = await loadReports();
1288
+ return jsonResponse$2({
1289
+ marker: INJECTED_MARKER$1,
1290
+ reports,
1291
+ });
1292
+ }
1293
+ if (url.pathname === '/ge/ee/getEcexmRptp.do') {
1294
+ const externalId = url.searchParams.get('ecexmRcno');
1295
+ const report = (await loadReports()).find((candidate) => candidate.externalId === externalId);
1296
+ if (report) {
1297
+ return jsonResponse$2({
1298
+ marker: INJECTED_MARKER$1,
1299
+ report,
1300
+ });
1301
+ }
1302
+ }
1303
+ return baseFetch(input, init);
1304
+ };
1305
+ };
1306
+ /** Renders a report's fields as the article body. */
1307
+ function renderExcavationReportContent(report) {
1308
+ const lines = Object.entries(report.fields)
1309
+ .filter(([, value]) => value != null && String(value).trim() !== '')
1310
+ .map(([label, value]) => `- **${label}**: ${String(value).trim()}`);
1311
+ return ['## 발굴조사 보고서 정보', '', ...lines].join('\n');
1312
+ }
1313
+ const parseExcavationReportList = (html) => {
1314
+ const injected = parseInjectedPayload$1(html);
1315
+ if (injected) {
1316
+ return injected.reports.map((report) => ({
1317
+ uniqId: report.externalId,
1318
+ title: report.title,
1319
+ date: report.submittedDate,
1320
+ detailUrl: buildExcavationReportDetailUrl(report.externalId),
1321
+ dateType: DateType.REGISTERED,
1322
+ }));
1323
+ }
1324
+ const $ = cheerio.load(html);
1325
+ const posts = [];
1326
+ const baseUrl = 'https://www.e-minwon.go.kr';
1327
+ $('table.td_left tbody tr.list_tr').each((index, element) => {
1328
+ const columns = $(element).find('td');
1329
+ if (columns.length === 0) {
1330
+ return;
1331
+ }
1332
+ const titleElement = columns.eq(2).find('a');
1333
+ const relativeHref = titleElement.attr('href');
1334
+ if (!relativeHref) {
1335
+ return;
1336
+ }
1337
+ const uniqId = getUniqIdFromExcavationItem(titleElement);
1338
+ const title = titleElement.attr('title')?.trim() ?? titleElement.text().trim() ?? '';
1339
+ const date = getDate(columns.eq(6).text().trim());
1340
+ const detailUrl = `${baseUrl}/ge/ee/getEcexmRptp.do?ecexmRcno=${uniqId}`;
1341
+ posts.push({
1342
+ uniqId,
1343
+ title,
1344
+ date,
1345
+ detailUrl,
1346
+ dateType: DateType.REGISTERED,
1347
+ });
1348
+ });
1349
+ return posts;
1350
+ };
1351
+ const parseExcavationSiteList = (html) => {
1352
+ const $ = cheerio.load(html);
1353
+ const posts = [];
1354
+ const baseUrl = 'https://www.e-minwon.go.kr';
1355
+ $('table.td_left tbody tr.list_tr').each((index, element) => {
1356
+ const columns = $(element).find('td');
1357
+ if (columns.length === 0) {
1358
+ return;
1359
+ }
1360
+ const titleElement = columns.eq(1).find('a');
1361
+ const relativeHref = titleElement.attr('href');
1362
+ if (!relativeHref) {
1363
+ return;
1364
+ }
1365
+ const uniqId = getUniqIdFromExcavationItem(titleElement);
1366
+ const title = titleElement.attr('title')?.trim() ?? titleElement.text().trim() ?? '';
1367
+ const date = getDate(columns.eq(4).text().trim());
1368
+ const detailUrl = `${baseUrl}/ge/ee/getLinkGrndsRls.do?grndsRlsSeqc=${uniqId}`;
1369
+ posts.push({
1370
+ uniqId,
1371
+ title,
1372
+ date,
1373
+ detailUrl,
1374
+ dateType: DateType.DURATION,
1375
+ });
1376
+ });
1377
+ return posts;
1378
+ };
1379
+ const parseExcavationReportDetail = (html) => {
1380
+ const injected = parseInjectedPayload$1(html);
1381
+ if (injected) {
1382
+ return {
1383
+ detailContent: renderExcavationReportContent(injected.report),
1384
+ hasAttachedFile: injected.report.hasAttachedFile ?? true,
1385
+ hasAttachedImage: false,
1386
+ };
1387
+ }
1388
+ const $ = cheerio.load(html);
1389
+ const content = $('table.td_left').parent();
1390
+ const trList = content.find('table tbody tr');
1391
+ trList.each((index, element) => {
1392
+ if (trList.length === index + 1) {
1393
+ $(element).remove();
1394
+ }
1395
+ });
1396
+ return {
1397
+ detailContent: new TurndownService().turndown(content.html() ?? ''),
1398
+ hasAttachedFile: true,
1399
+ hasAttachedImage: false,
1400
+ };
1401
+ };
1402
+ const parseExcavationSiteDetail = (html) => {
1403
+ const $ = cheerio.load(html);
1404
+ const content = $('div.board_view').parent();
1405
+ const dlList = content.find('div dl');
1406
+ dlList.each((index, element) => {
1407
+ if (dlList.length === index + 1) {
1408
+ $(element).remove();
1409
+ }
1410
+ });
1411
+ return {
1412
+ detailContent: new TurndownService().turndown(content.html() ?? ''),
1413
+ hasAttachedFile: true,
1414
+ hasAttachedImage: false,
1415
+ };
1416
+ };
1417
+ function getUniqIdFromExcavationItem(element) {
1418
+ return ((element.attr('onclick') ?? '').match(/dataSelected\('(.*)'\)/)?.[1] ?? '');
1419
+ }
1420
+
1421
+ const API_BASE$1 = 'https://apis.data.go.kr/1230000/ad/BidPublicInfoService';
1422
+ const SITE_BASE$1 = 'https://www.g2b.go.kr';
1423
+ /**
1424
+ * Public 나라장터 board URL used as this target's list page.
1425
+ *
1426
+ * Core fetches a target's `url` directly, so this stands in for the API calls:
1427
+ * `createG2bFetch` recognises it and queries the 조달청 open API instead, which
1428
+ * keeps the service key and the time window out of the configuration.
1429
+ */
1430
+ const G2B_LIST_URL = `${SITE_BASE$1}/co/co/ococ/CoOcOc.do`;
1431
+ /** Public notice URL, which is also what readers of the newsletter follow. */
1432
+ const buildG2bDetailUrl = (notice, order) => `${SITE_BASE$1}/link/PNPE027_01/single/?bidPbancNo=${notice}&bidPbancOrd=${order}`;
1433
+ /**
1434
+ * Business categories collected.
1435
+ *
1436
+ * 나라장터 splits its operations by 업무구분 and a notice only answers on the
1437
+ * matching one. Heritage work appears as 용역 (발굴조사, 학술연구, 보존처리) and
1438
+ * 공사 (수리, 정비); 물품 and 외자 carry none, so they are not requested.
1439
+ */
1440
+ const OPERATIONS = ['Servc', 'Cnstwk'];
1441
+ /** `resultCode` the service returns on success. */
1442
+ const SUCCESS_RESULT_CODE$1 = '00';
1443
+ /** Offset the service's wall clock runs on. */
1444
+ const KST_OFFSET_MS = 9 * 60 * 60 * 1000;
1445
+ /**
1446
+ * `YYYYMMDDHHMM` in KST, the format `inqryBgnDt` and `inqryEndDt` expect.
1447
+ *
1448
+ * The parameters carry no timezone and the service reads them as Korean local
1449
+ * time, the same clock `bidNtceDt` is published on. Serialising UTC instead
1450
+ * shifts the whole window back nine hours: on a live seven-day query that was
1451
+ * 2,595 notices against 2,975, with the most recent 380 falling outside it.
1452
+ */
1453
+ function toApiDateTime(date) {
1454
+ return new Date(date.getTime() + KST_OFFSET_MS)
1455
+ .toISOString()
1456
+ .replace(/[-:T]/g, '')
1457
+ .slice(0, 12);
1458
+ }
1459
+ /** `2026-09-15 13:42:20` to ISO `2026-09-15`. */
1460
+ function toIsoDate$1(value) {
1461
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(value ?? '');
1462
+ return match ? `${match[1]}-${match[2]}-${match[3]}` : '';
1463
+ }
1464
+ function jsonResponse$1(payload) {
891
1465
  return new Response(JSON.stringify(payload), {
892
1466
  status: 200,
893
1467
  headers: { 'content-type': 'application/json' },
@@ -929,7 +1503,7 @@ const createG2bFetch = (baseFetch = fetch, options) => {
929
1503
  if (!apiKey) {
930
1504
  // Without a key the board is simply not collected: answer with an empty
931
1505
  // payload so the parsers yield nothing and no request is made.
932
- return jsonResponse({ items: [] });
1506
+ return jsonResponse$1({ items: [] });
933
1507
  }
934
1508
  const end = new Date();
935
1509
  const begin = new Date(end.getTime() - windowHours * 60 * 60 * 1000);
@@ -1023,7 +1597,7 @@ const createG2bFetch = (baseFetch = fetch, options) => {
1023
1597
  for (const notice of heritage) {
1024
1598
  noticeCache.set(`${notice.bidNtceNo}:${notice.bidNtceOrd}`, notice);
1025
1599
  }
1026
- return jsonResponse({ items: heritage });
1600
+ return jsonResponse$1({ items: heritage });
1027
1601
  }
1028
1602
  if (url.pathname === '/link/PNPE027_01/single/') {
1029
1603
  if (refreshDetails) {
@@ -1060,13 +1634,13 @@ const createG2bFetch = (baseFetch = fetch, options) => {
1060
1634
  }
1061
1635
  const latest = revisions.sort((a, b) => Number(b.bidNtceOrd) - Number(a.bidNtceOrd))[0];
1062
1636
  return latest
1063
- ? jsonResponse({ item: latest })
1637
+ ? jsonResponse$1({ item: latest })
1064
1638
  : fail('나라장터 notice not found');
1065
1639
  }
1066
1640
  const key = `${url.searchParams.get('bidPbancNo')}:${url.searchParams.get('bidPbancOrd')}`;
1067
1641
  const notice = noticeCache.get(key);
1068
1642
  if (notice) {
1069
- return jsonResponse({ item: notice });
1643
+ return jsonResponse$1({ item: notice });
1070
1644
  }
1071
1645
  }
1072
1646
  return baseFetch(input, init);
@@ -1774,38 +2348,258 @@ const parseJinjuMuseumDetail = (html) => {
1774
2348
  };
1775
2349
  };
1776
2350
 
1777
- const parseKaahList = (html) => {
1778
- const $ = cheerio.load(html);
1779
- const posts = [];
1780
- $('table.board-table-list tbody tr').each((index, element) => {
1781
- const columns = $(element).find('td');
1782
- if (columns.length === 0) {
1783
- return;
1784
- }
1785
- const titleElement = columns.eq(1).find('a');
1786
- const relativeHref = titleElement.attr('href');
1787
- if (!relativeHref) {
1788
- return;
1789
- }
1790
- const fullUrl = new URL(relativeHref);
1791
- const detailUrl = fullUrl.href;
1792
- const uniqId = fullUrl.pathname.split('/').pop() ?? undefined;
1793
- const title = titleElement.text()?.trim() ?? '';
1794
- const date = getDate(columns
1795
- .eq(columns.length - 2)
1796
- .text()
1797
- .trim());
1798
- posts.push({
1799
- uniqId,
1800
- title,
1801
- date,
1802
- detailUrl: cleanUrl(detailUrl),
1803
- dateType: DateType.REGISTERED,
1804
- });
2351
+ /**
2352
+ * Board URL of the journal issue target.
2353
+ *
2354
+ * There is no list page behind it: the adapter below answers it from the
2355
+ * application's injected issues and never sends it. It points at KCI because
2356
+ * that is where the issues come from, and it is what the source list shows.
2357
+ */
2358
+ const JOURNAL_ISSUE_LIST_URL = 'https://www.kci.go.kr/kciportal/main.kci';
2359
+ /** Abstract length kept per paper, so a large issue stays a bounded input. */
2360
+ const ABSTRACT_MAX_LENGTH = 300;
2361
+ /** Keywords listed in the issue summary. */
2362
+ const KEYWORD_SUMMARY_LIMIT = 15;
2363
+ /**
2364
+ * Marks a response body as injected issue data rather than scraped HTML, so
2365
+ * the parsers below can tell the two apart without guessing.
2366
+ */
2367
+ const INJECTED_MARKER = '@heripo/research-radar:journal-issues';
2368
+ function parseInjectedPayload(body) {
2369
+ if (!body.includes(INJECTED_MARKER)) {
2370
+ return null;
2371
+ }
2372
+ try {
2373
+ const parsed = JSON.parse(body);
2374
+ return parsed.marker === INJECTED_MARKER ? parsed : null;
2375
+ }
2376
+ catch {
2377
+ return null;
2378
+ }
2379
+ }
2380
+ function jsonResponse(payload) {
2381
+ return new Response(JSON.stringify(payload), {
2382
+ status: 200,
2383
+ headers: { 'content-type': 'application/json' },
1805
2384
  });
1806
- return posts;
1807
- };
1808
- const parseKaahPlaceList = (html) => {
2385
+ }
2386
+ function requestHref(input) {
2387
+ return typeof input === 'string'
2388
+ ? input
2389
+ : input instanceof URL
2390
+ ? input.href
2391
+ : input.url;
2392
+ }
2393
+ /**
2394
+ * Settles with `promise`, or rejects once `signal` aborts. The promise keeps
2395
+ * running; only this request stops waiting for it, as a network fetch would.
2396
+ */
2397
+ function untilAborted(promise, signal) {
2398
+ if (!signal)
2399
+ return promise;
2400
+ if (signal.aborted)
2401
+ return Promise.reject(signal.reason);
2402
+ return new Promise((resolve, reject) => {
2403
+ const onAbort = () => reject(signal.reason);
2404
+ signal.addEventListener('abort', onAbort, { once: true });
2405
+ promise.then(resolve, reject).finally(() => {
2406
+ signal.removeEventListener('abort', onAbort);
2407
+ });
2408
+ });
2409
+ }
2410
+ /**
2411
+ * Serves the journal issue target from an injected source.
2412
+ *
2413
+ * Core's crawling chain always fetches a target's list URL and then each detail
2414
+ * URL, so the substitution happens at the fetch layer — the same seam
2415
+ * `createExcavationReportFetch` uses. Unlike that board there is nothing to
2416
+ * crawl instead, so the list URL is always answered here: with no source it is
2417
+ * an empty list and no request is made. Detail requests are matched against
2418
+ * the URLs of the issues already served; anything else is delegated.
2419
+ *
2420
+ * `source` is called once and its result reused for the detail requests that
2421
+ * follow. The adapter sits outermost on the fetch every target shares, so only
2422
+ * the list request ever waits on the source: other requests are matched
2423
+ * against issues already served, without awaiting, so a slow or failing source
2424
+ * cannot stall or break the rest of the crawl. Core requests this target's
2425
+ * details only after its list has parsed. A failed source is retried on the
2426
+ * next list request. The list request honors its abort signal, so core's
2427
+ * request timeout ends this target even when the source never settles.
2428
+ *
2429
+ * @param baseFetch - Fetch to delegate every other request to
2430
+ * @param source - Supplies the issues for this run
2431
+ */
2432
+ const createJournalIssueFetch = (baseFetch = fetch, source) => {
2433
+ let pending = null;
2434
+ const issuesByUrl = new Map();
2435
+ const loadIssues = () => (pending ??= (source ? source() : Promise.resolve([])).then((issues) => {
2436
+ for (const issue of issues)
2437
+ issuesByUrl.set(issue.url, issue);
2438
+ return issues;
2439
+ }, (error) => {
2440
+ pending = null;
2441
+ throw error;
2442
+ }));
2443
+ return async (input, init) => {
2444
+ const href = requestHref(input);
2445
+ if (href === JOURNAL_ISSUE_LIST_URL) {
2446
+ return jsonResponse({
2447
+ marker: INJECTED_MARKER,
2448
+ issues: await untilAborted(loadIssues(), init?.signal),
2449
+ });
2450
+ }
2451
+ const issue = issuesByUrl.get(href);
2452
+ if (issue) {
2453
+ return jsonResponse({
2454
+ marker: INJECTED_MARKER,
2455
+ issue,
2456
+ });
2457
+ }
2458
+ return baseFetch(input, init);
2459
+ };
2460
+ };
2461
+ /** "제59권 제3호", or whichever part the journal numbers. */
2462
+ function formatVolumeIssue(issue) {
2463
+ const label = (value, unit) => {
2464
+ const trimmed = value.trim();
2465
+ if (!trimmed)
2466
+ return '';
2467
+ return /^\d+$/.test(trimmed) ? `제${trimmed}${unit}` : trimmed;
2468
+ };
2469
+ // Some journals register the publication year as the volume on KCI
2470
+ // (한국고고학보 2026-3), which would read as "제2026권".
2471
+ const volume = issue.volume.trim() === String(issue.publishedYear) ? '' : issue.volume;
2472
+ return [label(volume, '권'), label(issue.issue, '호')]
2473
+ .filter(Boolean)
2474
+ .join(' ');
2475
+ }
2476
+ function formatJournalIssueTitle(issue) {
2477
+ const volumeIssue = formatVolumeIssue(issue);
2478
+ return [
2479
+ issue.journalName.trim(),
2480
+ volumeIssue,
2481
+ `발간 (${issue.publishedYear}년 ${issue.publishedMonth}월)`,
2482
+ ]
2483
+ .filter(Boolean)
2484
+ .join(' ');
2485
+ }
2486
+ /** Keyword counts by paper. A keyword repeated within one paper counts once. */
2487
+ function countKeywords(papers) {
2488
+ const counts = new Map();
2489
+ for (const paper of papers) {
2490
+ const keywords = new Set(paper.keywords.map((keyword) => keyword.trim()).filter(Boolean));
2491
+ for (const keyword of keywords) {
2492
+ counts.set(keyword, (counts.get(keyword) ?? 0) + 1);
2493
+ }
2494
+ }
2495
+ return [...counts]
2496
+ .map(([keyword, paperCount]) => ({ keyword, paperCount }))
2497
+ .sort((a, b) => b.paperCount - a.paperCount || a.keyword.localeCompare(b.keyword, 'ko'));
2498
+ }
2499
+ function truncate(text, maxLength) {
2500
+ const normalized = text.replace(/\s+/g, ' ').trim();
2501
+ const characters = [...normalized];
2502
+ return characters.length > maxLength
2503
+ ? `${characters.slice(0, maxLength).join('')}…`
2504
+ : normalized;
2505
+ }
2506
+ /** Renders an issue as the article body: summary, keywords, then every paper. */
2507
+ function renderJournalIssueContent(issue) {
2508
+ const volumeIssue = formatVolumeIssue(issue);
2509
+ const lines = [
2510
+ '## 학술지 권호 정보',
2511
+ '',
2512
+ `- **학술지**: ${issue.journalName.trim()}`,
2513
+ `- **발행**: ${issue.publishedYear}년 ${issue.publishedMonth}월`,
2514
+ ...(volumeIssue ? [`- **권호**: ${volumeIssue}`] : []),
2515
+ `- **수록 논문**: ${issue.papers.length}편`,
2516
+ ];
2517
+ // Counts are per paper and overlap, so they are not summed into a total.
2518
+ // Only keywords shared by several papers say anything about the issue; when
2519
+ // every keyword is unique the summary would just be the alphabetical head of
2520
+ // the list, so it is left out.
2521
+ const keywords = countKeywords(issue.papers)
2522
+ .filter(({ paperCount }) => paperCount > 1)
2523
+ .slice(0, KEYWORD_SUMMARY_LIMIT);
2524
+ if (keywords.length > 0) {
2525
+ lines.push('', '## 여러 논문이 다룬 키워드', '', keywords
2526
+ .map(({ keyword, paperCount }) => `${keyword}(${paperCount}편)`)
2527
+ .join(', '));
2528
+ }
2529
+ lines.push('', '## 수록 논문', '');
2530
+ issue.papers.forEach((paper, index) => {
2531
+ lines.push(`${index + 1}. **[${paper.title.trim()}](${paper.url})**`);
2532
+ const authors = paper.authors.map((name) => name.trim()).filter(Boolean);
2533
+ if (authors.length > 0) {
2534
+ lines.push(` - 저자: ${authors.join(', ')}`);
2535
+ }
2536
+ const keywords = [
2537
+ ...new Set(paper.keywords.map((k) => k.trim()).filter(Boolean)),
2538
+ ];
2539
+ if (keywords.length > 0) {
2540
+ lines.push(` - 키워드: ${keywords.join(', ')}`);
2541
+ }
2542
+ const abstract = paper.abstract?.trim();
2543
+ if (abstract) {
2544
+ lines.push(` - 초록: ${truncate(abstract, ABSTRACT_MAX_LENGTH)}`);
2545
+ }
2546
+ });
2547
+ return lines.join('\n');
2548
+ }
2549
+ const parseJournalIssueList = (html) => {
2550
+ const injected = parseInjectedPayload(html);
2551
+ if (!injected) {
2552
+ return [];
2553
+ }
2554
+ return injected.issues.map((issue) => ({
2555
+ uniqId: issue.externalId,
2556
+ title: formatJournalIssueTitle(issue),
2557
+ date: issue.registeredDate,
2558
+ detailUrl: issue.url,
2559
+ dateType: DateType.REGISTERED,
2560
+ }));
2561
+ };
2562
+ const parseJournalIssueDetail = (html) => {
2563
+ const injected = parseInjectedPayload(html);
2564
+ return {
2565
+ detailContent: injected ? renderJournalIssueContent(injected.issue) : '',
2566
+ hasAttachedFile: false,
2567
+ hasAttachedImage: false,
2568
+ };
2569
+ };
2570
+
2571
+ const parseKaahList = (html) => {
2572
+ const $ = cheerio.load(html);
2573
+ const posts = [];
2574
+ $('table.board-table-list tbody tr').each((index, element) => {
2575
+ const columns = $(element).find('td');
2576
+ if (columns.length === 0) {
2577
+ return;
2578
+ }
2579
+ const titleElement = columns.eq(1).find('a');
2580
+ const relativeHref = titleElement.attr('href');
2581
+ if (!relativeHref) {
2582
+ return;
2583
+ }
2584
+ const fullUrl = new URL(relativeHref);
2585
+ const detailUrl = fullUrl.href;
2586
+ const uniqId = fullUrl.pathname.split('/').pop() ?? undefined;
2587
+ const title = titleElement.text()?.trim() ?? '';
2588
+ const date = getDate(columns
2589
+ .eq(columns.length - 2)
2590
+ .text()
2591
+ .trim());
2592
+ posts.push({
2593
+ uniqId,
2594
+ title,
2595
+ date,
2596
+ detailUrl: cleanUrl(detailUrl),
2597
+ dateType: DateType.REGISTERED,
2598
+ });
2599
+ });
2600
+ return posts;
2601
+ };
2602
+ const parseKaahPlaceList = (html) => {
1809
2603
  const $ = cheerio.load(html);
1810
2604
  const posts = [];
1811
2605
  $('div.page-con-box div.data-list').each((index, element) => {
@@ -2265,31 +3059,6 @@ const parseNrichMajorEventList = (html) => {
2265
3059
  });
2266
3060
  return posts;
2267
3061
  };
2268
- const parseNrichJournalList = (html) => {
2269
- const $ = cheerio.load(html);
2270
- const posts = [];
2271
- const baseUrl = 'https://www.nrich.go.kr';
2272
- $('ul.list-body li').each((index, element) => {
2273
- const titleElement = $(element).find('.col2 a.cont-link');
2274
- const relativeHref = titleElement.attr('href');
2275
- if (!relativeHref) {
2276
- return;
2277
- }
2278
- const fullUrl = new URL(`${relativeHref}`, baseUrl);
2279
- const detailUrl = fullUrl.href;
2280
- const uniqId = fullUrl.searchParams.get('idx') ?? undefined;
2281
- const title = titleElement.text()?.trim() ?? '';
2282
- const date = getDate($(element).find('.col3 .cont-txt').text().trim());
2283
- posts.push({
2284
- uniqId,
2285
- title,
2286
- date,
2287
- detailUrl: cleanUrl(detailUrl),
2288
- dateType: DateType.REGISTERED,
2289
- });
2290
- });
2291
- return posts;
2292
- };
2293
3062
  const parseNrichPortalList = (html) => {
2294
3063
  const $ = cheerio.load(html);
2295
3064
  const posts = [];
@@ -2337,27 +3106,6 @@ const parseNrichMajorEventDetail = (html) => {
2337
3106
  hasAttachedImage: content.find('img').length > 0,
2338
3107
  };
2339
3108
  };
2340
- const parseNrichJournalDetail = (html) => {
2341
- const $ = cheerio.load(html);
2342
- $('script, style').remove();
2343
- const articles = [];
2344
- // 리스트의 각 항목을 순회하면서 논문 정보 추출
2345
- $('ul.list-body li').each((index, element) => {
2346
- const number = $(element).find('.col1 .cont-txt').text().trim();
2347
- const titleElement = $(element).find('.col2 a.cont-link');
2348
- const title = titleElement.text().trim();
2349
- const author = $(element).find('.col3 .cont-txt').text().trim();
2350
- if (title && author) {
2351
- articles.push(`${number}. **${title}**\n 저자: ${author}`);
2352
- }
2353
- });
2354
- const content = articles.length > 0 ? `## 논문 목록\n\n${articles.join('\n\n')}` : '';
2355
- return {
2356
- detailContent: content,
2357
- hasAttachedFile: true,
2358
- hasAttachedImage: false,
2359
- };
2360
- };
2361
3109
  const parseNrichPortalDetail = (html) => {
2362
3110
  const $ = cheerio.load(html);
2363
3111
  const content = $('div.detail_Area2');
@@ -2668,18 +3416,12 @@ function createCrawlingTargetGroups(customFetch) {
2668
3416
  parseDetail: parseNrichMajorEventDetail,
2669
3417
  },
2670
3418
  {
2671
- id: '국립문화유산연구원_학술지_헤리티지',
2672
- name: '국립문화유산연구원 헤리티지:역사와 과학 학술지',
2673
- url: 'https://www.nrich.go.kr/kor/subscriptionDataUsrList.do?menuIdx=1651&gubun=J',
2674
- parseList: parseNrichJournalList,
2675
- parseDetail: parseNrichJournalDetail,
2676
- },
2677
- {
2678
- id: '국립문화유산연구원_학술지_보존과학연구',
2679
- name: '국립문화유산연구원 보존과학연구 학술지',
2680
- url: 'https://www.nrich.go.kr/kor/subscriptionDataUsrList.do?menuIdx=2065&gubun=K',
2681
- parseList: parseNrichJournalList,
2682
- parseDetail: parseNrichJournalDetail,
3419
+ // Served from the application's injected KCI issues, never crawled.
3420
+ id: 'KCI_학술지_신간',
3421
+ name: 'KCI 학술지 신간 권호',
3422
+ url: JOURNAL_ISSUE_LIST_URL,
3423
+ parseList: parseJournalIssueList,
3424
+ parseDetail: parseJournalIssueDetail,
2683
3425
  },
2684
3426
  {
2685
3427
  id: '국가유산지식이음_공지사항',
@@ -4532,370 +5274,162 @@ const createNewsletterHtmlTemplate = (options) => `<!DOCTYPE html>
4532
5274
  }
4533
5275
 
4534
5276
  .kras-newsletter .kras-header-title {
4535
- color: #eeeeee !important;
4536
- }
4537
-
4538
- .kras-newsletter .kras-header-date {
4539
- color: #bbbbbb !important;
4540
- }
4541
-
4542
- .kras-newsletter .kras-header-divider {
4543
- border-top-color: #E59866 !important;
4544
- }
4545
- }
4546
- </style>
4547
- </head>
4548
- <body style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #f4f4f4; font-size: 16px; line-height: 1.7; letter-spacing: 0.01em; height: 100%; width: 100%; margin: 0; padding: 0;">
4549
- <table border="0" cellpadding="0" cellspacing="0" width="100%" role="presentation" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
4550
- <tr>
4551
- <td bgcolor="#f4f4f4" align="center" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 20px 0;" class="dark-mode-bg">
4552
- <!--[if (gte mso 9)|(IE)]>
4553
- <table align="center" border="0" cellspacing="0" cellpadding="0" width="700">
4554
- <tr>
4555
- <td align="center" valign="top" width="700">
4556
- <![endif]-->
4557
- <table border="0" cellpadding="0" cellspacing="0" width="100%" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; max-width: 700px;" class="container" role="presentation">
4558
- <tr>
4559
- <td bgcolor="#ffffff" align="left" class="content-cell dark-mode-content-bg${options?.isKrasNewsletter ? ' kras-newsletter' : ''}" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 44px 44px 36px 44px; border-radius: 12px; box-shadow: 0 4px 18px rgba(0,0,0,0.07);">
4560
- ${options?.isKrasNewsletter
4561
- ? `<!-- KRAS 50주년 헤더 -->
4562
- <div style="text-align: center; margin-bottom: 28px;">
4563
- <div style="width: 180px; min-height: 141px; display: inline-block; margin-bottom: 20px;"><img src="https://heripo.app/kras-50.png" width="180" alt="한국고고학회 50주년" style="-ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; display: block;" height="auto"></div>
4564
- <div class="kras-header-title" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 30px; font-weight: bold; color: #111111; line-height: 1.2; margin-bottom: 8px;">한국고고학회 뉴스레터</div>
4565
- <div class="kras-header-date" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; color: #666666; line-height: 1.5;">${options?.displayDate ?? ''}</div>
4566
- </div>
4567
- <hr class="kras-header-divider" style="border: 0; border-top: 2px solid #D2691E; margin: 0 0 32px 0;">
4568
- `
4569
- : `${heripoLogoHtml('12px')}
4570
- `}
4571
-
4572
- ${options?.krasNewsMarkdown
4573
- ? `<h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;"><span style="display: inline-block; width: 26px; height: 26px; vertical-align: -4px; margin-right: 6px;"><img src="https://heripo.app/kras-symbol.png" width="26" height="26" alt="" style="border: 0; display: block;"></span>학회 소식</h2>` +
4574
- safeMarkdown2Html(`${options.krasNewsMarkdown}
4575
-
4576
- ---
4577
- `, {
4578
- window: new JSDOM('').window,
4579
- linkTargetBlank: true,
4580
- fixMalformedUrls: true,
4581
- fixBoldSyntax: true,
4582
- convertStrikethrough: true,
4583
- }).replaceAll('%7B%7B%7BRESEND_UNSUBSCRIBE_URL%7D%7D%7D', '{{{RESEND_UNSUBSCRIBE_URL}}}')
4584
- : ''}
4585
-
4586
- ${options?.heripolabNewsMarkdown
4587
- ? safeMarkdown2Html(`## heripo lab 소식
4588
- ${options.heripolabNewsMarkdown}
4589
-
4590
- ---
4591
- `, {
4592
- window: new JSDOM('').window,
4593
- linkTargetBlank: true,
4594
- fixMalformedUrls: true,
4595
- fixBoldSyntax: true,
4596
- convertStrikethrough: true,
4597
- })
4598
- : ''}
4599
-
4600
- {{NEWSLETTER_CONTENT}}
4601
-
4602
- <div data-research-radar-closing="">
4603
-
4604
- ${options?.deadlineRemindersMarkdown
4605
- ? `<div data-research-radar-deadline-reminders="" data-research-radar-unified-deadlines="" class="deadline-reminders" style="background-color: #fff7ed; border: 1px solid #edc4a8; border-radius: 12px; padding: 20px; margin: 28px 0;">${safeMarkdown2Html(options.deadlineRemindersMarkdown, {
4606
- window: new JSDOM('').window,
4607
- linkTargetBlank: true,
4608
- fixMalformedUrls: true,
4609
- fixBoldSyntax: true,
4610
- convertStrikethrough: true,
4611
- })}</div>`
4612
- : ''}
4613
-
4614
- ${options?.shareNoticeMarkdown
4615
- ? safeMarkdown2Html(options.shareNoticeMarkdown, {
4616
- window: new JSDOM('').window,
4617
- linkTargetBlank: true,
4618
- fixMalformedUrls: true,
4619
- fixBoldSyntax: true,
4620
- convertStrikethrough: true,
4621
- })
4622
- : ''}
4623
- </div>
4624
-
4625
- <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
4626
-
4627
- ${options?.krasNoticeMarkdown
4628
- ? `<h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;"><span style="display: inline-block; width: 26px; height: 26px; vertical-align: -4px; margin-right: 6px;"><img src="https://heripo.app/kras-symbol.png" width="26" height="26" alt="" style="border: 0; display: block;"></span>학회 안내</h2>` +
4629
- safeMarkdown2Html(`${options.krasNoticeMarkdown}
4630
-
4631
- ---
4632
- `, {
4633
- window: new JSDOM('').window,
4634
- linkTargetBlank: true,
4635
- fixMalformedUrls: true,
4636
- fixBoldSyntax: true,
4637
- convertStrikethrough: true,
4638
- }).replaceAll('%7B%7B%7BRESEND_UNSUBSCRIBE_URL%7D%7D%7D', '{{{RESEND_UNSUBSCRIBE_URL}}}')
4639
- : ''}
4640
-
4641
- <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">🔍 뉴스레터 출처</h2>
4642
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">이 뉴스레터가 수집하는 모든 소식의 출처는 <a href="https://heripo.app/research-radar/sources" target="_blank">이곳에서</a> 확인할 수 있습니다. 새롭게 포함했으면 하는 출처나 오류가 있다면 <a href="https://github.com/heripo-lab/heripo-research-radar/issues" target="_blank">GitHub 이슈</a>로 알려주세요.</p>
4643
- <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
4644
- <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">📅 발행 정책</h2>
4645
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;"><strong>${options?.isKrasNewsletter ? '한국고고학회 뉴스레터' : 'heripo 리서치 레이더'}</strong>는 매일 발행을 원칙으로 하되, 독자분들께 의미 있는 정보를 제공하기 위해 다음과 같은 발행 기준을 적용합니다:</p>
4646
- <ul style="padding-left: 24px; margin: 0 0 18px 0;">
4647
- <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>정상 발행</strong>: 새로운 소식이 ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue + 1}개 이상이거나, ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue}개 이하여도 중요도 ${newsletterConfig.publicationCriteria.priorityArticleScoreThreshold}점 이상의 핵심 소식이 포함된 경우</li>
4648
- <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>이월 발행</strong>: 새로운 소식이 ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue}개 이하이면서 중요한 내용(${newsletterConfig.publicationCriteria.priorityArticleScoreThreshold}점 이상)이 없을 경우, 다음 호로 이월하여 더 풍성한 내용으로 제공</li>
4649
- <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>통합 발행</strong>: 이월된 소식과 새로운 소식을 함께 발행하여 보다 종합적인 업계 동향을 전달</li>
4650
- </ul>
4651
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">이러한 정책을 통해 매일 의미 없는 소식으로 독자분들의 시간을 낭비하지 않고, 정말 중요한 정보를 적절한 타이밍에 제공하고자 합니다.</p>
4652
- <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
4653
- <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">🔍 heripo 프로젝트 소개</h2>
4654
- ${platformIntroHtml()}
4655
- <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
4656
- <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">⚠️ 중요 안내</h2>
4657
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">본 뉴스레터는 국가유산청 공지사항, 관련 기관 입찰 정보 등 특정 웹 게시판의 모든 신규 소식을 빠짐없이 수집하여 제공합니다. 수집된 모든 정보는 정확한 크롤링 로직에 기반하므로 원본과 일치하여 신뢰할 수 있습니다.</p>
4658
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">다만, 수집된 정보를 바탕으로 한 <strong>분류, 요약, 분석, 중요도 판단</strong>은 LLM에 의해 수행되었습니다. LLM은 고도로 발전된 기술이지만, 정보를 해석하고 판단하는 과정에서 오류가 발생할 수 있습니다.</p>
4659
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">따라서 중요한 의사결정 시에는 <strong>반드시 원문 또는 원본 정보 출처를 직접 확인</strong>하시기를 권고합니다.</p>
4660
- </td>
4661
- </tr>
4662
- <tr>
4663
- <td align="center" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 30px 20px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 12px; line-height: 1.5; color: #888888;">
4664
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 10px 0;" class="footer-text">heripo lab | newsletter@heripo.org</p>
4665
- <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 10px 0;" class="footer-text">${options?.isKrasNewsletter ? '이 메일은 heripo.app에서 뉴스레터를 구독하신 분들과 한국고고학회 회원에게 발송됩니다.' : '이 메일은 heripo.app에서 리서치 레이더를 구독하신 분들에게 발송됩니다.'}<br>
4666
- 더 이상 이메일을 받고 싶지 않으시면 <a href="{{{RESEND_UNSUBSCRIBE_URL}}}" target="_blank" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; font-weight: bold; transition: color 0.2s; color: #888888; text-decoration: underline;" class="footer-link">여기에서 수신 거부</a>하세요.</p>
4667
- ${poweredByFooterHtml()}
4668
- </td>
4669
- </tr>
4670
- </table>
4671
- <!--[if (gte mso 9)|(IE)]>
4672
- </td>
4673
- </tr>
4674
- </table>
4675
- <![endif]-->
4676
- </td>
4677
- </tr>
4678
- </table>
4679
- </body>
4680
- </html>`;
4681
-
4682
- /**
4683
- * Date service implementation
4684
- * - Provides newsletter publication date strings (ISO and localized display form)
4685
- * - Always returns Korea Standard Time (KST, Asia/Seoul) regardless of server timezone
4686
- * - Accepts optional publishDate to override "today" (e.g., generating today's run for tomorrow's publication)
4687
- */
4688
- class DateService {
4689
- targetDate;
4690
- /**
4691
- * @param publishDate - Optional ISO date string (YYYY-MM-DD) representing the newsletter
4692
- * publication date. If omitted, the current wall-clock time (KST)
4693
- * is used. Pass tomorrow's date when building the issue the night before.
4694
- * @throws {Error} If publishDate is not in YYYY-MM-DD format or is not a real calendar date.
4695
- */
4696
- constructor(publishDate) {
4697
- if (publishDate !== undefined) {
4698
- if (!/^\d{4}-\d{2}-\d{2}$/.test(publishDate)) {
4699
- throw new Error(`Invalid publishDate format: "${publishDate}". Expected YYYY-MM-DD (e.g., "2025-02-12").`);
4700
- }
4701
- const date = new Date(publishDate + 'T00:00:00+09:00');
4702
- // Round-trip check: format back to YYYY-MM-DD in KST and compare.
4703
- // Catches invalid dates like "2025-02-30" that JS silently normalizes to "2025-03-02".
4704
- const roundTrip = date.toLocaleDateString('en-CA', {
4705
- timeZone: 'Asia/Seoul',
4706
- });
4707
- if (roundTrip !== publishDate) {
4708
- throw new Error(`Invalid publishDate: "${publishDate}" is not a real calendar date.`);
4709
- }
4710
- this.targetDate = date;
4711
- }
4712
- else {
4713
- this.targetDate = new Date();
4714
- }
4715
- }
4716
- /**
4717
- * Get the newsletter publication date in ISO format (YYYY-MM-DD).
4718
- * - Always returns date in Korea Standard Time (UTC+9)
4719
- * @returns ISO date string (e.g., "2024-10-15")
4720
- */
4721
- getPublicationISODateString() {
4722
- // Use Intl.DateTimeFormat to get date in Korea timezone
4723
- // 'en-CA' locale returns YYYY-MM-DD format by default
4724
- const kstDate = this.targetDate.toLocaleDateString('en-CA', {
4725
- timeZone: 'Asia/Seoul',
4726
- });
4727
- return kstDate;
4728
- }
4729
- getCurrentISODateString() {
4730
- return this.getPublicationISODateString();
4731
- }
4732
- /**
4733
- * Get the newsletter publication date as a localized display string.
4734
- * - Always returns date in Korea Standard Time (UTC+9)
4735
- * @returns Korean formatted date (e.g., "2024년 10월 15일")
4736
- */
4737
- getPublicationDisplayDateString() {
4738
- const formatter = new Intl.DateTimeFormat('ko-KR', {
4739
- timeZone: 'Asia/Seoul',
4740
- year: 'numeric',
4741
- month: 'long',
4742
- day: 'numeric',
4743
- });
4744
- return formatter.format(this.targetDate);
4745
- }
4746
- getDisplayDateString() {
4747
- return this.getPublicationDisplayDateString();
4748
- }
4749
- }
4750
-
4751
- function escapeLabel(value) {
4752
- return value
4753
- .replace(/\s+/g, ' ')
4754
- .replace(/&/g, '&amp;')
4755
- .replace(/</g, '&lt;')
4756
- .replace(/>/g, '&gt;')
4757
- .replace(/[\\`*_{}[\]()|!#]/g, '\\$&');
4758
- }
4759
- const clockPattern = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/;
4760
- const fullClock = (time) => (time.length === 5 ? `${time}:00` : time);
4761
- function calendarMs(date) {
4762
- if (!/^\d{4}-\d{2}-\d{2}$/.test(date))
4763
- return NaN;
4764
- const ms = Date.parse(`${date}T00:00:00Z`);
4765
- return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === date
4766
- ? ms
4767
- : NaN;
4768
- }
4769
- /** Deterministic deadlines/events, no LLM context. Host owns selection and history. */
4770
- function renderVerifiedDeadlineReminders(reminders, publicationDate, now = new Date()) {
4771
- const date = new DateService(publicationDate).getPublicationISODateString();
4772
- const publicationMs = Date.parse(`${date}T00:00:00Z`);
4773
- const rows = reminders
4774
- .flatMap((reminder) => {
4775
- const { deadline } = reminder;
4776
- if (reminder.verificationStatus !== 'verified' ||
4777
- deadline.status !== 'active' ||
4778
- !deadline.date ||
4779
- !/^\d{4}-\d{2}-\d{2}$/.test(deadline.date))
4780
- return [];
4781
- const isEvent = deadline.type === 'event';
4782
- const ms = calendarMs(deadline.date);
4783
- const endDate = isEvent
4784
- ? (deadline.endDate ?? deadline.date)
4785
- : deadline.date;
4786
- const endMs = calendarMs(endDate);
4787
- if (!Number.isFinite(ms) || !Number.isFinite(endMs) || endMs < ms)
4788
- return [];
4789
- if ((!isEvent && (deadline.endDate || deadline.endTime)) ||
4790
- (deadline.endTime && !deadline.endDate))
4791
- return [];
4792
- if ((deadline.time && !clockPattern.test(deadline.time)) ||
4793
- (deadline.endTime && !clockPattern.test(deadline.endTime)))
4794
- return [];
4795
- if (isEvent &&
4796
- endDate === deadline.date &&
4797
- deadline.time &&
4798
- deadline.endTime &&
4799
- fullClock(deadline.endTime) < fullClock(deadline.time))
4800
- return [];
4801
- const days = (ms - publicationMs) / 86_400_000;
4802
- // Events remain eligible through a known end date; a start time is never
4803
- // treated as an application cutoff. Unknown endpoints stay unknown.
4804
- if (days > 7 || endMs < publicationMs || !deadline.title.trim())
4805
- return [];
4806
- let url;
4807
- try {
4808
- url = new URL(reminder.url);
4809
- if (!['http:', 'https:'].includes(url.protocol) ||
4810
- url.username ||
4811
- url.password)
4812
- return [];
4813
- if (deadline.timeZone)
4814
- new Intl.DateTimeFormat('en', { timeZone: deadline.timeZone });
4815
- const closingTime = isEvent ? deadline.endTime : deadline.time;
4816
- if (closingTime) {
4817
- const parts = new Intl.DateTimeFormat('en', {
4818
- timeZone: deadline.timeZone ?? 'Asia/Seoul',
4819
- year: 'numeric',
4820
- month: '2-digit',
4821
- day: '2-digit',
4822
- hour: '2-digit',
4823
- minute: '2-digit',
4824
- second: '2-digit',
4825
- hourCycle: 'h23',
4826
- }).formatToParts(now);
4827
- const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
4828
- const localNow = `${values.year}-${values.month}-${values.day} ${values.hour}:${values.minute}:${values.second}`;
4829
- const closes = `${endDate} ${fullClock(closingTime)}`;
4830
- if (closes <= localNow)
4831
- return [];
4832
- }
4833
- }
4834
- catch {
4835
- return [];
4836
- }
4837
- return [
4838
- {
4839
- reminder,
4840
- days,
4841
- ms,
4842
- url: url.href.replace(/[()]/g, (value) => encodeURIComponent(value)),
4843
- },
4844
- ];
5277
+ color: #eeeeee !important;
5278
+ }
5279
+
5280
+ .kras-newsletter .kras-header-date {
5281
+ color: #bbbbbb !important;
5282
+ }
5283
+
5284
+ .kras-newsletter .kras-header-divider {
5285
+ border-top-color: #E59866 !important;
5286
+ }
5287
+ }
5288
+ </style>
5289
+ </head>
5290
+ <body style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: #f4f4f4; font-size: 16px; line-height: 1.7; letter-spacing: 0.01em; height: 100%; width: 100%; margin: 0; padding: 0;">
5291
+ <table border="0" cellpadding="0" cellspacing="0" width="100%" role="presentation" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt;">
5292
+ <tr>
5293
+ <td bgcolor="#f4f4f4" align="center" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 20px 0;" class="dark-mode-bg">
5294
+ <!--[if (gte mso 9)|(IE)]>
5295
+ <table align="center" border="0" cellspacing="0" cellpadding="0" width="700">
5296
+ <tr>
5297
+ <td align="center" valign="top" width="700">
5298
+ <![endif]-->
5299
+ <table border="0" cellpadding="0" cellspacing="0" width="100%" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; max-width: 700px;" class="container" role="presentation">
5300
+ <tr>
5301
+ <td bgcolor="#ffffff" align="left" class="content-cell dark-mode-content-bg${options?.isKrasNewsletter ? ' kras-newsletter' : ''}" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 44px 44px 36px 44px; border-radius: 12px; box-shadow: 0 4px 18px rgba(0,0,0,0.07);">
5302
+ ${options?.isKrasNewsletter
5303
+ ? `<!-- KRAS 50주년 헤더 -->
5304
+ <div style="text-align: center; margin-bottom: 28px;">
5305
+ <div style="width: 180px; min-height: 141px; display: inline-block; margin-bottom: 20px;"><img src="https://heripo.app/kras-50.png" width="180" alt="한국고고학회 50주년" style="-ms-interpolation-mode: bicubic; border: 0; height: auto; line-height: 100%; outline: none; text-decoration: none; display: block;" height="auto"></div>
5306
+ <div class="kras-header-title" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 30px; font-weight: bold; color: #111111; line-height: 1.2; margin-bottom: 8px;">한국고고학회 뉴스레터</div>
5307
+ <div class="kras-header-date" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; color: #666666; line-height: 1.5;">${options?.displayDate ?? ''}</div>
5308
+ </div>
5309
+ <hr class="kras-header-divider" style="border: 0; border-top: 2px solid #D2691E; margin: 0 0 32px 0;">
5310
+ `
5311
+ : `${heripoLogoHtml('12px')}
5312
+ `}
5313
+
5314
+ ${options?.krasNewsMarkdown
5315
+ ? `<h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;"><span style="display: inline-block; width: 26px; height: 26px; vertical-align: -4px; margin-right: 6px;"><img src="https://heripo.app/kras-symbol.png" width="26" height="26" alt="" style="border: 0; display: block;"></span>학회 소식</h2>` +
5316
+ safeMarkdown2Html(`${options.krasNewsMarkdown}
5317
+
5318
+ ---
5319
+ `, {
5320
+ window: new JSDOM('').window,
5321
+ linkTargetBlank: true,
5322
+ fixMalformedUrls: true,
5323
+ fixBoldSyntax: true,
5324
+ convertStrikethrough: true,
5325
+ }).replaceAll('%7B%7B%7BRESEND_UNSUBSCRIBE_URL%7D%7D%7D', '{{{RESEND_UNSUBSCRIBE_URL}}}')
5326
+ : ''}
5327
+
5328
+ ${options?.heripolabNewsMarkdown
5329
+ ? safeMarkdown2Html(`## heripo lab 소식
5330
+ ${options.heripolabNewsMarkdown}
5331
+
5332
+ ---
5333
+ `, {
5334
+ window: new JSDOM('').window,
5335
+ linkTargetBlank: true,
5336
+ fixMalformedUrls: true,
5337
+ fixBoldSyntax: true,
5338
+ convertStrikethrough: true,
4845
5339
  })
4846
- .sort((a, b) =>
4847
- // The five-row limit must not let older ongoing events displace
4848
- // today's or upcoming deadlines/events. Ongoing events fill spare rows.
4849
- Number(a.days < 0) - Number(b.days < 0) ||
4850
- a.ms - b.ms ||
4851
- (a.reminder.deadline.time ?? '23:59:59').localeCompare(b.reminder.deadline.time ?? '23:59:59'));
4852
- const seen = new Set();
4853
- const lines = [];
4854
- for (const { reminder, days, url } of rows) {
4855
- const d = reminder.deadline;
4856
- const key = JSON.stringify([
4857
- url,
4858
- d.type ?? 'deadline',
4859
- d.title,
4860
- d.kind,
4861
- d.date,
4862
- d.time,
4863
- d.endDate ?? null,
4864
- d.endTime ?? null,
4865
- ]);
4866
- if (seen.has(key))
4867
- continue;
4868
- seen.add(key);
4869
- const isEvent = d.type === 'event';
4870
- const time = d.time ? ` ${d.time}` : '';
4871
- const end = isEvent && d.endDate
4872
- ? d.endDate !== d.date
4873
- ? ` ~ ${d.endDate}${d.endTime ? ` ${d.endTime}` : ''}`
4874
- : d.endTime
4875
- ? ` ~ ${d.endTime}`
4876
- : ''
4877
- : '';
4878
- const zone = (d.time || (isEvent && d.endTime)) && d.timeZone
4879
- ? ` (${escapeLabel(d.timeZone)})`
4880
- : '';
4881
- const timing = days > 0
4882
- ? `D-${days}`
4883
- : days < 0
4884
- ? '진행 중'
4885
- : isEvent
4886
- ? /공개/.test(d.kind)
4887
- ? '오늘 공개'
4888
- : '오늘 개최'
4889
- : '오늘 마감';
4890
- const label = d.title.includes(d.kind) ? d.title : `${d.title} · ${d.kind}`;
4891
- lines.push(`| [${escapeLabel(label)}](${url}) | **${d.date}${time}${end}${zone} · ${timing}** |`);
4892
- if (lines.length === 5)
4893
- break;
4894
- }
4895
- return lines.length
4896
- ? `## ⏰ 다가오는 일정·마감\n\n| 안내 | 일정 |\n| --- | --- |\n${lines.join('\n')}`
4897
- : '';
4898
- }
5340
+ : ''}
5341
+
5342
+ {{NEWSLETTER_CONTENT}}
5343
+
5344
+ ${options?.journalIssuesMarkdown
5345
+ ? `<div data-research-radar-journal-issues="">${safeMarkdown2Html(options.journalIssuesMarkdown, {
5346
+ window: new JSDOM('').window,
5347
+ linkTargetBlank: true,
5348
+ fixMalformedUrls: true,
5349
+ fixBoldSyntax: true,
5350
+ convertStrikethrough: true,
5351
+ })}</div>`
5352
+ : ''}
5353
+
5354
+ <div data-research-radar-closing="">
5355
+
5356
+ ${options?.deadlineRemindersMarkdown
5357
+ ? `<div data-research-radar-deadline-reminders="" data-research-radar-unified-deadlines="" class="deadline-reminders" style="background-color: #fff7ed; border: 1px solid #edc4a8; border-radius: 12px; padding: 20px; margin: 28px 0;">${safeMarkdown2Html(options.deadlineRemindersMarkdown, {
5358
+ window: new JSDOM('').window,
5359
+ linkTargetBlank: true,
5360
+ fixMalformedUrls: true,
5361
+ fixBoldSyntax: true,
5362
+ convertStrikethrough: true,
5363
+ })}</div>`
5364
+ : ''}
5365
+
5366
+ ${options?.shareNoticeMarkdown
5367
+ ? safeMarkdown2Html(options.shareNoticeMarkdown, {
5368
+ window: new JSDOM('').window,
5369
+ linkTargetBlank: true,
5370
+ fixMalformedUrls: true,
5371
+ fixBoldSyntax: true,
5372
+ convertStrikethrough: true,
5373
+ })
5374
+ : ''}
5375
+ </div>
5376
+
5377
+ <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
5378
+
5379
+ ${options?.krasNoticeMarkdown
5380
+ ? `<h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;"><span style="display: inline-block; width: 26px; height: 26px; vertical-align: -4px; margin-right: 6px;"><img src="https://heripo.app/kras-symbol.png" width="26" height="26" alt="" style="border: 0; display: block;"></span>학회 안내</h2>` +
5381
+ safeMarkdown2Html(`${options.krasNoticeMarkdown}
5382
+
5383
+ ---
5384
+ `, {
5385
+ window: new JSDOM('').window,
5386
+ linkTargetBlank: true,
5387
+ fixMalformedUrls: true,
5388
+ fixBoldSyntax: true,
5389
+ convertStrikethrough: true,
5390
+ }).replaceAll('%7B%7B%7BRESEND_UNSUBSCRIBE_URL%7D%7D%7D', '{{{RESEND_UNSUBSCRIBE_URL}}}')
5391
+ : ''}
5392
+
5393
+ <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">🔍 뉴스레터 출처</h2>
5394
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">이 뉴스레터가 수집하는 모든 소식의 출처는 <a href="https://heripo.app/research-radar/sources" target="_blank">이곳에서</a> 확인할 수 있습니다. 새롭게 포함했으면 하는 출처나 오류가 있다면 <a href="https://github.com/heripo-lab/heripo-research-radar/issues" target="_blank">GitHub 이슈</a>로 알려주세요.</p>
5395
+ <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
5396
+ <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">📅 발행 정책</h2>
5397
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;"><strong>${options?.isKrasNewsletter ? '한국고고학회 뉴스레터' : 'heripo 리서치 레이더'}</strong>는 매일 발행을 원칙으로 하되, 독자분들께 의미 있는 정보를 제공하기 위해 다음과 같은 발행 기준을 적용합니다:</p>
5398
+ <ul style="padding-left: 24px; margin: 0 0 18px 0;">
5399
+ <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>정상 발행</strong>: 새로운 소식이 ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue + 1}개 이상이거나, ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue}개 이하여도 중요도 ${newsletterConfig.publicationCriteria.priorityArticleScoreThreshold}점 이상의 핵심 소식이 포함된 경우</li>
5400
+ <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>이월 발행</strong>: 새로운 소식이 ${newsletterConfig.publicationCriteria.minimumArticleCountForIssue}개 이하이면서 중요한 내용(${newsletterConfig.publicationCriteria.priorityArticleScoreThreshold}점 이상)이 없을 경우, 다음 호로 이월하여 더 풍성한 내용으로 제공</li>
5401
+ <li style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0; margin-bottom: 8px;"><strong>통합 발행</strong>: 이월된 소식과 새로운 소식을 함께 발행하여 보다 종합적인 업계 동향을 전달</li>
5402
+ </ul>
5403
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">이러한 정책을 통해 매일 의미 없는 소식으로 독자분들의 시간을 낭비하지 않고, 정말 중요한 정보를 적절한 타이밍에 제공하고자 합니다.</p>
5404
+ <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
5405
+ <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">🔍 heripo 프로젝트 소개</h2>
5406
+ ${platformIntroHtml()}
5407
+ <hr style="border: 0; border-top: 2px solid #D2691E; margin: 32px 0;">
5408
+ <h2 style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 24px; font-weight: bold; line-height: 1.3; color: #D2691E; margin: 0 0 16px 0; letter-spacing: -0.2px; border-left: 5px solid #D2691E; padding-left: 12px; background: none;">⚠️ 중요 안내</h2>
5409
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">본 뉴스레터는 국가유산청 공지사항, 관련 기관 입찰 정보 등 특정 웹 게시판의 모든 신규 소식을 빠짐없이 수집하여 제공합니다. 수집된 모든 정보는 정확한 크롤링 로직에 기반하므로 원본과 일치하여 신뢰할 수 있습니다.</p>
5410
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">다만, 수집된 정보를 바탕으로 한 <strong>분류, 요약, 분석, 중요도 판단</strong>은 LLM에 의해 수행되었습니다. LLM은 고도로 발전된 기술이지만, 정보를 해석하고 판단하는 과정에서 오류가 발생할 수 있습니다.</p>
5411
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 18px 0;">따라서 중요한 의사결정 시에는 <strong>반드시 원문 또는 원본 정보 출처를 직접 확인</strong>하시기를 권고합니다.</p>
5412
+ </td>
5413
+ </tr>
5414
+ <tr>
5415
+ <td align="center" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; mso-table-lspace: 0pt; mso-table-rspace: 0pt; padding: 30px 20px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 12px; line-height: 1.5; color: #888888;">
5416
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 10px 0;" class="footer-text">heripo lab | newsletter@heripo.org</p>
5417
+ <p style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.7; color: #444444; margin: 0 0 10px 0;" class="footer-text">${options?.isKrasNewsletter ? '이 메일은 heripo.app에서 뉴스레터를 구독하신 분들과 한국고고학회 회원에게 발송됩니다.' : '이 메일은 heripo.app에서 리서치 레이더를 구독하신 분들에게 발송됩니다.'}<br>
5418
+ 더 이상 이메일을 받고 싶지 않으시면 <a href="{{{RESEND_UNSUBSCRIBE_URL}}}" target="_blank" style="-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; font-weight: bold; transition: color 0.2s; color: #888888; text-decoration: underline;" class="footer-link">여기에서 수신 거부</a>하세요.</p>
5419
+ ${poweredByFooterHtml()}
5420
+ </td>
5421
+ </tr>
5422
+ </table>
5423
+ <!--[if (gte mso 9)|(IE)]>
5424
+ </td>
5425
+ </tr>
5426
+ </table>
5427
+ <![endif]-->
5428
+ </td>
5429
+ </tr>
5430
+ </table>
5431
+ </body>
5432
+ </html>`;
4899
5433
 
4900
5434
  function canonicalSourceUrl(value) {
4901
5435
  try {
@@ -4997,6 +5531,122 @@ function collectNewsletterDeadlines(content, articles, verified) {
4997
5531
  return result;
4998
5532
  }
4999
5533
 
5534
+ /** Heading of the journal issue section. Distinct from any 학술지 heading the model writes. */
5535
+ const JOURNAL_ISSUE_SECTION_HEADING = '📖 새로 나온 학술지';
5536
+ /** Authors listed per paper before the rest are counted. */
5537
+ const AUTHOR_LIMIT = 3;
5538
+ /** Topic labels named in the summary of papers left out of the table. */
5539
+ const TOPIC_LIMIT = 5;
5540
+ /**
5541
+ * Escapes a plain table cell: a `|` would end the cell, a newline the row.
5542
+ * Link labels go through `escapeLabel`, which already covers both.
5543
+ */
5544
+ function cell(value) {
5545
+ return value.replace(/\s+/g, ' ').trim().replace(/\|/g, '\\|');
5546
+ }
5547
+ function formatAuthors(authors) {
5548
+ const names = authors.map((name) => name.trim()).filter(Boolean);
5549
+ if (names.length === 0)
5550
+ return '—';
5551
+ return names.length > AUTHOR_LIMIT
5552
+ ? `${names.slice(0, AUTHOR_LIMIT).join(', ')} 외 ${names.length - AUTHOR_LIMIT}명`
5553
+ : names.join(', ');
5554
+ }
5555
+ function paperLink(paper) {
5556
+ return `[${escapeLabel(paper.title.trim())}](${paper.url})`;
5557
+ }
5558
+ function issueHeading(issue) {
5559
+ const label = [issue.journalName.trim(), formatVolumeIssue(issue)]
5560
+ .filter(Boolean)
5561
+ .join(' ');
5562
+ return `**[${escapeLabel(label)}](${issue.url})** · ${issue.publishedYear}년 ${issue.publishedMonth}월 · 논문 ${issue.papers.length}편`;
5563
+ }
5564
+ function topicSummary(topics) {
5565
+ const named = [
5566
+ ...new Set(topics.filter((topic) => Boolean(topic))),
5567
+ ];
5568
+ if (named.length === 0)
5569
+ return '';
5570
+ return named.slice(0, TOPIC_LIMIT).map(escapeLabel).join(', ');
5571
+ }
5572
+ /**
5573
+ * Renders one issue: the papers its readers would care about as a table, most
5574
+ * interesting first, and the rest as a count with their topics. Table rows plus
5575
+ * that count always equal the paper count.
5576
+ */
5577
+ function renderIssue({ issue, selection }) {
5578
+ const lines = [issueHeading(issue), ''];
5579
+ const featured = selection
5580
+ ? selection.featured
5581
+ : issue.papers.map((_, index) => index);
5582
+ const others = selection?.others ?? [];
5583
+ const topics = topicSummary(others.map(({ topic }) => topic));
5584
+ if (featured.length > 0) {
5585
+ lines.push('| 논문 | 저자 |', '| --- | --- |');
5586
+ for (const index of featured) {
5587
+ const paper = issue.papers[index];
5588
+ lines.push(`| ${paperLink(paper)} | ${cell(formatAuthors(paper.authors))} |`);
5589
+ }
5590
+ if (others.length > 0)
5591
+ lines.push('', topics
5592
+ ? `그 밖에 ${topics} 등을 다룬 논문 ${others.length}편이 함께 실렸습니다.`
5593
+ : `그 밖에 논문 ${others.length}편이 함께 실렸습니다.`);
5594
+ }
5595
+ else {
5596
+ lines.push(topics
5597
+ ? `${topics} 등을 다룬 논문이 실렸습니다.`
5598
+ : '이번 호에는 소개할 만한 논문이 없었습니다.');
5599
+ }
5600
+ return lines.join('\n');
5601
+ }
5602
+ /** Renders the whole section, or '' when there is no issue to show. */
5603
+ function renderJournalIssueSection(entries) {
5604
+ if (entries.length === 0)
5605
+ return '';
5606
+ return [
5607
+ `## ${JOURNAL_ISSUE_SECTION_HEADING}`,
5608
+ '',
5609
+ ...entries.flatMap((entry, index) => index === 0 ? [renderIssue(entry)] : ['', renderIssue(entry)]),
5610
+ ].join('\n');
5611
+ }
5612
+ /**
5613
+ * Headings the section is placed before, in order of preference.
5614
+ *
5615
+ * 사업·입찰 runs last so it does not bury academic news; placing journals after
5616
+ * it would bury them in turn. Without that section the journals go before
5617
+ * 마무리, and without either at the end of the body.
5618
+ */
5619
+ const JOURNAL_ISSUE_SECTION_ANCHORS = [
5620
+ '📑 사업·입찰 공고',
5621
+ '📌 마무리',
5622
+ ];
5623
+ /** Inserts the section Markdown before the first anchor heading found. */
5624
+ function insertJournalIssueMarkdown(content, section) {
5625
+ if (!section)
5626
+ return content;
5627
+ for (const anchor of JOURNAL_ISSUE_SECTION_ANCHORS) {
5628
+ const match = new RegExp(`^##\\s+${anchor.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`, 'm').exec(content);
5629
+ if (match)
5630
+ return `${content.slice(0, match.index)}${section}\n\n${content.slice(match.index)}`;
5631
+ }
5632
+ return `${content.trimEnd()}\n\n${section}`;
5633
+ }
5634
+ /**
5635
+ * Inserts the rendered section before the first anchor `<h2>` found, or before
5636
+ * `fallback` (the closing block) when neither heading is present.
5637
+ */
5638
+ function insertJournalIssueHtml(document, section, fallback) {
5639
+ const headings = [...document.querySelectorAll('h2')];
5640
+ for (const anchor of JOURNAL_ISSUE_SECTION_ANCHORS) {
5641
+ const heading = headings.find((element) => element.textContent?.replace(/\s+/g, ' ').trim() === anchor);
5642
+ if (heading) {
5643
+ heading.before(section);
5644
+ return;
5645
+ }
5646
+ }
5647
+ fallback.before(section);
5648
+ }
5649
+
5000
5650
  /**
5001
5651
  * Content generation provider implementation
5002
5652
  * - LLM-based newsletter content generation
@@ -5007,18 +5657,25 @@ class ContentGenerateProvider {
5007
5657
  articleRepository;
5008
5658
  newsletterRepository;
5009
5659
  templateOptions;
5660
+ selectDeadlineReminders;
5661
+ journalIssues;
5010
5662
  _issueOrder = null;
5011
5663
  deadlineRemindersMarkdown;
5664
+ heldJournalIssues = [];
5012
5665
  model;
5013
5666
  fetchRecentTitles;
5014
5667
  /** HTML template with markers for title and content injection */
5015
5668
  htmlTemplate;
5016
5669
  /** Newsletter brand name (defaults to config, can be overridden via constructor) */
5017
5670
  newsletterBrandName;
5018
- constructor(model, articleRepository, newsletterRepository, templateOptions, brandName) {
5671
+ constructor(model, articleRepository, newsletterRepository, templateOptions, brandName,
5672
+ /** Chooses displayed reminders; omitted, the first rows by date display. */
5673
+ selectDeadlineReminders, journalIssues) {
5019
5674
  this.articleRepository = articleRepository;
5020
5675
  this.newsletterRepository = newsletterRepository;
5021
5676
  this.templateOptions = templateOptions;
5677
+ this.selectDeadlineReminders = selectDeadlineReminders;
5678
+ this.journalIssues = journalIssues;
5022
5679
  this.model = model;
5023
5680
  this.deadlineRemindersMarkdown =
5024
5681
  templateOptions?.deadlineRemindersMarkdown?.trim() ?? '';
@@ -5069,7 +5726,29 @@ class ContentGenerateProvider {
5069
5726
  * @returns Articles eligible for inclusion in the newsletter
5070
5727
  */
5071
5728
  async fetchArticleCandidates() {
5072
- return this.articleRepository.findCandidatesForNewsletter();
5729
+ const candidates = await this.articleRepository.findCandidatesForNewsletter();
5730
+ this.heldJournalIssues = [];
5731
+ const journalCandidates = candidates.filter((article) => article.targetUrl === JOURNAL_ISSUE_LIST_URL);
5732
+ if (!this.journalIssues || journalCandidates.length === 0) {
5733
+ return candidates;
5734
+ }
5735
+ // An issue this run cannot load is left to the model, as before; it is
5736
+ // never dropped.
5737
+ let issues;
5738
+ try {
5739
+ issues = await this.journalIssues.load();
5740
+ }
5741
+ catch (error) {
5742
+ this.journalIssues.onUnavailable?.(error instanceof Error ? error.message : String(error));
5743
+ return candidates;
5744
+ }
5745
+ const issuesByUrl = new Map(issues.map((issue) => [issue.url, issue]));
5746
+ this.heldJournalIssues = journalCandidates.flatMap((article) => {
5747
+ const issue = issuesByUrl.get(article.url);
5748
+ return issue ? [{ article, issue }] : [];
5749
+ });
5750
+ const held = new Set(this.heldJournalIssues.map(({ article }) => article));
5751
+ return candidates.filter((article) => !held.has(article));
5073
5752
  }
5074
5753
  /**
5075
5754
  * Save generated newsletter to the repository
@@ -5086,9 +5765,10 @@ class ContentGenerateProvider {
5086
5765
  throw new Error('Generated body contains the sharing link before the closing block');
5087
5766
  const reminders = collectNewsletterDeadlines(newsletter.content, usedArticles, this.templateOptions?.verifiedDeadlineReminders ?? []);
5088
5767
  const markdown = this.templateOptions?.verifiedDeadlineReminders !== undefined
5089
- ? renderVerifiedDeadlineReminders(reminders, newsletter.date)
5768
+ ? await this.renderDeadlineReminders(reminders, newsletter.date)
5090
5769
  : this.deadlineRemindersMarkdown ||
5091
- renderVerifiedDeadlineReminders(reminders, newsletter.date);
5770
+ (await this.renderDeadlineReminders(reminders, newsletter.date));
5771
+ const journalMarkdown = await this.renderJournalIssues();
5092
5772
  const share = this.templateOptions?.shareNoticeMarkdown ??
5093
5773
  `이 소식이 도움이 되셨다면 동료 연구자에게도 소개해주시면 좋겠습니다. [${escapeLabel(this.newsletterBrandName)} 구독하기](${this.subscribePageUrl})`;
5094
5774
  // Render only the closing block with the original stylesheet. Keep core's
@@ -5097,22 +5777,52 @@ class ContentGenerateProvider {
5097
5777
  ...this.templateOptions,
5098
5778
  deadlineRemindersMarkdown: markdown,
5099
5779
  shareNoticeMarkdown: share,
5780
+ journalIssuesMarkdown: journalMarkdown,
5100
5781
  }))).window.document;
5101
5782
  const dom = new JSDOM(newsletter.htmlBody);
5102
5783
  const document = dom.window.document;
5103
5784
  const closing = document.querySelector('[data-research-radar-closing]');
5104
5785
  if (!closing)
5105
5786
  throw new Error('Newsletter closing block not found');
5787
+ const journalSection = closingDocument.querySelector('[data-research-radar-journal-issues]');
5788
+ if (journalSection) {
5789
+ insertJournalIssueHtml(document, document.importNode(journalSection, true), closing);
5790
+ }
5106
5791
  closing.outerHTML = closingDocument.querySelector('[data-research-radar-closing]').outerHTML;
5792
+ // Core hands back only the candidates the model saw; the held-aside
5793
+ // journal articles are part of this issue too.
5794
+ const usedIds = new Set(usedArticles.map((article) => article.id));
5107
5795
  return this.newsletterRepository.saveNewsletter({
5108
5796
  ...input,
5797
+ usedArticles: [
5798
+ ...usedArticles,
5799
+ ...this.heldJournalIssues
5800
+ .map(({ article }) => article)
5801
+ .filter((article) => !usedIds.has(article.id)),
5802
+ ],
5109
5803
  newsletter: {
5110
5804
  ...newsletter,
5111
- content: `${newsletter.content}${markdown ? `\n\n<!-- research-radar-deadline-reminders -->\n${markdown}` : ''}${share ? `\n\n<!-- research-radar-share-notice -->\n${share}` : ''}`,
5805
+ content: `${insertJournalIssueMarkdown(newsletter.content, journalMarkdown)}${markdown ? `\n\n<!-- research-radar-deadline-reminders -->\n${markdown}` : ''}${share ? `\n\n<!-- research-radar-share-notice -->\n${share}` : ''}`,
5112
5806
  htmlBody: dom.serialize(),
5113
5807
  },
5114
5808
  });
5115
5809
  }
5810
+ async renderJournalIssues() {
5811
+ if (this.heldJournalIssues.length === 0)
5812
+ return '';
5813
+ const select = this.journalIssues?.select;
5814
+ const entries = await Promise.all(this.heldJournalIssues.map(async ({ issue }) => ({
5815
+ issue,
5816
+ selection: select ? await select(issue) : null,
5817
+ })));
5818
+ return renderJournalIssueSection(entries);
5819
+ }
5820
+ async renderDeadlineReminders(reminders, publicationDate) {
5821
+ if (!this.selectDeadlineReminders)
5822
+ return renderVerifiedDeadlineReminders(reminders, publicationDate);
5823
+ const rows = eligibleDeadlineReminders(reminders, publicationDate);
5824
+ return formatDeadlineReminders(await this.selectDeadlineReminders(rows, publicationDate));
5825
+ }
5116
5826
  }
5117
5827
 
5118
5828
  /**
@@ -5360,7 +6070,7 @@ function createRobotsAwareFetch(baseFetch = fetch, options = {}) {
5360
6070
  }
5361
6071
 
5362
6072
  /** Shared network/adapters path for daily crawling and single-source refresh. */
5363
- function createResearchRadarFetch({ customFetch, excavationReportSource, logger, publicDataApiKey, bidTriage, refreshG2bDetails, } = {}) {
6073
+ function createResearchRadarFetch({ customFetch, excavationReportSource, journalIssueSource, logger, publicDataApiKey, bidTriage, refreshG2bDetails, } = {}) {
5364
6074
  // robots.txt is checked first, so a disallowed request is never sent — not
5365
6075
  // even through a proxy. The injected and KRAS adapters sit inside it: their
5366
6076
  // requests either bypass the network entirely or are rewritten to a URL
@@ -5408,9 +6118,13 @@ function createResearchRadarFetch({ customFetch, excavationReportSource, logger,
5408
6118
  // When the application supplies excavation reports, that board is served
5409
6119
  // from the injected source and never requested over the network. Every
5410
6120
  // other target keeps going through the same fetch as before.
5411
- return excavationReportSource
6121
+ const withExcavationReports = excavationReportSource
5412
6122
  ? createExcavationReportFetch(withPublicJobs, excavationReportSource)
5413
6123
  : withPublicJobs;
6124
+ // Journal issues have no live board to fall back to, so this adapter is
6125
+ // always installed: without a source the target is an empty list and its
6126
+ // URL is never requested.
6127
+ return createJournalIssueFetch(withExcavationReports, journalIssueSource);
5414
6128
  }
5415
6129
 
5416
6130
  /**
@@ -5427,11 +6141,12 @@ class CrawlingProvider {
5427
6141
  customFetch;
5428
6142
  /** Crawling target groups configuration */
5429
6143
  crawlingTargetGroups;
5430
- constructor(articleRepository, customFetch, excavationReportSource, logger, publicDataApiKey, bidTriage) {
6144
+ constructor(articleRepository, customFetch, excavationReportSource, logger, publicDataApiKey, bidTriage, journalIssueSource) {
5431
6145
  this.articleRepository = articleRepository;
5432
6146
  this.customFetch = createResearchRadarFetch({
5433
6147
  customFetch,
5434
6148
  excavationReportSource,
6149
+ journalIssueSource,
5435
6150
  logger,
5436
6151
  publicDataApiKey,
5437
6152
  bidTriage,
@@ -5550,6 +6265,10 @@ function createNewsletterGenerator(dependencies) {
5550
6265
  };
5551
6266
  const dateService = new DateService(dependencies.publishDate);
5552
6267
  const taskService = new TaskService(dependencies.taskRepository);
6268
+ // One source call serves both the crawl and the journal tables at save time.
6269
+ const loadJournalIssues = dependencies.journalIssueSource
6270
+ ? createJournalIssueLoader(dependencies.journalIssueSource)
6271
+ : undefined;
5553
6272
  const crawlingProvider = new CrawlingProvider(dependencies.articleRepository, dependencies.customFetch, dependencies.excavationReportSource, dependencies.logger, dependencies.publicDataApiKey,
5554
6273
  // 나라장터 publishes about 1,500 notices per 48-hour window, so which ones
5555
6274
  // reach per-article scoring is decided here, 100 titles per request. The
@@ -5562,7 +6281,7 @@ function createNewsletterGenerator(dependencies) {
5562
6281
  data: { reason, batchSize },
5563
6282
  });
5564
6283
  },
5565
- }));
6284
+ }), loadJournalIssues);
5566
6285
  const analysisProvider = new AnalysisProvider({
5567
6286
  classifyTags: resolveModel('classifyTags'),
5568
6287
  analyzeImages: resolveModel('analyzeImages'),
@@ -5599,7 +6318,46 @@ function createNewsletterGenerator(dependencies) {
5599
6318
  : dependencies.contentGeneration
5600
6319
  ? createContentGenerationModel(dependencies.contentGeneration)
5601
6320
  : resolveModel('generateNewsletter');
5602
- const contentGenerateProvider = new ContentGenerateProvider(contentModel, dependencies.articleRepository, dependencies.newsletterRepository, templateOptions, resolvedBrandName);
6321
+ const contentGenerateProvider = new ContentGenerateProvider(contentModel, dependencies.articleRepository, dependencies.newsletterRepository, templateOptions, resolvedBrandName,
6322
+ // Reminder selection judges relevance the way importance scoring does, so
6323
+ // it reuses that model rather than adding another configuration knob.
6324
+ createDeadlineReminderSelector({
6325
+ model: resolveModel('determineImportance'),
6326
+ onFallback: (reason, candidateCount) => {
6327
+ dependencies.logger?.info({
6328
+ event: 'newsletter.deadlines.selection.fallback',
6329
+ data: { reason, candidateCount },
6330
+ });
6331
+ },
6332
+ onSelected: (data) => {
6333
+ dependencies.logger?.info({
6334
+ event: 'newsletter.deadlines.selection',
6335
+ data,
6336
+ });
6337
+ },
6338
+ }), loadJournalIssues && {
6339
+ load: loadJournalIssues,
6340
+ // Choosing papers is a relevance judgement for the readers, like
6341
+ // importance, so it reuses that model.
6342
+ select: createJournalPaperSelector({
6343
+ model: resolveModel('determineImportance'),
6344
+ audience: templateOptions?.isKrasNewsletter
6345
+ ? '한국고고학회 회원(고고학 연구자, 발굴·조사기관 종사자, 관련 전공 학생)'
6346
+ : '문화유산 연구자와 실무자(고고학, 보존과학, 학예, 문화유산 행정)',
6347
+ onFallback: (reason, issue) => {
6348
+ dependencies.logger?.info({
6349
+ event: 'newsletter.journals.selection.fallback',
6350
+ data: { reason, issueUrl: issue.url },
6351
+ });
6352
+ },
6353
+ }),
6354
+ onUnavailable: (reason) => {
6355
+ dependencies.logger?.error({
6356
+ event: 'newsletter.journals.load.failed',
6357
+ data: { reason },
6358
+ });
6359
+ },
6360
+ });
5603
6361
  return new GenerateNewsletter({
5604
6362
  contentOptions: resolvedContentOptions,
5605
6363
  promptProvider: dependencies.promptProvider ?? researchRadarPromptProvider,
@@ -6124,5 +6882,5 @@ async function refreshResearchRadarDeadlines(config) {
6124
6882
  }
6125
6883
  }
6126
6884
 
6127
- export { AnalysisProvider, ContentGenerateProvider, CrawlingProvider, DateService, TaskService, contentOptions, createCrawlingTargetGroups, extractResearchRadarDeadlines, fetchResearchRadarDeadlineSource, generateNewsletter, generateWelcomeHTML, getSourceList, llmConfig, maximumImportanceScoreByDomain, newsletterConfig, refreshResearchRadarDeadlines, renderVerifiedDeadlineReminders, researchRadarPromptProvider, robotsExemptOrigins };
6885
+ export { AnalysisProvider, ContentGenerateProvider, CrawlingProvider, DEADLINE_REMINDER_LEAD_DAYS, DEADLINE_REMINDER_LIMIT, DateService, JOURNAL_ISSUE_LIST_URL, TaskService, contentOptions, createCrawlingTargetGroups, createDeadlineReminderSelector, extractResearchRadarDeadlines, fetchResearchRadarDeadlineSource, generateNewsletter, generateWelcomeHTML, getSourceList, llmConfig, maximumImportanceScoreByDomain, newsletterConfig, refreshResearchRadarDeadlines, renderVerifiedDeadlineReminders, researchRadarPromptProvider, robotsExemptOrigins };
6128
6886
  //# sourceMappingURL=index.js.map