viruagent-cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2393 @@
1
+ const { chromium } = require('playwright');
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const crypto = require('crypto');
5
+ const readline = require('readline');
6
+ const path = require('path');
7
+ const { saveProviderMeta, clearProviderMeta, getProviderMeta } = require('../storage/sessionStore');
8
+ const createTistoryApiClient = require('../services/tistoryApiClient');
9
+ const IMAGE_TRACE_ENABLED = process.env.VIRUAGENT_IMAGE_TRACE === '1';
10
+
11
+ const imageTrace = (message, data) => {
12
+ if (!IMAGE_TRACE_ENABLED) {
13
+ return;
14
+ }
15
+ if (data === undefined) {
16
+ console.log(`[이미지 추적] ${message}`);
17
+ return;
18
+ }
19
+ console.log(`[이미지 추적] ${message}`, data);
20
+ };
21
+
22
+ const LOGIN_OTP_SELECTORS = [
23
+ 'input[name*="otp"]',
24
+ 'input[placeholder*="인증"]',
25
+ 'input[autocomplete="one-time-code"]',
26
+ 'input[name*="code"]',
27
+ ];
28
+
29
+ const KAKAO_TRIGGER_SELECTORS = [
30
+ 'a.link_kakao_id',
31
+ 'a:has-text("카카오계정으로 로그인")',
32
+ ];
33
+
34
+ const KAKAO_LOGIN_SELECTORS = {
35
+ username: ['input[name="loginId"]', '#loginId--1', 'input[placeholder*="카카오메일"]'],
36
+ password: ['input[name="password"]', '#password--2', 'input[type="password"]'],
37
+ submit: ['button[type="submit"]', 'button:has-text("로그인")', '.btn_g.highlight.submit'],
38
+ rememberLogin: ['#saveSignedIn--4', 'input[name="saveSignedIn"]'],
39
+ };
40
+
41
+ const KAKAO_2FA_SELECTORS = {
42
+ start: ['#tmsTwoStepVerification', '#emailTwoStepVerification'],
43
+ emailModeButton: ['button:has-text("이메일로 인증하기")', '.link_certify'],
44
+ codeInput: ['input[name="email_passcode"]', '#passcode--6', 'input[placeholder*="인증번호"]'],
45
+ confirm: ['button:has-text("확인")', 'button.btn_g.submit', 'button[type="submit"]'],
46
+ rememberDevice: ['#isRememberBrowser--5', 'input[name="isRememberBrowser"]'],
47
+ };
48
+
49
+ const KAKAO_ACCOUNT_CONFIRM_SELECTORS = {
50
+ textMarker: [
51
+ 'text=해당 카카오 계정으로',
52
+ 'text=티스토리\n해당 카카오 계정으로',
53
+ 'text=해당 카카오계정으로 로그인',
54
+ ],
55
+ continue: [
56
+ 'button:has-text("계속하기")',
57
+ 'a:has-text("계속하기")',
58
+ 'button:has-text("다음")',
59
+ ],
60
+ otherAccount: [
61
+ 'button:has-text("다른 카카오계정으로 로그인")',
62
+ 'a:has-text("다른 카카오계정으로 로그인")',
63
+ ],
64
+ };
65
+
66
+ const MAX_IMAGE_UPLOAD_COUNT = 1;
67
+ const readCredentialsFromEnv = () => {
68
+ const username = process.env.TISTORY_USERNAME || process.env.TISTORY_USER || process.env.TISTORY_ID;
69
+ const password = process.env.TISTORY_PASSWORD || process.env.TISTORY_PW;
70
+ return {
71
+ username: typeof username === 'string' && username.trim() ? username.trim() : null,
72
+ password: typeof password === 'string' && password.trim() ? password.trim() : null,
73
+ };
74
+ };
75
+
76
+ const mapVisibility = (visibility) => {
77
+ const normalized = String(visibility || 'public').toLowerCase();
78
+ if (Number.isFinite(Number(visibility)) && [0, 15, 20].includes(Number(visibility))) {
79
+ return Number(visibility);
80
+ }
81
+ if (normalized === 'private') return 0;
82
+ if (normalized === 'protected') return 15;
83
+ return 20;
84
+ };
85
+
86
+ const normalizeTagList = (value = '') => {
87
+ const source = Array.isArray(value)
88
+ ? value
89
+ : String(value || '').replace(/\r?\n/g, ',').split(',');
90
+
91
+ return source
92
+ .map((tag) => String(tag || '').trim())
93
+ .filter(Boolean)
94
+ .map((tag) => tag.replace(/["']/g, '').trim())
95
+ .filter(Boolean)
96
+ .slice(0, 10)
97
+ .join(',');
98
+ };
99
+
100
+ const parseSessionError = (error) => {
101
+ const message = String(error?.message || '').toLowerCase();
102
+ return [
103
+ '세션이 만료',
104
+ '세션에 유효한 쿠키',
105
+ '세션 파일이 없습니다',
106
+ '블로그 정보 조회 실패: 401',
107
+ '블로그 정보 조회 실패: 403',
108
+ '세션이 만료되었습니다',
109
+ '다시 로그인',
110
+ ].some((token) => message.includes(token.toLowerCase()));
111
+ };
112
+
113
+ const buildLoginErrorMessage = (error) => String(error?.message || '세션 검증에 실패했습니다.');
114
+
115
+ const promptCategorySelection = async (categories = []) => {
116
+ if (!process.stdin || !process.stdin.isTTY) {
117
+ return null;
118
+ }
119
+ if (!Array.isArray(categories) || categories.length === 0) {
120
+ return null;
121
+ }
122
+
123
+ const candidates = categories.map((category, index) => `${index + 1}. ${category.name} (${category.id})`);
124
+ const lines = [
125
+ '발행할 카테고리를 선택해 주세요.',
126
+ ...candidates,
127
+ `입력: 번호(1-${categories.length}) 또는 카테고리 ID (엔터 입력 시 건너뛰기)`,
128
+ ];
129
+ const prompt = `${lines.join('\n')}\n> `;
130
+
131
+ const parseSelection = (input) => {
132
+ const normalized = String(input || '').trim();
133
+ if (!normalized) {
134
+ return null;
135
+ }
136
+
137
+ const numeric = Number(normalized);
138
+ if (Number.isInteger(numeric) && numeric > 0) {
139
+ if (numeric <= categories.length) {
140
+ return Number(categories[numeric - 1].id);
141
+ }
142
+ const matchedById = categories.find((item) => Number(item.id) === numeric);
143
+ if (matchedById) {
144
+ return Number(matchedById.id);
145
+ }
146
+ }
147
+
148
+ return null;
149
+ };
150
+
151
+ return new Promise((resolve) => {
152
+ const rl = readline.createInterface({
153
+ input: process.stdin,
154
+ output: process.stdout,
155
+ });
156
+
157
+ const ask = (retryCount = 0) => {
158
+ rl.question(prompt, (input) => {
159
+ const selectedId = parseSelection(input);
160
+ if (selectedId) {
161
+ rl.close();
162
+ resolve(selectedId);
163
+ return;
164
+ }
165
+
166
+ if (retryCount >= 2) {
167
+ rl.close();
168
+ resolve(null);
169
+ return;
170
+ }
171
+
172
+ console.log('잘못된 입력입니다. 번호 또는 카테고리 ID를 다시 입력해 주세요.');
173
+ ask(retryCount + 1);
174
+ });
175
+ };
176
+
177
+ ask(0);
178
+ });
179
+ };
180
+
181
+ const isPublishLimitError = (error) => {
182
+ const message = String(error?.message || '');
183
+ return /발행 실패:\s*403/.test(message) || /\b403\b/.test(message);
184
+ };
185
+
186
+ const isProvidedCategory = (value) => {
187
+ return value !== undefined && value !== null && String(value).trim() !== '';
188
+ };
189
+
190
+ const buildCategoryList = (rawCategories) => {
191
+ const entries = Object.entries(rawCategories || {});
192
+ const categories = entries.map(([name, id]) => ({
193
+ name,
194
+ id: Number(id),
195
+ }));
196
+ return categories.sort((a, b) => a.id - b.id);
197
+ };
198
+
199
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
200
+
201
+ const pickValue = async (page, selectors) => {
202
+ for (const selector of selectors) {
203
+ const element = await page.$(selector);
204
+ if (element) {
205
+ return selector;
206
+ }
207
+ }
208
+ return null;
209
+ };
210
+
211
+ const fillBySelector = async (page, selectors, value) => {
212
+ const selector = await pickValue(page, selectors);
213
+ if (!selector) {
214
+ return false;
215
+ }
216
+ await page.locator(selector).fill(value);
217
+ return true;
218
+ };
219
+
220
+ const clickSubmit = async (page, selectors) => {
221
+ const selector = await pickValue(page, selectors);
222
+ if (!selector) {
223
+ return false;
224
+ }
225
+ await page.locator(selector).click({ timeout: 5000 });
226
+ return true;
227
+ };
228
+
229
+ const checkBySelector = async (page, selectors) => {
230
+ const selector = await pickValue(page, selectors);
231
+ if (!selector) {
232
+ return false;
233
+ }
234
+ const locator = page.locator(selector);
235
+ const isChecked = await locator.isChecked().catch(() => false);
236
+ if (!isChecked) {
237
+ await locator.check({ force: true }).catch(() => {});
238
+ }
239
+ return true;
240
+ };
241
+
242
+ const hasElement = async (page, selectors) => {
243
+ for (const selector of selectors) {
244
+ const locator = page.locator(selector);
245
+ const count = await locator.count();
246
+ if (count > 0) {
247
+ return true;
248
+ }
249
+ }
250
+ return false;
251
+ };
252
+
253
+ const hasKakaoAccountConfirmScreen = async (page) => {
254
+ const url = page.url();
255
+ const isKakaoDomain = url.includes('accounts.kakao.com') || url.includes('kauth.kakao.com');
256
+ if (!isKakaoDomain) {
257
+ return false;
258
+ }
259
+
260
+ return await hasElement(page, KAKAO_ACCOUNT_CONFIRM_SELECTORS.textMarker);
261
+ };
262
+
263
+ const clickKakaoAccountContinue = async (page) => {
264
+ if (!(await hasKakaoAccountConfirmScreen(page))) {
265
+ return false;
266
+ }
267
+
268
+ const continueSelector = await pickValue(page, KAKAO_ACCOUNT_CONFIRM_SELECTORS.continue);
269
+ if (!continueSelector) {
270
+ return false;
271
+ }
272
+
273
+ await page.locator(continueSelector).click({ timeout: 5000 });
274
+ await page.waitForLoadState('domcontentloaded').catch(() => {});
275
+ await page.waitForTimeout(800);
276
+ return true;
277
+ };
278
+
279
+ const IMAGE_PLACEHOLDER_REGEX = /<!--\s*IMAGE:\s*([^>]*?)\s*-->/g;
280
+
281
+ const escapeRegExp = (value = '') => {
282
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
283
+ };
284
+
285
+ const sanitizeKeywordForFilename = (value = '') => {
286
+ return String(value)
287
+ .trim()
288
+ .toLowerCase()
289
+ .replace(/[^a-z0-9]+/gi, '-')
290
+ .replace(/^-+|-+$/g, '')
291
+ .replace(/-{2,}/g, '-')
292
+ .slice(0, 50) || 'image';
293
+ };
294
+
295
+ const normalizeTempDir = () => {
296
+ const tmpDir = path.join(os.tmpdir(), 'viruagent-cli-images');
297
+ fs.mkdirSync(tmpDir, { recursive: true });
298
+ return tmpDir;
299
+ };
300
+
301
+ const buildImageFileName = (keyword, ext = 'jpg') => {
302
+ const base = sanitizeKeywordForFilename(keyword || 'image');
303
+ const random = crypto.randomBytes(4).toString('hex');
304
+ return `${base}-${random}.${ext}`;
305
+ };
306
+
307
+ const buildTistoryImageTag = (uploadedImage, keyword) => {
308
+ const alt = String(keyword || '').replace(/"/g, '&quot;');
309
+ const normalizedKage = normalizeUploadedImageThumbnail(uploadedImage);
310
+ if (normalizedKage) {
311
+ return `<p data-ke-size="size16">[##_Image|${normalizedKage}|CDM|1.3|{"originWidth":0,"originHeight":0,"style":"alignCenter"}_##]</p>`;
312
+ }
313
+ if (uploadedImage?.uploadedKage) {
314
+ return `<p data-ke-size="size16">[##_Image|${uploadedImage.uploadedKage}|CDM|1.3|{"originWidth":0,"originHeight":0,"style":"alignCenter"}_##]</p>`;
315
+ }
316
+ if (uploadedImage?.uploadedUrl) {
317
+ return `<p data-ke-size="size16"><img src="${uploadedImage.uploadedUrl}" alt="${alt}" /></p>`;
318
+ }
319
+
320
+ return `<p data-ke-size="size16"><img src="${uploadedImage.uploadedUrl}" alt="${alt}" /></p>`;
321
+ };
322
+
323
+ const normalizeKageFromUrl = (value) => {
324
+ const trimmed = String(value || '').trim();
325
+ if (!trimmed) return null;
326
+
327
+ if (trimmed.startsWith('kage@')) {
328
+ return trimmed.replace(/["'`> )\]]+$/u, '');
329
+ }
330
+
331
+ try {
332
+ const parsed = new URL(trimmed);
333
+ const path = parsed.pathname || '';
334
+ const dnaIndex = path.indexOf('/dna/');
335
+ if (dnaIndex >= 0) {
336
+ const keyPath = path.slice(dnaIndex + '/dna/'.length).replace(/^\/+/, '');
337
+ if (keyPath) {
338
+ return `kage@${keyPath}`;
339
+ }
340
+ }
341
+ } catch {
342
+ // URL 파싱이 실패하면 기존 정규식 경로로 폴백
343
+ }
344
+
345
+ const directKageMatch = trimmed.match(/kage@([^|\s\]>"']+)/u);
346
+ if (directKageMatch?.[1]) {
347
+ return `kage@${directKageMatch[1]}`;
348
+ }
349
+
350
+ const dnaMatch = trimmed.match(/\/dna\/([^?#\s]+)/u);
351
+ if (dnaMatch?.[1]) {
352
+ return `kage@${dnaMatch[1].replace(/["'`> )\]]+$/u, '')}`;
353
+ }
354
+
355
+ if (/^[A-Za-z0-9_-]{10,}$/u.test(trimmed)) {
356
+ return `kage@${trimmed}`;
357
+ }
358
+
359
+ const rawPathMatch = trimmed.match(/([^/?#\s]+\.[A-Za-z0-9]+)$/u);
360
+ if (rawPathMatch?.[0] && !trimmed.includes('://') && trimmed.includes('/')) {
361
+ return `kage@${trimmed}`;
362
+ }
363
+
364
+ if (!trimmed.includes('://') && !trimmed.includes(' ')) {
365
+ if (trimmed.startsWith('kage@') || trimmed.includes('/')) {
366
+ return `kage@${trimmed}`;
367
+ }
368
+ }
369
+
370
+ return null;
371
+ };
372
+
373
+ const normalizeThumbnailForPublish = (value) => {
374
+ const normalized = normalizeKageFromUrl(value);
375
+ if (!normalized) {
376
+ return normalizeImageUrlForThumbnail(value);
377
+ }
378
+
379
+ const body = normalized.replace(/^kage@/i, '').split(/[?#]/)[0];
380
+ const pathPart = body?.trim();
381
+ if (!pathPart) return null;
382
+ const hasImageFile = /\/[^/]+\.[A-Za-z0-9]+$/u.test(pathPart);
383
+ if (hasImageFile) {
384
+ return `kage@${pathPart}`;
385
+ }
386
+ const suffix = pathPart.endsWith('/') ? 'img.jpg' : '/img.jpg';
387
+ return `kage@${pathPart}${suffix}`;
388
+ };
389
+
390
+ const normalizeImageUrlForThumbnail = (value) => {
391
+ const trimmed = String(value || '').trim();
392
+ if (!trimmed) return null;
393
+ if (!/^https?:\/\//i.test(trimmed)) {
394
+ return null;
395
+ }
396
+ if (trimmed.includes('data:image')) {
397
+ return null;
398
+ }
399
+ if (trimmed.includes(' ') || trimmed.length < 10) {
400
+ return null;
401
+ }
402
+ const imageExtensionMatch = trimmed.match(/\.(?:jpg|jpeg|png|gif|webp|bmp|avif|svg)(?:$|\?|#)/i);
403
+ return imageExtensionMatch ? trimmed : null;
404
+ };
405
+
406
+ const extractKageFromCandidate = (value) => {
407
+ const normalized = normalizeThumbnailForPublish(value);
408
+ if (normalized) {
409
+ return normalized;
410
+ }
411
+
412
+ if (typeof value !== 'string') {
413
+ return null;
414
+ }
415
+
416
+ const trimmed = value.trim();
417
+ if (!trimmed) return null;
418
+
419
+ const imageTagMatch = trimmed.match(/\[##_Image\|([^|]+)\|/);
420
+ if (imageTagMatch?.[1]) {
421
+ return normalizeKageFromUrl(imageTagMatch[1]);
422
+ }
423
+
424
+ if (!trimmed.includes('://') && trimmed.includes('|')) {
425
+ const match = trimmed.match(/kage@[^\s|]+/);
426
+ if (match?.[0]) {
427
+ return match[0];
428
+ }
429
+ }
430
+
431
+ return null;
432
+ };
433
+
434
+ const normalizeUploadedImageThumbnail = (uploadedImage) => {
435
+ const candidates = [
436
+ uploadedImage?.uploadedKage,
437
+ uploadedImage?.raw?.kage,
438
+ uploadedImage?.raw?.uploadedKage,
439
+ uploadedImage?.uploadedKey,
440
+ uploadedImage?.raw?.key,
441
+ uploadedImage?.raw?.attachmentKey,
442
+ uploadedImage?.raw?.imageKey,
443
+ uploadedImage?.raw?.id,
444
+ uploadedImage?.raw?.url,
445
+ uploadedImage?.raw?.attachmentUrl,
446
+ uploadedImage?.raw?.thumbnail,
447
+ uploadedImage?.url,
448
+ uploadedImage?.uploadedUrl,
449
+ ];
450
+
451
+ for (const candidate of candidates) {
452
+ const normalized = extractKageFromCandidate(candidate);
453
+ if (normalized) {
454
+ const final = normalizeThumbnailForPublish(normalized);
455
+ if (final) {
456
+ return final;
457
+ }
458
+ }
459
+ }
460
+
461
+ return null;
462
+ };
463
+
464
+ const dedupeTextValues = (values = []) => {
465
+ const seen = new Set();
466
+ return values
467
+ .filter(Boolean)
468
+ .map((value) => String(value || '').trim())
469
+ .filter(Boolean)
470
+ .filter((value) => {
471
+ if (seen.has(value)) {
472
+ return false;
473
+ }
474
+ seen.add(value);
475
+ return true;
476
+ });
477
+ };
478
+
479
+ const dedupeImageSources = (sources = []) => {
480
+ const seen = new Set();
481
+ return sources
482
+ .filter(Boolean)
483
+ .map((source) => String(source || '').trim())
484
+ .filter(Boolean)
485
+ .filter((source) => {
486
+ if (seen.has(source)) {
487
+ return false;
488
+ }
489
+ seen.add(source);
490
+ return true;
491
+ });
492
+ };
493
+
494
+ const buildFallbackImageSources = async (keyword = '') => {
495
+ const trimmedKeyword = String(keyword || '').trim();
496
+ if (!trimmedKeyword) {
497
+ return [];
498
+ }
499
+ if (trimmedKeyword.startsWith('image-')) {
500
+ return [];
501
+ }
502
+ return buildKeywordImageCandidates(trimmedKeyword);
503
+ };
504
+
505
+ const sanitizeImageQueryForProvider = (value = '') => {
506
+ return String(value || '')
507
+ .trim()
508
+ .replace(/[^a-z0-9가-힣\s]/gi, ' ')
509
+ .replace(/\s+/g, ' ')
510
+ .trim();
511
+ };
512
+
513
+ const buildLoremFlickrImageCandidates = (keyword = '') => {
514
+ const safeKeyword = sanitizeImageQueryForProvider(keyword);
515
+ if (!safeKeyword) {
516
+ return [];
517
+ }
518
+ const encoded = encodeURIComponent(safeKeyword.replace(/\s+/g, ','));
519
+ return [
520
+ `https://loremflickr.com/1200/800/${encoded}`,
521
+ `https://loremflickr.com/g/1200/800/${encoded}`,
522
+ ];
523
+ };
524
+
525
+ const buildPicsumImageCandidates = (keyword = '') => {
526
+ const safeKeyword = sanitizeImageQueryForProvider(keyword);
527
+ const hash = safeKeyword
528
+ ? crypto.createHash('md5').update(safeKeyword).digest('hex').slice(0, 10)
529
+ : 'default';
530
+ return [
531
+ `https://picsum.photos/seed/${hash}/1200/800`,
532
+ `https://picsum.photos/1200/800`,
533
+ ];
534
+ };
535
+
536
+ const buildPlaceholderImageCandidates = () => {
537
+ return [
538
+ 'https://placehold.co/1200x800.png',
539
+ 'https://via.placeholder.com/1200x800.jpg',
540
+ 'https://dummyimage.com/1200x800/000/fff.png&text=thumbnail',
541
+ ];
542
+ };
543
+
544
+ const buildWikimediaImageCandidates = async (keyword = '') => {
545
+ const safeKeyword = sanitizeImageQueryForProvider(keyword);
546
+ if (!safeKeyword) {
547
+ return [];
548
+ }
549
+ try {
550
+ const query = encodeURIComponent(`${safeKeyword} file`);
551
+ const apiUrl = `https://commons.wikimedia.org/w/api.php?action=query&generator=search&gsrsearch=${query}&gsrnamespace=6&gsrlimit=8&prop=imageinfo&iiprop=url&iiurlwidth=1200&format=json&origin=*`;
552
+ imageTrace('wikimedia.request', { keyword: safeKeyword, apiUrl });
553
+ const raw = await fetchText(apiUrl);
554
+ const parsed = JSON.parse(raw || '{}');
555
+ const pages = parsed?.query?.pages || {};
556
+ const candidates = [];
557
+ for (const page of Object.values(pages)) {
558
+ const imageInfo = Array.isArray(page?.imageinfo) ? page.imageinfo : [];
559
+ if (imageInfo.length === 0) {
560
+ continue;
561
+ }
562
+ const first = imageInfo[0];
563
+ if (first?.thumburl) {
564
+ candidates.push(first.thumburl);
565
+ } else if (first?.url) {
566
+ candidates.push(first.url);
567
+ }
568
+ }
569
+ imageTrace('wikimedia.response', { keyword: safeKeyword, count: candidates.length });
570
+ return candidates;
571
+ } catch {
572
+ imageTrace('wikimedia.error', { keyword: safeKeyword });
573
+ return [];
574
+ }
575
+ };
576
+
577
+ const extractThumbnailFromContent = (content = '') => {
578
+ const match = String(content).match(/\[##_Image\|([^|]+)\|/);
579
+ if (!match?.[1]) {
580
+ const imgMatch = String(content).match(/<img[^>]+src=["']([^"']+)["'][^>]*>/i);
581
+ if (!imgMatch?.[1]) {
582
+ return null;
583
+ }
584
+ return normalizeImageUrlForThumbnail(imgMatch[1]);
585
+ }
586
+ return extractKageFromCandidate(match[1]);
587
+ };
588
+
589
+ const resolveMandatoryThumbnail = async ({
590
+ rawThumbnail,
591
+ content,
592
+ uploadedImages = [],
593
+ relatedImageKeywords = [],
594
+ title = '',
595
+ }) => {
596
+ const directThumbnail = normalizeThumbnailForPublish(rawThumbnail);
597
+ if (directThumbnail) {
598
+ return directThumbnail;
599
+ }
600
+
601
+ const uploadedThumbnail = dedupeTextValues(
602
+ uploadedImages.flatMap((image) => [
603
+ normalizeUploadedImageThumbnail(image),
604
+ normalizeImageUrlForThumbnail(image?.uploadedUrl),
605
+ ]),
606
+ ).find(Boolean);
607
+ if (uploadedThumbnail) {
608
+ return normalizeThumbnailForPublish(uploadedThumbnail);
609
+ }
610
+
611
+ const contentThumbnail = extractThumbnailFromContent(content);
612
+ if (contentThumbnail) {
613
+ return normalizeThumbnailForPublish(contentThumbnail);
614
+ }
615
+
616
+ const normalizedKeywords = dedupeTextValues([
617
+ ...(Array.isArray(relatedImageKeywords)
618
+ ? relatedImageKeywords.map((item) => String(item || '').trim())
619
+ : String(relatedImageKeywords || '')
620
+ .split(',')
621
+ .map((item) => item.trim())),
622
+ String(title || '').trim(),
623
+ '뉴스 이미지',
624
+ '뉴스',
625
+ 'thumbnail',
626
+ ]);
627
+
628
+ for (const keyword of normalizedKeywords) {
629
+ const candidates = await buildKeywordImageCandidates(keyword);
630
+ const thumbnail = candidates
631
+ .map((candidate) => normalizeImageUrlForThumbnail(candidate))
632
+ .find(Boolean);
633
+ if (thumbnail) {
634
+ return normalizeThumbnailForPublish(thumbnail);
635
+ }
636
+ }
637
+
638
+ return null;
639
+ };
640
+
641
+ const guessExtensionFromContentType = (contentType = '') => {
642
+ const normalized = contentType.toLowerCase();
643
+ if (normalized.includes('png')) return 'png';
644
+ if (normalized.includes('webp')) return 'webp';
645
+ if (normalized.includes('gif')) return 'gif';
646
+ if (normalized.includes('bmp')) return 'bmp';
647
+ if (normalized.includes('jpeg') || normalized.includes('jpg')) return 'jpg';
648
+ return 'jpg';
649
+ };
650
+
651
+ const isImageContentType = (contentType = '') => {
652
+ const normalized = contentType.toLowerCase();
653
+ return normalized.startsWith('image/') || normalized.includes('application/octet-stream') || normalized.includes('binary/octet-stream');
654
+ };
655
+
656
+ const guessExtensionFromUrl = (rawUrl) => {
657
+ try {
658
+ const parsed = new URL(rawUrl);
659
+ const match = parsed.pathname.match(/\.([a-zA-Z0-9]+)(?:$|\?)/);
660
+ if (!match) return null;
661
+ const ext = match[1].toLowerCase();
662
+ if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'avif', 'heic', 'heif', 'ico'].includes(ext)) {
663
+ return ext === 'jpeg' ? 'jpg' : ext;
664
+ }
665
+ return null;
666
+ } catch {
667
+ return null;
668
+ }
669
+ };
670
+
671
+ const getImageSignatureExtension = (buffer) => {
672
+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return null;
673
+ const magic4 = buffer.slice(0, 4).toString('hex');
674
+ const magic2 = buffer.slice(0, 2).toString('hex');
675
+ const magic8 = buffer.slice(8, 12).toString('hex');
676
+ if (magic2 === 'ffd8') return 'jpg';
677
+ if (magic4 === '89504e47') return 'png';
678
+ if (magic4 === '47494638') return 'gif';
679
+ if (magic4 === '52494646' && magic8 === '57454250') return 'webp';
680
+ if (magic2 === '424d') return 'bmp';
681
+ return null;
682
+ };
683
+
684
+ const resolveLocalImagePath = (value) => {
685
+ if (typeof value !== 'string') {
686
+ return null;
687
+ }
688
+
689
+ const trimmed = value.trim();
690
+ if (!trimmed) return null;
691
+
692
+ if (trimmed.startsWith('file://')) {
693
+ try {
694
+ const filePath = decodeURIComponent(new URL(trimmed).pathname);
695
+ if (fs.existsSync(filePath)) {
696
+ const stat = fs.statSync(filePath);
697
+ if (stat.isFile()) return filePath;
698
+ }
699
+ } catch {}
700
+ return null;
701
+ }
702
+
703
+ const expanded = trimmed.startsWith('~')
704
+ ? path.join(os.homedir(), trimmed.slice(1))
705
+ : trimmed;
706
+ const candidate = path.isAbsolute(expanded) ? expanded : path.resolve(process.cwd(), expanded);
707
+ if (!fs.existsSync(candidate)) return null;
708
+
709
+ try {
710
+ const stat = fs.statSync(candidate);
711
+ return stat.isFile() ? candidate : null;
712
+ } catch {
713
+ return null;
714
+ }
715
+ };
716
+
717
+ const normalizeImageInput = (value) => {
718
+ if (typeof value !== 'string') {
719
+ return null;
720
+ }
721
+ const text = value.trim();
722
+ if (!text) {
723
+ return null;
724
+ }
725
+ const localPath = resolveLocalImagePath(text);
726
+ if (localPath) {
727
+ return localPath;
728
+ }
729
+
730
+ try {
731
+ const parsed = new URL(text);
732
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
733
+ return null;
734
+ }
735
+ return parsed.toString();
736
+ } catch (error) {
737
+ return null;
738
+ }
739
+ };
740
+
741
+ const normalizeImageInputs = (inputs) => {
742
+ if (typeof inputs === 'string') {
743
+ return inputs.split(',').map((item) => normalizeImageInput(item)).filter(Boolean);
744
+ }
745
+
746
+ if (!Array.isArray(inputs)) {
747
+ return [];
748
+ }
749
+
750
+ return inputs.map(normalizeImageInput).filter(Boolean);
751
+ };
752
+
753
+ const fetchText = async (url, retryCount = 0) => {
754
+ if (!url) {
755
+ throw new Error('텍스트 URL이 없습니다.');
756
+ }
757
+
758
+ const headers = {
759
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
760
+ 'Accept': 'text/html,application/xhtml+xml',
761
+ };
762
+ const controller = new AbortController();
763
+ const timeout = setTimeout(() => controller.abort(), 20000);
764
+
765
+ try {
766
+ imageTrace('fetchText', { url, retryCount });
767
+ const response = await fetch(url, {
768
+ method: 'GET',
769
+ redirect: 'follow',
770
+ headers,
771
+ signal: controller.signal,
772
+ });
773
+
774
+ if (!response.ok) {
775
+ throw new Error(`텍스트 요청 실패: ${response.status} ${response.statusText}, url=${url}`);
776
+ }
777
+
778
+ return response.text();
779
+ } catch (error) {
780
+ if (retryCount < 1) {
781
+ await sleep(700);
782
+ return fetchText(url, retryCount + 1);
783
+ }
784
+ throw new Error(`웹 텍스트 다운로드 실패: ${error.message}`);
785
+ } finally {
786
+ clearTimeout(timeout);
787
+ }
788
+ };
789
+
790
+ const fetchTextWithHeaders = async (url, headers = {}, retryCount = 0) => {
791
+ const merged = {
792
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
793
+ ...headers,
794
+ };
795
+ const controller = new AbortController();
796
+ const timeout = setTimeout(() => controller.abort(), 20000);
797
+ try {
798
+ const response = await fetch(url, {
799
+ method: 'GET',
800
+ redirect: 'follow',
801
+ headers: merged,
802
+ signal: controller.signal,
803
+ });
804
+ if (!response.ok) {
805
+ throw new Error(`텍스트 요청 실패: ${response.status} ${response.statusText}, url=${url}`);
806
+ }
807
+ return response.text();
808
+ } catch (error) {
809
+ if (retryCount < 1) {
810
+ await sleep(700);
811
+ return fetchTextWithHeaders(url, headers, retryCount + 1);
812
+ }
813
+ throw new Error(`웹 텍스트 다운로드 실패: ${error.message}`);
814
+ } finally {
815
+ clearTimeout(timeout);
816
+ }
817
+ };
818
+
819
+ const normalizeAbsoluteUrl = (value = '', base = '') => {
820
+ const trimmed = String(value || '').trim();
821
+ if (!trimmed) return null;
822
+ try {
823
+ const url = base ? new URL(trimmed, base) : new URL(trimmed);
824
+ if (!['http:', 'https:'].includes(url.protocol)) {
825
+ return null;
826
+ }
827
+ return url.toString();
828
+ } catch {
829
+ return null;
830
+ }
831
+ };
832
+
833
+ const extractArticleUrlsFromContent = (content = '') => {
834
+ const matches = Array.from(String(content).matchAll(/<a\s+[^>]*href=(['"])(.*?)\1/gi));
835
+ const urls = matches
836
+ .map((match) => match[2])
837
+ .filter((href) => /^https?:\/\//i.test(href))
838
+ .map((href) => href.trim())
839
+ .filter(Boolean);
840
+ return Array.from(new Set(urls));
841
+ };
842
+
843
+ const extractDuckDuckGoRedirectTarget = (value = '') => {
844
+ const urlText = String(value || '').trim();
845
+ if (!urlText) return null;
846
+
847
+ try {
848
+ const parsed = new URL(urlText);
849
+ if (parsed.hostname.includes('duckduckgo.com') && parsed.pathname === '/l/') {
850
+ const encoded = parsed.searchParams.get('uddg');
851
+ if (encoded) {
852
+ try {
853
+ return decodeURIComponent(encoded);
854
+ } catch {
855
+ return encoded;
856
+ }
857
+ }
858
+ }
859
+
860
+ if (parsed.hostname === 'duckduckgo.com' && parsed.pathname === '/y.js') {
861
+ const articleLike = parsed.searchParams.get('u3') || parsed.searchParams.get('url');
862
+ if (articleLike) {
863
+ try {
864
+ return decodeURIComponent(articleLike);
865
+ } catch {
866
+ return articleLike;
867
+ }
868
+ }
869
+ }
870
+ } catch {
871
+ return null;
872
+ }
873
+
874
+ return null;
875
+ };
876
+
877
+ const extractImageFromHtml = (html = '', base = '') => {
878
+ const normalizedHtml = String(html || '');
879
+ const metaCandidates = [
880
+ /<meta[^>]*property=["']og:image["'][^>]*content=["']([^"']+)["'][^>]*>/i,
881
+ /<meta[^>]*name=["']twitter:image["'][^>]*content=["']([^"']+)["'][^>]*>/i,
882
+ /<meta[^>]*name=["']og:image["'][^>]*content=["']([^"']+)["'][^>]*>/i,
883
+ /<meta[^>]*itemprop=["']image["'][^>]*content=["']([^"']+)["'][^>]*>/i,
884
+ /<link[^>]*rel=["']image_src["'][^>]*href=["']([^"']+)["'][^>]*>/i,
885
+ ];
886
+
887
+ for (const pattern of metaCandidates) {
888
+ const match = normalizedHtml.match(pattern);
889
+ if (match?.[1]) {
890
+ const url = normalizeAbsoluteUrl(match[1], base);
891
+ if (url && !/favicon/i.test(url) && !/logo/i.test(url)) {
892
+ return url;
893
+ }
894
+ }
895
+ }
896
+
897
+ const imageMatch = normalizedHtml.match(/<img[^>]+src=["']([^"']+)["'][^>]*>/i);
898
+ if (imageMatch?.[1]) {
899
+ const src = normalizeAbsoluteUrl(imageMatch[1], base);
900
+ if (src && !/logo|favicon|avatar|pixel|spacer/i.test(src)) {
901
+ return src;
902
+ }
903
+ }
904
+ return null;
905
+ };
906
+
907
+ const resolveArticleImageByUrl = async (articleUrl) => {
908
+ try {
909
+ const html = await fetchText(articleUrl);
910
+ const imageUrl = extractImageFromHtml(html, articleUrl);
911
+ if (imageUrl) {
912
+ return imageUrl;
913
+ }
914
+ } catch {
915
+ // fallback below
916
+ }
917
+
918
+ try {
919
+ const normalizedArticleUrl = String(articleUrl).trim();
920
+ if (!normalizedArticleUrl) return null;
921
+ const normalizedForJina = normalizedArticleUrl.startsWith('https://')
922
+ ? normalizedArticleUrl.slice(8)
923
+ : normalizedArticleUrl.startsWith('http://')
924
+ ? normalizedArticleUrl.slice(7)
925
+ : normalizedArticleUrl;
926
+ const jinaUrl = `https://r.jina.ai/http://${normalizedForJina}`;
927
+ const jinaHtml = await fetchText(jinaUrl);
928
+ return extractImageFromHtml(jinaHtml, articleUrl);
929
+ } catch {
930
+ return null;
931
+ }
932
+ };
933
+
934
+ const extractSearchUrlsFromText = (markdown = '') => {
935
+ const matched = [];
936
+ const pattern = /https?:\/\/duckduckgo\.com\/l\/\?uddg=([^)\s"']+)(?:&[^)\s"']*)?/g;
937
+ let m = pattern.exec(markdown);
938
+ while (m) {
939
+ const decoded = extractDuckDuckGoRedirectTarget(`https://duckduckgo.com/l/?uddg=${m[1]}`);
940
+ if (decoded && /^https?:\/\/.+/i.test(decoded)) {
941
+ matched.push(decoded);
942
+ }
943
+ m = pattern.exec(markdown);
944
+ }
945
+
946
+ if (matched.length === 0) {
947
+ const directLinks = String(markdown).match(/https?:\/\/(?:www\.)?[^\\s\)\]\[]+/g) || [];
948
+ directLinks.forEach((link) => {
949
+ if (link.length > 12) {
950
+ matched.push(link);
951
+ }
952
+ });
953
+ }
954
+
955
+ return Array.from(new Set(matched));
956
+ };
957
+
958
+ const extractDuckDuckGoVqd = (html = '') => {
959
+ const raw = String(html || '');
960
+ const patterns = [
961
+ /vqd='([^']+)'/i,
962
+ /vqd="([^"]+)"/i,
963
+ /["']vqd["']\s*:\s*["']([^"']+)["']/i,
964
+ /vqd=([^&"'\\s>]+)/i,
965
+ ];
966
+
967
+ for (const pattern of patterns) {
968
+ const matched = raw.match(pattern);
969
+ if (matched?.[1] && matched[1].trim()) {
970
+ return matched[1].trim();
971
+ }
972
+ }
973
+
974
+ return null;
975
+ };
976
+
977
+ const fetchDuckDuckGoImageResults = async (query = '') => {
978
+ try {
979
+ const safeKeyword = String(query || '').trim();
980
+ if (!safeKeyword) return [];
981
+ const searchUrl = `https://duckduckgo.com/?ia=images&origin=funnel_home_google&t=h_&q=${encodeURIComponent(safeKeyword)}&chip-select=search&iax=images`;
982
+ imageTrace('duckduckgo.searchPage', { query: safeKeyword, searchUrl });
983
+ const searchText = await fetchTextWithHeaders(searchUrl, {
984
+ Accept: 'text/html,application/xhtml+xml',
985
+ Referer: 'https://duckduckgo.com/',
986
+ });
987
+ const vqd = extractDuckDuckGoVqd(searchText);
988
+ if (!vqd) return [];
989
+
990
+ const apiCandidates = [
991
+ `https://duckduckgo.com/i.js?l=wt-wt&o=json&q=${encodeURIComponent(safeKeyword)}&vqd=${encodeURIComponent(vqd)}&ia=images&iax=images`,
992
+ `https://duckduckgo.com/i.js?l=wt-wt&o=json&q=${encodeURIComponent(safeKeyword)}&ia=images&iax=images&vqd=${encodeURIComponent(vqd)}&s=0`,
993
+ `https://duckduckgo.com/i.js?o=json&q=${encodeURIComponent(safeKeyword)}&ia=images&iax=images&vqd=${encodeURIComponent(vqd)}&p=1`,
994
+ `https://duckduckgo.com/i.js?l=en-gb&o=json&q=${encodeURIComponent(safeKeyword)}&ia=images&iax=images&vqd=${encodeURIComponent(vqd)}`,
995
+ ];
996
+
997
+ const jsonHeaders = {
998
+ Accept: 'application/json, text/javascript, */*; q=0.01',
999
+ 'Referer': `https://duckduckgo.com/?q=${encodeURIComponent(safeKeyword)}&ia=images&iax=images`,
1000
+ 'Origin': 'https://duckduckgo.com',
1001
+ };
1002
+
1003
+ let parsed = null;
1004
+ let apiUrl = null;
1005
+ for (const candidate of apiCandidates) {
1006
+ try {
1007
+ imageTrace('duckduckgo.apiUrl', { query: safeKeyword, apiUrl: candidate });
1008
+ const apiText = await fetchTextWithHeaders(candidate, jsonHeaders);
1009
+ const safeText = String(apiText || '').trim();
1010
+ if (!safeText) {
1011
+ continue;
1012
+ }
1013
+ if (!safeText.startsWith('{') && !safeText.startsWith('[')) {
1014
+ imageTrace('duckduckgo.apiParseSkipped', { query: safeKeyword, apiUrl: candidate, reason: 'nonJsonStart' });
1015
+ continue;
1016
+ }
1017
+ parsed = JSON.parse(safeText);
1018
+ if (Array.isArray(parsed.results) && parsed.results.length > 0) {
1019
+ apiUrl = candidate;
1020
+ break;
1021
+ }
1022
+ } catch {
1023
+ imageTrace('duckduckgo.apiParseError', { query: safeKeyword, apiUrl: candidate });
1024
+ }
1025
+ }
1026
+
1027
+ if (!parsed) return [];
1028
+ if (apiUrl) {
1029
+ imageTrace('duckduckgo.apiUsed', { query: safeKeyword, apiUrl });
1030
+ }
1031
+
1032
+ imageTrace('duckduckgo.apiResult', {
1033
+ query: safeKeyword,
1034
+ resultCount: Array.isArray(parsed?.results) ? parsed.results.length : 0,
1035
+ });
1036
+ const results = Array.isArray(parsed.results) ? parsed.results : [];
1037
+
1038
+ const images = [];
1039
+ for (const item of results) {
1040
+ if (typeof item !== 'object' || !item) continue;
1041
+ const candidates = [
1042
+ item.image,
1043
+ item.thumbnail,
1044
+ item.image_thumb,
1045
+ item.url,
1046
+ item.original,
1047
+ ];
1048
+ for (const candidate of candidates) {
1049
+ const candidateUrl = normalizeAbsoluteUrl(candidate);
1050
+ if (candidateUrl && !/favicon|logo|sprite|pixel/i.test(candidateUrl)) {
1051
+ images.push(candidateUrl);
1052
+ break;
1053
+ }
1054
+ }
1055
+ }
1056
+
1057
+ return images;
1058
+ } catch {
1059
+ return [];
1060
+ }
1061
+ };
1062
+
1063
+ const buildKeywordImageCandidates = async (keyword = '') => {
1064
+ const cleaned = String(keyword || '').trim().toLowerCase();
1065
+ const compacted = cleaned
1066
+ .replace(/[^a-z0-9가-힣\s]/g, ' ')
1067
+ .replace(/\s+/g, ' ')
1068
+ .trim();
1069
+ const safeKeyword = compacted;
1070
+ if (!safeKeyword) {
1071
+ return [];
1072
+ }
1073
+ imageTrace('buildKeywordImageCandidates.start', { safeKeyword });
1074
+
1075
+ const duckduckgoQueries = [
1076
+ safeKeyword,
1077
+ `${safeKeyword} 이미지`,
1078
+ `${safeKeyword} 뉴스`,
1079
+ ];
1080
+ const searchCandidates = [];
1081
+ const seen = new Set();
1082
+
1083
+ const collectIfImage = (imageUrl) => {
1084
+ const resolved = normalizeAbsoluteUrl(imageUrl);
1085
+ if (resolved && !seen.has(resolved)) {
1086
+ seen.add(resolved);
1087
+ searchCandidates.push(resolved);
1088
+ }
1089
+ };
1090
+
1091
+ for (const query of duckduckgoQueries) {
1092
+ if (searchCandidates.length >= 6) {
1093
+ break;
1094
+ }
1095
+ imageTrace('buildKeywordImageCandidates.ddgQuery', { query, currentCount: searchCandidates.length });
1096
+ const duckImages = await fetchDuckDuckGoImageResults(query);
1097
+ imageTrace('buildKeywordImageCandidates.ddgResult', { query, count: duckImages.length });
1098
+ for (const duckImage of duckImages.slice(0, 6)) {
1099
+ if (searchCandidates.length >= 6) break;
1100
+ collectIfImage(duckImage);
1101
+ }
1102
+ }
1103
+
1104
+ const fallbackQueries = [
1105
+ safeKeyword,
1106
+ `${safeKeyword} 이미지`,
1107
+ `${safeKeyword} news`,
1108
+ '뉴스',
1109
+ '세계 뉴스',
1110
+ ];
1111
+ for (const query of fallbackQueries) {
1112
+ if (searchCandidates.length >= 6) {
1113
+ break;
1114
+ }
1115
+ imageTrace('buildKeywordImageCandidates.fallbackQuery', { query, currentCount: searchCandidates.length });
1116
+ const wikiImages = await buildWikimediaImageCandidates(query);
1117
+ imageTrace('buildKeywordImageCandidates.wikimediaResult', { query, count: wikiImages.length });
1118
+ for (const candidate of wikiImages) {
1119
+ if (searchCandidates.length >= 6) {
1120
+ break;
1121
+ }
1122
+ collectIfImage(candidate);
1123
+ }
1124
+ for (const candidate of buildLoremFlickrImageCandidates(query)) {
1125
+ imageTrace('buildKeywordImageCandidates.loremflickrCandidate', { query, candidate });
1126
+ if (searchCandidates.length >= 6) {
1127
+ break;
1128
+ }
1129
+ collectIfImage(candidate);
1130
+ }
1131
+ for (const candidate of buildPicsumImageCandidates(query)) {
1132
+ imageTrace('buildKeywordImageCandidates.picsumCandidate', { query, candidate });
1133
+ if (searchCandidates.length >= 6) {
1134
+ break;
1135
+ }
1136
+ collectIfImage(candidate);
1137
+ }
1138
+ for (const candidate of buildPlaceholderImageCandidates()) {
1139
+ imageTrace('buildKeywordImageCandidates.placeholderCandidate', { candidate });
1140
+ if (searchCandidates.length >= 6) {
1141
+ break;
1142
+ }
1143
+ collectIfImage(candidate);
1144
+ }
1145
+ }
1146
+
1147
+ return searchCandidates.slice(0, 6);
1148
+ };
1149
+
1150
+ const extractImagePlaceholders = (content = '') => {
1151
+ const matches = Array.from(String(content).matchAll(IMAGE_PLACEHOLDER_REGEX));
1152
+ return matches.map((match) => ({
1153
+ raw: match[0],
1154
+ keyword: String(match[1] || '').trim(),
1155
+ }));
1156
+ };
1157
+
1158
+ const fetchImageBuffer = async (url, retryCount = 0) => {
1159
+ if (!url) {
1160
+ throw new Error('이미지 URL이 없습니다.');
1161
+ }
1162
+
1163
+ const localPath = resolveLocalImagePath(url);
1164
+ if (localPath && !/https?:/.test(url)) {
1165
+ const buffer = await fs.promises.readFile(localPath);
1166
+ if (!buffer || buffer.length === 0) {
1167
+ throw new Error(`이미지 파일이 비어 있습니다: ${localPath}`);
1168
+ }
1169
+
1170
+ const extensionFromSignature = getImageSignatureExtension(buffer);
1171
+ const extensionFromUrl = guessExtensionFromUrl(localPath);
1172
+ return {
1173
+ buffer,
1174
+ ext: extensionFromSignature || extensionFromUrl || 'jpg',
1175
+ finalUrl: localPath,
1176
+ isLocal: true,
1177
+ };
1178
+ }
1179
+
1180
+ const headers = {
1181
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
1182
+ 'Accept': 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
1183
+ 'Cache-Control': 'no-cache',
1184
+ };
1185
+ const controller = new AbortController();
1186
+ const timeout = setTimeout(() => controller.abort(), 20000);
1187
+
1188
+ try {
1189
+ const response = await fetch(url, {
1190
+ redirect: 'follow',
1191
+ signal: controller.signal,
1192
+ headers,
1193
+ });
1194
+
1195
+ if (!response.ok) {
1196
+ throw new Error(`이미지 다운로드 실패: ${response.status} ${response.statusText} (${url})`);
1197
+ }
1198
+
1199
+ const contentType = response.headers.get('content-type') || '';
1200
+ const normalizedContentType = contentType.toLowerCase();
1201
+ const finalUrl = response.url || url;
1202
+ const looksLikeHtml = normalizedContentType.includes('text/html') || normalizedContentType.includes('application/xhtml+xml');
1203
+ if (looksLikeHtml) {
1204
+ const html = await response.text();
1205
+ return {
1206
+ html,
1207
+ ext: 'jpg',
1208
+ finalUrl,
1209
+ isHtml: true,
1210
+ };
1211
+ }
1212
+
1213
+ const arrayBuffer = await response.arrayBuffer();
1214
+ const buffer = Buffer.from(arrayBuffer);
1215
+ const extensionFromUrl = guessExtensionFromUrl(finalUrl);
1216
+ const extensionFromSignature = getImageSignatureExtension(buffer);
1217
+ const isImage = isImageContentType(contentType)
1218
+ || extensionFromUrl
1219
+ || extensionFromSignature;
1220
+
1221
+ if (!isImage) {
1222
+ throw new Error(`이미지 콘텐츠가 아닙니다: ${contentType || '(미확인)'}, url=${finalUrl}`);
1223
+ }
1224
+
1225
+ return {
1226
+ buffer,
1227
+ ext: extensionFromSignature || guessExtensionFromContentType(contentType) || extensionFromUrl || 'jpg',
1228
+ finalUrl,
1229
+ };
1230
+ } catch (error) {
1231
+ if (retryCount < 1) {
1232
+ await new Promise((resolve) => setTimeout(resolve, 800));
1233
+ return fetchImageBuffer(url, retryCount + 1);
1234
+ }
1235
+ throw new Error(`이미지 다운로드 실패: ${error.message}`);
1236
+ } finally {
1237
+ clearTimeout(timeout);
1238
+ }
1239
+ };
1240
+
1241
+ const uploadImageFromRemote = async (api, remoteUrl, fallbackName = 'image', depth = 0) => {
1242
+ const downloaded = await fetchImageBuffer(remoteUrl);
1243
+
1244
+ if (downloaded?.isHtml && downloaded?.html) {
1245
+ const extractedImageUrl = extractImageFromHtml(downloaded.html, downloaded.finalUrl || remoteUrl);
1246
+ if (!extractedImageUrl) {
1247
+ throw new Error('이미지 페이지에서 유효한 대표 이미지를 찾지 못했습니다.');
1248
+ }
1249
+ if (depth >= 1 || extractedImageUrl === remoteUrl) {
1250
+ throw new Error('이미지 페이지에서 추출된 URL이 유효하지 않아 업로드를 중단했습니다.');
1251
+ }
1252
+ return uploadImageFromRemote(api, extractedImageUrl, fallbackName, depth + 1);
1253
+ }
1254
+ const tmpDir = normalizeTempDir();
1255
+ const filename = buildImageFileName(fallbackName, downloaded.ext);
1256
+ const filePath = path.join(tmpDir, filename);
1257
+
1258
+ await fs.promises.writeFile(filePath, downloaded.buffer);
1259
+ let uploaded;
1260
+ try {
1261
+ uploaded = await api.uploadImage(downloaded.buffer, filename);
1262
+ } finally {
1263
+ await fs.promises.unlink(filePath).catch(() => {});
1264
+ }
1265
+ const uploadedKage = normalizeUploadedImageThumbnail(uploaded) || (uploaded?.key ? `kage@${uploaded.key}` : null);
1266
+
1267
+ if (!uploaded || !(uploaded.url || uploaded.key)) {
1268
+ throw new Error('이미지 업로드 응답이 비정상적입니다.');
1269
+ }
1270
+
1271
+ return {
1272
+ sourceUrl: downloaded.finalUrl,
1273
+ uploadedUrl: uploaded.url,
1274
+ uploadedKey: uploaded.key || uploaded.url,
1275
+ uploadedKage,
1276
+ raw: uploaded,
1277
+ };
1278
+ };
1279
+
1280
+ const replaceImagePlaceholdersWithUploaded = async (
1281
+ api,
1282
+ content,
1283
+ autoUploadImages,
1284
+ relatedImageKeywords = [],
1285
+ imageUrls = [],
1286
+ _imageCountLimit = 1,
1287
+ _minimumImageCount = 1
1288
+ ) => {
1289
+ const originalContent = content || '';
1290
+ if (!autoUploadImages) {
1291
+ return {
1292
+ content: originalContent,
1293
+ uploaded: [],
1294
+ uploadedCount: 0,
1295
+ status: 'skipped',
1296
+ };
1297
+ }
1298
+
1299
+ let updatedContent = originalContent;
1300
+ const uploadedImages = [];
1301
+ const uploadErrors = [];
1302
+ const matches = extractImagePlaceholders(updatedContent);
1303
+ const collectedImageUrls = normalizeImageInputs(imageUrls);
1304
+ const hasPlaceholders = matches.length > 0;
1305
+
1306
+ const normalizedKeywords = Array.isArray(relatedImageKeywords)
1307
+ ? relatedImageKeywords.map((item) => String(item || '').trim()).filter(Boolean)
1308
+ : typeof relatedImageKeywords === 'string'
1309
+ ? relatedImageKeywords.split(',').map((item) => item.trim()).filter(Boolean)
1310
+ : [];
1311
+ const safeImageUploadLimit = MAX_IMAGE_UPLOAD_COUNT;
1312
+ const safeMinimumImageCount = MAX_IMAGE_UPLOAD_COUNT;
1313
+ const targetImageCount = MAX_IMAGE_UPLOAD_COUNT;
1314
+
1315
+ const uploadTargets = hasPlaceholders
1316
+ ? await Promise.all(matches.map(async (match, index) => {
1317
+ const keyword = match.keyword || normalizedKeywords[index] || '';
1318
+ const hasKeywordSource = Boolean(keyword);
1319
+ const primarySources = hasKeywordSource
1320
+ ? await buildKeywordImageCandidates(keyword)
1321
+ : [];
1322
+ const keywordSources = [...primarySources].filter(Boolean);
1323
+ const finalSources = keywordSources.length > 0
1324
+ ? keywordSources
1325
+ : [];
1326
+ return {
1327
+ placeholder: match,
1328
+ sources: [
1329
+ ...(collectedImageUrls[index] ? [collectedImageUrls[index]] : []),
1330
+ ...finalSources,
1331
+ ],
1332
+ keyword: keyword || `image-${index + 1}`,
1333
+ };
1334
+ }))
1335
+ : collectedImageUrls.slice(0, targetImageCount).map((imageUrl, index) => ({
1336
+ placeholder: null,
1337
+ sources: [imageUrl],
1338
+ keyword: normalizedKeywords[index] || `image-${index + 1}`,
1339
+ }));
1340
+
1341
+ const missingTargets = Math.max(0, targetImageCount - uploadTargets.length);
1342
+ const fallbackBaseKeywords = normalizedKeywords.length > 0 ? normalizedKeywords : [];
1343
+ const fallbackTargets = missingTargets > 0
1344
+ ? await Promise.all(Array.from({ length: missingTargets }).map(async (_, index) => {
1345
+ const keyword = fallbackBaseKeywords[index] || fallbackBaseKeywords[fallbackBaseKeywords.length - 1];
1346
+ const sources = await buildKeywordImageCandidates(keyword);
1347
+ return {
1348
+ placeholder: null,
1349
+ sources,
1350
+ keyword: keyword || `image-${uploadTargets.length + index + 1}`,
1351
+ };
1352
+ }))
1353
+ : [];
1354
+
1355
+ const finalUploadTargets = [...uploadTargets, ...fallbackTargets];
1356
+ const limitedUploadTargets = finalUploadTargets.slice(0, targetImageCount);
1357
+ const requestedImageCount = targetImageCount;
1358
+ const resolvedRequestedKeywords = dedupeTextValues(
1359
+ hasPlaceholders
1360
+ ? [
1361
+ ...matches.map((match) => match.keyword).filter(Boolean),
1362
+ ...finalUploadTargets.map((target) => target.keyword).filter(Boolean),
1363
+ ...normalizedKeywords,
1364
+ ]
1365
+ : normalizedKeywords
1366
+ );
1367
+
1368
+ const requestedKeywords = resolvedRequestedKeywords.length > 0
1369
+ ? resolvedRequestedKeywords
1370
+ : normalizedKeywords;
1371
+
1372
+ const hasUsableSource = limitedUploadTargets.some((target) => Array.isArray(target.sources) && target.sources.length > 0);
1373
+ if (!hasUsableSource) {
1374
+ return {
1375
+ content: originalContent,
1376
+ uploaded: [],
1377
+ uploadedCount: 0,
1378
+ status: 'need_image_urls',
1379
+ message: '자동 업로드할 이미지 후보 키워드가 없습니다. imageUrls 또는 relatedImageKeywords/플레이스홀더 키워드를 제공해 주세요.',
1380
+ requestedKeywords,
1381
+ requestedCount: requestedImageCount,
1382
+ providedImageUrls: collectedImageUrls.length,
1383
+ };
1384
+ }
1385
+
1386
+ for (let i = 0; i < limitedUploadTargets.length; i += 1) {
1387
+ const target = limitedUploadTargets[i];
1388
+ const uniqueSources = dedupeImageSources(target.sources);
1389
+ let uploadedImage = null;
1390
+ let lastMessage = '';
1391
+ let success = false;
1392
+
1393
+ if (uniqueSources.length === 0) {
1394
+ uploadErrors.push({
1395
+ index: i,
1396
+ sourceUrl: null,
1397
+ keyword: target.keyword,
1398
+ message: '이미지 소스가 없습니다.',
1399
+ });
1400
+ continue;
1401
+ }
1402
+
1403
+ for (let sourceIndex = 0; sourceIndex < uniqueSources.length; sourceIndex += 1) {
1404
+ const sourceUrl = uniqueSources[sourceIndex];
1405
+ if (IMAGE_TRACE_ENABLED) {
1406
+ imageTrace('uploadAttempt', {
1407
+ index: i,
1408
+ sourceIndex,
1409
+ sourceUrl,
1410
+ host: (() => {
1411
+ try {
1412
+ return new URL(sourceUrl).hostname;
1413
+ } catch {
1414
+ return 'invalid-url';
1415
+ }
1416
+ })(),
1417
+ });
1418
+ }
1419
+ try {
1420
+ uploadedImage = await uploadImageFromRemote(api, sourceUrl, target.keyword);
1421
+ success = true;
1422
+ break;
1423
+ } catch (error) {
1424
+ lastMessage = error.message;
1425
+ console.log('이미지 처리 실패:', sourceUrl, error.message);
1426
+ }
1427
+ }
1428
+
1429
+ if (!success) {
1430
+ const fallbackSources = dedupeImageSources([
1431
+ ...uniqueSources,
1432
+ ...(await buildFallbackImageSources(target.keyword)),
1433
+ ]);
1434
+
1435
+ for (let sourceIndex = 0; sourceIndex < fallbackSources.length; sourceIndex += 1) {
1436
+ const sourceUrl = fallbackSources[sourceIndex];
1437
+ if (uniqueSources.includes(sourceUrl)) {
1438
+ continue;
1439
+ }
1440
+ if (IMAGE_TRACE_ENABLED) {
1441
+ imageTrace('uploadAttempt.fallback', {
1442
+ index: i,
1443
+ sourceIndex,
1444
+ sourceUrl,
1445
+ host: (() => {
1446
+ try {
1447
+ return new URL(sourceUrl).hostname;
1448
+ } catch {
1449
+ return 'invalid-url';
1450
+ }
1451
+ })(),
1452
+ });
1453
+ }
1454
+ try {
1455
+ uploadedImage = await uploadImageFromRemote(api, sourceUrl, target.keyword);
1456
+ success = true;
1457
+ break;
1458
+ } catch (error) {
1459
+ lastMessage = error.message;
1460
+ console.log('이미지 처리 실패(보정 소스):', sourceUrl, error.message);
1461
+ }
1462
+ }
1463
+ }
1464
+
1465
+ if (!success) {
1466
+ uploadErrors.push({
1467
+ index: i,
1468
+ sourceUrl: uniqueSources[0],
1469
+ keyword: target.keyword,
1470
+ message: `이미지 업로드 실패(대체 이미지 재시도 포함): ${lastMessage}`,
1471
+ });
1472
+ continue;
1473
+ }
1474
+
1475
+ const tag = buildTistoryImageTag(uploadedImage, target.keyword);
1476
+ if (target.placeholder && target.placeholder.raw) {
1477
+ const replaced = new RegExp(escapeRegExp(target.placeholder.raw), 'g');
1478
+ updatedContent = updatedContent.replace(replaced, tag);
1479
+ } else {
1480
+ updatedContent = `${tag}\n${updatedContent}`;
1481
+ }
1482
+
1483
+ uploadedImages.push(uploadedImage);
1484
+ }
1485
+
1486
+ if (hasPlaceholders && uploadedImages.length === 0) {
1487
+ return {
1488
+ content: originalContent,
1489
+ uploaded: [],
1490
+ uploadedCount: 0,
1491
+ status: 'image_upload_failed',
1492
+ message: '이미지 업로드에 실패했습니다. 수집한 이미지 URL을 확인해 다시 호출해 주세요.',
1493
+ errors: uploadErrors,
1494
+ requestedKeywords,
1495
+ requestedCount: requestedImageCount,
1496
+ providedImageUrls: collectedImageUrls.length,
1497
+ };
1498
+ }
1499
+
1500
+ if (uploadErrors.length > 0) {
1501
+ if (uploadedImages.length < safeMinimumImageCount) {
1502
+ return {
1503
+ content: updatedContent,
1504
+ uploaded: uploadedImages,
1505
+ uploadedCount: uploadedImages.length,
1506
+ status: 'insufficient_images',
1507
+ message: `최소 이미지 업로드 장수를 충족하지 못했습니다. (요청: ${safeMinimumImageCount} / 실제: ${uploadedImages.length})`,
1508
+ errors: uploadErrors,
1509
+ requestedKeywords,
1510
+ requestedCount: requestedImageCount,
1511
+ uploadedPlaceholders: uploadedImages.length,
1512
+ providedImageUrls: collectedImageUrls.length,
1513
+ missingImageCount: Math.max(0, safeMinimumImageCount - uploadedImages.length),
1514
+ imageLimit: safeImageUploadLimit,
1515
+ };
1516
+ }
1517
+
1518
+ return {
1519
+ content: updatedContent,
1520
+ uploaded: uploadedImages,
1521
+ uploadedCount: uploadedImages.length,
1522
+ status: 'image_upload_partial',
1523
+ message: '일부 이미지 업로드가 실패했습니다.',
1524
+ errors: uploadErrors,
1525
+ requestedCount: requestedImageCount,
1526
+ uploadedPlaceholders: uploadedImages.length,
1527
+ providedImageUrls: collectedImageUrls.length,
1528
+ };
1529
+ }
1530
+
1531
+ if (safeMinimumImageCount > 0 && uploadedImages.length < safeMinimumImageCount) {
1532
+ return {
1533
+ content: updatedContent,
1534
+ uploaded: uploadedImages,
1535
+ uploadedCount: uploadedImages.length,
1536
+ status: 'insufficient_images',
1537
+ message: `최소 이미지 업로드 장수를 충족하지 못했습니다. (요청: ${safeMinimumImageCount} / 실제: ${uploadedImages.length})`,
1538
+ errors: uploadErrors,
1539
+ requestedKeywords,
1540
+ requestedCount: requestedImageCount,
1541
+ uploadedPlaceholders: uploadedImages.length,
1542
+ providedImageUrls: collectedImageUrls.length,
1543
+ missingImageCount: Math.max(0, safeMinimumImageCount - uploadedImages.length),
1544
+ imageLimit: safeImageUploadLimit,
1545
+ };
1546
+ }
1547
+
1548
+ return {
1549
+ content: updatedContent,
1550
+ uploaded: uploadedImages,
1551
+ uploadedCount: uploadedImages.length,
1552
+ status: 'ok',
1553
+ };
1554
+ };
1555
+
1556
+ const enrichContentWithUploadedImages = async ({
1557
+ api,
1558
+ rawContent,
1559
+ autoUploadImages,
1560
+ relatedImageKeywords = [],
1561
+ imageUrls = [],
1562
+ _imageUploadLimit = 1,
1563
+ _minimumImageCount = 1,
1564
+ }) => {
1565
+ const safeImageUploadLimit = MAX_IMAGE_UPLOAD_COUNT;
1566
+ const safeMinimumImageCount = MAX_IMAGE_UPLOAD_COUNT;
1567
+
1568
+ const shouldAutoUpload = autoUploadImages !== false;
1569
+ const enrichedImages = await replaceImagePlaceholdersWithUploaded(
1570
+ api,
1571
+ rawContent,
1572
+ shouldAutoUpload,
1573
+ relatedImageKeywords,
1574
+ imageUrls,
1575
+ safeImageUploadLimit,
1576
+ safeMinimumImageCount
1577
+ );
1578
+
1579
+ if (enrichedImages.status === 'need_image_urls') {
1580
+ return {
1581
+ status: 'need_image_urls',
1582
+ message: enrichedImages.message,
1583
+ requestedKeywords: enrichedImages.requestedKeywords,
1584
+ requestedCount: enrichedImages.requestedCount,
1585
+ providedImageUrls: enrichedImages.providedImageUrls,
1586
+ content: enrichedImages.content,
1587
+ images: enrichedImages.uploaded || [],
1588
+ imageCount: enrichedImages.uploadedCount,
1589
+ uploadedCount: enrichedImages.uploadedCount,
1590
+ uploadErrors: enrichedImages.errors || [],
1591
+ };
1592
+ }
1593
+
1594
+ if (enrichedImages.status === 'insufficient_images') {
1595
+ return {
1596
+ status: 'insufficient_images',
1597
+ message: enrichedImages.message,
1598
+ imageCount: enrichedImages.uploadedCount,
1599
+ requestedCount: enrichedImages.requestedCount,
1600
+ uploadedCount: enrichedImages.uploadedCount,
1601
+ images: enrichedImages.uploaded || [],
1602
+ content: enrichedImages.content,
1603
+ uploadErrors: enrichedImages.errors || [],
1604
+ providedImageUrls: enrichedImages.providedImageUrls,
1605
+ requestedKeywords: enrichedImages.requestedKeywords || [],
1606
+ missingImageCount: enrichedImages.missingImageCount || 0,
1607
+ imageLimit: enrichedImages.imageLimit || safeImageUploadLimit,
1608
+ minimumImageCount: safeMinimumImageCount,
1609
+ };
1610
+ }
1611
+
1612
+ if (enrichedImages.status === 'image_upload_failed' || enrichedImages.status === 'image_upload_partial') {
1613
+ return {
1614
+ status: enrichedImages.status,
1615
+ message: enrichedImages.message,
1616
+ imageCount: enrichedImages.uploadedCount,
1617
+ requestedCount: enrichedImages.requestedCount,
1618
+ uploadedCount: enrichedImages.uploadedCount,
1619
+ images: enrichedImages.uploaded || [],
1620
+ content: enrichedImages.content,
1621
+ uploadErrors: enrichedImages.errors || [],
1622
+ providedImageUrls: enrichedImages.providedImageUrls,
1623
+ };
1624
+ }
1625
+
1626
+ return {
1627
+ status: 'ok',
1628
+ content: enrichedImages.content,
1629
+ images: enrichedImages.uploaded || [],
1630
+ imageCount: enrichedImages.uploadedCount,
1631
+ uploadedCount: enrichedImages.uploadedCount,
1632
+ };
1633
+ };
1634
+
1635
+ const isLoggedInByCookies = async (context) => {
1636
+ const cookies = await context.cookies('https://www.tistory.com');
1637
+ return cookies.some((cookie) => {
1638
+ const name = cookie.name.toLowerCase();
1639
+ return name.includes('tistory') || name.includes('access') || name.includes('login');
1640
+ });
1641
+ };
1642
+
1643
+ const waitForLoginFinish = async (page, context, timeoutMs = 45000) => {
1644
+ const deadline = Date.now() + timeoutMs;
1645
+ while (Date.now() < deadline) {
1646
+ if (await isLoggedInByCookies(context)) {
1647
+ return true;
1648
+ }
1649
+
1650
+ if (await clickKakaoAccountContinue(page)) {
1651
+ continue;
1652
+ }
1653
+
1654
+ const url = page.url();
1655
+ if (!url.includes('/auth/login') && !url.includes('accounts.kakao.com/login') && !url.includes('kauth.kakao.com')) {
1656
+ return true;
1657
+ }
1658
+
1659
+ await sleep(1000);
1660
+ }
1661
+ return false;
1662
+ };
1663
+
1664
+ const withProviderSession = async (fn) => {
1665
+ const credentials = readCredentialsFromEnv();
1666
+ const hasCredentials = Boolean(credentials.username && credentials.password);
1667
+
1668
+ try {
1669
+ const result = await fn();
1670
+ saveProviderMeta('tistory', {
1671
+ loggedIn: true,
1672
+ lastValidatedAt: new Date().toISOString(),
1673
+ });
1674
+ return result;
1675
+ } catch (error) {
1676
+ if (!parseSessionError(error) || !hasCredentials) {
1677
+ throw error;
1678
+ }
1679
+
1680
+ try {
1681
+ const loginResult = await askForAuthentication({
1682
+ headless: false,
1683
+ manual: false,
1684
+ username: credentials.username,
1685
+ password: credentials.password,
1686
+ });
1687
+
1688
+ saveProviderMeta('tistory', {
1689
+ loggedIn: loginResult.loggedIn,
1690
+ blogName: loginResult.blogName,
1691
+ blogUrl: loginResult.blogUrl,
1692
+ sessionPath: loginResult.sessionPath,
1693
+ lastRefreshedAt: new Date().toISOString(),
1694
+ lastError: null,
1695
+ });
1696
+
1697
+ if (!loginResult.loggedIn) {
1698
+ throw new Error(loginResult.message || '세션 갱신 후 로그인 상태가 확인되지 않았습니다.');
1699
+ }
1700
+
1701
+ return fn();
1702
+ } catch (reloginError) {
1703
+ saveProviderMeta('tistory', {
1704
+ loggedIn: false,
1705
+ lastError: buildLoginErrorMessage(reloginError),
1706
+ lastValidatedAt: new Date().toISOString(),
1707
+ });
1708
+ throw reloginError;
1709
+ }
1710
+ }
1711
+ };
1712
+
1713
+ const persistTistorySession = async (context, targetSessionPath) => {
1714
+ const cookies = await context.cookies('https://www.tistory.com');
1715
+ const sanitized = cookies.map((cookie) => ({
1716
+ ...cookie,
1717
+ expires: Number(cookie.expires || -1),
1718
+ size: undefined,
1719
+ partitionKey: undefined,
1720
+ sourcePort: undefined,
1721
+ sourceScheme: undefined,
1722
+ }));
1723
+
1724
+ const payload = {
1725
+ cookies: sanitized,
1726
+ updatedAt: new Date().toISOString(),
1727
+ };
1728
+ await fs.promises.mkdir(path.dirname(targetSessionPath), { recursive: true });
1729
+ await fs.promises.writeFile(
1730
+ targetSessionPath,
1731
+ JSON.stringify(payload, null, 2),
1732
+ 'utf-8'
1733
+ );
1734
+ };
1735
+
1736
+ const createTistoryProvider = ({ sessionPath }) => {
1737
+ const tistoryApi = createTistoryApiClient({ sessionPath });
1738
+
1739
+ const pending2faResult = (mode = 'kakao') => ({
1740
+ provider: 'tistory',
1741
+ status: 'pending_2fa',
1742
+ loggedIn: false,
1743
+ message: mode === 'otp'
1744
+ ? '2차 인증이 필요합니다. otp 코드를 twoFactorCode로 전달해 주세요.'
1745
+ : '카카오 2차 인증이 필요합니다. 앱에서 인증 후 다시 실행하면 됩니다.',
1746
+ });
1747
+
1748
+ const askForAuthentication = async ({
1749
+ headless = false,
1750
+ manual = false,
1751
+ username,
1752
+ password,
1753
+ twoFactorCode,
1754
+ } = {}) => {
1755
+ fs.mkdirSync(path.dirname(sessionPath), { recursive: true });
1756
+
1757
+ const resolvedUsername = username || readCredentialsFromEnv().username;
1758
+ const resolvedPassword = password || readCredentialsFromEnv().password;
1759
+ const shouldAutoFill = !manual;
1760
+
1761
+ if (!manual && (!resolvedUsername || !resolvedPassword)) {
1762
+ throw new Error('티스토리 로그인 요청에 id/pw가 없습니다. id/pw를 먼저 전달하거나 TISTORY_USERNAME/TISTORY_PASSWORD를 설정해 주세요.');
1763
+ }
1764
+
1765
+ const browser = await chromium.launch({
1766
+ headless: manual ? false : headless,
1767
+ });
1768
+ const context = await browser.newContext();
1769
+
1770
+ const page = context.pages()[0] || (await context.newPage());
1771
+
1772
+ try {
1773
+ await page.goto('https://www.tistory.com/auth/login', {
1774
+ waitUntil: 'domcontentloaded',
1775
+ });
1776
+
1777
+ const loginId = resolvedUsername;
1778
+ const loginPw = resolvedPassword;
1779
+
1780
+ const kakaoLoginSelector = await pickValue(page, KAKAO_TRIGGER_SELECTORS);
1781
+ if (!kakaoLoginSelector) {
1782
+ throw new Error('카카오 로그인 버튼을 찾지 못했습니다. 로그인 화면 UI가 변경되었는지 확인해 주세요.');
1783
+ }
1784
+
1785
+ await page.locator(kakaoLoginSelector).click({ timeout: 5000 }).catch(() => {});
1786
+ await page.waitForLoadState('domcontentloaded').catch(() => {});
1787
+ await page.waitForTimeout(800);
1788
+
1789
+ let finalLoginStatus = false;
1790
+ let pendingTwoFactorAction = false;
1791
+
1792
+ if (manual) {
1793
+ console.log('');
1794
+ console.log('==============================');
1795
+ console.log('수동 로그인 모드로 전환합니다.');
1796
+ console.log('브라우저에서 직접 ID/PW/2차 인증을 완료한 뒤, 로그인 완료 상태를 기다립니다.');
1797
+ console.log('로그인 완료 또는 2차 인증은 최대 5분 내에 처리해 주세요.');
1798
+ console.log('==============================');
1799
+ finalLoginStatus = await waitForLoginFinish(page, context, 300000);
1800
+ } else if (shouldAutoFill) {
1801
+ const usernameFilled = await fillBySelector(page, KAKAO_LOGIN_SELECTORS.username, loginId);
1802
+ const passwordFilled = await fillBySelector(page, KAKAO_LOGIN_SELECTORS.password, loginPw);
1803
+ if (!usernameFilled || !passwordFilled) {
1804
+ throw new Error('카카오 로그인 폼 입력 필드를 찾지 못했습니다. 티스토리 로그인 화면 변경 시도를 확인해 주세요.');
1805
+ }
1806
+
1807
+ await checkBySelector(page, KAKAO_LOGIN_SELECTORS.rememberLogin);
1808
+ const kakaoSubmitted = await clickSubmit(page, KAKAO_LOGIN_SELECTORS.submit);
1809
+ if (!kakaoSubmitted) {
1810
+ await page.keyboard.press('Enter');
1811
+ }
1812
+
1813
+ finalLoginStatus = await waitForLoginFinish(page, context);
1814
+
1815
+ if (!finalLoginStatus && await hasElement(page, LOGIN_OTP_SELECTORS)) {
1816
+ if (!twoFactorCode) {
1817
+ return pending2faResult('otp');
1818
+ }
1819
+ const otpFilled = await fillBySelector(page, LOGIN_OTP_SELECTORS, twoFactorCode);
1820
+ if (!otpFilled) {
1821
+ throw new Error('OTP 입력 필드를 찾지 못했습니다. 로그인 페이지를 확인해 주세요.');
1822
+ }
1823
+ await page.keyboard.press('Enter');
1824
+ finalLoginStatus = await waitForLoginFinish(page, context, 45000);
1825
+ } else if (!finalLoginStatus && (await hasElement(page, KAKAO_2FA_SELECTORS.start) || page.url().includes('tmsTwoStepVerification') || page.url().includes('emailTwoStepVerification'))) {
1826
+ await checkBySelector(page, KAKAO_2FA_SELECTORS.rememberDevice);
1827
+ const isEmailModeAvailable = await hasElement(page, KAKAO_2FA_SELECTORS.emailModeButton);
1828
+ const hasEmailCodeInput = await hasElement(page, KAKAO_2FA_SELECTORS.codeInput);
1829
+
1830
+ if (hasEmailCodeInput && twoFactorCode) {
1831
+ const codeFilled = await fillBySelector(page, KAKAO_2FA_SELECTORS.codeInput, twoFactorCode);
1832
+ if (!codeFilled) {
1833
+ throw new Error('2차 인증 입력 필드를 찾지 못했습니다. 로그인 페이지를 확인해 주세요.');
1834
+ }
1835
+ const confirmed = await clickSubmit(page, KAKAO_2FA_SELECTORS.confirm);
1836
+ if (!confirmed) {
1837
+ await page.keyboard.press('Enter');
1838
+ }
1839
+ finalLoginStatus = await waitForLoginFinish(page, context, 45000);
1840
+ } else if (!twoFactorCode) {
1841
+ pendingTwoFactorAction = true;
1842
+ } else if (isEmailModeAvailable) {
1843
+ await clickSubmit(page, KAKAO_2FA_SELECTORS.emailModeButton).catch(() => {});
1844
+ await page.waitForLoadState('domcontentloaded').catch(() => {});
1845
+ await page.waitForTimeout(800);
1846
+
1847
+ const codeFilled = await fillBySelector(page, KAKAO_2FA_SELECTORS.codeInput, twoFactorCode);
1848
+ if (!codeFilled) {
1849
+ throw new Error('카카오 이메일 인증 입력 필드를 찾지 못했습니다. 로그인 페이지를 확인해 주세요.');
1850
+ }
1851
+
1852
+ const confirmed = await clickSubmit(page, KAKAO_2FA_SELECTORS.confirm);
1853
+ if (!confirmed) {
1854
+ await page.keyboard.press('Enter');
1855
+ }
1856
+ finalLoginStatus = await waitForLoginFinish(page, context, 45000);
1857
+ } else {
1858
+ return pending2faResult('kakao');
1859
+ }
1860
+ }
1861
+ }
1862
+
1863
+ if (!finalLoginStatus) {
1864
+ if (pendingTwoFactorAction) {
1865
+ return pending2faResult('kakao');
1866
+ }
1867
+ throw new Error('로그인에 실패했습니다. 아이디/비밀번호가 정확한지 확인하고, 없으면 환경변수 TISTORY_USERNAME/TISTORY_PASSWORD를 다시 설정해 주세요.');
1868
+ }
1869
+
1870
+ await context.storageState({ path: sessionPath });
1871
+ await persistTistorySession(context, sessionPath);
1872
+
1873
+ tistoryApi.resetState();
1874
+ const blogName = await tistoryApi.initBlog();
1875
+ return {
1876
+ provider: 'tistory',
1877
+ loggedIn: true,
1878
+ blogName,
1879
+ blogUrl: `https://${blogName}.tistory.com`,
1880
+ sessionPath,
1881
+ };
1882
+ } finally {
1883
+ if (browser) {
1884
+ await browser.close().catch(() => {});
1885
+ }
1886
+ }
1887
+ };
1888
+
1889
+ return {
1890
+ id: 'tistory',
1891
+ name: 'Tistory',
1892
+
1893
+ async authStatus() {
1894
+ return withProviderSession(async () => {
1895
+ try {
1896
+ const blogName = await tistoryApi.initBlog();
1897
+ return {
1898
+ provider: 'tistory',
1899
+ loggedIn: true,
1900
+ blogName,
1901
+ blogUrl: `https://${blogName}.tistory.com`,
1902
+ sessionPath,
1903
+ metadata: getProviderMeta('tistory') || {},
1904
+ };
1905
+ } catch (error) {
1906
+ return {
1907
+ provider: 'tistory',
1908
+ loggedIn: false,
1909
+ sessionPath,
1910
+ error: error.message,
1911
+ metadata: getProviderMeta('tistory') || {},
1912
+ };
1913
+ }
1914
+ });
1915
+ },
1916
+
1917
+ async login({
1918
+ headless = false,
1919
+ manual = false,
1920
+ username,
1921
+ password,
1922
+ twoFactorCode,
1923
+ } = {}) {
1924
+ const creds = readCredentialsFromEnv();
1925
+ const resolved = {
1926
+ headless,
1927
+ manual,
1928
+ username: username || creds.username,
1929
+ password: password || creds.password,
1930
+ twoFactorCode,
1931
+ };
1932
+
1933
+ if (!resolved.manual && (!resolved.username || !resolved.password)) {
1934
+ throw new Error('티스토리 자동 로그인을 진행하려면 username/password가 필요합니다. 요청 값으로 전달하거나, 환경변수 TISTORY_USERNAME / TISTORY_PASSWORD를 설정해 주세요.');
1935
+ }
1936
+
1937
+ const result = await askForAuthentication(resolved);
1938
+ saveProviderMeta('tistory', {
1939
+ loggedIn: result.loggedIn,
1940
+ blogName: result.blogName,
1941
+ blogUrl: result.blogUrl,
1942
+ sessionPath: result.sessionPath,
1943
+ });
1944
+ return result;
1945
+ },
1946
+
1947
+ async publish(payload) {
1948
+ return withProviderSession(async () => {
1949
+ const title = payload.title || '제목 없음';
1950
+ const rawContent = payload.content || '';
1951
+ const visibility = mapVisibility(payload.visibility);
1952
+ const tag = normalizeTagList(payload.tags);
1953
+ const rawThumbnail = payload.thumbnail || null;
1954
+ const relatedImageKeywords = payload.relatedImageKeywords || [];
1955
+ const imageUrls = payload.imageUrls || [];
1956
+ const autoUploadImages = payload.autoUploadImages !== false;
1957
+ const safeImageUploadLimit = MAX_IMAGE_UPLOAD_COUNT;
1958
+ const safeMinimumImageCount = MAX_IMAGE_UPLOAD_COUNT;
1959
+
1960
+ if (autoUploadImages) {
1961
+ await tistoryApi.initBlog();
1962
+ }
1963
+
1964
+ const enrichedImages = await enrichContentWithUploadedImages({
1965
+ api: tistoryApi,
1966
+ rawContent,
1967
+ autoUploadImages,
1968
+ relatedImageKeywords,
1969
+ imageUrls,
1970
+ imageUploadLimit: safeImageUploadLimit,
1971
+ minimumImageCount: safeMinimumImageCount,
1972
+ });
1973
+ if (enrichedImages.status === 'need_image_urls') {
1974
+ return {
1975
+ mode: 'publish',
1976
+ status: 'need_image_urls',
1977
+ loggedIn: true,
1978
+ provider: 'tistory',
1979
+ title,
1980
+ visibility,
1981
+ tags: tag,
1982
+ message: enrichedImages.message,
1983
+ requestedKeywords: enrichedImages.requestedKeywords,
1984
+ requestedCount: enrichedImages.requestedCount,
1985
+ providedImageUrls: enrichedImages.providedImageUrls,
1986
+ };
1987
+ }
1988
+
1989
+ if (enrichedImages.status === 'insufficient_images') {
1990
+ return {
1991
+ mode: 'publish',
1992
+ status: 'insufficient_images',
1993
+ loggedIn: true,
1994
+ provider: 'tistory',
1995
+ title,
1996
+ visibility,
1997
+ tags: tag,
1998
+ message: enrichedImages.message,
1999
+ imageCount: enrichedImages.uploadedCount,
2000
+ requestedCount: enrichedImages.requestedCount,
2001
+ uploadedCount: enrichedImages.uploadedCount,
2002
+ uploadErrors: enrichedImages.uploadErrors || [],
2003
+ providedImageUrls: enrichedImages.providedImageUrls,
2004
+ missingImageCount: enrichedImages.missingImageCount || 0,
2005
+ imageLimit: enrichedImages.imageLimit || safeImageUploadLimit,
2006
+ minimumImageCount: safeMinimumImageCount,
2007
+ };
2008
+ }
2009
+
2010
+ if (enrichedImages.status === 'image_upload_failed' || enrichedImages.status === 'image_upload_partial') {
2011
+ return {
2012
+ mode: 'publish',
2013
+ status: enrichedImages.status,
2014
+ loggedIn: true,
2015
+ provider: 'tistory',
2016
+ title,
2017
+ visibility,
2018
+ tags: tag,
2019
+ thumbnail: normalizeThumbnailForPublish(payload.thumbnail) || null,
2020
+ message: enrichedImages.message,
2021
+ imageCount: enrichedImages.uploadedCount,
2022
+ requestedCount: enrichedImages.requestedCount,
2023
+ uploadedCount: enrichedImages.uploadedCount,
2024
+ uploadErrors: enrichedImages.uploadErrors || [],
2025
+ providedImageUrls: enrichedImages.providedImageUrls,
2026
+ };
2027
+ }
2028
+ const content = enrichedImages.content;
2029
+ const uploadedImages = enrichedImages?.images || enrichedImages?.uploaded || [];
2030
+ const finalThumbnail = await resolveMandatoryThumbnail({
2031
+ rawThumbnail,
2032
+ content,
2033
+ uploadedImages,
2034
+ relatedImageKeywords,
2035
+ title,
2036
+ });
2037
+
2038
+ await tistoryApi.initBlog();
2039
+ const rawCategories = await tistoryApi.getCategories();
2040
+ const categories = buildCategoryList(rawCategories);
2041
+
2042
+ if (!isProvidedCategory(payload.category)) {
2043
+ if (categories.length === 0) {
2044
+ return {
2045
+ provider: 'tistory',
2046
+ mode: 'publish',
2047
+ status: 'need_category',
2048
+ loggedIn: true,
2049
+ title,
2050
+ visibility,
2051
+ tags: tag,
2052
+ message: '발행을 위해 카테고리가 필요합니다. categories를 확인하고 category를 지정해 주세요.',
2053
+ categories,
2054
+ };
2055
+ }
2056
+
2057
+ if (categories.length === 1) {
2058
+ payload = { ...payload, category: categories[0].id };
2059
+ } else {
2060
+ if (!process.stdin || !process.stdin.isTTY) {
2061
+ const sampleCategory = categories.slice(0, 5).map((item) => `${item.id}: ${item.name}`).join(', ');
2062
+ const sampleText = sampleCategory.length > 0 ? ` 예: ${sampleCategory}` : '';
2063
+ return {
2064
+ provider: 'tistory',
2065
+ mode: 'publish',
2066
+ status: 'need_category',
2067
+ loggedIn: true,
2068
+ title,
2069
+ visibility,
2070
+ tags: tag,
2071
+ message: `카테고리가 지정되지 않았습니다. 비대화형 환경에서는 --category 옵션이 필수입니다. 사용법: --category <카테고리ID>.${sampleText}`,
2072
+ categories,
2073
+ };
2074
+ }
2075
+
2076
+ const selectedCategoryId = await promptCategorySelection(categories);
2077
+ if (!selectedCategoryId) {
2078
+ return {
2079
+ provider: 'tistory',
2080
+ mode: 'publish',
2081
+ status: 'need_category',
2082
+ loggedIn: true,
2083
+ title,
2084
+ visibility,
2085
+ tags: tag,
2086
+ message: '카테고리가 지정되지 않았습니다. 카테고리를 입력해 발행을 진행해 주세요.',
2087
+ categories,
2088
+ };
2089
+ }
2090
+
2091
+ payload = { ...payload, category: selectedCategoryId };
2092
+ }
2093
+ }
2094
+
2095
+ const category = Number(payload.category);
2096
+ if (!Number.isInteger(category) || Number.isNaN(category)) {
2097
+ return {
2098
+ provider: 'tistory',
2099
+ mode: 'publish',
2100
+ status: 'invalid_category',
2101
+ loggedIn: true,
2102
+ title,
2103
+ visibility,
2104
+ tags: tag,
2105
+ message: '유효한 category를 숫자로 지정해 주세요.',
2106
+ categories,
2107
+ };
2108
+ }
2109
+
2110
+ const validCategoryIds = categories.map((item) => item.id);
2111
+ if (!validCategoryIds.includes(category) && categories.length > 0) {
2112
+ return {
2113
+ provider: 'tistory',
2114
+ mode: 'publish',
2115
+ status: 'invalid_category',
2116
+ loggedIn: true,
2117
+ title,
2118
+ visibility,
2119
+ tags: tag,
2120
+ message: '존재하지 않는 category입니다. categories를 확인해 주세요.',
2121
+ categories,
2122
+ };
2123
+ }
2124
+
2125
+ try {
2126
+ const result = await tistoryApi.publishPost({
2127
+ title,
2128
+ content,
2129
+ visibility,
2130
+ category,
2131
+ tag,
2132
+ thumbnail: finalThumbnail,
2133
+ });
2134
+
2135
+ return {
2136
+ provider: 'tistory',
2137
+ mode: 'publish',
2138
+ title,
2139
+ category,
2140
+ visibility,
2141
+ tags: tag,
2142
+ thumbnail: finalThumbnail,
2143
+ images: enrichedImages.images,
2144
+ imageCount: enrichedImages.uploadedCount,
2145
+ minimumImageCount: safeMinimumImageCount,
2146
+ url: result.entryUrl || null,
2147
+ raw: result,
2148
+ };
2149
+ } catch (error) {
2150
+ if (!isPublishLimitError(error)) {
2151
+ throw error;
2152
+ }
2153
+
2154
+ try {
2155
+ const fallbackPublishResult = await tistoryApi.publishPost({
2156
+ title,
2157
+ content,
2158
+ visibility: 0,
2159
+ category,
2160
+ tag,
2161
+ thumbnail: finalThumbnail,
2162
+ });
2163
+
2164
+ return {
2165
+ provider: 'tistory',
2166
+ mode: 'publish',
2167
+ status: 'publish_fallback_to_private',
2168
+ title,
2169
+ category,
2170
+ visibility: 0,
2171
+ tags: tag,
2172
+ thumbnail: finalThumbnail,
2173
+ images: enrichedImages.images,
2174
+ imageCount: enrichedImages.uploadedCount,
2175
+ minimumImageCount: safeMinimumImageCount,
2176
+ url: fallbackPublishResult.entryUrl || null,
2177
+ raw: fallbackPublishResult,
2178
+ message: '발행 제한(403)으로 인해 비공개로 발행했습니다.',
2179
+ fallbackThumbnail: finalThumbnail,
2180
+ };
2181
+ } catch (fallbackError) {
2182
+ if (!isPublishLimitError(fallbackError)) {
2183
+ throw fallbackError;
2184
+ }
2185
+
2186
+ return {
2187
+ provider: 'tistory',
2188
+ mode: 'publish',
2189
+ status: 'publish_fallback_to_private_failed',
2190
+ title,
2191
+ category,
2192
+ visibility: 0,
2193
+ tags: tag,
2194
+ thumbnail: finalThumbnail,
2195
+ images: enrichedImages.images,
2196
+ imageCount: enrichedImages.uploadedCount,
2197
+ minimumImageCount: safeMinimumImageCount,
2198
+ message: '발행 제한(403)으로 인해 공개/비공개 모두 실패했습니다.',
2199
+ raw: {
2200
+ success: false,
2201
+ error: fallbackError.message,
2202
+ },
2203
+ };
2204
+ }
2205
+ }
2206
+ });
2207
+ },
2208
+
2209
+ async saveDraft(payload) {
2210
+ return withProviderSession(async () => {
2211
+ const title = payload.title || '임시저장';
2212
+ const rawContent = payload.content || '';
2213
+ const rawThumbnail = payload.thumbnail || null;
2214
+ const tag = normalizeTagList(payload.tags);
2215
+ const relatedImageKeywords = payload.relatedImageKeywords || [];
2216
+ const imageUrls = payload.imageUrls || [];
2217
+ const autoUploadImages = payload.autoUploadImages !== false;
2218
+ const safeImageUploadCount = MAX_IMAGE_UPLOAD_COUNT;
2219
+ const safeMinimumImageCount = MAX_IMAGE_UPLOAD_COUNT;
2220
+
2221
+ if (autoUploadImages) {
2222
+ await tistoryApi.initBlog();
2223
+ }
2224
+
2225
+ const enrichedImages = await enrichContentWithUploadedImages({
2226
+ api: tistoryApi,
2227
+ rawContent,
2228
+ autoUploadImages,
2229
+ relatedImageKeywords,
2230
+ imageUrls,
2231
+ imageUploadLimit: safeImageUploadCount,
2232
+ minimumImageCount: safeMinimumImageCount,
2233
+ });
2234
+ if (enrichedImages.status === 'need_image_urls') {
2235
+ return {
2236
+ mode: 'draft',
2237
+ status: 'need_image_urls',
2238
+ loggedIn: true,
2239
+ provider: 'tistory',
2240
+ title,
2241
+ message: enrichedImages.message,
2242
+ requestedKeywords: enrichedImages.requestedKeywords,
2243
+ requestedCount: enrichedImages.requestedCount,
2244
+ providedImageUrls: enrichedImages.providedImageUrls,
2245
+ imageCount: enrichedImages.imageCount,
2246
+ minimumImageCount: safeMinimumImageCount,
2247
+ images: enrichedImages.uploaded || [],
2248
+ uploadedCount: enrichedImages.uploadedCount,
2249
+ };
2250
+ }
2251
+
2252
+ if (enrichedImages.status === 'insufficient_images') {
2253
+ return {
2254
+ mode: 'draft',
2255
+ status: 'insufficient_images',
2256
+ loggedIn: true,
2257
+ provider: 'tistory',
2258
+ title,
2259
+ message: enrichedImages.message,
2260
+ imageCount: enrichedImages.imageCount,
2261
+ requestedCount: enrichedImages.requestedCount,
2262
+ uploadedCount: enrichedImages.uploadedCount,
2263
+ uploadErrors: enrichedImages.uploadErrors,
2264
+ providedImageUrls: enrichedImages.providedImageUrls,
2265
+ minimumImageCount: safeMinimumImageCount,
2266
+ imageLimit: enrichedImages.imageLimit || safeImageUploadCount,
2267
+ images: enrichedImages.uploaded || [],
2268
+ };
2269
+ }
2270
+
2271
+ if (enrichedImages.status === 'image_upload_failed' || enrichedImages.status === 'image_upload_partial') {
2272
+ return {
2273
+ mode: 'draft',
2274
+ status: enrichedImages.status,
2275
+ loggedIn: true,
2276
+ provider: 'tistory',
2277
+ title,
2278
+ message: enrichedImages.message,
2279
+ imageCount: enrichedImages.imageCount,
2280
+ requestedCount: enrichedImages.requestedCount,
2281
+ uploadedCount: enrichedImages.uploadedCount,
2282
+ uploadErrors: enrichedImages.uploadErrors || [],
2283
+ providedImageUrls: enrichedImages.providedImageUrls,
2284
+ images: enrichedImages.uploaded || [],
2285
+ };
2286
+ }
2287
+
2288
+ const content = enrichedImages.content;
2289
+ const thumbnail = await resolveMandatoryThumbnail({
2290
+ rawThumbnail,
2291
+ content,
2292
+ uploadedImages: enrichedImages?.uploaded || [],
2293
+ relatedImageKeywords,
2294
+ title,
2295
+ });
2296
+
2297
+ await tistoryApi.initBlog();
2298
+ const result = await tistoryApi.saveDraft({ title, content });
2299
+ return {
2300
+ provider: 'tistory',
2301
+ mode: 'draft',
2302
+ title,
2303
+ status: 'ok',
2304
+ category: Number(payload.category) || 0,
2305
+ tags: tag,
2306
+ sequence: result.draft?.sequence || null,
2307
+ thumbnail,
2308
+ minimumImageCount: safeMinimumImageCount,
2309
+ imageCount: enrichedImages.imageCount,
2310
+ images: enrichedImages.uploaded || [],
2311
+ uploadErrors: enrichedImages.uploadErrors || null,
2312
+ draftContent: content,
2313
+ raw: result,
2314
+ };
2315
+ });
2316
+ },
2317
+
2318
+ async listCategories() {
2319
+ return withProviderSession(async () => {
2320
+ await tistoryApi.initBlog();
2321
+ const categories = await tistoryApi.getCategories();
2322
+ return {
2323
+ provider: 'tistory',
2324
+ categories: Object.entries(categories).map(([name, id]) => ({
2325
+ name,
2326
+ id: Number(id),
2327
+ })),
2328
+ };
2329
+ });
2330
+ },
2331
+
2332
+ async listPosts({ limit = 20 } = {}) {
2333
+ return withProviderSession(async () => {
2334
+ await tistoryApi.initBlog();
2335
+ const result = await tistoryApi.getPosts();
2336
+ const items = Array.isArray(result?.items) ? result.items : [];
2337
+ return {
2338
+ provider: 'tistory',
2339
+ totalCount: result.totalCount || items.length,
2340
+ posts: items.slice(0, Math.max(1, Number(limit) || 20)),
2341
+ };
2342
+ });
2343
+ },
2344
+
2345
+ async getPost({ postId, includeDraft = false } = {}) {
2346
+ return withProviderSession(async () => {
2347
+ const resolvedPostId = String(postId || '').trim();
2348
+ if (!resolvedPostId) {
2349
+ return {
2350
+ provider: 'tistory',
2351
+ mode: 'post',
2352
+ status: 'invalid_post_id',
2353
+ message: 'postId가 필요합니다.',
2354
+ };
2355
+ }
2356
+
2357
+ await tistoryApi.initBlog();
2358
+ const post = await tistoryApi.getPost({
2359
+ postId: resolvedPostId,
2360
+ includeDraft: Boolean(includeDraft),
2361
+ });
2362
+ if (!post) {
2363
+ return {
2364
+ provider: 'tistory',
2365
+ mode: 'post',
2366
+ status: 'not_found',
2367
+ postId: resolvedPostId,
2368
+ includeDraft: Boolean(includeDraft),
2369
+ message: '해당 postId의 글을 찾을 수 없습니다.',
2370
+ };
2371
+ }
2372
+ return {
2373
+ provider: 'tistory',
2374
+ mode: 'post',
2375
+ postId: resolvedPostId,
2376
+ post,
2377
+ includeDraft: Boolean(includeDraft),
2378
+ };
2379
+ });
2380
+ },
2381
+
2382
+ async logout() {
2383
+ clearProviderMeta('tistory');
2384
+ return {
2385
+ provider: 'tistory',
2386
+ loggedOut: true,
2387
+ sessionPath,
2388
+ };
2389
+ },
2390
+ };
2391
+ };
2392
+
2393
+ module.exports = createTistoryProvider;