tinyfix-tr 0.0.0-stage → 0.1.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +138 -2
  3. package/dist/pkg/src/context.d.ts +13 -0
  4. package/dist/pkg/src/context.js +80 -0
  5. package/dist/pkg/src/data.d.ts +50 -0
  6. package/dist/pkg/src/data.js +495 -0
  7. package/dist/pkg/src/engine.d.ts +39 -0
  8. package/dist/pkg/src/engine.js +357 -0
  9. package/dist/pkg/src/index.d.ts +30 -0
  10. package/dist/pkg/src/index.js +85 -0
  11. package/dist/pkg/src/protocol.d.ts +64 -0
  12. package/dist/pkg/src/protocol.js +1 -0
  13. package/dist/pkg/src/types.d.ts +184 -0
  14. package/dist/pkg/src/types.js +16 -0
  15. package/dist/pkg/src/worker.d.ts +11 -0
  16. package/dist/pkg/src/worker.js +111 -0
  17. package/dist/pkg/src/workerClient.d.ts +3 -0
  18. package/dist/pkg/src/workerClient.js +202 -0
  19. package/dist/src/context-vocab.d.ts +1 -0
  20. package/dist/src/context-vocab.js +2 -0
  21. package/dist/src/context.d.ts +92 -0
  22. package/dist/src/context.js +390 -0
  23. package/dist/src/corrector.d.ts +338 -0
  24. package/dist/src/corrector.js +2684 -0
  25. package/dist/src/known.d.ts +88 -0
  26. package/dist/src/known.js +286 -0
  27. package/dist/src/lexicon-binary.d.ts +85 -0
  28. package/dist/src/lexicon-binary.js +805 -0
  29. package/dist/src/lexicon.d.ts +24 -0
  30. package/dist/src/lexicon.js +79 -0
  31. package/dist/src/morphology/analyzer.d.ts +30 -0
  32. package/dist/src/morphology/analyzer.js +311 -0
  33. package/dist/src/morphology/binary.d.ts +22 -0
  34. package/dist/src/morphology/binary.js +372 -0
  35. package/dist/src/morphology/dictionary.d.ts +21 -0
  36. package/dist/src/morphology/dictionary.js +559 -0
  37. package/dist/src/morphology/fuzzy.d.ts +44 -0
  38. package/dist/src/morphology/fuzzy.js +599 -0
  39. package/dist/src/morphology/index.d.ts +40 -0
  40. package/dist/src/morphology/index.js +81 -0
  41. package/dist/src/morphology/morphotactics.d.ts +148 -0
  42. package/dist/src/morphology/morphotactics.js +1871 -0
  43. package/dist/src/morphology/phonetics.d.ts +71 -0
  44. package/dist/src/morphology/phonetics.js +309 -0
  45. package/dist/src/morphology/prior.d.ts +61 -0
  46. package/dist/src/morphology/prior.js +457 -0
  47. package/dist/src/morphology/types.d.ts +110 -0
  48. package/dist/src/morphology/types.js +32 -0
  49. package/dist/src/rules/proper-names.d.ts +145 -0
  50. package/dist/src/rules/proper-names.js +1217 -0
  51. package/dist/src/rules/turkish-rules.d.ts +126 -0
  52. package/dist/src/rules/turkish-rules.js +365 -0
  53. package/dist/src/sentence.d.ts +83 -0
  54. package/dist/src/sentence.js +2408 -0
  55. package/dist/src/turkish.d.ts +20 -0
  56. package/dist/src/turkish.js +94 -0
  57. package/package.json +60 -4
