-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
763 lines (660 loc) · 25.1 KB
/
content.js
File metadata and controls
763 lines (660 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
// LinkedIn Post to Markdown - Content Script v6
// Fixes: MutationObserver, scoped selectors, no silent failures
// v3: Document-wide fallback for author/date on single-post pages
// v4: Sponsored/promoted content filtering
// v5: i18n indicators, URN/URL correlation, siblings check
// v6: CJK-aware matching, self-tests
(function() {
'use strict';
// Patterns to identify sponsored/promoted content containers
const EXCLUDED_PATTERNS = [
'[data-urn*="sponsoredActivity"]',
'[data-urn*="promoted"]',
'[data-ad-banner]',
'[data-test-id*="promoted"]',
'[data-test-id*="suggested"]',
'.feed-shared-update-v2--e2e-promoted',
'.sponsored-update',
'.promoted-update',
'.ad-banner-container',
'.feed-shared-sponsored'
];
// Alphabetic script indicators (use word boundaries)
const SPONSORED_INDICATORS_ALPHABETIC = [
// English
'promoted', 'sponsored', 'ad',
// French
'sponsorisé', 'publicité', 'promu',
// German
'gesponsert', 'anzeige', 'werbung',
// Spanish
'promocionado', 'patrocinado', 'anuncio',
// Italian
'sponsorizzato', 'pubblicità', 'annuncio',
// Portuguese
'patrocinado', 'promovido', 'anúncio',
// Dutch
'gesponsord', 'advertentie',
// Polish
'promowane', 'sponsorowane', 'reklama',
// Swedish
'sponsrad', 'annons',
// Norwegian
'sponset', 'annonse',
// Danish
'sponsoreret', 'annonce',
// Finnish
'sponsoroitu', 'mainos',
// Russian (Cyrillic - uses spaces as word boundaries)
'реклама', 'продвигается', 'спонсор',
// Turkish
'sponsorlu', 'reklam', 'tanıtım',
// Indonesian/Malay
'disponsori', 'iklan', 'promosi',
// Vietnamese
'quảng cáo', 'được tài trợ',
// Czech
'sponzorováno', 'reklama',
// Greek
'χορηγούμενο', 'διαφήμιση',
// Hungarian
'szponzorált', 'hirdetés',
// Romanian
'sponsorizat', 'reclamă'
];
// CJK and other logographic/complex script indicators (use includes, no word boundaries)
const SPONSORED_INDICATORS_CJK = [
// Japanese
'広告', 'プロモーション', 'スポンサー', 'PR',
// Korean
'광고', '홍보', '스폰서',
// Chinese (Simplified)
'广告', '推广', '赞助',
// Chinese (Traditional)
'廣告', '推廣', '贊助',
// Thai
'โฆษณา', 'สนับสนุน', 'โปรโมท',
// Arabic
'إعلان', 'ممول', 'برعاية',
// Hebrew
'ממומן', 'פרסומת',
// Hindi
'प्रायोजित', 'विज्ञापन'
];
// Combined list for iteration
const SPONSORED_TEXT_INDICATORS = [
...SPONSORED_INDICATORS_ALPHABETIC,
...SPONSORED_INDICATORS_CJK
];
// Check if string contains CJK characters (Chinese, Japanese, Korean)
function containsCJK(text) {
// CJK Unified Ideographs, Hiragana, Katakana, Hangul
return /[\u4E00-\u9FFF\u3040-\u309F\u30A0-\u30FF\uAC00-\uD7AF]/.test(text);
}
// Check if string contains RTL or complex scripts (Arabic, Hebrew, Thai, Hindi)
function containsComplexScript(text) {
// Arabic, Hebrew, Thai, Devanagari (Hindi)
return /[\u0600-\u06FF\u0590-\u05FF\u0E00-\u0E7F\u0900-\u097F]/.test(text);
}
// Escape special regex characters
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Smart indicator matching - handles CJK and complex scripts properly
function matchesSponsoredIndicator(text, indicator) {
if (!text || !indicator) return false;
const lowerText = text.toLowerCase();
const lowerIndicator = indicator.toLowerCase();
// For CJK or complex script indicators, use simple includes (no word boundaries)
if (containsCJK(indicator) || containsComplexScript(indicator)) {
return lowerText.includes(lowerIndicator);
}
// For alphabetic scripts, use word boundaries to avoid partial matches
try {
const regex = new RegExp('\\b' + escapeRegex(lowerIndicator) + '\\b', 'i');
return regex.test(text);
} catch (e) {
// Fallback to includes if regex fails
return lowerText.includes(lowerIndicator);
}
}
const SELECTORS = {
postContainer: [
'[data-urn*="urn:li:activity"]',
'.feed-shared-update-v2',
'.occludable-update',
'article[data-id]'
],
postText: [
'.feed-shared-update-v2__description .break-words',
'.feed-shared-text__text-view',
'.feed-shared-inline-show-more-text',
'[data-test-id="main-feed-activity-card__commentary"]',
'.update-components-text'
],
seeMore: [
'.feed-shared-inline-show-more-text button',
'button[aria-label*="see more"]',
'button[aria-label*="voir plus"]',
'button[aria-label*="plus"]',
'.see-more'
],
// Scoped selectors (within post container)
authorName: [
'.feed-shared-actor__name .visually-hidden',
'.feed-shared-actor__name span[aria-hidden="true"]',
'.update-components-actor__name .visually-hidden',
'.update-components-actor__name span',
'[data-test-id="actor-name"]'
],
postDate: [
'time[datetime]',
'.feed-shared-actor__sub-description time',
'.update-components-actor__sub-description time',
'.feed-shared-actor__sub-description span[aria-hidden="true"]'
],
// Document-wide fallback selectors for single-post pages (/posts/, /feed/update/)
authorNameGlobal: [
// Actor name in various LinkedIn layouts
'.update-components-actor__title .visually-hidden',
'.update-components-actor__title span[aria-hidden="true"]',
'.update-components-actor__name',
'.feed-shared-actor__title .visually-hidden',
'.feed-shared-actor__title span[aria-hidden="true"]',
// Profile link text
'.update-components-actor__container a[href*="/in/"] .visually-hidden',
'.update-components-actor__container a[href*="/in/"] span[aria-hidden="true"]',
// Linked area author
'.linked-area .update-components-actor__name',
'.linked-area .feed-shared-actor__name span',
// Generic profile components
'[data-urn*="member"] .actor-name',
'.entity-result__title-text a',
// Post header on detail pages
'.share-update-card__actor-text',
'.share-update-card__actor-text-link'
],
postDateGlobal: [
// Any time element with datetime attribute
'time[datetime]',
// Actor sub-description areas
'.update-components-actor__sub-description time',
'.update-components-actor__sub-description span.visually-hidden',
'.feed-shared-actor__sub-description time',
'.feed-shared-actor__sub-description span.visually-hidden',
// Meta info
'.update-components-actor__meta time',
'.update-components-actor__meta span[aria-hidden="true"]',
// Linked area
'.linked-area time[datetime]',
'.linked-area .update-components-actor__sub-description'
]
};
// Scoped querySelector with fallbacks
function querySelector(selectors, container = document) {
for (const selector of selectors) {
const element = container.querySelector(selector);
if (element) return element;
}
return null;
}
// Check if element is within a sponsored/promoted container (multi-directional)
function isExcludedElement(element) {
if (!element) return false;
// 1. Check ancestors (closest)
for (const selector of EXCLUDED_PATTERNS) {
try {
if (element.closest(selector)) return true;
} catch (e) {}
}
// 2. Check if element itself matches
for (const selector of EXCLUDED_PATTERNS) {
try {
if (element.matches(selector)) return true;
} catch (e) {}
}
// 3. Check descendants (contains sponsored element)
for (const selector of EXCLUDED_PATTERNS) {
try {
if (element.querySelector(selector)) return true;
} catch (e) {}
}
// 4. Check text indicators in actor/meta area (v6: CJK-aware matching)
const actorMeta = element.querySelector(
'.feed-shared-actor__sub-description, .update-components-actor__sub-description, .update-components-actor__meta'
);
if (actorMeta) {
const text = actorMeta.textContent;
for (const indicator of SPONSORED_TEXT_INDICATORS) {
if (matchesSponsoredIndicator(text, indicator)) return true;
}
}
// 5. Check siblings for sponsored indicators (v5, v6: CJK-aware)
const parent = element.parentElement;
if (parent) {
for (const sibling of parent.children) {
if (sibling === element) continue;
// Check if sibling matches excluded patterns
for (const selector of EXCLUDED_PATTERNS) {
try {
if (sibling.matches && sibling.matches(selector)) return true;
if (sibling.querySelector && sibling.querySelector(selector)) return true;
} catch (e) {}
}
// Check sibling text for sponsored indicators (limit scope to small elements)
if (sibling.textContent && sibling.textContent.length < 100) {
const siblingText = sibling.textContent;
for (const indicator of SPONSORED_TEXT_INDICATORS) {
if (matchesSponsoredIndicator(siblingText, indicator)) return true;
}
}
}
}
return false;
}
// Count post containers on page (for context detection)
function countPostContainers() {
let count = 0;
for (const selector of SELECTORS.postContainer) {
count += document.querySelectorAll(selector).length;
if (count > 1) return count;
}
return count;
}
// Detect page context via DOM analysis
function getPageContext() {
const url = window.location.href;
const isSinglePostUrl = url.includes('/posts/') ||
url.includes('/feed/update/') ||
url.includes('/activity/');
// FIX v3: Si URL indique post unique, faire confiance à l'URL
// LinkedIn affiche des posts suggérés mais le post principal reste le premier dans le DOM
if (isSinglePostUrl) {
return { type: 'single-post', canExtract: true };
}
// Seulement sur les pages sans pattern d'URL post (feed principal)
const postCount = countPostContainers();
if (postCount > 1) {
return {
type: 'feed',
canExtract: false,
error: 'Plusieurs posts détectés. Ouvrez le post dans un nouvel onglet pour l\'extraire.'
};
}
if (postCount === 1) {
return { type: 'single-post', canExtract: true };
}
return {
type: 'unknown',
canExtract: false,
error: 'Aucun post LinkedIn détecté sur cette page.'
};
}
// Extract activity ID from URL for precise container targeting (v5)
function extractActivityIdFromUrl() {
const url = window.location.href;
// Pattern: /feed/update/urn:li:activity:1234567890/
const activityMatch = url.match(/urn:li:activity:(\d+)/);
if (activityMatch) return activityMatch[1];
// Pattern: /posts/username_activity-1234567890-xxxx/
const postsMatch = url.match(/activity-(\d+)/);
if (postsMatch) return postsMatch[1];
return null;
}
// Find container by specific activity ID (v5)
function findPostContainerByActivityId(activityId) {
if (!activityId) return null;
// Target directly the container with this ID
const selector = `[data-urn*="urn:li:activity:${activityId}"]`;
const container = document.querySelector(selector);
if (container && !isExcludedElement(container)) {
return container;
}
return null;
}
// Find the main post container (filters out sponsored/promoted)
function findPostContainer() {
// Priority 1: Try to find by activity ID from URL (most precise) - v5
const activityId = extractActivityIdFromUrl();
if (activityId) {
const container = findPostContainerByActivityId(activityId);
if (container) return container;
}
// Priority 2: Fallback to querySelectorAll with filtering
for (const selector of SELECTORS.postContainer) {
const containers = document.querySelectorAll(selector);
for (const container of containers) {
// Skip sponsored/promoted containers
if (!isExcludedElement(container)) {
return container;
}
}
}
return null;
}
// Wait for DOM stabilization after "see more" click (debounced MutationObserver)
function waitForContentExpansion(container, timeout = 2000) {
return new Promise((resolve) => {
let debounceTimer = null;
const DEBOUNCE_MS = 150;
const observer = new MutationObserver(() => {
// Reset debounce timer on each mutation
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
observer.disconnect();
resolve({ success: true });
}, DEBOUNCE_MS);
});
observer.observe(container, {
childList: true,
subtree: true,
characterData: true
});
// Max timeout fallback
setTimeout(() => {
if (debounceTimer) clearTimeout(debounceTimer);
observer.disconnect();
resolve({ success: true, timeout: true });
}, timeout);
});
}
// Expand "See more" with proper waiting
async function expandSeeMore(container) {
const seeMoreBtn = querySelector(SELECTORS.seeMore, container);
if (!seeMoreBtn || seeMoreBtn.offsetParent === null) {
return { expanded: false, alreadyExpanded: true };
}
seeMoreBtn.click();
const result = await waitForContentExpansion(container);
return { expanded: true, ...result };
}
// Parse relative date with word boundaries (FR/EN)
function parseRelativeDate(dateText, container, dateEl = null) {
// Priority 1: datetime attribute on the element itself (most reliable)
if (dateEl && dateEl.hasAttribute && dateEl.hasAttribute('datetime')) {
const dt = new Date(dateEl.getAttribute('datetime'));
if (!isNaN(dt)) return dt.toISOString().split('T')[0];
}
// Priority 2: Find time[datetime] in container
const timeEl = container.querySelector ? container.querySelector('time[datetime]') : null;
if (timeEl && timeEl.hasAttribute('datetime')) {
const dt = new Date(timeEl.getAttribute('datetime'));
if (!isNaN(dt)) return dt.toISOString().split('T')[0];
}
// Priority 3: Find any time[datetime] in document (for single-post pages)
const globalTimeEl = document.querySelector('time[datetime]');
if (globalTimeEl && globalTimeEl.hasAttribute('datetime')) {
const dt = new Date(globalTimeEl.getAttribute('datetime'));
if (!isNaN(dt)) return dt.toISOString().split('T')[0];
}
if (!dateText) return null;
const now = new Date();
const text = dateText.toLowerCase().trim();
// Word boundary patterns to avoid false positives
const patterns = [
{ regex: /\b(\d+)\s*(secondes?|seconds?|sec|s)\b/i, unit: 'seconds' },
{ regex: /\b(\d+)\s*(minutes?|min|m)\b/i, unit: 'minutes' },
{ regex: /\b(\d+)\s*(heures?|hours?|hr|h)\b/i, unit: 'hours' },
{ regex: /\b(\d+)\s*(jours?|days?|j|d)\b/i, unit: 'days' },
{ regex: /\b(\d+)\s*(semaines?|weeks?|sem|w)\b/i, unit: 'weeks' },
{ regex: /\b(\d+)\s*(mois|months?|mo)\b/i, unit: 'months' },
{ regex: /\b(\d+)\s*(ans?|years?|yr)\b/i, unit: 'years' },
{ regex: /\bhier\b|\byesterday\b/i, unit: 'yesterday' },
{ regex: /\baujourd'hui\b|\btoday\b/i, unit: 'today' }
];
for (const { regex, unit } of patterns) {
const match = text.match(regex);
if (match) {
const value = parseInt(match[1]) || 1;
const date = new Date(now);
switch (unit) {
case 'seconds': date.setSeconds(date.getSeconds() - value); break;
case 'minutes': date.setMinutes(date.getMinutes() - value); break;
case 'hours': date.setHours(date.getHours() - value); break;
case 'days': date.setDate(date.getDate() - value); break;
case 'weeks': date.setDate(date.getDate() - (value * 7)); break;
case 'months': date.setMonth(date.getMonth() - value); break;
case 'years': date.setFullYear(date.getFullYear() - value); break;
case 'yesterday': date.setDate(date.getDate() - 1); break;
case 'today': break;
}
return date.toISOString().split('T')[0];
}
}
// Fallback: try to parse as absolute date
const parsed = new Date(dateText);
if (!isNaN(parsed) && parsed < now) {
return parsed.toISOString().split('T')[0];
}
return null;
}
// Extract post text (scoped to container)
function extractPostText(container) {
const textEl = querySelector(SELECTORS.postText, container);
if (!textEl) return null;
let text = '';
const walker = document.createTreeWalker(
textEl,
NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
null,
false
);
let node;
while (node = walker.nextNode()) {
if (node.nodeType === Node.TEXT_NODE) {
text += node.textContent;
} else if (node.nodeName === 'BR') {
text += '\n';
} else if (node.nodeName === 'P' || node.nodeName === 'DIV') {
if (text && !text.endsWith('\n')) text += '\n';
}
}
const cleaned = text
.replace(/\n{3,}/g, '\n\n')
.replace(/[ \t]+/g, ' ')
.trim();
return cleaned || null;
}
// Extract author (scoped with document-wide fallback for single-post pages)
function extractAuthor(container, isSinglePost = false) {
// Try scoped selectors first
let authorEl = querySelector(SELECTORS.authorName, container);
// Fallback to document-wide selectors on single-post pages
if (!authorEl && isSinglePost) {
authorEl = querySelector(SELECTORS.authorNameGlobal, document);
}
// Reject if element is within sponsored/promoted container
if (authorEl && isExcludedElement(authorEl)) {
authorEl = null;
}
if (!authorEl) return null;
let name = authorEl.textContent.trim();
// Clean up common prefixes/suffixes
name = name
.replace(/^(View|Voir)\s+/i, '')
.replace(/('s profile|profil de)$/i, '')
.replace(/\s+•.*$/, '') // Remove "• 1st" connection indicators
.trim();
return name || null;
}
// Extract date (scoped with document-wide fallback for single-post pages)
function extractDate(container, isSinglePost = false) {
// Try scoped selectors first
let dateEl = querySelector(SELECTORS.postDate, container);
// Fallback to document-wide selectors on single-post pages
if (!dateEl && isSinglePost) {
dateEl = querySelector(SELECTORS.postDateGlobal, document);
}
// Reject if element is within sponsored/promoted container
if (dateEl && isExcludedElement(dateEl)) {
dateEl = null;
}
if (!dateEl) return null;
// Use the element's container for datetime attribute lookup
const searchContainer = dateEl.closest('[data-urn]') || container;
return parseRelativeDate(dateEl.textContent, searchContainer, dateEl);
}
// Clean URL
function cleanUrl(url) {
try {
const u = new URL(url);
['trk', 'trackingId', 'lipi', 'licu', 'utm_source', 'utm_medium', 'utm_campaign'].forEach(p => {
u.searchParams.delete(p);
});
return u.toString();
} catch {
return url;
}
}
// Generate filename
function generateFilename(text, date) {
const dateStr = date || new Date().toISOString().split('T')[0];
let title = (text || 'linkedin-post').split('\n')[0].substring(0, 50);
title = title
.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-zA-Z0-9\s-]/g, '')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.toLowerCase()
.substring(0, 50);
if (!title) title = 'linkedin-post';
return `${dateStr}_${title}.md`;
}
// Generate Markdown (with placeholders for missing data)
function generateMarkdown(data) {
const author = data.author || '[Auteur non trouvé]';
const date = data.date || '[Date inconnue]';
const frontMatter = `---
date: ${date}
auteur: ${author}
origine: LinkedIn
url: ${data.url}
---`;
return `${frontMatter}\n\n${data.text}`;
}
// Main extraction function
async function extractPost() {
const warnings = [];
// Check page context
const context = getPageContext();
if (!context.canExtract) {
return { error: context.error };
}
// Find container
const container = findPostContainer();
if (!container) {
return { error: 'Impossible de trouver le conteneur du post.' };
}
// Expand "see more" and wait
const expandResult = await expandSeeMore(container);
if (expandResult.timeout) {
warnings.push('Le contenu "voir plus" peut être incomplet (timeout).');
}
// Extract data
const text = extractPostText(container);
if (!text) {
return { error: 'Impossible d\'extraire le texte du post.' };
}
// Use document-wide fallback on single-post pages
const isSinglePost = context.type === 'single-post';
const author = extractAuthor(container, isSinglePost);
if (!author) {
warnings.push('Auteur non trouvé.');
}
const date = extractDate(container, isSinglePost);
if (!date) {
warnings.push('Date non trouvée.');
}
const cleanedUrl = cleanUrl(window.location.href);
const data = {
text,
author,
date,
url: cleanedUrl,
filename: generateFilename(text, date),
warnings
};
data.markdown = generateMarkdown(data);
return data;
}
// Message listener (async compatible)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'extractPost') {
extractPost().then(result => {
sendResponse(result);
}).catch(err => {
sendResponse({ error: 'Erreur inattendue: ' + err.message });
});
return true; // Keep channel open for async
}
});
// v4: Removed window.__linkedInExtractor exposure for security
// v6: Self-test function for validation
function runSelfTests() {
const tests = [
// CJK detection
{ fn: () => containsCJK('広告'), expected: true, name: 'CJK detect JP' },
{ fn: () => containsCJK('promoted'), expected: false, name: 'CJK detect EN' },
{ fn: () => containsCJK('광고테스트'), expected: true, name: 'CJK detect KR' },
{ fn: () => containsCJK('推广内容'), expected: true, name: 'CJK detect ZH' },
// Complex script detection
{ fn: () => containsComplexScript('إعلان'), expected: true, name: 'Complex detect AR' },
{ fn: () => containsComplexScript('โฆษณา'), expected: true, name: 'Complex detect TH' },
{ fn: () => containsComplexScript('hello'), expected: false, name: 'Complex detect EN' },
// Alphabetic matching with word boundaries
{ fn: () => matchesSponsoredIndicator('This is promoted content', 'promoted'), expected: true, name: 'EN match promoted' },
{ fn: () => matchesSponsoredIndicator('promotedextra', 'promoted'), expected: false, name: 'EN no partial match' },
{ fn: () => matchesSponsoredIndicator('Contenu sponsorisé', 'sponsorisé'), expected: true, name: 'FR match' },
// CJK matching with includes
{ fn: () => matchesSponsoredIndicator('これは広告です', '広告'), expected: true, name: 'JP match' },
{ fn: () => matchesSponsoredIndicator('这是推广内容', '推广'), expected: true, name: 'ZH match' },
{ fn: () => matchesSponsoredIndicator('광고 콘텐츠입니다', '광고'), expected: true, name: 'KR match' },
// Complex script matching
{ fn: () => matchesSponsoredIndicator('هذا إعلان', 'إعلان'), expected: true, name: 'AR match' },
{ fn: () => matchesSponsoredIndicator('นี่คือโฆษณา', 'โฆษณา'), expected: true, name: 'TH match' },
// Activity ID extraction
{ fn: () => {
const original = window.location.href;
try {
// Can't actually test URL parsing without mocking, so just test function exists
return typeof extractActivityIdFromUrl === 'function';
} catch (e) { return false; }
}, expected: true, name: 'extractActivityIdFromUrl exists' },
];
let passed = 0;
const results = [];
for (const test of tests) {
try {
const result = test.fn();
const success = result === test.expected;
if (success) passed++;
results.push({
name: test.name,
success,
got: result,
expected: test.expected
});
} catch (e) {
results.push({
name: test.name,
success: false,
error: e.message
});
}
}
console.log(`LinkDown v6 self-test: ${passed}/${tests.length} passed`);
results.forEach(r => {
if (r.success) {
console.log(` ✓ ${r.name}`);
} else {
console.error(` ✗ ${r.name}: got ${r.got}, expected ${r.expected}${r.error ? ' ('+r.error+')' : ''}`);
}
});
return { passed, total: tests.length, allPassed: passed === tests.length };
}
// Expose self-test for development (only logs, no security risk)
if (typeof window !== 'undefined') {
window.__linkdownSelfTest = runSelfTests;
}
})();