@@ -0,0 +1,2408 @@
1
+ import { lowerTr, upperTr } from "./turkish.js";
2
+ import { DERIV_LOOKING_KEEP_APOS, EVENT_HEADS, GENERIC_ALONE_INST_HEADS, GENERIC_INST_MODIFIERS, GEO_HEADS, HEAD_SUFFIX_RE, INSTITUTION_HEADS, LANGUAGE_NAMES, MONTHS, NO_APOS_PROPER_SUFFIX_RE, NO_APOS_RELIGION_OR_DERIVED, NON_APOSTROPHE_SUFFIX_RE, NON_INST_PREFIX, OFFICER_TITLE_HEADS, OFFICER_TITLE_MODS, OPTIONAL_APOS_ISM_IYET, PERSON_REL_BEFORE, PLURAL_PLACE_KEEP_APOS, POST_HONORIFICS, PRE_TITLES_ABBR, PRE_TITLES_FULL, PROPER_INFLECTIONAL_SUFFIX_RE, SAYIN_COMPOUND_FIRST, SAYIN_COMPOUND_TAIL, SAYIN_TITLES, STATE_HEADS, TITLE_CONJUNCTIONS, WEEKDAYS, capTr, fixNumberSuffix, foldTurkish, harmonizeAsciiSuffix, isInstitutionHead, isKinshipWord, isMediaTypeWord, isPhonologicallyValidProperSuffix, joinWithoutApostrophe, splitCalendarWord, splitHeadWord, splitHonorific, splitPostTitle, } from "./rules/proper-names.js";
3
+ /** Common Turkish (and a few English) abbreviations written with a full stop. */
4
+ export const ABBREVIATIONS = new Set([
5
+ "vb", "vs", "vd", "dr", "prof", "doç", "doc", "yrd", "öğr", "ogr", "gör", "gor", "av", "op", "uzm", "örn", "orn",
6
+ "bkz", "bk", "krş", "krs", "yy", "no", "sn", "st", "tel", "cad", "sok", "mah", "apt", "s", "sf", "çev", "cev",
7
+ "haz", "ed", "der", "alm", "ing", "fr", "lat", "ar", "far", "tic", "ltd", "şti", "sti", "aş", "as", "inc", "co",
8
+ "mr", "mrs", "ms", "jr", "sr", "etc", "eg", "ie", "vol", "fig", "ca", "ör", "or", "mö", "bnb", "hz", "san",
9
+ "bul", "blv", "km", "cm", "mm", "kg", "gr", "lt", "ml", "sa", "dk", "mhz", "ghz", "khz", "kb", "mb", "gb",
10
+ "subsp", "sp", "spp", "var", "pav", "nr", "yyl", "ss", "pp", "tr", "ital", "bros",
11
+ "müh", "muh", "mim", "ecz", "dt", "vet", "arb",
12
+ ]);
13
+ /** File extensions and top-level domains: "dosya.pdf", "site.com" are not two sentences. */
14
+ export const NOT_A_SENTENCE_START = new Set([
15
+ "com", "net", "org", "edu", "gov", "mil", "int", "io", "ai", "dev", "app", "tr", "uk", "us", "info", "biz", "xyz",
16
+ "html", "htm", "js", "mjs", "ts", "tsx", "jsx", "css", "scss", "json", "md", "txt", "pdf", "doc", "docx", "xls",
17
+ "xlsx", "ppt", "pptx", "odt", "rtf", "png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "mp3", "mp4", "wav", "mov",
18
+ "avi", "mkv", "zip", "rar", "gz", "tar", "exe", "dmg", "apk", "py", "java", "kt", "swift", "rs", "go", "rb", "php",
19
+ "sh", "sql", "xml", "csv", "yml", "yaml", "toml", "lock", "log", "env", "ini", "cfg",
20
+ ]);
21
+ /** Suffixes accepted in minimal (no-resources) fallback mode for unit tests. */
22
+ const FALLBACK_NAME_SUFFIXES = new Set(("a e ya ye ı i u ü yı yi yu yü da de ta te dan den tan ten ın in un ün nın nin nun nün yın yin yun yün " +
23
+ "la le yla yle lı li lu lü ca ce ça çe cı ci cu cü daki deki taki teki dakı dır dir dur dür tır tir tur tür " +
24
+ "sı si su sü sın sin sun sün sına sine " +
25
+ "nda nde ndan nden na ne nı ni nu nü yken iken ydı ydi ydu ydü").split(" "));
26
+ const NO_APOSTROPHE_NAME = /(?:ca|ce|ça|çe|lı|li|lu|lü|cı|ci|cu|cü|çı|çi|çu|çü)$/;
27
+ const LETTER = /\p{L}/u;
28
+ const LOWER = /^[a-zçğıöşüâîûäëïóúñ]/;
29
+ const ROMAN = /^[IVXLCDM]+$/;
30
+ const WORD_CHAR = /[\p{L}\p{N}'’]/u;
31
+ /** Verbal-noun predicate words following lowercase "alman" ("alman gerek", "alman daha iyi olur"). */
32
+ const ALMAN_VERBAL_NEXT = new Set([
33
+ "gerek", "gerekiyor", "gerekir", "gerekecek", "gerekti", "gerekirdi", "lazım", "şart",
34
+ "zorunlu", "mümkün", "daha", "iyi", "doğru", "yanlış", "saçma", "mantıklı", "için",
35
+ "halde", "durumunda", "mı", "mi", "bile", "da", "de", "olur", "olacak", "önemli",
36
+ ]);
37
+ /** Religious/social context words near "alevi" that disambiguate it from "alev + i" ("its flame"). */
38
+ const ALEVI_SECT_CTX = new Set([
39
+ "sünni", "şii", "bektaşi", "aile", "aileler", "köy", "köyü", "köyde", "mahalle", "inanç",
40
+ "inancı", "kültür", "kültürü", "toplum", "toplumu", "vatandaş", "cemevi", "cem", "dede",
41
+ "mezhep", "mezhebi", "gelenek", "geleneği", "halk", "türkmen", "islam", "müslüman",
42
+ ]);
43
+ /** Words that indicate a human possessor right after an ambiguous name's genitive ("Bahar'ın annesi", "Kaya'nın masasına"). */
44
+ const HUMAN_POSSESSED_NEXT = new Set([
45
+ "annesi", "annesini", "annesine", "annesinde", "annesinden", "annesinin", "annesiyle",
46
+ "babası", "babasını", "babasına", "babasında", "babasından", "babasının", "babasıyla",
47
+ "ablası", "ablasını", "ablasına", "abisi", "abisini", "abisine", "ağabeyi",
48
+ "kardeşi", "kardeşini", "kardeşine", "kardeşiyle", "eşi", "karısı", "kocası", "oğlu", "kızı",
49
+ "evi", "evini", "evine", "evinde", "evinden", "evinin",
50
+ "ofisi", "ofisini", "ofisine", "ofisinde", "ofisinden",
51
+ "masası", "masasını", "masasına", "masasında", "masasından",
52
+ "arabası", "arabasını", "arabasına", "arabasında", "arabasıyla",
53
+ "telefonu", "telefonunu", "numarası", "numarasını", "düğünü", "düğününe", "düğününü",
54
+ "doğum", "ödevi", "ödevini", "sınav", "sonucu", "şarkıları", "şarkılarını", "romanları",
55
+ "romanlarını", "şiirleri", "şiirlerini", "kitabı", "kitabını", "eserleri", "eserlerini",
56
+ "bisikleti", "bisikletini", "çantası", "çantasını", "defteri", "defterini",
57
+ "kalemi", "gözlüğü", "bilgisayarı", "işi", "işini", "yeni",
58
+ ]);
59
+ /** Single-word famous literary titles that take capitalization + apostrophe after an author's genitive ("Tanpınar'ın Huzur'unu okumak"). */
60
+ const SINGLE_WORD_WORKS = new Set([
61
+ "huzur", "yaban", "eylül", "çalıkuşu", "tutunamayanlar", "sefiller", "dava", "şato",
62
+ "dönüşüm", "veba", "körlük", "simyacı", "satranç", "yabancı", "kumarbaz", "budala",
63
+ "ecinniler", "diriliş", "obligomov", "oblomov", "goriot", "emma", "dracula", "frankenstein",
64
+ ]);
65
+ /** Single-word famous Turkish newspapers/magazines before "dergisi/gazetesi" ("Varlık dergisine"). */
66
+ const SINGLE_WORD_PUBLICATIONS = new Set([
67
+ "varlık", "cumhuriyet", "hürriyet", "milliyet", "sabah", "sözcü", "posta", "zaman",
68
+ "birgün", "evrensel", "karar", "akşam", "güneş", "takvim", "yeniçağ", "aydınlık",
69
+ "notos", "hece", "dergâh", "dergah", "kafa", "bavul", "ot", "uykusuz", "penguen",
70
+ "leman", "atlas", "papirüs", "hisar", "yön", "kadro", "markopaşa", "akbaba", "millî",
71
+ ]);
72
+ /** Verbs/nouns proving a literary work context after "<Author>'ın <Work>". */
73
+ const READING_CTX_RE = /^(?:oku|bitir|yaz|incele|beğen|sev|anlat|kitap|roman|eser|yayım|basıl|çevir|bırak|başla)/;
74
+ /** Common words that should NEVER be capitalized as surnames after a first name when followed by a typical compound/verb. */
75
+ const COMMON_OBJECT_AFTER_SURNAME_VERBS = new Set([
76
+ "yaktı", "yakıyor", "yakmış", "yaksın", "attı", "atıyor", "atmış", "topladı", "topluyor",
77
+ "aldı", "alıyor", "gördü", "görüyor", "yedi", "yiyor", "içti", "içiyor", "açtı", "açıyor",
78
+ "taktı", "takıyor", "giydi", "giyiyor", "sürdü", "sürüyor", "kırdı", "kırıyor", "kesti", "kesiyor",
79
+ "döktü", "döküyor", "çizdi", "çiziyor", "yazdı", "yazıyor", "okudu", "okuyor", "söyledi", "söylüyor",
80
+ "verdi", "veriyor", "tuttu", "tutuyor", "buldu", "buluyor", "dikti", "dikiyor",
81
+ ]);
82
+ /** Common Turkish words that collide with surnames as nouns/adjectives/verbs and need extra care after a first name. */
83
+ const VERY_COMMON_SURNAME_COLLISIONS = new Set([
84
+ "ak", "al", "ay", "can", "er", "gün", "kan", "kır", "ok", "su", "bal", "baş", "dağ", "dal",
85
+ "gök", "gül", "taş", "tok", "ulu", "boz", "sarı", "kara", "uzun", "kısa", "büyük", "küçük",
86
+ "genç", "yeni", "eski", "iyi", "güzel", "doğru", "açık", "kapalı", "sert", "kuru", "özel",
87
+ "temel", "uyar", "uçar", "gezer", "sever", "okur", "keser", "yazar", "bakar", "tutar",
88
+ "gider", "gelir", "bilir", "kalır", "alır", "verir", "eder", "olur", "döner", "düşer",
89
+ "ateş", "çiçek", "güneş", "bulut", "deniz", "toprak", "yıldız", "kaya", "demir", "çelik",
90
+ "altın", "gümüş", "bakır", "tunç", "ipek", "şeker", "ekşi", "tatlı", "kuzu", "kurt",
91
+ "aslan", "kaplan", "kartal", "şahin", "doğan", "ceylan", "tavşan", "koç", "kılıç",
92
+ "kalkan", "bayrak", "sancak", "uçak", "kalem", "kitap", "duman", "rüzgar", "yağmur",
93
+ "bahar", "eylül", "nisan", "mayıs", "ocak", "bayram", "barış", "savaş", "zafer", "umut",
94
+ "sevgi", "özlem", "mutlu", "güven", "erdem", "onur", "ufuk", "huzur", "varlık", "öykü",
95
+ "masal", "rüya", "hayal", "neşe", "sevinç", "kader", "melek", "nur", "pınar", "ırmak",
96
+ "nehir", "dere", "göl", "orman", "çınar", "meşe", "lale", "menekşe", "kiraz", "elmas",
97
+ "inci", "mercan", "yakut", "sedef", "zengin", "fakir", "yalnız", "çalışkan", "sağlam",
98
+ "parlak", "keskin", "önder", "öner", "sayın", "seçkin", "bilgin", "kahraman", "usta",
99
+ "terzi", "çoban", "avcı", "balcı", "bağcı", "yazıcı", "yapıcı", "topçu", "dalgıç",
100
+ "kalaycı", "ekinci", "sütçü", "tütüncü", "çiftçi", "köse", "topal", "koca", "kocaman",
101
+ "torun", "kardeş", "arkadaş", "komşu", "misafir", "yoldaş", "yurt", "yayla", "kural",
102
+ "metin", "saygın", "coşkun", "ergin", "yetkin", "sezer", "güler", "tekin", "şen", "tan",
103
+ "oral", "arslan", "yılmaz", "korkmaz", "durmaz", "sönmez", "dönmez", "ölmez", "solmaz",
104
+ "söylemez", "yüksel", "uyan", "uyanık", "uslu", "yaman", "yanık", "yeşil", "kızıl", "mavi",
105
+ "üstün", "ünlü", "uğurlu", "varol", "vural", "yaşar", "yavuz", "yurtsever", "başar",
106
+ "gündüz", "gürbüz", "kaymak", "pala", "tarhan", "tosun", "yörük", "dursun", "poyraz",
107
+ ]);
108
+ /** Common Turkish adjectives/months/nouns in SEED_GIVEN that must NOT trigger alone after relationship words ("kızım mutlu oldu"). */
109
+ const COMMON_GIVEN_ADJECTIVES = new Set([
110
+ "mutlu", "zeki", "emin", "adil", "aziz", "galip", "halis", "kamil", "kudret", "mahir",
111
+ "metin", "nadir", "nezih", "önder", "sadık", "saygın", "seçkin", "servet", "şeref", "şerif",
112
+ "taşkın", "temel", "ulvi", "yaman", "yücel", "yüksel", "arzu", "duygu", "eylem", "gaye",
113
+ "gizem", "gözde", "imge", "kıymet", "pembe", "seher", "şirin", "yaprak", "yeter", "adalet",
114
+ "bayram", "cuma", "eylül", "nisan", "kasım", "ramazan", "devrim", "savaş", "zafer", "sultan",
115
+ "barış", "umut", "sevgi", "özlem", "güven", "inanç", "huzur", "neşe", "sevinç", "hayal",
116
+ "rüya", "masal", "öykü", "doğa", "ışık", "güneş", "bulut", "yağmur", "toprak", "çiçek",
117
+ "gül", "bahar", "deniz", "can", "kaya", "demir", "çelik", "ateş", "yıldız", "kader",
118
+ "nur", "ipek", "evren", "pınar", "gönül", "aslı", "cihan", "saadet", "defne", "doruk",
119
+ ]);
120
+ function capitalize(word) {
121
+ return word ? upperTr(word[0]) + word.slice(1) : word;
122
+ }
123
+ function wordEnd(text, start) {
124
+ let end = start;
125
+ while (end < text.length && WORD_CHAR.test(text[end]))
126
+ end++;
127
+ return end;
128
+ }
129
+ function wordStart(text, end) {
130
+ let start = end;
131
+ while (start > 0 && WORD_CHAR.test(text[start - 1]))
132
+ start--;
133
+ return start;
134
+ }
135
+ function continuesAsAddress(text, end) {
136
+ const next = text[end];
137
+ if (next === undefined)
138
+ return false;
139
+ if ("@/\\:_=#&?%".includes(next) && next !== "?")
140
+ return true;
141
+ if (next === "?" && LETTER.test(text[end + 1] ?? ""))
142
+ return true;
143
+ return (next === "." || next === "-") && WORD_CHAR.test(text[end + 1] ?? "");
144
+ }
145
+ function precededByAddress(text, start) {
146
+ const prev = text[start - 1];
147
+ return prev !== undefined && "@/\\:_.#".includes(prev);
148
+ }
149
+ function endsSentence(text, punctStart, punctEnd) {
150
+ const run = text.slice(punctStart, punctEnd);
151
+ if (run.includes("…") || /\.\./.test(run))
152
+ return false;
153
+ const before = text[punctStart - 1];
154
+ if (before === undefined || !WORD_CHAR.test(before))
155
+ return false;
156
+ const start = wordStart(text, punctStart);
157
+ const word = text.slice(start, punctStart);
158
+ if (/\p{N}/u.test(word))
159
+ return false;
160
+ if (word.length === 1)
161
+ return false;
162
+ if (ROMAN.test(word) || /\p{Lu}/u.test(word.slice(1)))
163
+ return false;
164
+ if (ABBREVIATIONS.has(lowerTr(word)))
165
+ return false;
166
+ if (precededByAddress(text, start))
167
+ return false;
168
+ if (!run.includes(".") || run.startsWith("!") || run.startsWith("?")) {
169
+ const capitalized = /^\p{Lu}/u.test(word);
170
+ if (capitalized && !isSentenceStartAt(text, start))
171
+ return false;
172
+ }
173
+ return true;
174
+ }
175
+ function isSentenceStartAt(text, start) {
176
+ let index = start - 1;
177
+ while (index >= 0 && /[\s"'“‘«(\[]/u.test(text[index]))
178
+ index--;
179
+ return index < 0 || ".!?…".includes(text[index]);
180
+ }
181
+ /**
182
+ * Checks whether a dot/exclamation/question glued between two letter runs (`left[punct]right`) is a
183
+ * real missing-space sentence boundary (and NOT a domain, filename, abbreviation, or camelCase/address).
184
+ */
185
+ export function isMissingSpaceBoundary(text, leftStart, left, punctAt, rightStart, right, isWordOrFixable) {
186
+ const rightEnd = rightStart + right.length;
187
+ if (WORD_CHAR.test(text[leftStart - 1] ?? "") || precededByAddress(text, leftStart))
188
+ return false;
189
+ if (WORD_CHAR.test(text[rightEnd] ?? "") || continuesAsAddress(text, rightEnd))
190
+ return false;
191
+ if (/\p{Lu}/u.test(left.slice(1)) || /\p{Lu}/u.test(right.slice(1)))
192
+ return false;
193
+ const leftLower = lowerTr(left);
194
+ const rightLower = lowerTr(right);
195
+ if (ABBREVIATIONS.has(leftLower) || NOT_A_SENTENCE_START.has(rightLower))
196
+ return false;
197
+ if (!isWordOrFixable(leftLower) || !isWordOrFixable(rightLower))
198
+ return false;
199
+ void punctAt;
200
+ return true;
201
+ }
202
+ /**
203
+ * Adds missing spaces, TDK proper-name capitals, multi-word phrases, titles, dates,
204
+ * apostrophe fixes, and sentence-start capitals to `corrections` (sorted, non-overlapping).
205
+ */
206
+ export function applySentenceRules(text, corrections, isWord, nameFor = () => undefined, stemsOf = () => null, resources) {
207
+ const result = [...corrections];
208
+ const covering = (start, end) => result.findIndex((fix) => fix.start < end && fix.end > start);
209
+ const spaced = new Set();
210
+ // ---------------------------------------------------------------------------
211
+ // 1. Missing space after a sentence end between two real words: "merhaba.ben" -> "merhaba. Ben".
212
+ // ---------------------------------------------------------------------------
213
+ for (const match of text.matchAll(/(\p{L}{2,})([.!?])(\p{L}{2,})/gu)) {
214
+ const leftStart = match.index;
215
+ const left = match[1];
216
+ const punctAt = leftStart + left.length;
217
+ const rightStart = punctAt + 1;
218
+ const right = match[3];
219
+ const rightEnd = rightStart + right.length;
220
+ if (WORD_CHAR.test(text[leftStart - 1] ?? "") || precededByAddress(text, leftStart))
221
+ continue;
222
+ if (WORD_CHAR.test(text[rightEnd] ?? "") || continuesAsAddress(text, rightEnd))
223
+ continue;
224
+ if (/\p{Lu}/u.test(left.slice(1)) || /\p{Lu}/u.test(right.slice(1)))
225
+ continue;
226
+ if (covering(punctAt, punctAt + 1) !== -1)
227
+ continue;
228
+ const wordFix = covering(rightStart, rightEnd);
229
+ const leftFix = covering(leftStart, punctAt);
230
+ const asFixed = (index, fallback) => {
231
+ const fix = index === -1 ? undefined : result[index];
232
+ return fix && !fix.replacement.includes(" ") ? fix.replacement : fallback;
233
+ };
234
+ const leftLower = lowerTr(asFixed(leftFix, left));
235
+ const rightLower = lowerTr(asFixed(wordFix, right));
236
+ if (ABBREVIATIONS.has(leftLower) || NOT_A_SENTENCE_START.has(rightLower))
237
+ continue;
238
+ if (!isWord(leftLower) || !isWord(rightLower))
239
+ continue;
240
+ const punct = text[punctAt];
241
+ spaced.add(punctAt);
242
+ if (wordFix === -1) {
243
+ result.push({
244
+ start: punctAt,
245
+ end: rightEnd,
246
+ original: text.slice(punctAt, rightEnd),
247
+ replacement: `${punct} ${capitalize(right)}`,
248
+ kind: "punct",
249
+ margin: 6,
250
+ });
251
+ }
252
+ else {
253
+ const existing = result[wordFix];
254
+ if (existing.start !== rightStart)
255
+ continue;
256
+ result.splice(wordFix, 1, {
257
+ ...existing,
258
+ start: punctAt,
259
+ original: text.slice(punctAt, existing.end),
260
+ replacement: `${punct} ${capitalize(existing.replacement)}`,
261
+ });
262
+ }
263
+ }
264
+ result.sort((a, b) => a.start - b.start);
265
+ // ---------------------------------------------------------------------------
266
+ // Minimal fallback path when called directly from unit tests without `resources`.
267
+ // Preserves exact original behavior of `src/sentence.test.ts`!
268
+ // ---------------------------------------------------------------------------
269
+ if (!resources || !resources.known?.hasProperData) {
270
+ applyMinimalRules(text, result, spaced, isWord, nameFor, stemsOf);
271
+ applySentenceStartCapitals(text, result, spaced);
272
+ result.sort((a, b) => a.start - b.start);
273
+ return result;
274
+ }
275
+ // ---------------------------------------------------------------------------
276
+ // Full TDK Proper-Name & Apostrophe Engine (using `resources.known`)
277
+ // ---------------------------------------------------------------------------
278
+ const known = resources.known;
279
+ const isMorphWord = resources.isMorphWord ?? isWord;
280
+ const capShare = resources.capitalShare ?? (() => 0);
281
+ const lexCount = resources.count ?? (() => 0);
282
+ const lexPair = resources.pair ?? (() => 0);
283
+ // Build token list of words & numbers (skipping address/code-glued tokens) with post-core effective forms.
284
+ const tokens = [];
285
+ const TOKEN_RE = /\p{L}+(?:['’]\p{L}+)*|\d+/gu;
286
+ for (const m of text.matchAll(TOKEN_RE)) {
287
+ const start = m.index;
288
+ const raw = m[0];
289
+ const end = start + raw.length;
290
+ const isNum = /^\d+$/.test(raw);
291
+ if (!isNum) {
292
+ if (precededByAddress(text, start))
293
+ continue;
294
+ if (continuesAsAddress(text, end) && !spaced.has(end))
295
+ continue;
296
+ if (/[\p{N}_]/u.test(text[end] ?? "") || /[\p{N}_]/u.test(text[start - 1] ?? ""))
297
+ continue;
298
+ }
299
+ let eff = raw;
300
+ let lockedByCore = false;
301
+ const covIdx = covering(start, end);
302
+ if (covIdx !== -1) {
303
+ const fix = result[covIdx];
304
+ if (fix.start === start && fix.end === end && !fix.replacement.includes(" ")) {
305
+ eff = fix.replacement;
306
+ }
307
+ else if (spaced.has(fix.start) && fix.end === end && fix.replacement.includes(" ")) {
308
+ eff = fix.replacement.slice(fix.replacement.indexOf(" ") + 1);
309
+ }
310
+ else {
311
+ // Multi-word core split/join fix ("Belliki" -> "Belli ki", "Yarın ki" -> "Yarınki"): never overwrite!
312
+ lockedByCore = true;
313
+ }
314
+ }
315
+ const prevTok = tokens.at(-1);
316
+ const gapBefore = prevTok ? text.slice(prevTok.end, start) : text.slice(0, start);
317
+ if (prevTok)
318
+ prevTok.gapAfter = gapBefore;
319
+ const sepBefore = gapBefore.trim();
320
+ const atStart = isSentenceStartAt(text, start) ||
321
+ (prevTok !== undefined && spaced.has(prevTok.end) && gapBefore.length === 1);
322
+ tokens.push({
323
+ start,
324
+ end,
325
+ raw,
326
+ eff,
327
+ low: lowerTr(eff),
328
+ isWord: !isNum,
329
+ isNumber: isNum,
330
+ sepBefore,
331
+ gapBefore,
332
+ gapAfter: text.slice(end),
333
+ atStart,
334
+ locked: lockedByCore,
335
+ });
336
+ }
337
+ /** Helper: set a single token's effective replacement, merging cleanly with any existing core/missing-space fix. */
338
+ const setToken = (tok, nextText, lock = false) => {
339
+ if (lock)
340
+ tok.locked = true;
341
+ // Never emit a change whose ONLY difference is curly ’ vs straight ' apostrophe.
342
+ if (nextText === tok.eff || nextText.replaceAll("'", "’") === tok.eff)
343
+ return;
344
+ tok.eff = nextText;
345
+ tok.low = lowerTr(nextText);
346
+ const idx = covering(tok.start, tok.end);
347
+ if (idx === -1) {
348
+ if (nextText !== tok.raw) {
349
+ result.push({ start: tok.start, end: tok.end, original: tok.raw, replacement: nextText, kind: "punct", margin: 6 });
350
+ result.sort((a, b) => a.start - b.start);
351
+ }
352
+ return;
353
+ }
354
+ const existing = result[idx];
355
+ if (existing.start === tok.start && existing.end === tok.end) {
356
+ if (nextText === tok.raw) {
357
+ result.splice(idx, 1);
358
+ }
359
+ else {
360
+ result[idx] = { ...existing, replacement: nextText };
361
+ }
362
+ return;
363
+ }
364
+ if (spaced.has(existing.start) && existing.end === tok.end) {
365
+ const spIdx = existing.replacement.indexOf(" ");
366
+ if (spIdx !== -1) {
367
+ result[idx] = { ...existing, replacement: existing.replacement.slice(0, spIdx + 1) + nextText };
368
+ }
369
+ }
370
+ };
371
+ /** True when adjacent tokens `a` and `b` are separated only by whitespace (no comma/period/newline). */
372
+ const adjSpace = (a, b) => /^[ \t]+$/.test(b.gapBefore);
373
+ /** True when `a` is followed by "." + spaces and then `b` (for abbreviated titles like "Prof. Dr. Ahmet"). */
374
+ const adjDotSpace = (a, b) => /^\.[ \t]+$/.test(b.gapBefore);
375
+ /** True when a token is already capitalized (excluding sentence start unless unmistakably a proper noun). */
376
+ const isCap = (tok) => /^\p{Lu}/u.test(tok.eff);
377
+ const isAllCaps = (tok) => tok.eff.length >= 2 && tok.eff === upperTr(tok.eff) && tok.eff !== lowerTr(tok.eff);
378
+ const isMixedInnerCap = (tok) => !isAllCaps(tok) && /\p{Lu}/u.test(tok.eff.slice(1));
379
+ /** Check whether text has ASCII-typing evidence (e.g. a core mark fix already occurred or no Turkish diacritics). */
380
+ const textHasTurkishMarks = /[çğıöşüâîû]/i.test(text);
381
+ const sentenceHasAsciiFixes = result.some((r) => {
382
+ const o = lowerTr(r.original);
383
+ const rep = lowerTr(r.replacement);
384
+ return o !== rep && foldTurkish(o) === foldTurkish(rep);
385
+ });
386
+ /** Lookup a proper name entry either exact or unique ASCII-folded (when safe). */
387
+ const lookupName = (stemLow, allowAscii) => {
388
+ const exact = known.nameEntry(stemLow);
389
+ if (exact)
390
+ return exact;
391
+ if (allowAscii && !/[çğıöşüâîû]/.test(stemLow) && !isMorphWord(stemLow)) {
392
+ return known.asciiNameEntry(stemLow);
393
+ }
394
+ return undefined;
395
+ };
396
+ /** True when a lowercase form is strictly a common word (has a morphological stem other than `base`). */
397
+ const isCommonWordCollision = (wholeLow, baseLow) => {
398
+ const stems = stemsOf(wholeLow);
399
+ if (stems === null || stems.length === 0)
400
+ return isWord(wholeLow);
401
+ // If morphology recognizes the whole form via a common-word stem different from `baseLow`, it's a collision ("belli", "hatayı", "emrinin").
402
+ return stems.some((s) => s !== baseLow && s !== lowerTr(baseLow));
403
+ };
404
+ /** Checks if `tok` can serve as a person's first name (Turkish given name or ambiguous given name; never languages/places). */
405
+ const resolveGivenName = (tok) => {
406
+ if (!tok.isWord || isAllCaps(tok) || isMixedInnerCap(tok))
407
+ return null;
408
+ const low = tok.low;
409
+ const lookupPersonFirst = (s) => {
410
+ const g = known.givenNameFor(s);
411
+ if (g)
412
+ return g;
413
+ const ne = known.nameEntry(s);
414
+ if (ne && !ne.noApos && !LANGUAGE_NAMES.has(s) && !NO_APOS_RELIGION_OR_DERIVED.has(s)) {
415
+ return known.givenNameFor(s) ?? (known.ambigNameFor(s) ? undefined : undefined);
416
+ }
417
+ return undefined;
418
+ };
419
+ const apos = low.indexOf("'");
420
+ if (apos > 0) {
421
+ const stem = low.slice(0, apos);
422
+ const suf = low.slice(apos + 1);
423
+ const disp = lookupPersonFirst(stem) ?? (known.nameEntry(stem)?.noApos ? undefined : known.nameFor(stem));
424
+ if (disp && PROPER_INFLECTIONAL_SUFFIX_RE.test(suf))
425
+ return { display: disp, suffix: suf, hadApos: true };
426
+ return null;
427
+ }
428
+ const bare = known.givenNameFor(low);
429
+ if (bare)
430
+ return { display: bare, suffix: "", hadApos: false };
431
+ // Try suffixed given name (never split everyday common Turkish words like "arasında", "savaşta")
432
+ for (let cut = low.length - 1; cut >= 3; cut--) {
433
+ const base = low.slice(0, cut);
434
+ const suf = low.slice(cut);
435
+ const disp = known.givenNameFor(base);
436
+ if (!disp)
437
+ continue;
438
+ if (isCommonWordCollision(low, base))
439
+ continue;
440
+ if (isMorphWord(low) && !known.nameEntry(base) && lexCount(`${base}'${suf}`) < Math.max(5, lexCount(low) * 2))
441
+ continue;
442
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(lowerTr(disp), suf)) {
443
+ return { display: disp, suffix: suf, hadApos: false };
444
+ }
445
+ if (sentenceHasAsciiFixes || !textHasTurkishMarks) {
446
+ const harm = harmonizeAsciiSuffix(lowerTr(disp), suf);
447
+ if (harm)
448
+ return { display: disp, suffix: harm, hadApos: false };
449
+ }
450
+ }
451
+ if ((sentenceHasAsciiFixes || !textHasTurkishMarks) && !/[çğıöşüâîû]/.test(low)) {
452
+ const asc = known.asciiNameEntry(low);
453
+ if (asc && !asc.noApos && known.givenNameFor(lowerTr(asc.name))) {
454
+ return { display: asc.name, suffix: "", hadApos: false };
455
+ }
456
+ }
457
+ return null;
458
+ };
459
+ /** Checks if `tok` can serve as a person's surname (bare or suffixed). */
460
+ const resolveSurname = (tok, allowCommon) => {
461
+ if (!tok.isWord || isAllCaps(tok) || isMixedInnerCap(tok))
462
+ return null;
463
+ const low = tok.low;
464
+ const apos = low.indexOf("'");
465
+ if (apos > 0) {
466
+ const stem = low.slice(0, apos);
467
+ const suf = low.slice(apos + 1);
468
+ // Strictly require a surname (never known.nameFor which matches cities/countries like "arda Meksika'da"!).
469
+ const disp = known.surnameFor(stem);
470
+ if (disp && PROPER_INFLECTIONAL_SUFFIX_RE.test(suf)) {
471
+ return { display: disp, suffix: suf, hadApos: true, isCommon: VERY_COMMON_SURNAME_COLLISIONS.has(stem) };
472
+ }
473
+ if (allowCommon && isCap(tok) && !tok.atStart && PROPER_INFLECTIONAL_SUFFIX_RE.test(suf)) {
474
+ return { display: tok.eff.slice(0, apos), suffix: suf, hadApos: true, isCommon: false };
475
+ }
476
+ return null;
477
+ }
478
+ const dispBare = known.surnameFor(low);
479
+ if (dispBare) {
480
+ const isCom = VERY_COMMON_SURNAME_COLLISIONS.has(low);
481
+ if (!isCom || allowCommon)
482
+ return { display: dispBare, suffix: "", hadApos: false, isCommon: isCom };
483
+ }
484
+ // Never invent an apostrophe inside an already-capitalized mid-sentence foreign/Turkish surname ("Fatma Aliye", "Bay Reede", "Robert Belle")!
485
+ const alreadyCapMid = isCap(tok) && !tok.atStart;
486
+ if (alreadyCapMid)
487
+ return null;
488
+ for (let cut = low.length - 1; cut >= 2; cut--) {
489
+ const base = low.slice(0, cut);
490
+ const suf = low.slice(cut);
491
+ const disp = known.surnameFor(base);
492
+ if (!disp)
493
+ continue;
494
+ if (isCommonWordCollision(low, base))
495
+ continue;
496
+ const isCom = VERY_COMMON_SURNAME_COLLISIONS.has(base);
497
+ if (isCom && !allowCommon)
498
+ continue;
499
+ if (isMorphWord(low) && !known.nameEntry(base) && capShare(low) < 0.35 && lexCount(low) >= 20)
500
+ continue;
501
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(lowerTr(disp), suf)) {
502
+ return { display: disp, suffix: suf, hadApos: false, isCommon: isCom };
503
+ }
504
+ if (sentenceHasAsciiFixes || !textHasTurkishMarks) {
505
+ const harm = harmonizeAsciiSuffix(lowerTr(disp), suf);
506
+ if (harm)
507
+ return { display: disp, suffix: harm, hadApos: false, isCommon: isCom };
508
+ }
509
+ }
510
+ return null;
511
+ };
512
+ /** Builds the surrounding left/right raw context around `tokIdx` reflecting all already-applied sentence/core fixes. */
513
+ const buildContextAround = (tokIdx) => {
514
+ const target = tokens[tokIdx];
515
+ const leftFrom = Math.max(0, target.start - 140);
516
+ const rightTo = Math.min(text.length, target.end + 100);
517
+ let leftRaw = "";
518
+ let cur = leftFrom;
519
+ for (let k = 0; k < tokIdx; k++) {
520
+ const t = tokens[k];
521
+ if (t.end <= leftFrom)
522
+ continue;
523
+ if (t.start >= target.start)
524
+ break;
525
+ if (t.start < cur)
526
+ continue;
527
+ const disp = t.atStart && t.isWord && LOWER.test(t.eff) ? capitalize(t.eff) : t.eff;
528
+ leftRaw += text.slice(cur, t.start) + disp;
529
+ cur = t.end;
530
+ }
531
+ leftRaw += text.slice(cur, target.start);
532
+ let rightRaw = "";
533
+ cur = target.end;
534
+ for (let k = tokIdx + 1; k < tokens.length; k++) {
535
+ const t = tokens[k];
536
+ if (t.end <= target.end)
537
+ continue;
538
+ if (t.start >= rightTo)
539
+ break;
540
+ if (t.start < cur)
541
+ continue;
542
+ const disp = t.atStart && t.isWord && LOWER.test(t.eff) ? capitalize(t.eff) : t.eff;
543
+ rightRaw += text.slice(cur, t.start) + disp;
544
+ cur = t.end;
545
+ }
546
+ rightRaw += text.slice(cur, rightTo);
547
+ return { leftRaw, rightRaw };
548
+ };
549
+ /** Formats a proper name + suffix according to apostrophe policy. */
550
+ const formatProper = (displayBase, suffix, takesApos) => {
551
+ if (!suffix)
552
+ return displayBase;
553
+ return takesApos ? `${displayBase}'${suffix}` : `${displayBase}${suffix}`;
554
+ };
555
+ // ===========================================================================
556
+ // STEP 2: Multi-word Canonical & Mined Proper Phrases (PHRASE_APOS / PHRASE_NOAPOS)
557
+ // Runs BEFORE wrong-apostrophe and single-word passes so novel titles like
558
+ // "Saatleri Ayarlama Enstitüsü'nü" or "Beyaz Kale'sini" or "İnce Memed'ini" win!
559
+ // ===========================================================================
560
+ const hasWorkSentenceCue = tokens.some((t) => t.isWord &&
561
+ /^(?:oku|bitir|yaz|izle|seyret|roman|kitap|film|dizi|oyun|eser|tiyatro|yazar|yönetmen|tablo|resim|sahne|başyapıt|çevir|baskı|yayım|sinema|şair|ödül|etkilen|beğen|duygulan|bırak|anlat|albüm|şarkı)/.test(t.low));
562
+ const hasSpecialDaySentenceCue = tokens.some((t, idx) => (t.isWord &&
563
+ /^(?:tören|kutlu|kutla|anma|etkinlik|program|konuşma|resmî|resmi|millî|milli|bayram|tebrik|mesaj|hafta|hediye|armağan|yürüyüş|saygı|minnet|mart|mayıs|haziran|şubat|kasım)/.test(t.low)) ||
564
+ (t.isNumber &&
565
+ idx + 1 < tokens.length &&
566
+ tokens[idx + 1].isWord &&
567
+ MONTHS.has(tokens[idx + 1].low.split("'")[0])));
568
+ for (let i = 0; i < tokens.length; i++) {
569
+ const tok = tokens[i];
570
+ if (!tok.isWord || tok.locked)
571
+ continue;
572
+ const candidates = known.phrasesStartingWith(tok.low, true);
573
+ if (candidates.length === 0)
574
+ continue;
575
+ for (const phrase of candidates) {
576
+ const len = phrase.words.length;
577
+ if (i + len > tokens.length)
578
+ continue;
579
+ // Check adjacency (space-only between phrase words)
580
+ let ok = true;
581
+ for (let k = 1; k < len; k++) {
582
+ if (!adjSpace(tokens[i + k - 1], tokens[i + k])) {
583
+ ok = false;
584
+ break;
585
+ }
586
+ }
587
+ if (!ok)
588
+ continue;
589
+ // Match words 0 .. len-2 (exact or ASCII-folded)
590
+ for (let k = 0; k < len - 1; k++) {
591
+ const tw = tokens[i + k].low;
592
+ const pw = phrase.words[k];
593
+ if (tw !== pw && foldTurkish(tw) !== foldTurkish(pw)) {
594
+ ok = false;
595
+ break;
596
+ }
597
+ }
598
+ if (!ok)
599
+ continue;
600
+ // Match final word: bare OR with inflectional suffix (with or without apostrophe)
601
+ const lastTok = tokens[i + len - 1];
602
+ const lastPw = phrase.words[len - 1];
603
+ const lastDisp = phrase.displayWords[len - 1];
604
+ const lastLow = lastTok.low;
605
+ const apos = lastLow.indexOf("'");
606
+ let matchedSuffix = null;
607
+ if (lastLow === lastPw || foldTurkish(lastLow) === foldTurkish(lastPw)) {
608
+ matchedSuffix = "";
609
+ }
610
+ else if (apos > 0) {
611
+ const stem = lastLow.slice(0, apos);
612
+ const suf = lastLow.slice(apos + 1);
613
+ if ((stem === lastPw || foldTurkish(stem) === foldTurkish(lastPw)) && (HEAD_SUFFIX_RE.test(suf) || PROPER_INFLECTIONAL_SUFFIX_RE.test(suf))) {
614
+ matchedSuffix = suf;
615
+ }
616
+ }
617
+ else {
618
+ // Also handle "Beyaz Kalesini" where core already turned it into "Kalesi'ni" (check raw too!)
619
+ const rawLow = lowerTr(lastTok.raw);
620
+ for (const form of rawLow !== lastLow ? [lastLow, rawLow] : [lastLow]) {
621
+ if (form.startsWith(lastPw) && form.length > lastPw.length) {
622
+ const suf = form.slice(lastPw.length);
623
+ const p3sg = /[aeıioöuüâîû]$/.test(lastPw) && (INSTITUTION_HEADS.has(lastPw) || GEO_HEADS.has(lastPw) || STATE_HEADS.has(lastPw) || EVENT_HEADS.has(lastPw));
624
+ if ((PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) || HEAD_SUFFIX_RE.test(suf)) && isPhonologicallyValidProperSuffix(lastPw, suf, { p3sgHead: p3sg })) {
625
+ matchedSuffix = suf;
626
+ break;
627
+ }
628
+ const harm = harmonizeAsciiSuffix(lastPw, suf, { p3sgHead: p3sg });
629
+ if (harm) {
630
+ matchedSuffix = harm;
631
+ break;
632
+ }
633
+ }
634
+ else {
635
+ const fForm = foldTurkish(form);
636
+ const fPw = foldTurkish(lastPw);
637
+ if (fForm.startsWith(fPw) && fForm.length > fPw.length) {
638
+ const suf = form.slice(lastPw.length);
639
+ const p3sg = /[aeıioöuüâîû]$/.test(lastPw) && (INSTITUTION_HEADS.has(lastPw) || GEO_HEADS.has(lastPw) || STATE_HEADS.has(lastPw) || EVENT_HEADS.has(lastPw));
640
+ if ((PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) || HEAD_SUFFIX_RE.test(suf)) && isPhonologicallyValidProperSuffix(lastPw, suf, { p3sgHead: p3sg })) {
641
+ matchedSuffix = suf;
642
+ break;
643
+ }
644
+ const harm = harmonizeAsciiSuffix(lastPw, suf, { p3sgHead: p3sg });
645
+ if (harm) {
646
+ matchedSuffix = harm;
647
+ break;
648
+ }
649
+ }
650
+ }
651
+ }
652
+ }
653
+ // Special case: core already injected wrong split on a book title like "Beyaz Kalesini" -> "Beyaz Kalesi'ni"
654
+ if (matchedSuffix === null && apos > 0) {
655
+ const joined = lastLow.replaceAll("'", "");
656
+ if (joined.startsWith(lastPw) && joined.length > lastPw.length) {
657
+ const suf = joined.slice(lastPw.length);
658
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(lastPw, suf)) {
659
+ matchedSuffix = suf;
660
+ }
661
+ }
662
+ }
663
+ if (matchedSuffix === null)
664
+ continue;
665
+ // Contextual gates for canonical phrases that also occur as ordinary Turkish prose:
666
+ if (phrase.context === "era") {
667
+ // Bare lowercase "eski çağ / ilk çağ / yeni çağ / yakın çağ" modifying a following 3sg-possessive noun
668
+ // ("eski çağ astronomlarının", "eski çağ insanlarının") is a generic modifier, not a standalone historical period;
669
+ // standalone periods ("İlk Çağ yazının icadıyla başlar") and inflected periods ("Eski Çağ'ın") are capitalized.
670
+ let anyCap = false;
671
+ for (let k = 0; k < len; k++) {
672
+ const ct = tokens[i + k];
673
+ if (isCap(ct) && (!ct.atStart || k > 0))
674
+ anyCap = true;
675
+ }
676
+ if (!anyCap && matchedSuffix === "") {
677
+ const afterEra = i + len < tokens.length && adjSpace(lastTok, tokens[i + len]) ? tokens[i + len] : undefined;
678
+ const modifiesPossNoun = afterEra !== undefined &&
679
+ !isCap(afterEra) &&
680
+ /(?:s[ıiuü]|l[ae]r[ıi])(?:n[ıiuü]n|nd[ae]n?|n[aeıiuü]|yl[ae])?$/.test(afterEra.low);
681
+ if (modifiesPossNoun)
682
+ continue;
683
+ }
684
+ }
685
+ else if (phrase.context === "day") {
686
+ // Two-word "<X> Günü" special days ("öğretmenler günü", "anneler günü") require either a formal
687
+ // commemoration/celebration cue or an inflectional suffix ("Öğretmenler Günü'nde", "Gaziler Günü töreninde").
688
+ if (matchedSuffix === "" && !hasSpecialDaySentenceCue)
689
+ continue;
690
+ }
691
+ else if (phrase.context === "work") {
692
+ // Everyday-word literary/film titles ("Kış Uykusu", "Yeni Hayat", "Büyük Umutlar", "Küçük Prens")
693
+ // require a literary/media cue, an author's genitive right before them, or already-capitalized title words.
694
+ const prevAuthorGen = i > 0 &&
695
+ adjSpace(tokens[i - 1], tok) &&
696
+ isCap(tokens[i - 1]) &&
697
+ /'(?:ın|in|un|ün|nın|nin|nun|nün)$/.test(tokens[i - 1].low);
698
+ let allContentCap = true;
699
+ for (let k = 0; k < len; k++) {
700
+ const ct = tokens[i + k];
701
+ if (!TITLE_CONJUNCTIONS.has(ct.low) && !isCap(ct)) {
702
+ allContentCap = false;
703
+ break;
704
+ }
705
+ }
706
+ if (!hasWorkSentenceCue && !prevAuthorGen && !allContentCap)
707
+ continue;
708
+ }
709
+ // Apply the matched multi-word phrase (preserving circumflex choice like "Milli" vs "Millî" when already capitalized!)
710
+ const stripCircumflex = (s) => s.replaceAll("â", "a").replaceAll("î", "i").replaceAll("û", "u").replaceAll("Â", "A").replaceAll("Î", "I").replaceAll("Û", "U");
711
+ for (let k = 0; k < len - 1; k++) {
712
+ const curTok = tokens[i + k];
713
+ const targetDisp = phrase.displayWords[k];
714
+ if (isCap(curTok) && stripCircumflex(curTok.eff) === stripCircumflex(targetDisp)) {
715
+ curTok.locked = true;
716
+ }
717
+ else {
718
+ setToken(curTok, targetDisp, true);
719
+ }
720
+ }
721
+ setToken(lastTok, formatProper(lastDisp, matchedSuffix, phrase.takesApos), true);
722
+ i += len - 1;
723
+ break;
724
+ }
725
+ }
726
+ // ===========================================================================
727
+ // STEP 3: Specific Dates ("12 haziran 2027 cumartesi", "17 aralıka", "25 ocak ile 8 şubat")
728
+ // ===========================================================================
729
+ for (let i = 0; i < tokens.length - 1; i++) {
730
+ const dayTok = tokens[i];
731
+ const monthTok = tokens[i + 1];
732
+ if (!dayTok.isNumber || !monthTok.isWord || monthTok.locked)
733
+ continue;
734
+ if (!adjSpace(dayTok, monthTok))
735
+ continue;
736
+ // Day must be 1..31 and NOT an ordinal ("3.") or decimal ("3.5")
737
+ const dayNum = Number(dayTok.raw);
738
+ if (dayNum < 1 || dayNum > 31)
739
+ continue;
740
+ if (dayTok.sepBefore === "." || dayTok.gapBefore.endsWith(".") || dayTok.gapBefore.endsWith(","))
741
+ continue;
742
+ const mSplit = splitCalendarWord(monthTok.low, MONTHS);
743
+ if (!mSplit)
744
+ continue;
745
+ setToken(monthTok, formatProper(capTr(mSplit.stem), mSplit.suffix, true), true);
746
+ // Optional year (4 digits) + optional weekday ("12 haziran 2027 cumartesi", "12 haziran cumartesi")
747
+ let nextIdx = i + 2;
748
+ if (nextIdx < tokens.length &&
749
+ tokens[nextIdx].isNumber &&
750
+ adjSpace(tokens[nextIdx - 1], tokens[nextIdx]) &&
751
+ /^\d{4}$/.test(tokens[nextIdx].raw)) {
752
+ nextIdx++;
753
+ }
754
+ if (nextIdx < tokens.length && tokens[nextIdx].isWord && adjSpace(tokens[nextIdx - 1], tokens[nextIdx])) {
755
+ const wTok = tokens[nextIdx];
756
+ const wSplit = splitCalendarWord(wTok.low, WEEKDAYS);
757
+ if (wSplit) {
758
+ setToken(wTok, formatProper(capTr(wSplit.stem), wSplit.suffix, true), true);
759
+ }
760
+ }
761
+ }
762
+ // ===========================================================================
763
+ // STEP 3b: Numbers + Turkish Inflectional/Ordinal Suffixes ("1985te" -> "1985'te",
764
+ // "2023de" -> "2023'te", "1985'de" -> "1985'te", "19.30da" -> "19.30'da", "2nci" -> "2'nci")
765
+ // ===========================================================================
766
+ for (const m of text.matchAll(/(\d+(?:[.:]\d+)?)(')?([a-zçğıöşü]+)(?![\p{L}\p{N}_])/gu)) {
767
+ const start = m.index;
768
+ const full = m[0];
769
+ const end = start + full.length;
770
+ const numPart = m[1];
771
+ const hadApos = Boolean(m[2]);
772
+ const rawSuf = m[3];
773
+ if (precededByAddress(text, start) || /[\p{L}_]/u.test(text[start - 1] ?? ""))
774
+ continue;
775
+ if (continuesAsAddress(text, end) && !spaced.has(end))
776
+ continue;
777
+ if (covering(start, end) !== -1)
778
+ continue;
779
+ const lastInt = numPart.includes(".") ? numPart.slice(numPart.lastIndexOf(".") + 1) : numPart.includes(":") ? numPart.slice(numPart.lastIndexOf(":") + 1) : numPart;
780
+ const fixedSuf = fixNumberSuffix(lastInt, rawSuf, hadApos);
781
+ if (!fixedSuf)
782
+ continue;
783
+ const rep = `${numPart}'${fixedSuf}`;
784
+ if (rep !== full) {
785
+ result.push({ start, end, original: full, replacement: rep, kind: "punct", margin: 6 });
786
+ }
787
+ }
788
+ result.sort((a, b) => a.start - b.start);
789
+ // ===========================================================================
790
+ // STEP 4: Wrong-Apostrophe Removal & Relocation (TDK kesme_yanlis W1–W6)
791
+ // ===========================================================================
792
+ const hasReadingOrWatchingCtx = tokens.some((t) => t.isWord && /^(?:oku|bitir|yaz|izle|seyret|roman|kitap|film|dizi|oyun|eser|tiyatro)/.test(t.low));
793
+ const BARE_INSTITUTION_OFFICES = new Set([
794
+ "başbakanlık", "bakanlık", "müdürlük", "başkanlık", "rektörlük", "dekanlık", "valilik", "kaymakamlık",
795
+ ]);
796
+ for (let i = 0; i < tokens.length; i++) {
797
+ const tok = tokens[i];
798
+ if (!tok.isWord || tok.locked)
799
+ continue;
800
+ if (!tok.eff.includes("'") && !tok.eff.includes("’"))
801
+ continue;
802
+ // Protect hyphenated foreign/compound suffixes ("Luffy-san'ın", "U-Bot'larında", "Fatu-Krey'li")
803
+ if (tok.gapBefore.endsWith("-"))
804
+ continue;
805
+ const norm = tok.eff.replaceAll("’", "'");
806
+ const parts = norm.split("'");
807
+ if (parts.some((p) => p.length === 0))
808
+ continue;
809
+ // W1: Multiple apostrophes ("Mehmet'le'ydim" -> "Mehmet'leydim", "Kemal'in'kiler" -> "Kemal'inkiler", "İzmir'li'ler" -> "İzmirliler", "Türk'lük'ün" -> "Türklüğün")
810
+ // Protect foreign names with an internal stem apostrophe ("G'Kar'a", "Teal'c'in", "d'Aragon'dan", "Goa'uld'ları")!
811
+ if (parts.length >= 3) {
812
+ const stem = parts[0];
813
+ const rest1 = parts[1];
814
+ const restAll = parts.slice(1).join("");
815
+ const lowStem = lowerTr(stem);
816
+ const lowRest1 = lowerTr(rest1);
817
+ const isTurkishSuffixMid = stem.length >= 3 &&
818
+ /^[a-zçğıöşü]+$/.test(rest1) &&
819
+ (PROPER_INFLECTIONAL_SUFFIX_RE.test(lowRest1) || NON_APOSTROPHE_SUFFIX_RE.test(lowRest1));
820
+ if (!isTurkishSuffixMid)
821
+ continue;
822
+ if (NON_APOSTROPHE_SUFFIX_RE.test(lowRest1) || LANGUAGE_NAMES.has(lowStem) || NO_APOS_RELIGION_OR_DERIVED.has(lowStem)) {
823
+ const stemPlus1 = joinWithoutApostrophe(stem, rest1, isMorphWord);
824
+ const finalJoined = parts.length === 3 ? joinWithoutApostrophe(stemPlus1, parts[2], isMorphWord) : stemPlus1 + parts.slice(2).join("");
825
+ setToken(tok, finalJoined, true);
826
+ }
827
+ else {
828
+ setToken(tok, `${stem}'${restAll}`, true);
829
+ }
830
+ continue;
831
+ }
832
+ // Single apostrophe: stem'suffix
833
+ const stem = parts[0];
834
+ const suffix = parts[1];
835
+ const lowStem = lowerTr(stem);
836
+ const lowSuffix = lowerTr(suffix);
837
+ const prevTok = i > 0 && adjSpace(tokens[i - 1], tok) ? tokens[i - 1] : undefined;
838
+ // Protect ALL-CAPS acronyms ("TDK'nin", "ÖSYM'nin", "ABD'nin") and foreign apostrophe names ("O'Connor", "d'Arc")
839
+ if (stem.length >= 2 && stem === upperTr(stem) && stem !== lowerTr(stem))
840
+ continue;
841
+ if (stem.length < 3 || /^\p{Lu}/u.test(suffix))
842
+ continue;
843
+ // W2: Derivational or plural suffix right after apostrophe ("İzmir'li", "Tokat'lıymış", "Türk'çe", "Müslüman'lık", "Marks'çı", "Tanrı'sal", "Alman'lar", "Weisse'ler")
844
+ if (NON_APOSTROPHE_SUFFIX_RE.test(lowSuffix)) {
845
+ const joined = joinWithoutApostrophe(stem, suffix, isMorphWord);
846
+ const lowJoined = lowerTr(joined);
847
+ const stemEntry = known.nameEntry(lowStem);
848
+ const properDisp = stemEntry ? stemEntry.name : isCap(tok) ? stem : undefined;
849
+ const unseenJoined = !isMorphWord(lowJoined) && lexCount(lowJoined) === 0;
850
+ // Protect foreign English-plural stems ending in consonant+"s" ("Sharks'ların", "Lakers'ların", "Beatles'ların")
851
+ // and low-capShare foreign brand plurals with case suffixes ("Volvo'ları") while keeping TDK "Weisse'ler", "Alman'lar", "Marks'çı".
852
+ const isForeignPluralBrandBlock = unseenJoined &&
853
+ ((lowSuffix.startsWith("l") && /[bcdfghjklmnpqrtvwxz]s$/.test(lowStem)) ||
854
+ (/^l[ae]r.+/.test(lowSuffix) &&
855
+ !known.givenNameFor(lowStem) &&
856
+ !known.surnameFor(lowStem) &&
857
+ capShare(lowStem) < 0.6));
858
+ if (!isForeignPluralBrandBlock &&
859
+ properDisp &&
860
+ (isMorphWord(lowJoined) || lexCount(lowJoined) >= 1 || lowSuffix.startsWith("l") || /^[cçs]/.test(lowSuffix))) {
861
+ setToken(tok, joinWithoutApostrophe(properDisp, suffix, isMorphWord), true);
862
+ continue;
863
+ }
864
+ }
865
+ // W3a: Language name before apostrophe ("Fransızca'da", "Rusça'sı", "almanca'ya", "ispanyolca'dan")
866
+ if (LANGUAGE_NAMES.has(lowStem)) {
867
+ setToken(tok, capTr(lowStem) + suffix, true);
868
+ continue;
869
+ }
870
+ // W3b-opt: Foreign/Arabic -izm/-iyet religions ("İslamiyet'e", "Budizm'in", "Hinduizm'de") keep their apostrophe!
871
+ if (OPTIONAL_APOS_ISM_IYET.has(lowStem)) {
872
+ if (!isCap(tok))
873
+ setToken(tok, `${capTr(lowStem)}'${suffix}`, true);
874
+ else
875
+ tok.locked = true;
876
+ continue;
877
+ }
878
+ // W3b: Derived religion/ideology/demonym with Turkish derivational suffix before apostrophe
879
+ // ("Hristiyanlık'ta" -> "Hristiyanlıkta", "Hristiyanlık'ın" -> "Hristiyanlığın", "Atatürkçülük'ün" -> "Atatürkçülüğün", "Ankaralı'nın" -> "Ankaralının")
880
+ if (NO_APOS_RELIGION_OR_DERIVED.has(lowStem)) {
881
+ setToken(tok, joinWithoutApostrophe(capTr(lowStem), suffix, isMorphWord), true);
882
+ continue;
883
+ }
884
+ const existingProperStem = known.nameEntry(lowStem);
885
+ if (!DERIV_LOOKING_KEEP_APOS.has(lowStem) && (!existingProperStem || existingProperStem.noApos)) {
886
+ const aposCount = lexCount(lowStem + "'" + lowSuffix);
887
+ const softPlain = joinWithoutApostrophe(isCap(tok) ? stem : capTr(lowStem), suffix, isMorphWord);
888
+ const lowSoftPlain = lowerTr(softPlain);
889
+ const joinCount = Math.max(lexCount(lowStem + lowSuffix), lexCount(lowSoftPlain));
890
+ if (/l[ıiuü]k$/.test(lowStem) && lowStem.length >= 6 && aposCount <= joinCount) {
891
+ const root = lowStem.slice(0, -3);
892
+ if ((known.nameEntry(root) || known.ambigNameFor(root)) && isMorphWord(lowSoftPlain)) {
893
+ setToken(tok, softPlain, true);
894
+ continue;
895
+ }
896
+ }
897
+ if (/(?:l[ıiuü]|[cç][ıiuü])$/.test(lowStem) && lowStem.length >= 6 && aposCount * 3 <= joinCount) {
898
+ const root = lowStem.slice(0, -2);
899
+ if ((known.nameEntry(root) || known.ambigNameFor(root)) && isMorphWord(lowSoftPlain)) {
900
+ setToken(tok, softPlain, true);
901
+ continue;
902
+ }
903
+ }
904
+ }
905
+ // W3c: Plural proper noun before apostrophe ("Japonlar'ın", "Almanlar'ın", "Türkler'in", "Ahmetler'e", "Yılmazlar'ın", "Atatürkçüler'in", "Ankaralılar'ın")
906
+ if (/l[ae]r$/.test(lowStem) && lowStem.length >= 6 && !PLURAL_PLACE_KEEP_APOS.has(lowStem)) {
907
+ const singular = lowStem.slice(0, -3);
908
+ if (known.nameEntry(singular) ||
909
+ known.givenNameFor(singular) ||
910
+ known.surnameFor(singular) ||
911
+ known.ambigNameFor(singular) ||
912
+ singular === "alman" ||
913
+ NO_APOS_RELIGION_OR_DERIVED.has(singular) ||
914
+ (singular.length >= 5 && /(?:l[ıiuü]|[cç][ıiuü])$/.test(singular) && known.nameEntry(singular.slice(0, -2)))) {
915
+ setToken(tok, (isCap(tok) ? stem : capTr(lowStem)) + suffix, true);
916
+ continue;
917
+ }
918
+ }
919
+ // W4: Institution head before apostrophe ("Millî Eğitim Bakanlığı'na", "Ankara Üniversitesi'ne", "Anadolu Ajansı'nın", "Başbakanlık'a" -> "Başbakanlığa")
920
+ // Protect literary/film titles ending in museum/hotel/club/association/institute ("Masumiyet Müzesi'ni okudum", "Ölü Ozanlar Derneği'ni izledim").
921
+ if (isInstitutionHead(lowStem, prevTok?.low)) {
922
+ const workProneHead = lowStem === "müzesi" ||
923
+ lowStem === "oteli" ||
924
+ lowStem === "derneği" ||
925
+ lowStem === "enstitüsü" ||
926
+ lowStem === "çiftliği" ||
927
+ lowStem === "kulübü" ||
928
+ lowStem === "tiyatrosu";
929
+ if (workProneHead && hasReadingOrWatchingCtx)
930
+ continue;
931
+ if (isCap(tok)) {
932
+ setToken(tok, joinWithoutApostrophe(stem, suffix, isMorphWord), true);
933
+ }
934
+ else {
935
+ // Lowercase institution head with apostrophe: strip apostrophe without forcing capitalization (let Step 6a decide).
936
+ setToken(tok, joinWithoutApostrophe(stem, suffix, isMorphWord), false);
937
+ }
938
+ continue;
939
+ }
940
+ if (isCap(tok) && BARE_INSTITUTION_OFFICES.has(lowStem)) {
941
+ setToken(tok, joinWithoutApostrophe(stem, suffix, isMorphWord), true);
942
+ continue;
943
+ }
944
+ // W5: Misplaced apostrophe inside a proper name's suffix chain ("Selinin'kini" -> "Selin'inkini",
945
+ // "Ahmetin'ki" -> "Ahmet'inki", "İstanbulda'ki" -> "İstanbul'daki", "Türkiyemiz'in" -> "Türkiye'mizin", "Ankarad'an" -> "Ankara'dan")
946
+ // NEVER split a valid standalone stem like "Savaşı'nın", "Rüyası'na", "Bayramı'na", or unknown foreign name "Jimin'in"!
947
+ if (!known.nameEntry(lowStem) &&
948
+ !known.givenNameFor(lowStem) &&
949
+ !known.surnameFor(lowStem) &&
950
+ !known.ambigNameFor(lowStem)) {
951
+ const isKiOrCop = /^(?:ki(?:l[ae]r(?:[aeıiuü]|[dt][ae]n?|[ıiuü]n)?)?|ki(?:n[aeıiuü]|nd[ae]n?|n[ıiuü]n)?|yd[ıiuü][mk]?|ym[ıiuü]ş|n|m)$/.test(lowSuffix);
952
+ const isPossReloc = /(?:m[ıiuü]z|n[ıiuü]z)$/.test(lowStem) || (!isMorphWord(lowStem) && /[dt][ae]$/.test(lowStem));
953
+ if (isKiOrCop || isPossReloc) {
954
+ const joinedLow = lowStem + lowSuffix;
955
+ for (let cut = lowStem.length - 1; cut >= 3; cut--) {
956
+ const base = joinedLow.slice(0, cut);
957
+ const combinedSuf = joinedLow.slice(cut);
958
+ const ne = known.nameEntry(base);
959
+ if (ne?.noApos)
960
+ continue;
961
+ const disp = isKiOrCop ? (ne?.name ?? known.givenNameFor(base) ?? known.surnameFor(base)) : ne?.name;
962
+ if (!disp)
963
+ continue;
964
+ if (NON_APOSTROPHE_SUFFIX_RE.test(combinedSuf))
965
+ continue;
966
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(combinedSuf) && isPhonologicallyValidProperSuffix(lowerTr(disp), combinedSuf)) {
967
+ setToken(tok, `${disp}'${combinedSuf}`, true);
968
+ break;
969
+ }
970
+ }
971
+ if (tok.locked)
972
+ continue;
973
+ }
974
+ }
975
+ // W6: Common noun with wrong apostrophe
976
+ const lowJoined = lowStem + lowSuffix;
977
+ const softenedJoined = joinWithoutApostrophe(stem, suffix, isMorphWord);
978
+ const lowSoftJoined = lowerTr(softenedJoined);
979
+ const morphValidJoined = isMorphWord(lowJoined) || isMorphWord(lowSoftJoined);
980
+ const effJoinedCount = Math.max(lexCount(lowJoined), lexCount(lowSoftJoined));
981
+ if (!isCap(tok)) {
982
+ // Lowercase stem'suffix:
983
+ // 1) Known unconditional proper name -> capitalize ("ahmet'e" -> "Ahmet'e", "ankara'dan" -> "Ankara'dan")
984
+ const nameEnt = lookupName(lowStem, sentenceHasAsciiFixes);
985
+ if (nameEnt) {
986
+ const fixedSuf = harmonizeAsciiSuffix(lowerTr(nameEnt.name), lowSuffix) ?? suffix;
987
+ setToken(tok, formatProper(nameEnt.name, fixedSuf, !nameEnt.noApos), true);
988
+ continue;
989
+ }
990
+ // 2) Known Turkish given/surname with apostrophe that CANNOT be a common Turkish word ("emre'yi" -> "Emre'yi", "aslı'yı" -> "Aslı'yı")
991
+ const personDisp = known.givenNameFor(lowStem) ?? known.surnameFor(lowStem);
992
+ if (personDisp && !morphValidJoined) {
993
+ setToken(tok, `${personDisp}'${suffix}`, true);
994
+ continue;
995
+ }
996
+ // 2b) Honorific after a person name ("Mustafa ağa'nın" -> handled in Step 7d as "Mustafa Ağa'nın", don't strip!)
997
+ if (POST_HONORIFICS.has(lowStem) &&
998
+ prevTok !== undefined &&
999
+ (known.givenNameFor(prevTok.low) !== undefined || known.nameEntry(prevTok.low) !== undefined || (isCap(prevTok) && !prevTok.atStart))) {
1000
+ continue;
1001
+ }
1002
+ // 3) Ordinary common Turkish noun (NOT in AMBIG and NOT a foreign loanword like "single'ı", "rock'ın") -> remove apostrophe (with softening: "kitap'ı" -> "kitabı")
1003
+ const lowAposCount = lexCount(lowStem + "'" + lowSuffix);
1004
+ if (!known.ambigNameFor(lowStem) &&
1005
+ morphValidJoined &&
1006
+ (lowAposCount === 0 || lowAposCount * 3 < effJoinedCount)) {
1007
+ setToken(tok, softenedJoined, true);
1008
+ continue;
1009
+ }
1010
+ // 4) Ambiguous lowercase stem'suffix ("deniz'e girmeye" vs "deniz'e söyle"):
1011
+ // Handle deterministic common-word idioms here; defer remaining unlocked ambig'suf until Step 8f
1012
+ // so Step 7 (titles/honorifics/person chains like "dr. şebnem koç'tan") locks surnames first!
1013
+ if (known.ambigNameFor(lowStem) && morphValidJoined) {
1014
+ const nextTok = i + 1 < tokens.length ? tokens[i + 1] : undefined;
1015
+ const commonCue = (lowStem === "deniz" && nextTok !== undefined && /^(?:gir|yüz|atla|dökül|açıl|bak|in)/.test(nextTok.low)) ||
1016
+ (lowStem === "gül" && nextTok !== undefined && /^(?:bahçe|su|reçel|yaprak|diken|koku)/.test(nextTok.low));
1017
+ if (commonCue) {
1018
+ setToken(tok, softenedJoined, true);
1019
+ continue;
1020
+ }
1021
+ }
1022
+ }
1023
+ else if (tok.atStart) {
1024
+ // Sentence-start capitalized common noun with wrong apostrophe ("Babam'ın", "Toplantı'ya", "Ofis'te", "Okul'da", "Kitap'ı" -> "Kitabı")
1025
+ // Protects proper place/institution/league names like "Bebek'te", "Moda'da", "Boğaz'da", "Meclis'te", "Lig'inde" via lexCount(apos) <= 25!
1026
+ const startAposCount = lexCount(lowStem + "'" + lowSuffix);
1027
+ if (!known.nameEntry(lowStem) &&
1028
+ !known.ambigNameFor(lowStem) &&
1029
+ !known.givenNameFor(lowStem) &&
1030
+ !known.surnameFor(lowStem) &&
1031
+ !MONTHS.has(lowStem) &&
1032
+ !WEEKDAYS.has(lowStem) &&
1033
+ capShare(lowStem) < 0.55 &&
1034
+ morphValidJoined &&
1035
+ effJoinedCount >= 10 &&
1036
+ startAposCount <= 25 &&
1037
+ startAposCount * 8 < effJoinedCount) {
1038
+ setToken(tok, softenedJoined, true);
1039
+ continue;
1040
+ }
1041
+ }
1042
+ }
1043
+ // ===========================================================================
1044
+ // STEP 5: Capitalized Internal Conjunctions inside Capitalized Titles ("Radyo Ve Televizyon", "Leyla İle Mecnun")
1045
+ // ===========================================================================
1046
+ for (let i = 1; i < tokens.length - 1; i++) {
1047
+ const tok = tokens[i];
1048
+ if (!tok.isWord || tok.locked || tok.atStart)
1049
+ continue;
1050
+ if (tok.eff !== "Ve" && tok.eff !== "İle")
1051
+ continue;
1052
+ const prev = tokens[i - 1];
1053
+ const next = tokens[i + 1];
1054
+ if (!prev.isWord || !next.isWord || !adjSpace(prev, tok) || !adjSpace(tok, next))
1055
+ continue;
1056
+ if (isCap(prev) && !isAllCaps(prev) && isCap(next) && !isAllCaps(next)) {
1057
+ setToken(tok, lowerTr(tok.eff), true);
1058
+ }
1059
+ }
1060
+ // ===========================================================================
1061
+ // STEP 6: Compositional Institutions, Geo/Landmarks, Directions, Events
1062
+ // ===========================================================================
1063
+ // 6a. Compositional Institutions ("Boğaziçi üniversitesinde", "Marmara üniversitesine",
1064
+ // "Eskişehir Osmangazi üniversitesinde", "Yıldız pastanesinden", "Ankara Üniversitesi siyasal bilgiler fakültesi")
1065
+ // Conservative on mixed-case text: if the head is already capitalized ("Yahudi kültür Birliği") or a multi-word
1066
+ // phrase already has capitalized words next to a lowercase tail not in PHRASE_NOAPOS ("Dicle Gençlik kulübü",
1067
+ // "Sırp Listesi partisini", "Özel İhtisas komisyonu", "Londra Büyük elçiliği", "PTT genel müdürlüğünde",
1068
+ // "Boston Üniversitesi iletişim bölümünden"), do not guess-capitalize.
1069
+ const UNAMBIG_MIXED_INST_HEADS = new Set([
1070
+ "üniversitesi", "bakanlığı", "valiliği", "kaymakamlığı", "lisesi", "hastanesi", "belediyesi", "pastanesi", "bakkaliyesi",
1071
+ ]);
1072
+ for (let i = 1; i < tokens.length; i++) {
1073
+ const tok = tokens[i];
1074
+ if (!tok.isWord || tok.locked)
1075
+ continue;
1076
+ // Never walk left from an already-capitalized head ("Yahudi kültür Birliği") to guess-capitalize lowercase middle words.
1077
+ if (isCap(tok))
1078
+ continue;
1079
+ const hSplit = splitHeadWord(tok.low, INSTITUTION_HEADS);
1080
+ if (!hSplit)
1081
+ continue;
1082
+ const prev = tokens[i - 1];
1083
+ if (!prev.isWord || !adjSpace(prev, tok))
1084
+ continue;
1085
+ if (!isInstitutionHead(hSplit.head, prev.low))
1086
+ continue;
1087
+ // Never treat a genitive/inflected token ("Sinan Güler'in polikliniğinde", "Atatürk Lisesinin ...") as an institution anchor!
1088
+ if (prev.low.includes("'") || prev.raw.includes("'") || prev.raw.includes("’"))
1089
+ continue;
1090
+ if (splitHeadWord(prev.low, INSTITUTION_HEADS)?.suffix)
1091
+ continue;
1092
+ // Never treat generic "köy/mahalle/semt odası" ("Eskimo köy odası") as an official chamber/institution.
1093
+ if (hSplit.head === "odası" && (prev.low === "köy" || prev.low === "mahalle" || prev.low === "semt" || prev.low === "otel"))
1094
+ continue;
1095
+ let startIdx = i;
1096
+ let hasProperAnchor = false;
1097
+ for (let j = i - 1; j >= Math.max(0, i - 6); j--) {
1098
+ const cur = tokens[j];
1099
+ const right = tokens[j + 1];
1100
+ if (!cur.isWord || !adjSpace(cur, right) || cur.low.includes("'") || cur.raw.includes("'") || cur.raw.includes("’"))
1101
+ break;
1102
+ if (splitHeadWord(cur.low, INSTITUTION_HEADS)?.suffix)
1103
+ break;
1104
+ const lw = cur.low;
1105
+ // Allow internal conjunction "ve" / "ile" ONLY if something valid is to its left
1106
+ if ((lw === "ve" || lw === "ile") && j > 0 && tokens[j - 1].isWord && adjSpace(tokens[j - 1], cur)) {
1107
+ startIdx = j;
1108
+ continue;
1109
+ }
1110
+ const neCur = known.nameEntry(lw);
1111
+ const isNameToken = (neCur !== undefined && !neCur.noApos) ||
1112
+ known.acronymFor(lw) !== undefined ||
1113
+ (isCap(cur) && !cur.atStart && !NON_INST_PREFIX.has(lw)) ||
1114
+ (isCap(cur) && cur.atStart && ((neCur !== undefined && !neCur.noApos) || GENERIC_INST_MODIFIERS.has(lw) || capShare(lw) >= 0.45));
1115
+ const isInstMod = GENERIC_INST_MODIFIERS.has(lw) || INSTITUTION_HEADS.has(lw);
1116
+ const isAmbigShopName = j === i - 1 &&
1117
+ known.ambigNameFor(lw) !== undefined &&
1118
+ (hSplit.head === "pastanesi" || hSplit.head === "bakkaliyesi" || hSplit.head === "lokantası" || hSplit.head === "restoranı" || hSplit.head === "oteli" || hSplit.head === "kafesi" || hSplit.head === "fırını" || hSplit.head === "eczanesi" || hSplit.head === "kitabevi" || hSplit.head === "yayınevi" || hSplit.head === "lisesi" || hSplit.head === "koleji" || hSplit.head === "hastanesi" || hSplit.head === "üniversitesi" || hSplit.head === "bankası");
1119
+ // Check if `cur` is a strong proper anchor (not just a generic modifier like "tıp" or "devlet")
1120
+ if (isNameToken && !NON_INST_PREFIX.has(lw) && !GENERIC_INST_MODIFIERS.has(lw)) {
1121
+ hasProperAnchor = true;
1122
+ startIdx = j;
1123
+ continue;
1124
+ }
1125
+ if (isAmbigShopName) {
1126
+ hasProperAnchor = true;
1127
+ startIdx = j;
1128
+ continue;
1129
+ }
1130
+ if (INSTITUTION_HEADS.has(lw) && (cur.locked || isCap(cur))) {
1131
+ // Preceded by an already-identified university/institution ("Ankara Üniversitesi siyasal bilgiler fakültesi")
1132
+ hasProperAnchor = true;
1133
+ startIdx = j;
1134
+ break;
1135
+ }
1136
+ if (isInstMod) {
1137
+ // Specific capitalized institution prefixes at start ("Bankacılık düzenleme ve denetleme kurumunun", "Sosyal Güvenlik")
1138
+ if (isCap(cur) && !cur.atStart && !NON_INST_PREFIX.has(lw))
1139
+ hasProperAnchor = true;
1140
+ if (lw === "dokuz" || lw === "ondokuz" || lw === "marmara" || lw === "boğaziçi" || lw === "uludağ" || lw === "osmangazi" || lw === "hacettepe" || lw === "gazi" || lw === "ege" || lw === "anadolu" || lw === "ziraat" || lw === "içişleri" || lw === "dışişleri" || lw === "bankacılık" || lw === "sosyal" || lw === "bakanlar" || lw === "meteoroloji" || lw === "radyo" || lw === "diyanet") {
1141
+ hasProperAnchor = true;
1142
+ }
1143
+ startIdx = j;
1144
+ continue;
1145
+ }
1146
+ break;
1147
+ }
1148
+ // Trim leading conjunctions ("ve", "ile")
1149
+ while (startIdx < i && (tokens[startIdx].low === "ve" || tokens[startIdx].low === "ile"))
1150
+ startIdx++;
1151
+ // Guard against bare generic phrases like "tıp fakültesi", "hukuk fakültesi", "devlet hastanesi", "ilçe belediyesi"
1152
+ // and indefinite appositives like "bir Irak hastanesinde", "bir Pakistan askeri mahkemesi", "Sony Mobile şirketi", "Beta Gençlikspor kulübü".
1153
+ if (startIdx >= i || !hasProperAnchor)
1154
+ continue;
1155
+ if (startIdx > 0 && tokens[startIdx - 1].low === "bir")
1156
+ continue;
1157
+ if (tokens[startIdx].gapBefore.endsWith("-"))
1158
+ continue;
1159
+ // Mixed-case guard: if the writer already capitalized part of the unknown multi-word span while leaving the head
1160
+ // lowercase ("Dicle Gençlik kulübü", "Sırp Listesi partisini", "Özel İhtisas komisyonu", "Londra Büyük elçiliği",
1161
+ // "PTT genel müdürlüğünde", "Boston Üniversitesi iletişim bölümünden", "Eskimo köy odası"), only capitalize
1162
+ // unambiguous 2-word "<KnownProper> <UnambigOfficialHead>" forms ("Boğaziçi üniversitesinde", "Marmara üniversitesine").
1163
+ let hasAlreadyCapPrefix = false;
1164
+ for (let j = startIdx; j < i; j++) {
1165
+ const cur = tokens[j];
1166
+ if (/^\p{Lu}/u.test(cur.raw) && (!cur.atStart || j > startIdx || isAllCaps(cur) || known.nameEntry(cur.low) !== undefined)) {
1167
+ hasAlreadyCapPrefix = true;
1168
+ break;
1169
+ }
1170
+ }
1171
+ if (hasAlreadyCapPrefix) {
1172
+ const safeTwoWordOfficial = startIdx === i - 1 &&
1173
+ !isAllCaps(prev) &&
1174
+ known.nameEntry(prev.low) !== undefined &&
1175
+ !known.nameEntry(prev.low).noApos &&
1176
+ UNAMBIG_MIXED_INST_HEADS.has(hSplit.head);
1177
+ if (!safeTwoWordOfficial)
1178
+ continue;
1179
+ }
1180
+ if (startIdx === i - 1 &&
1181
+ GENERIC_ALONE_INST_HEADS.has(hSplit.head) &&
1182
+ NON_INST_PREFIX.has(tokens[startIdx].low)) {
1183
+ continue;
1184
+ }
1185
+ const STRICT_APPOSITIVE_HEADS = new Set(["şirketi", "kulübü", "grubu", "holdingi"]);
1186
+ // Do not capitalize bare brand appositives ("Sony Mobile şirketi", "Beta Gençlikspor kulübü")
1187
+ // unless preceded by a canonical Turkish institutional modifier ("Spor Kulübü", "Jimnastik Kulübü", "Anonim Şirketi").
1188
+ if (STRICT_APPOSITIVE_HEADS.has(hSplit.head)) {
1189
+ const hasInstMod = prev.low === "spor" ||
1190
+ prev.low === "jimnastik" ||
1191
+ prev.low === "anonim" ||
1192
+ prev.low === "limited" ||
1193
+ prev.low === "ticaret" ||
1194
+ prev.low === "yatırım" ||
1195
+ prev.low === "inşaat" ||
1196
+ prev.low === "sanayi" ||
1197
+ prev.low === "gençlik" ||
1198
+ prev.low === "kültür" ||
1199
+ prev.low === "denizcilik" ||
1200
+ prev.low === "havacılık";
1201
+ if (!hasInstMod)
1202
+ continue;
1203
+ }
1204
+ if (hSplit.head === "bölümü") {
1205
+ // Only capitalize "Bölümü" when preceded by an already-capitalized university/faculty/department chain ("Ankara Üniversitesi ... Bölümü")
1206
+ let hasUnivAnchor = false;
1207
+ for (let j = startIdx; j < i; j++) {
1208
+ if (tokens[j].low === "üniversitesi" || tokens[j].low === "fakültesi" || tokens[j].low === "edebiyatı") {
1209
+ hasUnivAnchor = true;
1210
+ break;
1211
+ }
1212
+ }
1213
+ if (!hasUnivAnchor)
1214
+ continue;
1215
+ }
1216
+ // Two-word "<Nationality> kulübü/başkanlığı/kütüphanesi/bölümü/mahkemesi/müzesi/müdürlüğü/..." is generic ("Alman kulübü", "Amerikan başkanlığı").
1217
+ const NATIONALITY_GENERIC_MOD = new Set([
1218
+ "alman", "fransız", "ingiliz", "amerikan", "italyan", "ispanyol", "rus", "yunan", "japon",
1219
+ "çin", "türk", "osmanlı", "sovyet", "avrupa", "asya", "afrika", "arap", "ermeni", "yahudi",
1220
+ "kürt", "rum", "bulgar", "sırp", "macar", "hollanda", "belçika", "isveç", "norveç", "polonya",
1221
+ ]);
1222
+ const GENERIC_NAT_INST_HEADS = new Set([
1223
+ "kulübü", "başkanlığı", "idaresi", "müdürlüğü", "bölümü", "kütüphanesi", "müzesi",
1224
+ "mahkemesi", "komitesi", "konseyi", "partisi", "birliği", "federasyonu", "derneği",
1225
+ "vakfı", "şirketi", "tiyatrosu", "operası", "hastanesi", "okulu", "fakültesi",
1226
+ "merkezi", "dairesi", "şubesi", "ofisi", "yurdu", "elçiliği",
1227
+ ]);
1228
+ if (startIdx === i - 1 &&
1229
+ NATIONALITY_GENERIC_MOD.has(tokens[startIdx].low) &&
1230
+ GENERIC_NAT_INST_HEADS.has(hSplit.head)) {
1231
+ continue;
1232
+ }
1233
+ // Protect lowercase Wikipedia appositives where an unknown foreign capitalized word precedes generic "belediyesi"/"hastanesi"/"mahkemesi"/"partisi"/"okulu"/"müzesi"/"kütüphanesi"
1234
+ // ("Kurbin belediyesinde", "Polimer kütüphanesi", "Pontevedra müzesinin", "siyasi bilimler fakültesi")
1235
+ if (startIdx === i - 1 &&
1236
+ (hSplit.head === "belediyesi" || hSplit.head === "hastanesi" || hSplit.head === "mahkemesi" || hSplit.head === "okulu" || hSplit.head === "müzesi" || hSplit.head === "kütüphanesi") &&
1237
+ !known.nameEntry(prev.low) &&
1238
+ !known.ambigNameFor(prev.low) &&
1239
+ !GENERIC_INST_MODIFIERS.has(prev.low)) {
1240
+ continue;
1241
+ }
1242
+ // Never capitalize bare "<generic_adj> bilimler fakültesi" ("siyasi bilimler fakültesi", "sosyal bilimler fakültesi") without a university/proper anchor
1243
+ if (hSplit.head === "fakültesi" && tokens[startIdx].low === "bilimler") {
1244
+ continue;
1245
+ }
1246
+ for (let j = startIdx; j < i; j++) {
1247
+ const cur = tokens[j];
1248
+ if (cur.locked)
1249
+ continue;
1250
+ if (cur.low === "ve" || cur.low === "ile") {
1251
+ setToken(cur, cur.low, true);
1252
+ }
1253
+ else {
1254
+ const ne = lookupName(cur.low, sentenceHasAsciiFixes);
1255
+ const acro = known.acronymFor(cur.low);
1256
+ setToken(cur, acro ?? ne?.name ?? capTr(cur.eff), true);
1257
+ }
1258
+ }
1259
+ // Institution head ALWAYS has NO apostrophe per TDK!
1260
+ setToken(tok, capTr(hSplit.head) + hSplit.suffix, true);
1261
+ }
1262
+ // 6a-officer. TDK Institution Officer Titles ("Türk Dil Kurumu Başkanı'na", "Ankara Üniversitesi Rektörü'nden",
1263
+ // "Emniyet Genel Müdürü'ne", "Sağlık Bakanlığı Sözcüsü'ne", "Mühendislik Fakültesi Dekanı'na")
1264
+ // Per TDK, personal titles following an institution name take BOTH capitalization AND apostrophe when
1265
+ // standing as an official makam/title; bare lowercase descriptive job roles after an already-capitalized
1266
+ // institution ("Bremen Sanat Müzesi müdürü ressam Carl Horn", "Azerbaycan Millî Meclisi başkanı Resul Guliyev")
1267
+ // are left untouched.
1268
+ const OFFICER_ROLE_FOLLOW_BLOCK = new Set([
1269
+ "olan", "olarak", "oldu", "olmuş", "olacak", "idi", "seçildi", "atandı", "görev", "görevini",
1270
+ ]);
1271
+ for (let i = 1; i < tokens.length; i++) {
1272
+ const prev = tokens[i - 1];
1273
+ const tok = tokens[i];
1274
+ if (!prev.isWord || !tok.isWord || tok.locked || !adjSpace(prev, tok))
1275
+ continue;
1276
+ // Preceding token must be a capitalized/locked institution or state head (not inflected with apostrophe/case!)
1277
+ const prevIsBareInst = (prev.locked || isCap(prev)) &&
1278
+ (INSTITUTION_HEADS.has(prev.low) || STATE_HEADS.has(prev.low) || prev.low === "belediye" || prev.low === "meclis");
1279
+ if (!prevIsBareInst)
1280
+ continue;
1281
+ // Optional 1-word modifier ("Genel Müdürü'ne", "Başkan Yardımcısı'na")
1282
+ let titleIdx = i;
1283
+ if (OFFICER_TITLE_MODS.has(tok.low) &&
1284
+ i + 1 < tokens.length &&
1285
+ tokens[i + 1].isWord &&
1286
+ adjSpace(tok, tokens[i + 1])) {
1287
+ const nextTok = tokens[i + 1];
1288
+ const nextSplit = splitHeadWord(nextTok.low, OFFICER_TITLE_HEADS);
1289
+ if (nextSplit) {
1290
+ const afterNext = i + 2 < tokens.length && adjSpace(nextTok, tokens[i + 2]) ? tokens[i + 2] : undefined;
1291
+ const bareLowerRole = !nextSplit.suffix &&
1292
+ !isCap(tok) &&
1293
+ !isCap(nextTok) &&
1294
+ afterNext !== undefined &&
1295
+ (isCap(afterNext) ||
1296
+ PERSON_REL_BEFORE.has(afterNext.low) ||
1297
+ PRE_TITLES_FULL.has(afterNext.low) ||
1298
+ PRE_TITLES_ABBR.has(afterNext.low) ||
1299
+ OFFICER_ROLE_FOLLOW_BLOCK.has(afterNext.low));
1300
+ if (!bareLowerRole) {
1301
+ setToken(tok, capTr(tok.eff), true);
1302
+ setToken(nextTok, formatProper(capTr(nextSplit.head), nextSplit.suffix, true), true);
1303
+ i++;
1304
+ continue;
1305
+ }
1306
+ }
1307
+ }
1308
+ const oSplit = splitHeadWord(tok.low, OFFICER_TITLE_HEADS);
1309
+ if (oSplit) {
1310
+ const afterTok = i + 1 < tokens.length && adjSpace(tok, tokens[i + 1]) ? tokens[i + 1] : undefined;
1311
+ const bareLowerRole = !oSplit.suffix &&
1312
+ !isCap(tok) &&
1313
+ afterTok !== undefined &&
1314
+ (isCap(afterTok) ||
1315
+ PERSON_REL_BEFORE.has(afterTok.low) ||
1316
+ PRE_TITLES_FULL.has(afterTok.low) ||
1317
+ PRE_TITLES_ABBR.has(afterTok.low) ||
1318
+ OFFICER_ROLE_FOLLOW_BLOCK.has(afterTok.low));
1319
+ if (!bareLowerRole) {
1320
+ setToken(tokens[titleIdx], formatProper(capTr(oSplit.head), oSplit.suffix, true), true);
1321
+ }
1322
+ }
1323
+ }
1324
+ // 6b. Compositional Multi-Word Geographic / Monument / Landmark / State / Event Phrases (up to 4 words left!)
1325
+ // ("Sapanca gölü", "Rumeli hisarında", "Marmara bölgesinde", "Doğu Anadolu bölgesinde", "Efes antik kentinde",
1326
+ // "Büyük Menderes nehrinde", "Fatih Sultan Mehmet köprüsünden", "Yedigöller millî parkında", "Kore savaşı")
1327
+ const GEO_MODIFIERS = new Set([
1328
+ "antik", "millî", "milli", "tabiat", "büyük", "küçük", "yeni", "eski", "kızıl", "kara", "ak", "beyaz",
1329
+ "yeşil", "mavi", "sarı", "orta", "iç", "doğu", "batı", "kuzey", "güney", "kuzeydoğu", "kuzeybatı",
1330
+ "güneydoğu", "güneybatı", "yukarı", "aşağı", "birinci", "ikinci", "üçüncü", "meydan", "deniz", "barış",
1331
+ "ateşkes", "şehitler", "şehitleri", "sultan", "gazi", "paşa", "mustafa", "kemal", "atatürk", "selçuklu",
1332
+ "anadolu", "uluslararası", "devlet",
1333
+ ]);
1334
+ const STRICT_KNOWN_GEO_HEADS = new Set([
1335
+ "kanalı", "sokağı", "savaşı", "dağları", "mahallesi", "hanı", "koyu", "kemeri", "feneri",
1336
+ "istasyonu", "otogarı", "stadı", "arenası", "plajı", "tepesi", "vadisi", "kenti", "hamamı",
1337
+ "çarşısı", "çeşmesi", "kilisesi", "otoyolu", "geçidi", "limanı", "iskelesi",
1338
+ ]);
1339
+ for (let i = 1; i < tokens.length; i++) {
1340
+ const tok = tokens[i];
1341
+ if (!tok.isWord || tok.locked)
1342
+ continue;
1343
+ const prev = tokens[i - 1];
1344
+ if (!prev.isWord ||
1345
+ !adjSpace(prev, tok) ||
1346
+ prev.low.includes("'") ||
1347
+ prev.raw.includes("'") ||
1348
+ prev.raw.includes("’") ||
1349
+ prev.gapBefore.endsWith("-")) {
1350
+ continue;
1351
+ }
1352
+ if (splitHeadWord(prev.low, INSTITUTION_HEADS)?.suffix)
1353
+ continue;
1354
+ if (isAllCaps(prev))
1355
+ continue;
1356
+ const geoSplit = splitHeadWord(tok.low, GEO_HEADS);
1357
+ const stateSplit = !geoSplit ? splitHeadWord(tok.low, STATE_HEADS) : null;
1358
+ const eventSplit = !geoSplit && !stateSplit ? splitHeadWord(tok.low, EVENT_HEADS) : null;
1359
+ const headSplit = geoSplit ?? stateSplit ?? eventSplit;
1360
+ if (!headSplit)
1361
+ continue;
1362
+ if (isCap(tok) && !headSplit.hadApostrophe)
1363
+ continue;
1364
+ // Lowercase predicative copula ("Atatürk Lisesinin sokağıdır", "Türkiye'nin en büyük gölüdür") is a predicate, not a proper name.
1365
+ if (!isCap(tok) && isCap(prev) && /^[dt][ıiuü]r$/.test(headSplit.suffix))
1366
+ continue;
1367
+ // "kenti" ONLY after "antik" ("Efes Antik Kenti", "Patara Antik Kenti")
1368
+ if (headSplit.head === "kenti" && prev.low !== "antik")
1369
+ continue;
1370
+ // "boğazı/sokağı" after a person name or non-place word ("Ahmet boğazında") is anatomical/common, not geographic!
1371
+ if ((headSplit.head === "boğazı" || headSplit.head === "sokağı") && known.givenNameFor(prev.low) && !known.nameEntry(prev.low)) {
1372
+ continue;
1373
+ }
1374
+ // Walk left up to 4 tokens collecting proper/modifier tokens
1375
+ let startIdx = i;
1376
+ let hasStrongProperAnchor = false;
1377
+ let hasCapAnchor = false;
1378
+ for (let j = i - 1; j >= Math.max(0, i - 4); j--) {
1379
+ const cur = tokens[j];
1380
+ const right = tokens[j + 1];
1381
+ if (!cur.isWord ||
1382
+ !adjSpace(cur, right) ||
1383
+ cur.low.includes("'") ||
1384
+ cur.raw.includes("'") ||
1385
+ cur.raw.includes("’") ||
1386
+ cur.gapBefore.endsWith("-")) {
1387
+ break;
1388
+ }
1389
+ if (splitHeadWord(cur.low, INSTITUTION_HEADS)?.suffix)
1390
+ break;
1391
+ const lw = cur.low;
1392
+ const ne = lookupName(lw, sentenceHasAsciiFixes);
1393
+ if (ne && !ne.noApos && !NON_INST_PREFIX.has(lw)) {
1394
+ hasStrongProperAnchor = true;
1395
+ startIdx = j;
1396
+ continue;
1397
+ }
1398
+ if (cur.locked && !NON_INST_PREFIX.has(lw)) {
1399
+ hasStrongProperAnchor = true;
1400
+ startIdx = j;
1401
+ continue;
1402
+ }
1403
+ if (isCap(cur) && !cur.atStart && !NON_INST_PREFIX.has(lw) && !isAllCaps(cur)) {
1404
+ hasCapAnchor = true;
1405
+ startIdx = j;
1406
+ continue;
1407
+ }
1408
+ if (GEO_MODIFIERS.has(lw)) {
1409
+ if (j === i - 1 && (lw === "büyük" || lw === "küçük" || lw === "yeni" || lw === "eski" || lw === "devlet" || lw === "uluslararası")) {
1410
+ // Don't start a 2-word generic phrase like "büyük nehir", "eski kale", "yeni köprü"
1411
+ break;
1412
+ }
1413
+ startIdx = j;
1414
+ continue;
1415
+ }
1416
+ if (j === i - 1 && cur.atStart && capShare(lw) >= 0.5 && !NON_INST_PREFIX.has(lw)) {
1417
+ hasCapAnchor = true;
1418
+ startIdx = j;
1419
+ continue;
1420
+ }
1421
+ break;
1422
+ }
1423
+ if (startIdx >= i)
1424
+ continue;
1425
+ if (startIdx > 0 && tokens[startIdx - 1].low === "bir")
1426
+ continue;
1427
+ const strictHead = STRICT_KNOWN_GEO_HEADS.has(headSplit.head);
1428
+ if (strictHead ? !hasStrongProperAnchor : !(hasStrongProperAnchor || hasCapAnchor))
1429
+ continue;
1430
+ if (startIdx === i - 1 && NON_INST_PREFIX.has(prev.low))
1431
+ continue;
1432
+ if (headSplit.head === "mahallesi" &&
1433
+ startIdx === i - 1 &&
1434
+ (prev.low === "yahudi" || prev.low === "ermeni" || prev.low === "rum" || prev.low === "türk" || prev.low === "yunan" || prev.low === "arap" || prev.low === "kürt" || prev.low === "çin" || prev.low === "italyan" || prev.low === "fransız" || prev.low === "alman")) {
1435
+ continue;
1436
+ }
1437
+ if ((headSplit.head === "istasyonu" || headSplit.head === "havaalanı" || headSplit.head === "havalimanı") &&
1438
+ startIdx === i - 1 &&
1439
+ (prev.low === "tren" || prev.low === "metro" || prev.low === "tramvay" || prev.low === "otobüs" || prev.low === "uluslararası")) {
1440
+ continue;
1441
+ }
1442
+ for (let j = startIdx; j < i; j++) {
1443
+ const cur = tokens[j];
1444
+ if (cur.locked)
1445
+ continue;
1446
+ const ne = lookupName(cur.low, sentenceHasAsciiFixes);
1447
+ setToken(cur, ne?.name ?? capTr(cur.eff), true);
1448
+ }
1449
+ setToken(tok, formatProper(capTr(headSplit.head), headSplit.suffix, true), true);
1450
+ }
1451
+ // (Step 6c blind "<direction> + <place>" removed: established official directional regions such as
1452
+ // "Batı Anadolu", "Doğu Karadeniz", "Kuzey Amerika", "Güney Kore", "Orta Asya" are handled in Step 2 via
1453
+ // CANONICAL_PHRASES / corpus-verified PHRASE_APOS; descriptive adjectives like "orta Şili", "güney Şili",
1454
+ // "güney Hint Okyanusu" are left lowercase per TDK.)
1455
+ // ===========================================================================
1456
+ // STEP 7: Titles, Ranks, Honorifics, Kinship, Media Titles & Person Chains
1457
+ // ===========================================================================
1458
+ // 7a. Abbreviated title chains before a person name ("prof. dr. halil inalcık'ın", "op. dr. sinan güler'in",
1459
+ // "dr. öğr. üyesi ahmet kaya", "av. melike sönmez", "dr. şebnem koç'tan", "Dekan doç. dr. barış sezer")
1460
+ for (let i = 0; i < tokens.length - 1; i++) {
1461
+ const t0 = tokens[i];
1462
+ if (!t0.isWord || !PRE_TITLES_ABBR.has(t0.low))
1463
+ continue;
1464
+ // Collect consecutive abbreviated titles ("Prof. Dr.", "Op. Dr.", "Doç. Dr.", "Yrd. Doç. Dr.", "Dr. Öğr.")
1465
+ let endTitle = i;
1466
+ while (endTitle + 1 < tokens.length &&
1467
+ adjDotSpace(tokens[endTitle], tokens[endTitle + 1]) &&
1468
+ PRE_TITLES_ABBR.has(tokens[endTitle + 1].low)) {
1469
+ endTitle++;
1470
+ }
1471
+ // Optional "Üyesi" after "Öğr." ("Dr. Öğr. Üyesi Ahmet Kaya")
1472
+ let uyesiIdx = -1;
1473
+ let nameIdx = endTitle + 1;
1474
+ if (nameIdx + 1 < tokens.length &&
1475
+ (tokens[endTitle].low === "öğr" || tokens[endTitle].low === "ogr") &&
1476
+ adjDotSpace(tokens[endTitle], tokens[nameIdx]) &&
1477
+ tokens[nameIdx].low === "üyesi" &&
1478
+ adjSpace(tokens[nameIdx], tokens[nameIdx + 1])) {
1479
+ uyesiIdx = nameIdx;
1480
+ nameIdx = nameIdx + 1;
1481
+ }
1482
+ else if (nameIdx >= tokens.length || !adjDotSpace(tokens[endTitle], tokens[nameIdx])) {
1483
+ continue;
1484
+ }
1485
+ const firstTok = tokens[nameIdx];
1486
+ const g = resolveGivenName(firstTok) ??
1487
+ resolveSurname(firstTok, false) ??
1488
+ (known.nameEntry(firstTok.low) && !known.nameEntry(firstTok.low).noApos
1489
+ ? { display: known.nameEntry(firstTok.low).name, suffix: "", hadApos: false }
1490
+ : null);
1491
+ const firstIsPerson = g !== null || (isCap(firstTok) && !firstTok.atStart);
1492
+ if (!firstIsPerson)
1493
+ continue;
1494
+ // Capitalize any full rank or "Sayın" immediately preceding the abbreviated title chain ("Dekan doç. dr. barış sezer", "Sayın prof. dr.")
1495
+ if (i > 0 && adjSpace(tokens[i - 1], t0) && (PRE_TITLES_FULL.has(tokens[i - 1].low) || tokens[i - 1].low === "sayın")) {
1496
+ setToken(tokens[i - 1], capTr(tokens[i - 1].eff), true);
1497
+ }
1498
+ for (let k = i; k <= endTitle; k++) {
1499
+ setToken(tokens[k], capTr(tokens[k].eff), true);
1500
+ }
1501
+ if (uyesiIdx !== -1) {
1502
+ setToken(tokens[uyesiIdx], "Üyesi", true);
1503
+ }
1504
+ if (g && !firstTok.locked) {
1505
+ setToken(firstTok, formatProper(g.display, g.suffix, true), true);
1506
+ }
1507
+ // Also capitalize following surname ("Melike Sönmez", "Halil İnalcık'ın", "Sinan Güler'in", "Şebnem Koç'tan", "Barış Sezer", "Ece Çınar")
1508
+ const surIdx = nameIdx + 1;
1509
+ if (surIdx < tokens.length && adjSpace(firstTok, tokens[surIdx]) && (!g || !g.suffix)) {
1510
+ const surTok = tokens[surIdx];
1511
+ const sur = resolveSurname(surTok, true);
1512
+ if (sur && !surTok.locked) {
1513
+ setToken(surTok, formatProper(sur.display, sur.suffix, true), true);
1514
+ }
1515
+ else if (!surTok.locked && surTok.isWord && !isCap(surTok) && surTok.low.includes("'")) {
1516
+ const ap = surTok.low.indexOf("'");
1517
+ setToken(surTok, capTr(surTok.eff.slice(0, ap)) + surTok.eff.slice(ap), true);
1518
+ }
1519
+ }
1520
+ i = uyesiIdx !== -1 ? uyesiIdx : endTitle;
1521
+ }
1522
+ // 7b. Pre-nominal full titles / ranks ("bayan elif tan", "cumhurbaşkanı ismet inönü'nün", "albay nurettin şahin'in",
1523
+ // "Kaymakam sena tunç'a", "Hâkim nermin oral", "Kaptan rüştü alkan", "Başkomiser nazlı ekinci", "mimar sinanın", "Bay Kaya")
1524
+ for (let i = 0; i < tokens.length - 1; i++) {
1525
+ const titleTok = tokens[i];
1526
+ if (!titleTok.isWord || !PRE_TITLES_FULL.has(titleTok.low))
1527
+ continue;
1528
+ const nextTok = tokens[i + 1];
1529
+ if (!nextTok.isWord || !adjSpace(titleTok, nextTok))
1530
+ continue;
1531
+ const g = resolveGivenName(nextTok) ?? ((titleTok.low === "bay" || titleTok.low === "bayan" || titleTok.low === "doktor" || titleTok.low === "avukat" || titleTok.low === "profesör" || titleTok.low === "albay" || titleTok.low === "komiser" || titleTok.low === "kaptan") ? resolveSurname(nextTok, false) : null);
1532
+ if (!g)
1533
+ continue;
1534
+ const surTok = i + 2 < tokens.length && adjSpace(nextTok, tokens[i + 2]) ? tokens[i + 2] : undefined;
1535
+ const sur = !g.suffix && surTok ? resolveSurname(surTok, true) : null;
1536
+ const strongFirst = known.nameEntry(lowerTr(g.display)) !== undefined ||
1537
+ sur !== null ||
1538
+ titleTok.low === "bay" ||
1539
+ titleTok.low === "bayan" ||
1540
+ titleTok.low === "mimar" ||
1541
+ titleTok.low === "gazi" ||
1542
+ titleTok.low === "albay" ||
1543
+ titleTok.low === "kaymakam" ||
1544
+ titleTok.low === "hâkim" ||
1545
+ titleTok.low === "hakim" ||
1546
+ titleTok.low === "savcı" ||
1547
+ titleTok.low === "başsavcı" ||
1548
+ titleTok.low === "kaptan" ||
1549
+ titleTok.low === "başkomiser" ||
1550
+ titleTok.low === "komiser" ||
1551
+ titleTok.low === "büyükelçi" ||
1552
+ titleTok.low === "başhekim" ||
1553
+ titleTok.low === "cumhurbaşkanı";
1554
+ if (!strongFirst)
1555
+ continue;
1556
+ // Also capitalize a two-word rank prefix ("belediye başkanı ...", "dışişleri bakanı ...", "genel müdür ...")
1557
+ if (i > 0 &&
1558
+ adjSpace(tokens[i - 1], titleTok) &&
1559
+ (tokens[i - 1].low === "belediye" ||
1560
+ tokens[i - 1].low === "genel" ||
1561
+ tokens[i - 1].low === "bölüm" ||
1562
+ tokens[i - 1].low === "okul" ||
1563
+ tokens[i - 1].low === "meclis" ||
1564
+ tokens[i - 1].low === "cumhuriyet" ||
1565
+ tokens[i - 1].low === "dışişleri" ||
1566
+ tokens[i - 1].low === "içişleri" ||
1567
+ tokens[i - 1].low === "sağlık" ||
1568
+ tokens[i - 1].low === "adalet" ||
1569
+ tokens[i - 1].low === "maliye" ||
1570
+ tokens[i - 1].low === "savunma")) {
1571
+ setToken(tokens[i - 1], capTr(tokens[i - 1].eff), true);
1572
+ }
1573
+ setToken(titleTok, capTr(titleTok.eff), true);
1574
+ if (!nextTok.locked)
1575
+ setToken(nextTok, formatProper(g.display, g.suffix, true), true);
1576
+ if (sur && surTok && !surTok.locked) {
1577
+ setToken(surTok, formatProper(sur.display, sur.suffix, true), true);
1578
+ }
1579
+ }
1580
+ // 7c. Vocative & Formal "Sayın + <OfficialTitle | PersonName>"
1581
+ // ("Sayın Başkan", "sayın başkan", "Sayın Genel Müdür", "Sayın Belediye Başkanı", "Sayın Başkan'a", "sayın ahmet yılmaz")
1582
+ for (let i = 0; i < tokens.length - 1; i++) {
1583
+ const sayin = tokens[i];
1584
+ const role = tokens[i + 1];
1585
+ if (!sayin.isWord || !role.isWord || sayin.low !== "sayın" || !adjSpace(sayin, role))
1586
+ continue;
1587
+ const roleSplit = splitHeadWord(role.low, SAYIN_TITLES);
1588
+ if (SAYIN_TITLES.has(role.low)) {
1589
+ if (!sayin.locked)
1590
+ setToken(sayin, "Sayın", true);
1591
+ setToken(role, capTr(role.eff), true);
1592
+ for (let k = i + 2; k <= Math.min(i + 3, tokens.length - 1); k++) {
1593
+ if (!adjSpace(tokens[k - 1], tokens[k]))
1594
+ break;
1595
+ const w = tokens[k].low;
1596
+ if (SAYIN_TITLES.has(w) || SAYIN_COMPOUND_TAIL.has(w)) {
1597
+ setToken(tokens[k], capTr(tokens[k].eff), true);
1598
+ }
1599
+ else {
1600
+ const tailSplit = splitHeadWord(w, SAYIN_COMPOUND_TAIL);
1601
+ if (tailSplit)
1602
+ setToken(tokens[k], formatProper(capTr(tailSplit.head), tailSplit.suffix, true), true);
1603
+ break;
1604
+ }
1605
+ }
1606
+ }
1607
+ else if (roleSplit && roleSplit.suffix) {
1608
+ if (!sayin.locked)
1609
+ setToken(sayin, "Sayın", true);
1610
+ setToken(role, formatProper(capTr(roleSplit.head), roleSplit.suffix, true), true);
1611
+ }
1612
+ else if (SAYIN_COMPOUND_FIRST.has(role.low) &&
1613
+ i + 2 < tokens.length &&
1614
+ adjSpace(role, tokens[i + 2])) {
1615
+ const t2 = tokens[i + 2];
1616
+ const t2Split = splitHeadWord(t2.low, SAYIN_COMPOUND_TAIL) ?? splitHeadWord(t2.low, SAYIN_TITLES);
1617
+ if (SAYIN_TITLES.has(t2.low) || SAYIN_COMPOUND_TAIL.has(t2.low) || t2Split) {
1618
+ if (!sayin.locked)
1619
+ setToken(sayin, "Sayın", true);
1620
+ setToken(role, capTr(role.eff), true);
1621
+ if (t2Split && t2Split.suffix) {
1622
+ setToken(t2, formatProper(capTr(t2Split.head), t2Split.suffix, true), true);
1623
+ }
1624
+ else {
1625
+ setToken(t2, capTr(t2.eff), true);
1626
+ if (i + 3 < tokens.length && adjSpace(t2, tokens[i + 3])) {
1627
+ const t3 = tokens[i + 3];
1628
+ const t3Split = splitHeadWord(t3.low, SAYIN_COMPOUND_TAIL);
1629
+ if (SAYIN_COMPOUND_TAIL.has(t3.low))
1630
+ setToken(t3, capTr(t3.eff), true);
1631
+ else if (t3Split)
1632
+ setToken(t3, formatProper(capTr(t3Split.head), t3Split.suffix, true), true);
1633
+ }
1634
+ }
1635
+ }
1636
+ }
1637
+ else {
1638
+ // "sayın <PersonName> [Surname]" ("sayın ahmet yılmaz", "sayın ayşe hanım")
1639
+ const g = resolveGivenName(role);
1640
+ if (g && (known.nameEntry(lowerTr(g.display)) || !COMMON_GIVEN_ADJECTIVES.has(lowerTr(g.display)))) {
1641
+ if (!sayin.locked)
1642
+ setToken(sayin, "Sayın", true);
1643
+ if (!role.locked)
1644
+ setToken(role, formatProper(g.display, g.suffix, true), true);
1645
+ if (!g.suffix && i + 2 < tokens.length && adjSpace(role, tokens[i + 2])) {
1646
+ const surTok = tokens[i + 2];
1647
+ const sur = resolveSurname(surTok, true);
1648
+ if (sur && !surTok.locked)
1649
+ setToken(surTok, formatProper(sur.display, sur.suffix, true), true);
1650
+ }
1651
+ }
1652
+ }
1653
+ }
1654
+ // 7d. Post-nominal honorifics & titles ("Ayşe hanım", "Mahmut efendiye", "kerem bey", "orhan beyde",
1655
+ // "Kâzım karabekir paşanın", "Ahmet hocaya", "Mehmet ustaya", "Ali çavuşun", "Temel kaptana")
1656
+ const PREDICATE_AFTER_BARE_TITLE = new Set([
1657
+ "oldu", "olmuş", "olacak", "olmak", "olarak", "olur", "oluyor", "olsa", "olsun",
1658
+ "gibi", "değil", "mı", "mi", "mu", "mü", "var", "yok", "kalmış", "kaldı",
1659
+ ]);
1660
+ for (let i = 1; i < tokens.length; i++) {
1661
+ const honTok = tokens[i];
1662
+ if (!honTok.isWord || honTok.locked)
1663
+ continue;
1664
+ const honSplit = splitHonorific(honTok.low);
1665
+ const postTitleSplit = !honSplit ? splitPostTitle(honTok.low) : null;
1666
+ const hSplit = honSplit ?? postTitleSplit;
1667
+ if (!hSplit)
1668
+ continue;
1669
+ const prev = tokens[i - 1];
1670
+ if (!prev.isWord || !adjSpace(prev, honTok))
1671
+ continue;
1672
+ // Guard bare post-nominal occupational titles ("hoca", "usta", "öğretmen", "kaptan", "sultan", "han"):
1673
+ // never capitalize if used as a predicate ("Ahmet öğretmen oldu", "Mehmet usta gibi") or if unanchored!
1674
+ if (postTitleSplit) {
1675
+ const afterTok = i + 1 < tokens.length && adjSpace(honTok, tokens[i + 1]) ? tokens[i + 1] : undefined;
1676
+ if (!postTitleSplit.suffix && afterTok && PREDICATE_AFTER_BARE_TITLE.has(afterTok.low))
1677
+ continue;
1678
+ // Require an unmistakable person name before post-title (avoid "köy hocası", "genç öğretmen", "bir kaptan")
1679
+ const prevIsStrongPerson = (known.givenNameFor(prev.low) !== undefined && !COMMON_GIVEN_ADJECTIVES.has(prev.low)) ||
1680
+ (known.nameEntry(prev.low) !== undefined && known.givenNameFor(prev.low) !== undefined);
1681
+ if (!prevIsStrongPerson)
1682
+ continue;
1683
+ // For "öğretmen"/"kaptan"/"han"/"sultan", require either a suffix ("Ayşe Öğretmen'e", "Temel Kaptan'a") OR a known Turkish person name NOT followed by a noun compound
1684
+ if ((postTitleSplit.head === "han" || postTitleSplit.head === "şah") &&
1685
+ !postTitleSplit.suffix &&
1686
+ !isCap(prev) &&
1687
+ !known.givenNameFor(prev.low)) {
1688
+ continue;
1689
+ }
1690
+ }
1691
+ // Guard bare "-ı/-i" suffix ("Sancak Beyi Berham Bey", "Osmanlı beyi", "Türk hanımı"):
1692
+ // only treat as accusative ("Ayşe Hanım'ı", "Kerem Bey'i") when preceded by a real person's given name and NOT followed by a given name!
1693
+ if ((hSplit.suffix === "ı" || hSplit.suffix === "i") && !hSplit.hadApostrophe) {
1694
+ if (!known.givenNameFor(prev.low))
1695
+ continue;
1696
+ const afterHon = i + 1 < tokens.length && adjSpace(honTok, tokens[i + 1]) ? tokens[i + 1] : undefined;
1697
+ if (afterHon && (known.givenNameFor(afterHon.low) || isCap(afterHon)))
1698
+ continue;
1699
+ }
1700
+ // Check if previous word is a person name (never a sentence-start occupation like "Memur bey", "Doktor bey", "Hemşire hanım")
1701
+ const prevDisp = known.givenNameFor(prev.low) ??
1702
+ known.surnameFor(prev.low) ??
1703
+ known.ambigNameFor(prev.low) ??
1704
+ (known.nameEntry(prev.low) && !known.nameEntry(prev.low).noApos ? known.nameFor(prev.low) : undefined) ??
1705
+ (isCap(prev) && !prev.atStart && !NON_INST_PREFIX.has(prev.low) && !PRE_TITLES_FULL.has(prev.low) ? prev.eff : undefined);
1706
+ if (!prevDisp || NON_INST_PREFIX.has(prev.low) || PRE_TITLES_FULL.has(prev.low))
1707
+ continue;
1708
+ // Guard against "sayın bey", "genç bey", "yaşlı hanım", "güzel hanım", "küçük bey"
1709
+ if (prev.low === "sayın" || prev.low === "genç" || prev.low === "yaşlı" || prev.low === "güzel" || prev.low === "küçük" || prev.low === "büyük" || prev.low === "sevgili" || prev.low === "değerli" || prev.low === "kibar" || prev.low === "efendi") {
1710
+ continue;
1711
+ }
1712
+ if (!prev.locked)
1713
+ setToken(prev, prevDisp, true);
1714
+ // Also capitalize a preceding given name if `prev` was a surname ("Kâzım karabekir paşanın")
1715
+ if (i >= 2 && adjSpace(tokens[i - 2], prev) && !tokens[i - 2].locked) {
1716
+ const p2 = tokens[i - 2];
1717
+ const p2Disp = known.givenNameFor(p2.low) ?? known.nameFor(p2.low);
1718
+ if (p2Disp && !NON_INST_PREFIX.has(p2.low) && (isCap(p2) || known.surnameFor(prev.low) !== undefined)) {
1719
+ setToken(p2, p2Disp, true);
1720
+ }
1721
+ }
1722
+ setToken(honTok, formatProper(hSplit.displayHead, hSplit.suffix, true), true);
1723
+ }
1724
+ // 7e. Kinship cue ("tülay ablama", "zehra halamın", "rıza enişteme", "hatice ninemin")
1725
+ // Kinship word stays LOWERCASE per TDK; preceding person name gets capitalized!
1726
+ for (let i = 1; i < tokens.length; i++) {
1727
+ const kin = tokens[i];
1728
+ if (!kin.isWord || !isKinshipWord(kin.low))
1729
+ continue;
1730
+ const prev = tokens[i - 1];
1731
+ if (!prev.isWord || prev.locked || !adjSpace(prev, kin))
1732
+ continue;
1733
+ const disp = known.givenNameFor(prev.low) ?? known.nameFor(prev.low);
1734
+ if (disp && !NON_INST_PREFIX.has(prev.low) && !COMMON_GIVEN_ADJECTIVES.has(prev.low) && prev.low !== "küçük" && prev.low !== "büyük" && prev.low !== "sevgili" && prev.low !== "canım") {
1735
+ setToken(prev, disp, true);
1736
+ }
1737
+ }
1738
+ // 7f. Nominative relationship/occupation descriptor before person name ("arkadaşım melek", "komşumuz baharın",
1739
+ // "kardeşim ateş", "arkadaşım umut", "genç yazar defne arslan", "adı elif demirtaş")
1740
+ for (let i = 0; i < tokens.length - 1; i++) {
1741
+ const rel = tokens[i];
1742
+ if (!rel.isWord || !PERSON_REL_BEFORE.has(rel.low))
1743
+ continue;
1744
+ const nameTok = tokens[i + 1];
1745
+ if (!nameTok.isWord || !adjSpace(rel, nameTok))
1746
+ continue;
1747
+ const g = resolveGivenName(nameTok);
1748
+ if (!g)
1749
+ continue;
1750
+ const surTok = !g.suffix && i + 2 < tokens.length && adjSpace(nameTok, tokens[i + 2]) ? tokens[i + 2] : undefined;
1751
+ const sur = surTok ? resolveSurname(surTok, true) : null;
1752
+ // Avoid false alarms like "kızım mutlu oldu", "oğlum zeki bir çocuk", "yazar metin boyunca" unless followed by a surname
1753
+ // OR the ambiguous name is a genuine personal name frame (not an adjective followed by a predicate/noun)
1754
+ const bareLow = lowerTr(g.display);
1755
+ if (!g.suffix &&
1756
+ !sur &&
1757
+ COMMON_GIVEN_ADJECTIVES.has(bareLow) &&
1758
+ !["melek", "ateş", "umut", "bahar", "deniz", "can", "barış", "gül", "ırmak", "özlem", "sevgi", "defne", "doruk", "pınar", "gönül", "aslı", "cihan", "saadet", "çiçek", "yağmur", "toprak", "bulut", "güneş", "yıldız", "kader", "nur", "ipek", "evren", "kaya"].includes(bareLow)) {
1759
+ continue;
1760
+ }
1761
+ if (!nameTok.locked)
1762
+ setToken(nameTok, formatProper(g.display, g.suffix, true), true);
1763
+ if (sur && surTok && !surTok.locked) {
1764
+ setToken(surTok, formatProper(sur.display, sur.suffix, true), true);
1765
+ }
1766
+ }
1767
+ // 7g. Media / Publication titles ("varlık dergisine") & Author's classic novel ("Tanpınar'ın huzurunu okumak")
1768
+ for (let i = 1; i < tokens.length; i++) {
1769
+ const tok = tokens[i];
1770
+ if (!tok.isWord)
1771
+ continue;
1772
+ const prev = tokens[i - 1];
1773
+ if (prev.isWord && !prev.locked && adjSpace(prev, tok) && isMediaTypeWord(tok.low)) {
1774
+ if (SINGLE_WORD_PUBLICATIONS.has(prev.low)) {
1775
+ setToken(prev, capTr(prev.low), true);
1776
+ }
1777
+ }
1778
+ // "<Author>'ın <SingleWordWork>[suffix]" + reading/book context
1779
+ if (prev.isWord && adjSpace(prev, tok) && isCap(prev) && /'(?:ın|in|un|ün|nın|nin|nun|nün)$/.test(prev.low)) {
1780
+ for (const work of SINGLE_WORD_WORKS) {
1781
+ if (!tok.low.startsWith(work) || tok.low.length <= work.length)
1782
+ continue;
1783
+ const suf = tok.low.slice(work.length);
1784
+ if (!PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) || !isPhonologicallyValidProperSuffix(work, suf))
1785
+ continue;
1786
+ // Require a reading/literary cue in the rest of the sentence
1787
+ const hasReadingCtx = tokens.some((t, idx) => idx !== i && t.isWord && READING_CTX_RE.test(t.low));
1788
+ if (hasReadingCtx) {
1789
+ setToken(tok, `${capTr(work)}'${suf}`, true);
1790
+ break;
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1795
+ // 7h. [FirstName] + [Surname] & [PersonName] ile/ve [PersonName]
1796
+ // ("hüseyin çelik", "hatice şahin", "cengiz ateş", "hasan tekin", "erkin bulut", "Elif kayanın",
1797
+ // "barış Manço'nun", "yaşar kemalin", "barış mançonun", "yunus emrenin", "ece ile ali", "nur ile yavuz",
1798
+ // "aylin ile doruk", "atakan ile ece şen")
1799
+ for (let i = 0; i < tokens.length - 1; i++) {
1800
+ const t1 = tokens[i];
1801
+ const t2 = tokens[i + 1];
1802
+ if (!t1.isWord || !t2.isWord || !adjSpace(t1, t2))
1803
+ continue;
1804
+ // Case 1: t1 is a strong/capitalized/unconditional Turkish first name, t2 is a surname (bare or suffixed)
1805
+ const t1Uncond = known.nameEntry(t1.low);
1806
+ const t1Given = known.givenNameFor(t1.low);
1807
+ const t1StrongFirst = (t1Uncond !== undefined && !t1Uncond.noApos && t1Given !== undefined) ||
1808
+ (t1Given !== undefined && isCap(t1) && !t1.atStart) ||
1809
+ (t1.locked && t1Given !== undefined);
1810
+ if (t1StrongFirst && !t2.locked) {
1811
+ const sur = resolveSurname(t2, true);
1812
+ if (sur) {
1813
+ const nextTok = i + 2 < tokens.length && adjSpace(t2, tokens[i + 2]) ? tokens[i + 2] : undefined;
1814
+ // Guard common-word surnames against noun-noun compounds ("çelik tencere", "güneş gözlüğü") and object verbs ("ateş yaktı", "çiçek topladı")
1815
+ let blocked = false;
1816
+ if (sur.isCommon) {
1817
+ if (nextTok && COMMON_OBJECT_AFTER_SURNAME_VERBS.has(nextTok.low))
1818
+ blocked = true;
1819
+ if (!sur.suffix && nextTok && lexPair(t2.low, nextTok.low) >= 25 && !NON_INST_PREFIX.has(nextTok.low))
1820
+ blocked = true;
1821
+ // Also block if t2 is an ambiguous word and the sentence starts with a common noun (e.g. "Bahar geldi", not a first name!)
1822
+ if (t1.atStart && !t1Uncond)
1823
+ blocked = true;
1824
+ }
1825
+ if (!blocked) {
1826
+ if (!t1.locked)
1827
+ setToken(t1, t1Uncond?.name ?? t1Given, true);
1828
+ setToken(t2, formatProper(sur.display, sur.suffix, true), true);
1829
+ i++;
1830
+ continue;
1831
+ }
1832
+ }
1833
+ }
1834
+ // Case 2: t1 is an ambiguous/known first name AND t2 is an UNAMBIGUOUS or already-capitalized surname
1835
+ // ("barış Manço'nun", "barış mançonun", "erkin bulut", "yaşar kemalin", "yunus emrenin")
1836
+ // NEVER match `known.nameEntry(t2)` here (that matches cities/countries like "arda Meksika'da"!), repeated idioms
1837
+ // ("arda arda"), or common participles/verbs before an already-complete "<FirstName> <Surname>" ("sona eren Okan Buruk")!
1838
+ if (!t1.locked && t1Given && t1.low.length >= 3 && t1.low !== t2.low && !NON_INST_PREFIX.has(t1.low)) {
1839
+ const prevTok1 = i > 0 && adjSpace(tokens[i - 1], t1) ? tokens[i - 1] : undefined;
1840
+ const nextTok2 = i + 2 < tokens.length && adjSpace(t2, tokens[i + 2]) ? tokens[i + 2] : undefined;
1841
+ const t1IsAmbigCommon = !known.nameEntry(t1.low) && isMorphWord(t1.low);
1842
+ // Guard against common phrase/participle before a capitalized full name ("sona eren Okan Buruk")
1843
+ const phraseBeforeBlocked = t1IsAmbigCommon &&
1844
+ prevTok1 !== undefined &&
1845
+ !isCap(prevTok1) &&
1846
+ lexPair(prevTok1.low, t1.low) >= 20;
1847
+ const beforeFullCapName = t1IsAmbigCommon &&
1848
+ isCap(t2) &&
1849
+ nextTok2 !== undefined &&
1850
+ isCap(nextTok2) &&
1851
+ !isAllCaps(nextTok2);
1852
+ const surUnambig = phraseBeforeBlocked || beforeFullCapName ? null : resolveSurname(t2, false);
1853
+ const t2Base = t2.low.split("'")[0];
1854
+ const t2AlreadyCapSur = !phraseBeforeBlocked &&
1855
+ !beforeFullCapName &&
1856
+ isCap(t2) &&
1857
+ !t2.atStart &&
1858
+ known.surnameFor(t2Base) !== undefined &&
1859
+ !(t1IsAmbigCommon && known.givenNameFor(t2Base) !== undefined);
1860
+ if (surUnambig || t2AlreadyCapSur) {
1861
+ setToken(t1, t1Given, true);
1862
+ if (surUnambig && !t2.locked) {
1863
+ setToken(t2, formatProper(surUnambig.display, surUnambig.suffix, true), true);
1864
+ }
1865
+ }
1866
+ else if (
1867
+ // Pair of Turkish first name + surname where first name has high capShare (>=0.55, e.g. "erkin", "yaşar", "yunus")
1868
+ capShare(t1.low) >= 0.55 &&
1869
+ !t2.locked) {
1870
+ const surAny = resolveSurname(t2, true);
1871
+ if (surAny) {
1872
+ const nextTok = i + 2 < tokens.length && adjSpace(t2, tokens[i + 2]) ? tokens[i + 2] : undefined;
1873
+ const nextBlocks = surAny.isCommon &&
1874
+ nextTok !== undefined &&
1875
+ (COMMON_OBJECT_AFTER_SURNAME_VERBS.has(nextTok.low) ||
1876
+ (!surAny.suffix && lexPair(t2.low, nextTok.low) >= 25 && !NON_INST_PREFIX.has(nextTok.low)));
1877
+ if (!nextBlocks) {
1878
+ setToken(t1, t1Given, true);
1879
+ setToken(t2, formatProper(surAny.display, surAny.suffix, true), true);
1880
+ }
1881
+ }
1882
+ }
1883
+ }
1884
+ // Case 3: Coordination "[PersonName] (ile|ve) [PersonName]" ("ece ile ali", "nur ile yavuz", "aylin ile doruk", "atakan ile ece şen")
1885
+ if (i + 2 < tokens.length && (t2.low === "ile" || t2.low === "ve") && adjSpace(t2, tokens[i + 2])) {
1886
+ const t3 = tokens[i + 2];
1887
+ const t1IsPerson = (known.givenNameFor(t1.low) !== undefined && (known.nameEntry(t1.low) !== undefined || isCap(t1) || t1.locked)) ||
1888
+ (t1.atStart && known.givenNameFor(t1.low) !== undefined && capShare(t1.low) >= 0.55);
1889
+ const t3IsPerson = known.givenNameFor(t3.low) !== undefined && (known.nameEntry(t3.low) !== undefined || isCap(t3) || t3.locked);
1890
+ const t1GivenDisp = known.givenNameFor(t1.low);
1891
+ const t3GivenDisp = known.givenNameFor(t3.low);
1892
+ if (t1IsPerson && t3GivenDisp && !t3.locked) {
1893
+ const nextTok = i + 3 < tokens.length && adjSpace(t3, tokens[i + 3]) ? tokens[i + 3] : undefined;
1894
+ // Guard against "Ahmet ile barış yaptık" / "Ayşe ile umut doluyuz"
1895
+ const idiomBlock = known.ambigNameFor(t3.low) !== undefined &&
1896
+ nextTok !== undefined &&
1897
+ (COMMON_OBJECT_AFTER_SURNAME_VERBS.has(nextTok.low) || lexPair(t3.low, nextTok.low) >= 40);
1898
+ if (!idiomBlock) {
1899
+ if (!t1.locked && t1GivenDisp)
1900
+ setToken(t1, t1GivenDisp, true);
1901
+ setToken(t3, t3GivenDisp, true);
1902
+ // Optional surname after coordinated person ("atakan ile ece şen")
1903
+ if (nextTok && !nextTok.locked) {
1904
+ const sur = resolveSurname(nextTok, true);
1905
+ if (sur) {
1906
+ const afterSur = i + 4 < tokens.length && adjSpace(nextTok, tokens[i + 4]) ? tokens[i + 4] : undefined;
1907
+ const surBlocked = sur.isCommon &&
1908
+ afterSur !== undefined &&
1909
+ (COMMON_OBJECT_AFTER_SURNAME_VERBS.has(afterSur.low) || lexPair(nextTok.low, afterSur.low) >= 25);
1910
+ if (!surBlocked)
1911
+ setToken(nextTok, formatProper(sur.display, sur.suffix, true), true);
1912
+ }
1913
+ }
1914
+ }
1915
+ }
1916
+ else if (t3IsPerson && t1GivenDisp && !t1.locked && !NON_INST_PREFIX.has(t1.low)) {
1917
+ setToken(t1, t1GivenDisp, true);
1918
+ }
1919
+ }
1920
+ }
1921
+ // ===========================================================================
1922
+ // STEP 8: Single-word Proper Names, Acronyms, Languages, Non-Softening Ambiguous Inflections
1923
+ // ===========================================================================
1924
+ for (let i = 0; i < tokens.length; i++) {
1925
+ const tok = tokens[i];
1926
+ if (!tok.isWord || tok.locked)
1927
+ continue;
1928
+ if (isAllCaps(tok) || isMixedInnerCap(tok))
1929
+ continue;
1930
+ const low = tok.low;
1931
+ const prevTok = i > 0 ? tokens[i - 1] : undefined;
1932
+ const nextTok = i + 1 < tokens.length ? tokens[i + 1] : undefined;
1933
+ // 8-apos: Unresolved lowercase ambiguous stem'suffix (deferred from Step 4 W6 #4 until after Step 7 titles!)
1934
+ if (low.includes("'")) {
1935
+ if (!isCap(tok)) {
1936
+ const apos = low.indexOf("'");
1937
+ const lowStem = low.slice(0, apos);
1938
+ const lowSuf = low.slice(apos + 1);
1939
+ const ambDisp = known.ambigNameFor(lowStem);
1940
+ if (ambDisp && lowSuf) {
1941
+ const softCommon = joinWithoutApostrophe(tok.eff.slice(0, apos), tok.eff.slice(apos + 1), isMorphWord);
1942
+ const { leftRaw, rightRaw } = buildContextAround(i);
1943
+ const q = {
1944
+ start: tok.start,
1945
+ end: tok.end,
1946
+ base: lowStem,
1947
+ displayBase: ambDisp,
1948
+ suffix: lowSuf,
1949
+ hadApostrophe: true,
1950
+ atStart: tok.atStart,
1951
+ isGiven: known.givenNameFor(lowStem) !== undefined,
1952
+ commonCand: softCommon,
1953
+ properCand: `${ambDisp}'${lowSuf}`,
1954
+ leftRaw,
1955
+ rightRaw,
1956
+ };
1957
+ if (resources.collectAmbig)
1958
+ resources.collectAmbig.push(q);
1959
+ if (resources.disambiguateAmbig) {
1960
+ const decided = resources.disambiguateAmbig(q);
1961
+ if (decided)
1962
+ setToken(tok, decided, true);
1963
+ }
1964
+ }
1965
+ }
1966
+ continue;
1967
+ }
1968
+ // 8a. Special contextual rules for "hindistan" (not "hindistan cevizi"), "alman", "alevi", and "aliye"
1969
+ if (low === "hindistan" && (!nextTok || !nextTok.low.startsWith("ceviz"))) {
1970
+ setToken(tok, "Hindistan", true);
1971
+ continue;
1972
+ }
1973
+ if (low.startsWith("hindistan") && low.length > 9 && (!isCap(tok) || tok.atStart)) {
1974
+ const hSuf = low.slice(9);
1975
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(hSuf) && isPhonologicallyValidProperSuffix("hindistan", hSuf)) {
1976
+ setToken(tok, `Hindistan'${hSuf}`, true);
1977
+ continue;
1978
+ }
1979
+ }
1980
+ if (low === "aliye" && (!isCap(tok) || tok.atStart)) {
1981
+ const dativeCue = nextTok !== undefined &&
1982
+ /^(?:söyle|ver|gönder|yaz|sor|ilet|mesaj|haber|bak|uğra|telefon|git|gid|gel|dön|bırak|de|da|ulaş)/.test(nextTok.low);
1983
+ if (dativeCue) {
1984
+ setToken(tok, "Ali'ye", true);
1985
+ continue;
1986
+ }
1987
+ }
1988
+ if (low === "alman") {
1989
+ const verbalNext = nextTok !== undefined && ALMAN_VERBAL_NEXT.has(nextTok.low);
1990
+ const accPrev = prevTok !== undefined && /(?:ini|ını|unu|ünü|yi|yı|yu|yü)$/.test(prevTok.low);
1991
+ if (!verbalNext && !accPrev) {
1992
+ setToken(tok, "Alman", true);
1993
+ continue;
1994
+ }
1995
+ }
1996
+ if (low === "alevi") {
1997
+ const hasSectCtx = tokens.some((t, idx) => idx !== i && Math.abs(idx - i) <= 4 && ALEVI_SECT_CTX.has(t.low));
1998
+ if (hasSectCtx) {
1999
+ setToken(tok, "Alevi", true);
2000
+ continue;
2001
+ }
2002
+ }
2003
+ // 8b. Acronyms (bare 3+ letters, or suffixed 2+ letters: "tbmmde" -> "TBMM'de", "İtüye" -> "İTÜ'ye", "abye" -> "AB'ye", "natonun" -> "NATO'nun")
2004
+ const bareAcro = low.length >= 3 ? known.acronymFor(low) : undefined;
2005
+ if (bareAcro && !isCommonWordCollision(low, low)) {
2006
+ setToken(tok, bareAcro, true);
2007
+ continue;
2008
+ }
2009
+ // Suffixed acronym (works for lowercase AND sentence-case like "İtüye", "Abye", "Tbmmde", "Natonun"!)
2010
+ if (low.length >= 4) {
2011
+ let matchedAcro = false;
2012
+ for (let cut = Math.min(low.length - 1, 8); cut >= 2; cut--) {
2013
+ const base = low.slice(0, cut);
2014
+ const suf = low.slice(cut);
2015
+ const acro = known.acronymFor(base) ?? (base.length >= 3 && !isMorphWord(base) ? known.asciiAcronymFor(base) : undefined);
2016
+ if (!acro)
2017
+ continue;
2018
+ if (isCommonWordCollision(low, base))
2019
+ continue;
2020
+ if (isPhonologicallyValidProperSuffix(base, suf, { acronym: true })) {
2021
+ setToken(tok, `${acro}'${suf}`, true);
2022
+ matchedAcro = true;
2023
+ break;
2024
+ }
2025
+ }
2026
+ if (matchedAcro)
2027
+ continue;
2028
+ }
2029
+ // 8c. Bare unconditional proper name ("ahmet" -> "Ahmet", "istanbul" -> "İstanbul", "türkçe" -> "Türkçe", "macka" -> "Maçka")
2030
+ if (!isCap(tok)) {
2031
+ const bareName = lookupName(low, sentenceHasAsciiFixes);
2032
+ if (bareName) {
2033
+ setToken(tok, bareName.name, true);
2034
+ continue;
2035
+ }
2036
+ }
2037
+ // 8d. Suffixed unconditional proper name (works BOTH lowercase mid-sentence AND sentence-start like "Özgeyi", "Boludan", "Türkiyemizin"!)
2038
+ // Skip mid-sentence already-capitalized words (core `addApostrophes` already handles those!).
2039
+ if (!isCap(tok) || tok.atStart) {
2040
+ let matchedName = false;
2041
+ const allowAscii = sentenceHasAsciiFixes || !textHasTurkishMarks;
2042
+ for (let cut = low.length - 1; cut >= 3; cut--) {
2043
+ const base = low.slice(0, cut);
2044
+ const suf = low.slice(cut);
2045
+ // Also check "alman" + plural/derivational ("almanlar", "almanların", "alman'sınız")
2046
+ const entry = base === "alman"
2047
+ ? { name: "Alman", count: 40000, noApos: false }
2048
+ : lookupName(base, allowAscii);
2049
+ if (!entry)
2050
+ continue;
2051
+ const baseLow = lowerTr(entry.name);
2052
+ // Guard against common-word collisions ("belli", "hatayı", "türkü", "hindi", "ıraklık") and standalone foreign names ("Anna", "Paula", "Jimi", "Michelin"),
2053
+ // while allowing strongly proper-name-dominated forms ("taksimde", "murata" where "murat'a" >> "murata").
2054
+ const aposFreq = lexCount(`${baseLow}'${suf}`);
2055
+ const wholeFreq = lexCount(low);
2056
+ const strongProperApos = (aposFreq >= 25 && aposFreq >= wholeFreq * 5) ||
2057
+ (!isMorphWord(low) && aposFreq >= 15 && aposFreq >= wholeFreq * 2);
2058
+ if (!strongProperApos &&
2059
+ isCommonWordCollision(low, baseLow) &&
2060
+ !LANGUAGE_NAMES.has(baseLow) &&
2061
+ !NO_APOS_RELIGION_OR_DERIVED.has(baseLow)) {
2062
+ continue;
2063
+ }
2064
+ // Case 1: Language / noApos proper noun ("türkçeyi", "yunancanın", "almancanın", "gürcücesini", "türkmencenin", "korecesini", "moğolcadaki", "türkçedekilere", "hinduizmde")
2065
+ if (entry.noApos || LANGUAGE_NAMES.has(baseLow) || NO_APOS_RELIGION_OR_DERIVED.has(baseLow)) {
2066
+ if (NO_APOS_PROPER_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(baseLow, suf)) {
2067
+ setToken(tok, entry.name + suf, true);
2068
+ matchedName = true;
2069
+ break;
2070
+ }
2071
+ continue;
2072
+ }
2073
+ // Case 2: Derivational or plural suffix on proper noun -> NO apostrophe ("lazların", "selçuklular", "hunlar", "ispanyolların", "rumların", "avrupalılar", "japonlar", "türklerin")
2074
+ // Protect lowercase common Turkish derivations whose stem collides with a place ("ıraklık" = "parallax", not "Iraklık"!).
2075
+ if (NON_APOSTROPHE_SUFFIX_RE.test(suf)) {
2076
+ if (lexCount(low) >= 3 && capShare(low) < 0.35)
2077
+ continue;
2078
+ const firstV = [...suf].find((c) => "aeıioöuü".includes(c));
2079
+ const okStart = (suf.startsWith("l") || /^[cçs]/.test(suf)) &&
2080
+ (!firstV || isPhonologicallyValidProperSuffix(baseLow, suf.slice(0, 3)) || true);
2081
+ if (okStart && (isMorphWord(baseLow + suf) || lexCount(baseLow + suf) >= 2 || /^l[ae]r(?:[ıiuü]n(?:d[ae]n?)?|d[ae]n?|[aeıiuü]|l[ae]|$)/.test(suf))) {
2082
+ setToken(tok, entry.name + suf, true);
2083
+ matchedName = true;
2084
+ break;
2085
+ }
2086
+ continue;
2087
+ }
2088
+ // Case 3: Inflectional suffix on bare proper noun -> WITH apostrophe ("istanbula" -> "İstanbul'a", "fatmadan" -> "Fatma'dan", "türkiyemizin" -> "Türkiye'mizin", "ahmetinki" -> "Ahmet'inki", "burakin" -> "Burak'ın", "palandokende" -> "Palandöken'de")
2089
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(baseLow, suf)) {
2090
+ setToken(tok, `${entry.name}'${suf}`, true);
2091
+ matchedName = true;
2092
+ break;
2093
+ }
2094
+ if (allowAscii) {
2095
+ const harm = harmonizeAsciiSuffix(baseLow, suf);
2096
+ if (harm) {
2097
+ setToken(tok, `${entry.name}'${harm}`, true);
2098
+ matchedName = true;
2099
+ break;
2100
+ }
2101
+ }
2102
+ }
2103
+ if (matchedName)
2104
+ continue;
2105
+ }
2106
+ // 8e. Non-softening / morphologically-impossible inflections of AMBIGUOUS or GIVEN names!
2107
+ // E.g. "umutun" -> "Umut'un" (common word is "umudun"), "umuta" -> "Umut'a" ("umuda"),
2108
+ // "kıvança" -> "Kıvanç'a" ("kıvanca"), "emrenin" -> "Emre'nin", "aslıyı" -> "Aslı'yı",
2109
+ // "tokata" -> "Tokat'a" ("tokada"), "çiçeke" -> "Çiçek'e" ("çiçeğe"), "ufukun" -> "Ufuk'un" ("ufkun")!
2110
+ // Guard against standalone known/foreign names ("Anna", "Jimi", "Gabrielle", "Lynne", "Michelin")
2111
+ // and common nouns with 3sg possessive ("zümrütünü") by checking corpus counts and standalone name lists.
2112
+ if ((!isCap(tok) || tok.atStart) &&
2113
+ low.length >= 4 &&
2114
+ !known.givenNameFor(low) &&
2115
+ !known.nameEntry(low) &&
2116
+ !known.surnameFor(low) &&
2117
+ !known.ambigNameFor(low)) {
2118
+ let matchedNonSoft = false;
2119
+ for (let cut = low.length - 1; cut >= 3; cut--) {
2120
+ const base = low.slice(0, cut);
2121
+ const suf = low.slice(cut);
2122
+ const isAmbig = known.ambigNameFor(base) !== undefined;
2123
+ const ambDisp = known.ambigNameFor(base) ?? known.givenNameFor(base);
2124
+ if (!ambDisp)
2125
+ continue;
2126
+ if (!isAmbig && !/^(?:n?[ıiuü]n|[dt][ae]n?|y?l[ae]|y?[aeıiuü])$/.test(suf))
2127
+ continue;
2128
+ const baseLow = lowerTr(ambDisp);
2129
+ const wholeFreq = lexCount(low);
2130
+ const aposFreq = lexCount(`${baseLow}'${suf}`);
2131
+ // Protect standalone foreign/brand names at sentence start ("Anna", "Jimi", "Gabrielle", "Lynne", "Michelin")
2132
+ // and any corpus-attested word unless the apostrophized proper form strongly dominates.
2133
+ if (tok.atStart && isCap(tok) && (aposFreq < 5 || aposFreq < wholeFreq * 3))
2134
+ continue;
2135
+ if (wholeFreq >= 5 && aposFreq < wholeFreq * 3)
2136
+ continue;
2137
+ // Must either fail morphology completely ("umutun", "emrenin", "tokata", "kıvança") OR be completely dominated by the proper-name apostrophe form ("aslıyı")
2138
+ const nonCommonForm = !isMorphWord(low) ||
2139
+ (wholeFreq === 0 && aposFreq >= 5);
2140
+ if (!nonCommonForm)
2141
+ continue;
2142
+ if (PROPER_INFLECTIONAL_SUFFIX_RE.test(suf) && isPhonologicallyValidProperSuffix(baseLow, suf)) {
2143
+ setToken(tok, `${ambDisp}'${suf}`, true);
2144
+ matchedNonSoft = true;
2145
+ break;
2146
+ }
2147
+ if (sentenceHasAsciiFixes) {
2148
+ const harm = harmonizeAsciiSuffix(baseLow, suf);
2149
+ if (harm) {
2150
+ setToken(tok, `${ambDisp}'${harm}`, true);
2151
+ matchedNonSoft = true;
2152
+ break;
2153
+ }
2154
+ }
2155
+ }
2156
+ if (matchedNonSoft)
2157
+ continue;
2158
+ }
2159
+ // 8f. High-precision human-only frames + optional contextual disambiguator for AMBIGUOUS names
2160
+ if (!isCap(tok) || tok.atStart) {
2161
+ // Bare ambiguous name or suffixed ambiguous name
2162
+ let ambBase;
2163
+ let ambDisp;
2164
+ let ambSuf = "";
2165
+ if (known.ambigNameFor(low)) {
2166
+ ambBase = low;
2167
+ ambDisp = known.ambigNameFor(low);
2168
+ }
2169
+ else {
2170
+ for (let cut = low.length - 1; cut >= 3; cut--) {
2171
+ const base = low.slice(0, cut);
2172
+ const suf = low.slice(cut);
2173
+ const disp = known.ambigNameFor(base);
2174
+ if (!disp)
2175
+ continue;
2176
+ // Exclude 1sg/3sg possessives ("canım", "gülüm", "sevgisi") and copulas from ambiguous-name splitting.
2177
+ if (/^(?:n?[ıiuü]n|[dt][ae]n?|[dt][ae]ki|n?[ıiuü]nki|y?l[ae]|y?[aeıiuü])$/.test(suf) && isPhonologicallyValidProperSuffix(base, suf)) {
2178
+ ambBase = base;
2179
+ ambDisp = disp;
2180
+ ambSuf = suf;
2181
+ break;
2182
+ }
2183
+ }
2184
+ }
2185
+ if (ambBase && ambDisp) {
2186
+ // High-precision human-possessor frame: "<AmbigGiven>'ın annesi/babası/evi/ofisi/masası..."
2187
+ if (known.givenNameFor(ambBase) !== undefined &&
2188
+ /^(?:n?[ıiuü]n)$/.test(ambSuf) &&
2189
+ nextTok !== undefined &&
2190
+ adjSpace(tok, nextTok) &&
2191
+ HUMAN_POSSESSED_NEXT.has(nextTok.low) &&
2192
+ // Guard against "toprağın evi"? No, "toprak" softens to "toprağın", so "toprakın" already won in 8e!
2193
+ // Guard against "baharın yeni", "kaderin yeni"
2194
+ nextTok.low !== "yeni") {
2195
+ setToken(tok, `${ambDisp}'${ambSuf}`, true);
2196
+ continue;
2197
+ }
2198
+ // High-precision human-communication dative frame: "<AmbigGiven>'a/e mesaj at / haber ver / söyle / gönder"
2199
+ if (known.givenNameFor(ambBase) !== undefined &&
2200
+ /^y?[ae]$/.test(ambSuf) &&
2201
+ nextTok !== undefined &&
2202
+ (nextTok.low === "mesaj" ||
2203
+ nextTok.low === "söyle" ||
2204
+ nextTok.low === "söyledim" ||
2205
+ nextTok.low === "söyleyin" ||
2206
+ nextTok.low === "gönderdim" ||
2207
+ nextTok.low === "gönder" ||
2208
+ nextTok.low === "ilettim" ||
2209
+ nextTok.low === "sürpriz" ||
2210
+ (nextTok.low === "de" && i + 2 < tokens.length && (tokens[i + 2].low === "gönderdim" || tokens[i + 2].low === "söyle" || tokens[i + 2].low === "yazdım")))) {
2211
+ setToken(tok, `${ambDisp}'${ambSuf}`, true);
2212
+ continue;
2213
+ }
2214
+ // High-precision human-companion instrumental frame: "<AmbigGiven>'la/le telefonda / buluş / aynı odada / aynı otobüste / aynı sınıfta / birlikte hazırla"
2215
+ if (known.givenNameFor(ambBase) !== undefined &&
2216
+ /^y?l[ae]$/.test(ambSuf) &&
2217
+ nextTok !== undefined &&
2218
+ (nextTok.low === "telefonda" ||
2219
+ nextTok.low.startsWith("buluş") ||
2220
+ (nextTok.low === "aynı" && i + 2 < tokens.length && /^(?:oda|sınıf|otobüs|okul|ev|apartman|masa|takım|grup)/.test(tokens[i + 2].low)) ||
2221
+ (nextTok.low === "birlikte" && i + 2 < tokens.length && /^(?:hazırl|çalış|git|gid|gel|otur|kal|yap|konuş|yürü)/.test(tokens[i + 2].low)))) {
2222
+ setToken(tok, `${ambDisp}'${ambSuf}`, true);
2223
+ continue;
2224
+ }
2225
+ // Optional contextual disambiguator (neural context model)
2226
+ // Only query for genuine ambiguous given names or ambiguous place names (not pure surnames/colors/metals like "al", "altın", "taş").
2227
+ // Skip bare sentence-start words (already capitalized by Step 9 -> no ambiguity!).
2228
+ const isCtxEligible = known.givenNameFor(ambBase) !== undefined ||
2229
+ ambBase === "afyon" ||
2230
+ ambBase === "ağrı" ||
2231
+ ambBase === "aydın" ||
2232
+ ambBase === "bebek" ||
2233
+ ambBase === "bodrum" ||
2234
+ ambBase === "boğaz" ||
2235
+ ambBase === "çeşme" ||
2236
+ ambBase === "kartal" ||
2237
+ ambBase === "kaş" ||
2238
+ ambBase === "kemer" ||
2239
+ ambBase === "konak" ||
2240
+ ambBase === "mısır" ||
2241
+ ambBase === "moda" ||
2242
+ ambBase === "ordu" ||
2243
+ ambBase === "tokat" ||
2244
+ ambBase === "tuzla" ||
2245
+ ambBase === "uşak" ||
2246
+ ambBase === "van";
2247
+ // Skip quoted metalinguistic glosses (`"güneş" anlamına gelen`) and stems that also appear lowercase
2248
+ // as ordinary words elsewhere in the same sentence (`savaşa ... savaş başladıktan sonra`).
2249
+ const prevCh = text[tok.start - 1] ?? "";
2250
+ const nextCh = text[tok.end] ?? "";
2251
+ const isQuotedGloss = (`"'“‘«`.includes(prevCh) && `"'”’»`.includes(nextCh)) ||
2252
+ (nextTok !== undefined && /^(?:anlamına|anlamında|demek|kelimesi|sözcüğü)$/.test(nextTok.low));
2253
+ const sameStemLowerElsewhere = tokens.some((t, idx) => idx !== i &&
2254
+ t.isWord &&
2255
+ !isCap(t) &&
2256
+ (t.low === ambBase || (t.low.startsWith(ambBase) && isMorphWord(t.low))));
2257
+ if (isCtxEligible && !(tok.atStart && !ambSuf) && !isQuotedGloss && !sameStemLowerElsewhere) {
2258
+ const { leftRaw, rightRaw } = buildContextAround(i);
2259
+ const commonCand = ambSuf ? (tok.atStart ? capTr(ambBase + ambSuf) : ambBase + ambSuf) : ambBase;
2260
+ const properCand = ambSuf ? `${ambDisp}'${ambSuf}` : ambDisp;
2261
+ const q = {
2262
+ start: tok.start,
2263
+ end: tok.end,
2264
+ base: ambBase,
2265
+ displayBase: ambDisp,
2266
+ suffix: ambSuf,
2267
+ hadApostrophe: false,
2268
+ atStart: tok.atStart,
2269
+ isGiven: known.givenNameFor(ambBase) !== undefined,
2270
+ commonCand,
2271
+ properCand,
2272
+ leftRaw,
2273
+ rightRaw,
2274
+ };
2275
+ if (resources.collectAmbig)
2276
+ resources.collectAmbig.push(q);
2277
+ if (resources.disambiguateAmbig) {
2278
+ const decided = resources.disambiguateAmbig(q);
2279
+ if (decided) {
2280
+ setToken(tok, decided, true);
2281
+ continue;
2282
+ }
2283
+ }
2284
+ }
2285
+ }
2286
+ }
2287
+ }
2288
+ // ===========================================================================
2289
+ // STEP 9: Sentence-Start Capitalization
2290
+ // ===========================================================================
2291
+ applySentenceStartCapitals(text, result, spaced);
2292
+ result.sort((a, b) => a.start - b.start);
2293
+ return result;
2294
+ }
2295
+ /** Minimal proper-name & title fallback when `applySentenceRules` is called without `resources` (unit tests). */
2296
+ function applyMinimalRules(text, result, spaced, isWord, nameFor, stemsOf) {
2297
+ const covering = (start, end) => result.findIndex((fix) => fix.start < end && fix.end > start);
2298
+ for (const match of text.matchAll(/\p{L}+(?:['’]\p{L}+)?/gu)) {
2299
+ const start = match.index;
2300
+ const word = match[0];
2301
+ const end = start + word.length;
2302
+ if (!LOWER.test(word) || /\p{Lu}/u.test(word))
2303
+ continue;
2304
+ if (WORD_CHAR.test(text[start - 1] ?? "") || precededByAddress(text, start))
2305
+ continue;
2306
+ if (continuesAsAddress(text, end) && !spaced.has(end))
2307
+ continue;
2308
+ if (/[\p{N}_]/u.test(text[end] ?? ""))
2309
+ continue;
2310
+ if (covering(start, end) !== -1)
2311
+ continue;
2312
+ const apostrophe = word.search(/['’]/);
2313
+ let replacement;
2314
+ if (apostrophe > 0) {
2315
+ const name = nameFor(word.slice(0, apostrophe));
2316
+ if (name)
2317
+ replacement = name + word.slice(apostrophe);
2318
+ }
2319
+ else {
2320
+ replacement = nameFor(word);
2321
+ const previous = /(\p{L}+)[^\p{L}]*$/u.exec(text.slice(Math.max(0, start - 40), start))?.[1];
2322
+ const foreignBefore = previous !== undefined && !/^\p{Lu}/u.test(previous) && !isWord(lowerTr(previous));
2323
+ if (!replacement && word.length >= 5 && !foreignBefore) {
2324
+ for (let cut = word.length - 1; cut >= 3; cut--) {
2325
+ const rest = word.slice(cut);
2326
+ if (!FALLBACK_NAME_SUFFIXES.has(rest))
2327
+ continue;
2328
+ const base = word.slice(0, cut);
2329
+ const name = nameFor(base, true);
2330
+ const stems = name ? stemsOf(word) : null;
2331
+ const unknown = stems === null || stems.length === 0;
2332
+ if (unknown ? isWord(word) : stems.some((stem) => stem !== base)) {
2333
+ if (name)
2334
+ break;
2335
+ continue;
2336
+ }
2337
+ if (name) {
2338
+ replacement = NO_APOSTROPHE_NAME.test(name) ? name + rest : `${name}'${rest}`;
2339
+ break;
2340
+ }
2341
+ }
2342
+ }
2343
+ }
2344
+ if (replacement && replacement !== word) {
2345
+ result.push({ start, end, original: word, replacement, kind: "punct", margin: 6 });
2346
+ }
2347
+ }
2348
+ result.sort((a, b) => a.start - b.start);
2349
+ const TITLES = new Set(["dr", "prof", "doç", "doc", "av", "op", "uzm", "yrd", "öğr", "ogr", "gör", "gor", "sn", "mr", "mrs", "ms"]);
2350
+ for (const match of text.matchAll(/\p{L}+(?=\.\s+\p{L})/gu)) {
2351
+ const start = match.index;
2352
+ const word = match[0];
2353
+ const end = start + word.length;
2354
+ if (!TITLES.has(word) || WORD_CHAR.test(text[start - 1] ?? ""))
2355
+ continue;
2356
+ const nextStart = end + 1 + /^\s+/u.exec(text.slice(end + 1))[0].length;
2357
+ const nextFix = result.find((fix) => fix.start === nextStart);
2358
+ const nextText = nextFix ? nextFix.replacement : text.slice(nextStart);
2359
+ if (!/^\p{Lu}/u.test(nextText) || covering(start, end) !== -1)
2360
+ continue;
2361
+ result.push({ start, end, original: word, replacement: capitalize(word), kind: "punct", margin: 6 });
2362
+ }
2363
+ result.sort((a, b) => a.start - b.start);
2364
+ }
2365
+ /** Capitalizes lowercase sentence-initial words (merging into existing single-word fixes at that offset). */
2366
+ function applySentenceStartCapitals(text, result, spaced) {
2367
+ const covering = (start, end) => result.findIndex((fix) => fix.start < end && fix.end > start);
2368
+ const starts = [];
2369
+ const lead = /^[\s"'“‘«(\[]*/u.exec(text);
2370
+ starts.push(lead ? lead[0].length : 0);
2371
+ for (const match of text.matchAll(/([.!?…]+)(["'”’»)\]]*)(\s+)(["'“‘«(\[]*)/gu)) {
2372
+ const punctStart = match.index;
2373
+ const punctEnd = punctStart + match[1].length;
2374
+ if (!endsSentence(text, punctStart, punctEnd))
2375
+ continue;
2376
+ if (match[2])
2377
+ continue;
2378
+ const nextStart = match.index + match[0].length;
2379
+ // Do not force-capitalize inside a lowercase parenthetical whose closing ")" is followed by "." (". (başka bir deyişle, ...).").
2380
+ if (match[4]?.includes("(")) {
2381
+ const closeParen = text.indexOf(")", nextStart);
2382
+ if (closeParen !== -1 && text[closeParen + 1] === ".")
2383
+ continue;
2384
+ }
2385
+ starts.push(nextStart);
2386
+ }
2387
+ for (const start of starts) {
2388
+ if (!LOWER.test(text[start] ?? ""))
2389
+ continue;
2390
+ const end = wordEnd(text, start);
2391
+ const word = text.slice(start, end);
2392
+ if (word.length === 0 || /\p{N}/u.test(word) || /\p{Lu}/u.test(word))
2393
+ continue;
2394
+ if (word.length === 1 && word !== "o")
2395
+ continue;
2396
+ if (!spaced.has(end) && continuesAsAddress(text, end))
2397
+ continue;
2398
+ const index = covering(start, end);
2399
+ if (index === -1) {
2400
+ result.push({ start, end, original: word, replacement: capitalize(word), kind: "punct", margin: 6 });
2401
+ continue;
2402
+ }
2403
+ const existing = result[index];
2404
+ if (existing.start === start && LOWER.test(existing.replacement)) {
2405
+ result[index] = { ...existing, replacement: capitalize(existing.replacement) };
2406
+ }
2407
+ }
2408
+ }