tinyfix-tr 0.0.0-stage → 0.1.1

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 +139 -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 +53 -0
  6. package/dist/pkg/src/data.js +498 -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,2684 @@
1
+ import { buildContextFeatures } from "./context.js";
2
+ import { Lexicon } from "./lexicon.js";
3
+ import { ABBREVIATIONS, NOT_A_SENTENCE_START, applySentenceRules } from "./sentence.js";
4
+ import { PROPER_INFLECTIONAL_SUFFIX_RE, isPhonologicallyValidProperSuffix, splitHonorific, } from "./rules/proper-names.js";
5
+ import { turkishEditCost } from "./morphology/fuzzy.js";
6
+ import { ALSO, COMPOUND_VERB_JOINS, FINITE, HONORIFIC_TITLES, JOIN_FIRST, JOIN_SECOND, JOINED_ETMEK_STEMS, MUSIC_AFTER, MUSIC_NOTES, NEVER_ALONE, NO_LOCATIVE_AFTER, QUESTION, SEPARATE_ETMEK_BARE_IMPERATIVE, SEPARATE_ETMEK_SHORT, SOMBAHCEMI_KI, STRONG_NO_LOCATIVE_AFTER, TE_TA_SKIP, TIME_NAMES_NO_START_APOSTROPHE, collapsedDoubledLocative, fixDisharmoniousApostropheSuffix, followsHarmony, harmonizeQuestionParticle, hasBlockedApostropheStem, isHarmoniousApostropheMarkChange, isPlaceApostropheHead, isValidGenericApostrophe, isValidPlaceApostrophe, isVoicelessFinal, isAuxiliaryOl, matchAcronymApostrophe, sameHighVowels, } from "./rules/turkish-rules.js";
7
+ import { ALPHABET, LETTERS, areNearKeys, hasTurkishMarks, isAllUpper, isUpperInitial, lowerTr, markVariants, matchCase, stripMarksIn, upperTr, } from "./turkish.js";
8
+ export const CAREFUL = {
9
+ threshold: { marks: 2.5, apostrophe: 2.5, split: 2.5, join: 2.5, typo: 3, known: 1, context: 3, contraction: 1, punct: 1 },
10
+ cost: { marks: 0.5, apostrophe: 0.5, split: 0.5, join: 0.5, typo: 2, known: 0, context: 0, contraction: 0, punct: 0 },
11
+ ambiguity: 1,
12
+ knownWord: 3,
13
+ contractions: false,
14
+ sentenceCase: false,
15
+ typoInvalidThreshold: 1.5,
16
+ deDaJoinCost: 0,
17
+ typoEndWindow: 2,
18
+ typoEndCost: 1,
19
+ typoFarExtra: 3,
20
+ typoVowelSwap: 1.2,
21
+ typoStemShare: 0,
22
+ shortSwapMinCount: 300,
23
+ contextWord: 5,
24
+ contextVeto: 6.0,
25
+ contextTypoOverride: 1.2,
26
+ contextTypoAmbigGap: 1.25,
27
+ contextTypoAmbigVsTyped: 1.5,
28
+ contextTypoRescue: 2.5,
29
+ contextNameThreshold: 2.5,
30
+ knownMarked: 20,
31
+ markedOverride: 5.5,
32
+ minName: 20,
33
+ };
34
+ const VOICING_PAIRS = new Set(["dt", "td", "bp", "pb", "cç", "çc", "gk", "kg", "gğ", "ğg"]);
35
+ const VOWELS = new Set(["a", "e", "ı", "i", "o", "ö", "u", "ü"]);
36
+ const FINITE_VERB_MORPHEMES = new Set(["Prog1", "Prog2", "Past", "Narr", "Fut", "Aor", "Opt", "Desr", "Neces", "Imp"]);
37
+ /** Pronoun + "de" written as one word, with the verb person that proves it is the conjunction "de". */
38
+ const PRONOUN_DE = { bende: "A1sg", sende: "A2sg", bizde: "A1pl", sizde: "A2pl" };
39
+ const NON_FINITE_DERIVATIONS = new Set(["PastPart", "NarrPart", "FutPart", "PresPart", "AorPart", "Inf1", "Inf2", "Inf3"]);
40
+ const TOKEN = new RegExp(`[${LETTERS}]+(?:['’][${LETTERS}]+)?|\\s+|.`, "gu");
41
+ const SENTENCE_END = new Set([".", "!", "?", ":", "\n"]);
42
+ const log = (count) => Math.log(count + 1);
43
+ const marginOf = (candidate) => candidate.score - candidate.base;
44
+ /** A word typed without marks counts as evidence of an ASCII keyboard when its marked form is seen this often. */
45
+ const ASCII_EVIDENCE_COUNT = 50;
46
+ /** Morphemes indicating a stem is already plural, oblique-inflected or derived and must not take a new apostrophe. */
47
+ const BLOCKED_STEM_MORPHEMES = new Set([
48
+ "A3pl", "Abl", "Loc", "Ins", "Equ", "Cop",
49
+ "With", "Without", "Ness", "Agt", "Rel",
50
+ ]);
51
+ /** 1st/2nd person nominal predicate endings blocked for zero-count unseen mark guesses ("alveolusun" -> "alveolüsün"). */
52
+ const NOMINAL_PERSONAL_AGREEMENT = new Set(["A1sg", "A2sg", "A1pl", "A2pl"]);
53
+ /** Productive Turkish nominal suffixes allowed on attested OOV loanword/compound roots missing from Zemberek ("özgeçmişimi", "tripodlar"). */
54
+ const OOV_NOMINAL_SUFFIX = /^(?:l[ae]r(?:(?:[ıiuü]m(?:[ıiuü]z)?|[ıiuü]n(?:[ıiuü]z)?|[ıiuü])(?:n?[dt][ae]n?|n?[dt][ae]ki|n?[aeıiuü]|n[ıiuü]n|y?l[ae])?|[dt][ae]n?|[dt][ae]ki|[ıiuü]n|[aeıiuü]|l[ae])?|(?:[ıiuü]m(?:[ıiuü]z)?|[ıiuü]n(?:[ıiuü]z)?|s?[ıiuü])(?:n?[dt][ae]n?|n?[dt][ae]ki|n?[aeıiuü]|n[ıiuü]n|y?l[ae])?|[dt][ae]n?|[dt][ae]ki|n?[ıiuü]n|y?[aeıiuü]|y?l[ae]|l[ıiuü]k?)(?:[dt][ıiuü]r|y?[dt][ıiuü]|y?m[ıiuü]ş)?$/;
55
+ /** Latin/scientific taxonomic or clearly foreign suffix patterns that shouldn't be flagged when no close Turkish candidate exists. */
56
+ const FOREIGN_TAXONOMIC_SUFFIX = /(?:idae|aceae|inae|formes|ensis|oides|phyllus|flora|saurus|stoma|poda|comulus|ischer|lichkeit|hausen|shire|burgh|stadt|field|worth|ingham)$/;
57
+ export function tokenize(text) {
58
+ return [...text.matchAll(TOKEN)].map((match) => {
59
+ const value = match[0];
60
+ return { text: value, start: match.index, end: match.index + value.length, isWord: /^\p{L}/u.test(value) };
61
+ });
62
+ }
63
+ function lastSpaceWord(value) {
64
+ const space = value.lastIndexOf(" ");
65
+ return space === -1 ? value : value.slice(space + 1);
66
+ }
67
+ /** Copies the typed word's capital letters onto a replacement that only adds spaces, apostrophes or marks. */
68
+ function keepCase(typed, replacement) {
69
+ const plain = (text) => text.replace(/[ ']/g, "");
70
+ if (plain(lowerTr(typed)).length !== plain(replacement).length)
71
+ return matchCase(typed, replacement);
72
+ const typedLetters = typed.replace(/[ '’]/g, "");
73
+ let index = 0;
74
+ let output = "";
75
+ for (const char of replacement) {
76
+ if (char === " " || char === "'") {
77
+ output += char;
78
+ continue;
79
+ }
80
+ const original = typedLetters[index++] ?? "";
81
+ output += original !== lowerTr(original) ? upperTr(char) : char;
82
+ }
83
+ return output;
84
+ }
85
+ const FOLD_TR = { ç: "c", ğ: "g", ı: "i", ö: "o", ş: "s", ü: "u", â: "a", î: "i", û: "u" };
86
+ const foldTr = (word) => word.replace(/[çğıöşüâîû]/g, (ch) => FOLD_TR[ch] ?? ch);
87
+ /** TDK SOMBAHCEMİ words that are always written joined and must never be split by the context model. */
88
+ const FIXED_KI_WORDS = new Set(["oysaki", "halbuki", "mademki", "meğerki", "illaki", "sanki", "belki", "çünkü"]);
89
+ export class Corrector {
90
+ lexicon;
91
+ known;
92
+ morphology;
93
+ settings;
94
+ constructor(lexicon, settings = CAREFUL, known, morphology) {
95
+ this.lexicon = lexicon;
96
+ this.settings = settings;
97
+ this.known = known;
98
+ this.morphology = morphology;
99
+ }
100
+ /** A word the lexicon has rarely or never seen, but that Turkish suffix rules accept ("getirsek", "kitabımı"). */
101
+ isRealWord(word) {
102
+ return this.morphology?.isWord(word) ?? false;
103
+ }
104
+ /** True when a stem takes both front locative and front ablative (filters accidental Dat collisions like "varit" -> "varde"). */
105
+ hasFrontLocative(stem) {
106
+ return ((this.isRealWord(stem + "de") && this.isRealWord(stem + "den")) ||
107
+ (this.isRealWord(stem + "te") && this.isRealWord(stem + "ten")));
108
+ }
109
+ /** True when a stem takes both back locative and back ablative. */
110
+ hasBackLocative(stem) {
111
+ return ((this.isRealWord(stem + "da") && this.isRealWord(stem + "dan")) ||
112
+ (this.isRealWord(stem + "ta") && this.isRealWord(stem + "tan")));
113
+ }
114
+ /** True when a -ca/-ce/-ça/-çe stem is derived from a proper/nationality stem ("Danimarkaca", "Türkçe", "Hırvatça"). */
115
+ isDerivedLanguageStem(stem) {
116
+ if (stem.length < 5 || !/[cç][ae]$/.test(stem))
117
+ return false;
118
+ const analyses = this.morphology?.analyze?.(stem);
119
+ if (!analyses || analyses.length === 0)
120
+ return false;
121
+ return analyses.some((analysis) => analysis.morphemes.includes("Equ") &&
122
+ analysis.stem !== stem &&
123
+ this.lexicon.capitalShare(analysis.stem) >= 0.45);
124
+ }
125
+ /** True when a stem is blocked from taking an apostrophe by TDK rules (respecting morphology for -ca/-ce names like "Karaca"). */
126
+ isBlockedApostropheStem(stem, allowPlaceHead = false) {
127
+ if (this.morphology !== undefined) {
128
+ if (hasBlockedApostropheStem(stem, true, allowPlaceHead))
129
+ return true;
130
+ return this.isDerivedLanguageStem(stem);
131
+ }
132
+ return hasBlockedApostropheStem(stem, false, allowPlaceHead);
133
+ }
134
+ /** True when a form has a bare Noun/Adj/Adv root analysis (used for separate Noun+etmek compound verb splits). */
135
+ isBareNominalRoot(word) {
136
+ const analyses = this.morphology?.analyze?.(word);
137
+ if (!analyses || analyses.length === 0)
138
+ return false;
139
+ return analyses.some((a) => (a.pos === "Noun" || a.pos === "Adj" || a.pos === "Adv") &&
140
+ (a.morphemes.length === 0 || (a.morphemes.length === 1 && a.morphemes[0] === "A3sg")));
141
+ }
142
+ /** True when `word` is an inflected verb form of `auxStem` ("et", "ol", "geç", "vur", ...). */
143
+ isVerbFormOf(word, auxStem) {
144
+ const analyses = this.morphology?.analyze?.(word);
145
+ if (!analyses || analyses.length === 0)
146
+ return false;
147
+ return analyses.some((a) => a.pos === "Verb" && a.stem === auxStem);
148
+ }
149
+ /** True when `word` has a finite conjugated verb analysis (never part of an OOV noun compound). */
150
+ isFiniteVerb(word) {
151
+ const analyses = this.morphology?.analyze?.(word);
152
+ if (!analyses || analyses.length === 0)
153
+ return false;
154
+ return analyses.some((a) => a.pos === "Verb" &&
155
+ a.morphemes.some((m) => FINITE_VERB_MORPHEMES.has(m)) &&
156
+ !a.morphemes.some((m) => NON_FINITE_DERIVATIONS.has(m)));
157
+ }
158
+ /**
159
+ * True when morphology only parses a candidate apostrophe stem as an already-inflected or derived form
160
+ * ("japonların", "yunanlardan", "ankaradan", "türkçeden"), never as an uninflected bare root.
161
+ * Bare personal names that coincide with lowercase inflected words ("Emre", "Selin", "Güler") are preserved.
162
+ */
163
+ isInflectedApostropheStem(stem) {
164
+ const analyses = this.morphology?.analyze?.(stem);
165
+ if (!analyses || analyses.length === 0)
166
+ return false;
167
+ const hasBareRoot = analyses.some((analysis) => analysis.morphemes.length === 0 || (analysis.morphemes.length === 1 && analysis.morphemes[0] === "A3sg"));
168
+ if (hasBareRoot)
169
+ return false;
170
+ return analyses.every((analysis) => {
171
+ if (analysis.morphemes.some((morpheme) => BLOCKED_STEM_MORPHEMES.has(morpheme)))
172
+ return true;
173
+ if (analysis.stem !== stem && this.lexicon.capitalShare(analysis.stem) >= 0.45)
174
+ return true;
175
+ return false;
176
+ });
177
+ }
178
+ /**
179
+ * Extra morphological/lexical guard for unseen (count === 0) unique mark restorations on long lowercase words:
180
+ * keeps genuine Turkish inflections ("yukleyince", "sisirmesinden", "dalgakiranlarla") while blocking Latin/foreign
181
+ * terms that accidentally match nominal 1st/2nd person copula readings ("alveolusun" -> "alveolüsün").
182
+ */
183
+ isSafeUnseenMarkVariant(word, candidate, context) {
184
+ const analyses = this.morphology?.analyze?.(candidate);
185
+ if (!analyses)
186
+ return true;
187
+ if (analyses.length === 0)
188
+ return false;
189
+ let hasNewConsonantMark = false;
190
+ for (let i = 0; i < candidate.length; i++) {
191
+ const ch = candidate[i];
192
+ if (ch !== word[i] && (ch === "ç" || ch === "ğ" || ch === "ş")) {
193
+ hasNewConsonantMark = true;
194
+ break;
195
+ }
196
+ }
197
+ return analyses.some((analysis) => {
198
+ if (analysis.morphemes.includes("Zero") &&
199
+ analysis.morphemes.some((morpheme) => NOMINAL_PERSONAL_AGREEMENT.has(morpheme))) {
200
+ return false;
201
+ }
202
+ const lemma = analysis.pos === "Verb" ? analysis.stem + (followsHarmony(analysis.stem, "a") ? "mak" : "mek") : analysis.stem;
203
+ if (this.lexicon.count(lemma) < 5 || this.lexicon.capitalShare(lemma) >= 0.5)
204
+ return false;
205
+ const stemChanged = word.slice(0, analysis.stem.length) !== candidate.slice(0, analysis.stem.length);
206
+ if (context.textHasMarks && analysis.pos !== "Verb" && !stemChanged && !hasNewConsonantMark)
207
+ return false;
208
+ return true;
209
+ });
210
+ }
211
+ withSentenceRules(text, corrections, opts) {
212
+ const disambiguateAmbig = opts?.preDecidedAmbig
213
+ ? (q) => opts.preDecidedAmbig.get(q.start) ?? null
214
+ : undefined;
215
+ return applySentenceRules(text, corrections, (lower) => this.isRealWord(lower) || this.lexicon.exactCount(lower) >= 20, (lower, common) => this.known?.nameFor(lower, common ? 1500 : 0), (lower) => {
216
+ const analyses = this.morphology?.analyze?.(lower);
217
+ return analyses ? analyses.map((analysis) => lowerTr(analysis.stem)) : null;
218
+ }, {
219
+ known: this.known,
220
+ capitalShare: (lower) => this.lexicon.capitalShare(lower),
221
+ count: (lower) => this.lexicon.count(lower),
222
+ pair: (a, b) => this.lexicon.pair(a, b),
223
+ isMorphWord: (lower) => this.isRealWord(lower),
224
+ disambiguateAmbig,
225
+ collectAmbig: opts?.collectAmbig,
226
+ });
227
+ }
228
+ /**
229
+ * True when `word` (when `sentenceCase` is enabled) is an unseen lowercase proper name or honorific with an
230
+ * inflectional suffix ("nerminin", "emrenin", "kocaelide", "orhan beyde", "gönül hanımda") that should be
231
+ * handled by TDK proper-name rules instead of being overwritten by a typo/split fix ("merminin", "emrinin", "bey de").
232
+ */
233
+ isLowercaseProperForSentence(word, typed, context) {
234
+ if (!this.settings.sentenceCase || !this.known?.hasProperData)
235
+ return false;
236
+ if (typed !== word || word.includes("'"))
237
+ return false;
238
+ // Honorific + suffix after a person name ("orhan beyde", "gönül hanımda")
239
+ if (context.prevWord && splitHonorific(word)?.suffix) {
240
+ if (this.known.nameEntry(context.prevWord) ||
241
+ this.known.givenNameFor(context.prevWord) ||
242
+ this.known.ambigNameFor(context.prevWord) ||
243
+ context.prevCapitalized) {
244
+ return true;
245
+ }
246
+ }
247
+ // Check if `word` is an acronym + suffix ("tbmmde", "abye", "natonun") or proper name + suffix ("nerminin", "kocaelide", "emrenin")
248
+ if (!this.isRealWord(word)) {
249
+ if (word.length >= 4) {
250
+ for (let cut = Math.min(word.length - 1, 8); cut >= 2; cut--) {
251
+ const base = word.slice(0, cut);
252
+ const suf = word.slice(cut);
253
+ if (this.known.acronymFor(base) && isPhonologicallyValidProperSuffix(base, suf, { acronym: true })) {
254
+ return true;
255
+ }
256
+ }
257
+ }
258
+ for (let cut = word.length - 1; cut >= 3; cut--) {
259
+ const base = word.slice(0, cut);
260
+ const suf = word.slice(cut);
261
+ if (!PROPER_INFLECTIONAL_SUFFIX_RE.test(suf))
262
+ continue;
263
+ if ((this.known.nameEntry(base) || this.known.givenNameFor(base) || this.known.ambigNameFor(base)) &&
264
+ isPhonologicallyValidProperSuffix(base, suf)) {
265
+ return true;
266
+ }
267
+ }
268
+ // Classic book title stem + suffix ("ince memedini")
269
+ if (context.prevWord === "ince" && word.startsWith("memed"))
270
+ return true;
271
+ }
272
+ return false;
273
+ }
274
+ /** Returns the corrected text and the list of changes made. */
275
+ correct(text, options = {}) {
276
+ const { text: corrected, corrections } = this.runCorePass(text, options, false);
277
+ return { text: corrected, corrections };
278
+ }
279
+ /**
280
+ * Like correct(), but also flags every suspicious untouched word (rejected by morphology or very rare near a
281
+ * much stronger valid word) with up to 5 ranked suggestions.
282
+ */
283
+ inspect(text, options = {}) {
284
+ return this.runCorePass(text, options, true);
285
+ }
286
+ runCorePass(text, options, collectFlags) {
287
+ const tokens = tokenize(text);
288
+ const corrections = [];
289
+ const flags = [];
290
+ const evidence = stripMarksIn(text, options.autoMarked ?? []);
291
+ const textHasMarks = hasTurkishMarks(evidence);
292
+ const { asciiTyped, sentenceOf } = this.asciiEvidence(tokenize(evidence));
293
+ let atSentenceStart = true;
294
+ let prevWord;
295
+ let prevIsName = false;
296
+ let prevCapitalized = false;
297
+ for (let index = 0; index < tokens.length; index++) {
298
+ const token = tokens[index];
299
+ if (!token.isWord) {
300
+ if (SENTENCE_END.has(token.text) || token.text.includes("\n"))
301
+ atSentenceStart = true;
302
+ else if (/\d/.test(token.text))
303
+ atSentenceStart = false;
304
+ if (token.text !== " ") {
305
+ prevWord = undefined;
306
+ prevIsName = false;
307
+ prevCapitalized = false;
308
+ }
309
+ continue;
310
+ }
311
+ const next = this.nextWord(tokens, index);
312
+ const sentenceHasAsciiTurkish = !textHasMarks && asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]);
313
+ const context = {
314
+ atSentenceStart,
315
+ textHasMarks: textHasMarks &&
316
+ hasTurkishMarks(evidence.slice(0, token.start) + evidence.slice(token.end)) &&
317
+ !asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]),
318
+ questionAhead: this.questionAhead(tokens, index),
319
+ prevWord,
320
+ prevIsName,
321
+ prevCapitalized,
322
+ nextIsolated: next ? this.isIsolated(tokens, next.index) : false,
323
+ sentenceHasAsciiTurkish,
324
+ };
325
+ atSentenceStart = false;
326
+ if (!this.isIsolated(tokens, index)) {
327
+ prevWord = undefined;
328
+ prevIsName = false;
329
+ prevCapitalized = false;
330
+ continue;
331
+ }
332
+ const fix = this.check(token.text, context, next?.token.text);
333
+ if (!fix) {
334
+ if (collectFlags) {
335
+ const flag = this.detectFlag(token, context, next?.token.text);
336
+ if (flag)
337
+ flags.push(flag);
338
+ }
339
+ prevWord = lowerTr(token.text);
340
+ prevIsName = !context.atSentenceStart && isUpperInitial(token.text);
341
+ prevCapitalized = isUpperInitial(token.text);
342
+ continue;
343
+ }
344
+ const end = fix.joinsNext && next ? next.token.end : token.end;
345
+ corrections.push({
346
+ start: token.start,
347
+ end,
348
+ original: text.slice(token.start, end),
349
+ replacement: fix.replacement,
350
+ kind: fix.kind,
351
+ margin: fix.margin,
352
+ });
353
+ const trailing = lastSpaceWord(fix.replacement);
354
+ prevWord = lowerTr(trailing);
355
+ prevIsName = !(context.atSentenceStart && !fix.replacement.includes(" ")) && isUpperInitial(trailing);
356
+ prevCapitalized = isUpperInitial(trailing);
357
+ if (fix.joinsNext && next)
358
+ index = next.index;
359
+ }
360
+ if (this.settings.sentenceCase)
361
+ corrections.splice(0, corrections.length, ...this.withSentenceRules(text, corrections));
362
+ let output = "";
363
+ let cursor = 0;
364
+ for (const correction of corrections) {
365
+ output += text.slice(cursor, correction.start) + correction.replacement;
366
+ cursor = correction.end;
367
+ }
368
+ return { text: output + text.slice(cursor), corrections, flags };
369
+ }
370
+ /**
371
+ * Like correct(), but contested real-word ambiguities ("bende" / "ben de", "oldu" / "öldü", "sevgimi" / "sevgi mi")
372
+ * and ambiguous/contested typo candidates ("yllar" -> "yıllar"/"yollar", "hber" -> "her"/"haber") are scored in
373
+ * sentence context by the context model. Core behavior without a context model is unchanged.
374
+ */
375
+ async correctAsync(text, model, options = {}) {
376
+ const { text: corrected, corrections } = await this.runAsyncPass(text, model, options, false);
377
+ return { text: corrected, corrections };
378
+ }
379
+ /**
380
+ * Like inspect(), using the context model both to resolve ambiguities and to re-rank flag suggestions in sentence context.
381
+ */
382
+ async inspectAsync(text, model, options = {}) {
383
+ return this.runAsyncPass(text, model, options, true);
384
+ }
385
+ async runAsyncPass(text, model, options, collectFlags) {
386
+ const tokens = tokenize(text);
387
+ const evidence = stripMarksIn(text, options.autoMarked ?? []);
388
+ const textHasMarks = hasTurkishMarks(evidence);
389
+ const { asciiTyped, sentenceOf } = this.asciiEvidence(tokenize(evidence));
390
+ const priorTypoByStart = new Map();
391
+ if (options.priorTypoOriginals) {
392
+ for (const item of options.priorTypoOriginals)
393
+ priorTypoByStart.set(item.start, item);
394
+ }
395
+ const decided = [];
396
+ const pending = [];
397
+ let atSentenceStart = true;
398
+ let prevWord;
399
+ let prevIsName = false;
400
+ let prevCapitalized = false;
401
+ for (let index = 0; index < tokens.length; index++) {
402
+ const token = tokens[index];
403
+ if (!token.isWord) {
404
+ if (SENTENCE_END.has(token.text) || token.text.includes("\n"))
405
+ atSentenceStart = true;
406
+ else if (/\d/.test(token.text))
407
+ atSentenceStart = false;
408
+ if (token.text !== " ") {
409
+ prevWord = undefined;
410
+ prevIsName = false;
411
+ prevCapitalized = false;
412
+ }
413
+ continue;
414
+ }
415
+ const next = this.nextWord(tokens, index);
416
+ const sentenceHasAsciiTurkish = !textHasMarks && asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]);
417
+ const context = {
418
+ atSentenceStart,
419
+ textHasMarks: textHasMarks &&
420
+ hasTurkishMarks(evidence.slice(0, token.start) + evidence.slice(token.end)) &&
421
+ !asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]),
422
+ questionAhead: this.questionAhead(tokens, index),
423
+ prevWord,
424
+ prevIsName,
425
+ prevCapitalized,
426
+ nextIsolated: next ? this.isIsolated(tokens, next.index) : false,
427
+ sentenceHasAsciiTurkish,
428
+ };
429
+ atSentenceStart = false;
430
+ if (!this.isIsolated(tokens, index)) {
431
+ prevWord = undefined;
432
+ prevIsName = false;
433
+ prevCapitalized = false;
434
+ continue;
435
+ }
436
+ for (const option of this.contestedSpans(token, next?.token, context, tokens, index)) {
437
+ pending.push({ ...option, surfaceOriginal: option.typed });
438
+ }
439
+ const fix = this.check(token.text, context, next?.token.text);
440
+ const asciiContext = !context.textHasMarks || Boolean(context.sentenceHasAsciiTurkish);
441
+ // Re-evaluate a word previously rewritten as a typo during live typing (pause-pass override).
442
+ const priorTypo = priorTypoByStart.get(token.start);
443
+ if (priorTypo && priorTypo.end === token.end && !fix) {
444
+ const typoCands = this.typoCandidatesFor(priorTypo.original, context, next?.token.text, 7);
445
+ if (typoCands.length >= 2) {
446
+ const alts = typoCands.map((c) => (c.kind === "typo" ? matchCase(priorTypo.original, c.text) : keepCase(priorTypo.original, c.text)));
447
+ if (alts.some((alt) => lowerTr(alt) === lowerTr(token.text))) {
448
+ pending.push({
449
+ start: token.start,
450
+ end: token.end,
451
+ typed: priorTypo.original,
452
+ surfaceOriginal: token.text,
453
+ alternatives: alts,
454
+ kind: "typo",
455
+ direction: "typo",
456
+ typoMode: "override",
457
+ coreReplacement: token.text,
458
+ typoMeta: [
459
+ { coreMargin: 0, slipCost: 0, isMarkVariant: false },
460
+ ...typoCands.map((c) => ({ coreMargin: c.margin, slipCost: c.slipCost, isMarkVariant: c.isMarkVariant })),
461
+ ],
462
+ asciiContext,
463
+ typedHasMarks: hasTurkishMarks(priorTypo.original),
464
+ });
465
+ }
466
+ }
467
+ }
468
+ // Contested or rescued typo candidates for invalid/rare words.
469
+ const typoCands = this.typoCandidatesFor(token.text, context, next?.token.text, 7);
470
+ if (typoCands.length > 0) {
471
+ const word = lowerTr(token.text);
472
+ const typedCount = this.lexicon.count(word);
473
+ const alts = typoCands.map((c) => (c.kind === "typo" ? matchCase(token.text, c.text) : keepCase(token.text, c.text)));
474
+ const meta = [
475
+ { coreMargin: 0, slipCost: 0, isMarkVariant: false },
476
+ ...typoCands.map((c) => ({ coreMargin: c.margin, slipCost: c.slipCost, isMarkVariant: c.isMarkVariant })),
477
+ ];
478
+ if (fix &&
479
+ !fix.joinsNext &&
480
+ typoCands.length >= 2 &&
481
+ fix.kind === "typo" &&
482
+ alts.some((alt) => lowerTr(alt) === lowerTr(fix.replacement))) {
483
+ pending.push({
484
+ start: token.start,
485
+ end: token.end,
486
+ typed: token.text,
487
+ surfaceOriginal: token.text,
488
+ alternatives: alts,
489
+ kind: "typo",
490
+ direction: "typo",
491
+ typoMode: "override",
492
+ coreReplacement: fix.replacement,
493
+ typoMeta: meta,
494
+ asciiContext,
495
+ typedHasMarks: hasTurkishMarks(word),
496
+ });
497
+ }
498
+ else if (!fix) {
499
+ const top = typoCands[0];
500
+ if (typoCands.length >= 2 && (top.margin >= top.threshold || (typedCount === 0 && top.margin >= 0))) {
501
+ pending.push({
502
+ start: token.start,
503
+ end: token.end,
504
+ typed: token.text,
505
+ surfaceOriginal: token.text,
506
+ alternatives: alts,
507
+ kind: "typo",
508
+ direction: "typo",
509
+ typoMode: "ambiguous",
510
+ typoMeta: meta,
511
+ asciiContext,
512
+ typedHasMarks: hasTurkishMarks(word),
513
+ });
514
+ }
515
+ else if (typedCount === 0 && token.text === word && top.margin >= -0.5) {
516
+ pending.push({
517
+ start: token.start,
518
+ end: token.end,
519
+ typed: token.text,
520
+ surfaceOriginal: token.text,
521
+ alternatives: alts,
522
+ kind: "typo",
523
+ direction: "typo",
524
+ typoMode: "rescue",
525
+ typoMeta: meta,
526
+ asciiContext,
527
+ typedHasMarks: hasTurkishMarks(word),
528
+ });
529
+ }
530
+ }
531
+ }
532
+ if (!fix) {
533
+ prevWord = lowerTr(token.text);
534
+ prevIsName = !context.atSentenceStart && isUpperInitial(token.text);
535
+ prevCapitalized = isUpperInitial(token.text);
536
+ continue;
537
+ }
538
+ const end = fix.joinsNext && next ? next.token.end : token.end;
539
+ decided.push({ start: token.start, end, original: text.slice(token.start, end), replacement: fix.replacement, kind: fix.kind, margin: fix.margin });
540
+ const trailing = lastSpaceWord(fix.replacement);
541
+ prevWord = lowerTr(trailing);
542
+ prevIsName = !(context.atSentenceStart && !fix.replacement.includes(" ")) && isUpperInitial(trailing);
543
+ prevCapitalized = isUpperInitial(trailing);
544
+ if (fix.joinsNext && next)
545
+ index = next.index;
546
+ }
547
+ // Build core-restored surrounding context so ASCII/multi-typo sentences give the context model clean neighbors.
548
+ const contextSlice = (spanStart, spanEnd) => {
549
+ const leftFrom = Math.max(0, spanStart - 180);
550
+ const rightTo = Math.min(text.length, spanEnd + 150);
551
+ if (decided.length === 0) {
552
+ return { left: text.slice(leftFrom, spanStart), right: text.slice(spanEnd, rightTo) };
553
+ }
554
+ let left = "";
555
+ let cur = leftFrom;
556
+ for (const d of decided) {
557
+ if (d.end <= leftFrom)
558
+ continue;
559
+ if (d.start >= spanStart)
560
+ break;
561
+ if (d.start < cur || d.end > spanStart)
562
+ continue;
563
+ left += text.slice(cur, d.start) + d.replacement;
564
+ cur = d.end;
565
+ }
566
+ left += text.slice(cur, spanStart);
567
+ let right = "";
568
+ cur = spanEnd;
569
+ for (const d of decided) {
570
+ if (d.end <= spanEnd)
571
+ continue;
572
+ if (d.start >= rightTo)
573
+ break;
574
+ if (d.start < cur || d.end > rightTo)
575
+ continue;
576
+ right += text.slice(cur, d.start) + d.replacement;
577
+ cur = d.end;
578
+ }
579
+ right += text.slice(cur, rightTo);
580
+ return { left, right };
581
+ };
582
+ const scores = await model.score(pending.map((option) => {
583
+ const candidates = [option.typed, ...option.alternatives];
584
+ const { left, right } = contextSlice(option.start, option.end);
585
+ return {
586
+ left,
587
+ right,
588
+ candidates,
589
+ features: buildContextFeatures(candidates, option.kind, option.asciiContext, this.lexicon, this.morphology, option.typoMeta),
590
+ };
591
+ }));
592
+ const overlaps = (a, b) => a.start < b.end && b.start < a.end;
593
+ const typoOverrideBar = this.settings.contextTypoOverride ?? 2.5;
594
+ const typoAmbigGap = this.settings.contextTypoAmbigGap ?? 1.5;
595
+ const typoAmbigVsTyped = this.settings.contextTypoAmbigVsTyped ?? 2.5;
596
+ const typoRescueBar = this.settings.contextTypoRescue ?? 4.5;
597
+ // 1. Keep core fixes, allowing (a) contextVeto on count-based join/split, and (b) high-confidence context switch
598
+ // between competing valid typo candidates (e.g. "hber": core "her" -> context "haber").
599
+ const kept = [];
600
+ for (const fix of decided) {
601
+ if (fix.kind === "join" || fix.kind === "split") {
602
+ const index = pending.findIndex((option) => option.kind !== "typo" &&
603
+ option.start === fix.start &&
604
+ option.end === fix.end &&
605
+ option.alternatives.some((alt) => lowerTr(alt) === lowerTr(fix.replacement)));
606
+ if (index !== -1) {
607
+ const row = scores[index];
608
+ const option = pending[index];
609
+ const alternative = option.alternatives.findIndex((alt) => lowerTr(alt) === lowerTr(fix.replacement));
610
+ if (row[alternative + 1] - row[0] <= -this.settings.contextVeto)
611
+ continue;
612
+ }
613
+ kept.push(fix);
614
+ continue;
615
+ }
616
+ const overrideIdx = pending.findIndex((option) => option.kind === "typo" && option.typoMode === "override" && option.start === fix.start && option.end === fix.end);
617
+ if (overrideIdx !== -1) {
618
+ const option = pending[overrideIdx];
619
+ const row = scores[overrideIdx];
620
+ const coreAltIdx = option.alternatives.findIndex((alt) => lowerTr(alt) === lowerTr(fix.replacement));
621
+ if (coreAltIdx !== -1) {
622
+ let bestAlt = coreAltIdx;
623
+ for (let i = 0; i < option.alternatives.length; i++) {
624
+ if (row[i + 1] > row[bestAlt + 1])
625
+ bestAlt = i;
626
+ }
627
+ const delta = row[bestAlt + 1] - row[coreAltIdx + 1];
628
+ if (bestAlt !== coreAltIdx && delta >= typoOverrideBar) {
629
+ kept.push({
630
+ start: fix.start,
631
+ end: fix.end,
632
+ original: fix.original,
633
+ replacement: option.alternatives[bestAlt],
634
+ kind: "context",
635
+ margin: delta,
636
+ });
637
+ continue;
638
+ }
639
+ }
640
+ }
641
+ kept.push(fix);
642
+ }
643
+ // 2. Where no core fix touches a span (or for priorTypoOriginals in pause-pass), apply confident context decisions.
644
+ const offsets = this.settings.contextOffsets;
645
+ const thresholdFor = (option) => {
646
+ const base = this.settings.threshold.context;
647
+ if (!offsets)
648
+ return base;
649
+ if (option.kind === "marks") {
650
+ if (option.asciiContext)
651
+ return base + (offsets.marksAscii ?? 0);
652
+ return base + (option.typedHasMarks ? (offsets.marksMarkedOnMarked ?? 3.0) : (offsets.marksMarked ?? 1.5));
653
+ }
654
+ if (option.kind === "de_da")
655
+ return base + (option.direction === "split" ? (offsets.deDaSplit ?? 0) : (offsets.deDaJoin ?? 0));
656
+ if (option.kind === "ki")
657
+ return base + (option.direction === "split" ? (offsets.kiSplit ?? 0) : (offsets.kiJoin ?? 0));
658
+ return base + (option.direction === "split" ? (offsets.miSplit ?? 0) : (offsets.miJoin ?? 0));
659
+ };
660
+ const judged = [];
661
+ pending.forEach((option, index) => {
662
+ if (decided.some((fix) => overlaps(fix, option)))
663
+ return;
664
+ const row = scores[index];
665
+ if (option.kind === "typo") {
666
+ if (option.typoMode === "override" && option.coreReplacement) {
667
+ // Pause-pass override for a priorTypoOriginals span not touched in this pass.
668
+ const coreAltIdx = option.alternatives.findIndex((alt) => lowerTr(alt) === lowerTr(option.coreReplacement));
669
+ if (coreAltIdx === -1)
670
+ return;
671
+ let bestAlt = coreAltIdx;
672
+ for (let i = 0; i < option.alternatives.length; i++) {
673
+ if (row[i + 1] > row[bestAlt + 1])
674
+ bestAlt = i;
675
+ }
676
+ const delta = row[bestAlt + 1] - row[coreAltIdx + 1];
677
+ if (bestAlt !== coreAltIdx && delta >= typoOverrideBar) {
678
+ judged.push({
679
+ start: option.start,
680
+ end: option.end,
681
+ original: option.surfaceOriginal,
682
+ replacement: option.alternatives[bestAlt],
683
+ kind: "context",
684
+ margin: delta,
685
+ });
686
+ }
687
+ return;
688
+ }
689
+ let best = 1;
690
+ let second = -1;
691
+ for (let i = 2; i < row.length; i++) {
692
+ if (row[i] > row[best]) {
693
+ second = best;
694
+ best = i;
695
+ }
696
+ else if (second === -1 || row[i] > row[second]) {
697
+ second = i;
698
+ }
699
+ }
700
+ const vsTyped = row[best] - row[0];
701
+ const gap = second !== -1 ? row[best] - row[second] : Infinity;
702
+ if (option.typoMode === "ambiguous") {
703
+ if (vsTyped >= typoAmbigVsTyped && gap >= typoAmbigGap) {
704
+ judged.push({
705
+ start: option.start,
706
+ end: option.end,
707
+ original: option.surfaceOriginal,
708
+ replacement: option.alternatives[best - 1],
709
+ kind: "context",
710
+ margin: Math.min(vsTyped, gap),
711
+ });
712
+ }
713
+ }
714
+ else if (option.typoMode === "rescue") {
715
+ if (vsTyped >= typoRescueBar && gap >= typoAmbigGap) {
716
+ judged.push({
717
+ start: option.start,
718
+ end: option.end,
719
+ original: option.surfaceOriginal,
720
+ replacement: option.alternatives[best - 1],
721
+ kind: "context",
722
+ margin: vsTyped,
723
+ });
724
+ }
725
+ }
726
+ return;
727
+ }
728
+ let best = 1;
729
+ for (let i = 2; i < row.length; i++)
730
+ if (row[i] > row[best])
731
+ best = i;
732
+ const margin = row[best] - row[0];
733
+ if (margin >= thresholdFor(option)) {
734
+ judged.push({ start: option.start, end: option.end, original: option.surfaceOriginal, replacement: option.alternatives[best - 1], kind: "context", margin });
735
+ }
736
+ });
737
+ const all = [...kept, ...judged].sort((a, b) => a.start - b.start || b.margin - a.margin);
738
+ const corrections = [];
739
+ for (const fix of all)
740
+ if (!corrections.some((done) => overlaps(done, fix)))
741
+ corrections.push(fix);
742
+ if (this.settings.sentenceCase) {
743
+ if (model.supportsNameContext && this.known?.hasProperData) {
744
+ const collectAmbig = [];
745
+ const pass1 = this.withSentenceRules(text, corrections, { collectAmbig });
746
+ if (collectAmbig.length === 0) {
747
+ corrections.splice(0, corrections.length, ...pass1);
748
+ }
749
+ else {
750
+ const asciiCtx = !textHasMarks;
751
+ const nameScores = await model.score(collectAmbig.map((q) => {
752
+ const candidates = [q.commonCand, q.properCand];
753
+ const stemCapShare = this.lexicon.capitalShare(q.base);
754
+ let aposShare = 0;
755
+ if (q.suffix) {
756
+ const cApos = this.lexicon.count(`${q.base}'${q.suffix}`);
757
+ const cJoin = this.lexicon.count(`${q.base}${q.suffix}`);
758
+ aposShare = cApos / (cApos + cJoin + 1);
759
+ }
760
+ const meta = [
761
+ { isProper: false, stemCapShare, aposShare, isGiven: q.isGiven, atSentenceStart: q.atStart },
762
+ { isProper: true, stemCapShare, aposShare, isGiven: q.isGiven, atSentenceStart: q.atStart },
763
+ ];
764
+ return {
765
+ left: q.leftRaw,
766
+ right: q.rightRaw,
767
+ candidates,
768
+ features: buildContextFeatures(candidates, "name", asciiCtx, this.lexicon, this.morphology, undefined, meta),
769
+ };
770
+ }));
771
+ const preDecidedAmbig = new Map();
772
+ const nameBar = this.settings.contextNameThreshold ?? 2.5;
773
+ for (let i = 0; i < collectAmbig.length; i++) {
774
+ const q = collectAmbig[i];
775
+ const row = nameScores[i];
776
+ if (!row || row.length < 2)
777
+ continue;
778
+ const margin = row[1] - row[0];
779
+ if (q.hadApostrophe) {
780
+ if (margin >= 1.5)
781
+ preDecidedAmbig.set(q.start, q.properCand);
782
+ else if (-margin >= 2.0)
783
+ preDecidedAmbig.set(q.start, q.commonCand);
784
+ }
785
+ else {
786
+ // At sentence start, an overwhelmingly common inflected lowercase Turkish noun ("Savaşa gitme",
787
+ // where "savaşa" has high frequency and <=5% cap share) needs a stronger margin to split with apostrophe.
788
+ let effBar = nameBar;
789
+ if (q.atStart && q.suffix) {
790
+ const wholeLow = `${q.base}${q.suffix}`;
791
+ if (this.lexicon.count(wholeLow) >= 1000 && this.lexicon.capitalShare(wholeLow) <= 0.05) {
792
+ effBar = nameBar + 1.5;
793
+ }
794
+ }
795
+ if (margin >= effBar) {
796
+ preDecidedAmbig.set(q.start, q.properCand);
797
+ }
798
+ }
799
+ }
800
+ if (preDecidedAmbig.size > 0) {
801
+ corrections.splice(0, corrections.length, ...this.withSentenceRules(text, corrections, { preDecidedAmbig }));
802
+ }
803
+ else {
804
+ corrections.splice(0, corrections.length, ...pass1);
805
+ }
806
+ }
807
+ }
808
+ else {
809
+ corrections.splice(0, corrections.length, ...this.withSentenceRules(text, corrections));
810
+ }
811
+ }
812
+ let output = "";
813
+ let cursor = 0;
814
+ for (const correction of corrections) {
815
+ output += text.slice(cursor, correction.start) + correction.replacement;
816
+ cursor = correction.end;
817
+ }
818
+ const finalText = output + text.slice(cursor);
819
+ if (!collectFlags) {
820
+ return { text: finalText, corrections, flags: [] };
821
+ }
822
+ // Collect flags for every suspicious token left untouched by both core and context corrections.
823
+ const rawFlags = [];
824
+ let fAtStart = true;
825
+ let fPrevWord;
826
+ let fPrevIsName = false;
827
+ let fPrevCapitalized = false;
828
+ let corrIdx = 0;
829
+ for (let index = 0; index < tokens.length; index++) {
830
+ const token = tokens[index];
831
+ if (!token.isWord) {
832
+ if (SENTENCE_END.has(token.text) || token.text.includes("\n"))
833
+ fAtStart = true;
834
+ else if (/\d/.test(token.text))
835
+ fAtStart = false;
836
+ if (token.text !== " ") {
837
+ fPrevWord = undefined;
838
+ fPrevIsName = false;
839
+ fPrevCapitalized = false;
840
+ }
841
+ continue;
842
+ }
843
+ while (corrIdx < corrections.length && corrections[corrIdx].end <= token.start)
844
+ corrIdx++;
845
+ const overlappingCorr = corrIdx < corrections.length && overlaps(corrections[corrIdx], token) ? corrections[corrIdx] : undefined;
846
+ const next = this.nextWord(tokens, index);
847
+ const sentenceHasAsciiTurkish = !textHasMarks && asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]);
848
+ const ctx = {
849
+ atSentenceStart: fAtStart,
850
+ textHasMarks: textHasMarks &&
851
+ hasTurkishMarks(evidence.slice(0, token.start) + evidence.slice(token.end)) &&
852
+ !asciiTyped.some((other) => other !== index && sentenceOf[other] === sentenceOf[index]),
853
+ questionAhead: this.questionAhead(tokens, index),
854
+ prevWord: fPrevWord,
855
+ prevIsName: fPrevIsName,
856
+ prevCapitalized: fPrevCapitalized,
857
+ nextIsolated: next ? this.isIsolated(tokens, next.index) : false,
858
+ sentenceHasAsciiTurkish,
859
+ };
860
+ fAtStart = false;
861
+ if (overlappingCorr) {
862
+ const trailing = lastSpaceWord(overlappingCorr.replacement);
863
+ fPrevWord = lowerTr(trailing);
864
+ fPrevIsName = !(ctx.atSentenceStart && !overlappingCorr.replacement.includes(" ")) && isUpperInitial(trailing);
865
+ fPrevCapitalized = isUpperInitial(trailing);
866
+ continue;
867
+ }
868
+ if (!this.isIsolated(tokens, index)) {
869
+ fPrevWord = undefined;
870
+ fPrevIsName = false;
871
+ fPrevCapitalized = false;
872
+ continue;
873
+ }
874
+ const detected = this.detectFlagDetailed(token, ctx, next?.token.text);
875
+ if (detected) {
876
+ rawFlags.push({
877
+ ...detected,
878
+ asciiContext: !ctx.textHasMarks || Boolean(ctx.sentenceHasAsciiTurkish),
879
+ });
880
+ }
881
+ fPrevWord = lowerTr(token.text);
882
+ fPrevIsName = !ctx.atSentenceStart && isUpperInitial(token.text);
883
+ fPrevCapitalized = isUpperInitial(token.text);
884
+ }
885
+ // Re-rank multi-suggestion flags in sentence context using a single batched context-model call.
886
+ const rerankTargets = rawFlags.filter((entry) => entry.flag.suggestions.length >= 2);
887
+ if (rerankTargets.length > 0) {
888
+ // Build context slice using final `corrections` so neighboring core+context fixes are visible.
889
+ const finalContextSlice = (spanStart, spanEnd) => {
890
+ const leftFrom = Math.max(0, spanStart - 180);
891
+ const rightTo = Math.min(text.length, spanEnd + 150);
892
+ if (corrections.length === 0) {
893
+ return { left: text.slice(leftFrom, spanStart), right: text.slice(spanEnd, rightTo) };
894
+ }
895
+ let left = "";
896
+ let cur = leftFrom;
897
+ for (const d of corrections) {
898
+ if (d.end <= leftFrom)
899
+ continue;
900
+ if (d.start >= spanStart)
901
+ break;
902
+ if (d.start < cur || d.end > spanStart)
903
+ continue;
904
+ left += text.slice(cur, d.start) + d.replacement;
905
+ cur = d.end;
906
+ }
907
+ left += text.slice(cur, spanStart);
908
+ let right = "";
909
+ cur = spanEnd;
910
+ for (const d of corrections) {
911
+ if (d.end <= spanEnd)
912
+ continue;
913
+ if (d.start >= rightTo)
914
+ break;
915
+ if (d.start < cur || d.end > rightTo)
916
+ continue;
917
+ right += text.slice(cur, d.start) + d.replacement;
918
+ cur = d.end;
919
+ }
920
+ right += text.slice(cur, rightTo);
921
+ return { left, right };
922
+ };
923
+ // When re-ranking flag suggestions with the context model, expose the morphological generative prior for
924
+ // unseen/rare valid candidates (e.g. "düzenlemiyor") so corpus sparsity doesn't bias feature slots 0..2.
925
+ const priorAwareLexicon = {
926
+ count: (form) => {
927
+ const raw = this.lexicon.count(form);
928
+ if (raw >= 20 || form.includes("'") || !this.isRealWord(form))
929
+ return raw;
930
+ return Math.max(raw, Math.round(this.effectiveCount(form, "rank")));
931
+ },
932
+ pair: (a, b) => this.lexicon.pair(a, b),
933
+ };
934
+ const flagScores = await model.score(rerankTargets.map((entry) => {
935
+ const candidates = [entry.flag.original, ...entry.flag.suggestions];
936
+ const { left, right } = finalContextSlice(entry.flag.start, entry.flag.end);
937
+ return {
938
+ left,
939
+ right,
940
+ candidates,
941
+ features: buildContextFeatures(candidates, "typo", entry.asciiContext, priorAwareLexicon, this.morphology, entry.meta),
942
+ };
943
+ }));
944
+ for (let i = 0; i < rerankTargets.length; i++) {
945
+ const entry = rerankTargets[i];
946
+ const row = flagScores[i];
947
+ if (!row || row.length !== entry.flag.suggestions.length + 1)
948
+ continue;
949
+ const ranked = entry.flag.suggestions.map((sugg, idx) => ({
950
+ sugg,
951
+ // Combine sentence context score with core linguistic/edit-cost score (including case-voice agreement).
952
+ score: row[idx + 1] + 0.65 * (entry.coreScores[idx] ?? 0),
953
+ }));
954
+ ranked.sort((a, b) => b.score - a.score);
955
+ entry.flag.suggestions = ranked.map((r) => r.sugg);
956
+ }
957
+ }
958
+ return { text: finalText, corrections, flags: rawFlags.map((entry) => entry.flag) };
959
+ }
960
+ /**
961
+ * Returns morphologically valid typo/mark candidates (sorted by core score) for an invalid/rare word,
962
+ * along with core margin, threshold, slip cost, and mark-variant flag.
963
+ * Used by `correctAsync()` and Stage 2 training data generation.
964
+ */
965
+ typoCandidatesFor(typed, context, nextTyped, maxCandidates = 7) {
966
+ if (this.morphology === undefined || isAllUpper(typed) || typed.length < 4)
967
+ return [];
968
+ const word = lowerTr(typed);
969
+ if (word.includes("'") || typed.slice(1) !== word.slice(1))
970
+ return [];
971
+ if (isUpperInitial(typed) && !context.atSentenceStart)
972
+ return [];
973
+ if (this.isRealWord(word))
974
+ return [];
975
+ const listed = this.knownFix(typed, word, context, nextTyped);
976
+ if (listed !== null)
977
+ return [];
978
+ const typedCount = this.lexicon.count(word);
979
+ const rareInvalidSlip = typed === word && typedCount < 50 && this.lexicon.capitalShare(word) < 0.5;
980
+ if (typedCount >= this.settings.knownWord && !rareInvalidSlip)
981
+ return [];
982
+ const cands = this.candidates(word, typed, context, typedCount, nextTyped);
983
+ const foldedWord = foldTr(word);
984
+ const valid = [];
985
+ for (const c of cands) {
986
+ if (c.kind !== "typo" && c.kind !== "marks")
987
+ continue;
988
+ if (c.text.includes(" ") || !this.isRealWord(c.text) || this.lexicon.exactCount(c.text) < 1)
989
+ continue;
990
+ const invalidTyped = c.kind === "typo" && typedCount === 0 && typed === word;
991
+ const threshold = c.threshold ?? (invalidTyped ? this.settings.typoInvalidThreshold : this.settings.threshold[c.kind]);
992
+ valid.push({
993
+ text: c.text,
994
+ kind: c.kind,
995
+ margin: marginOf(c),
996
+ threshold,
997
+ slipCost: c.slipCost ?? 0,
998
+ isMarkVariant: foldTr(c.text) === foldedWord,
999
+ });
1000
+ }
1001
+ valid.sort((a, b) => b.margin - a.margin);
1002
+ return valid.slice(0, maxCandidates);
1003
+ }
1004
+ /** Places where the typed span and another real-word reading compete, for the context model to judge. */
1005
+ contestedSpans(token, next, context, tokens, tokenIndex) {
1006
+ const typed = token.text;
1007
+ const word = lowerTr(typed);
1008
+ if (isAllUpper(typed) || typed.length < 2 || (isUpperInitial(typed) && !context.atSentenceStart) || typed.slice(1) !== word.slice(1)) {
1009
+ return [];
1010
+ }
1011
+ const known = (form) => this.lexicon.count(form) >= this.settings.contextWord;
1012
+ const asciiContext = !context.textHasMarks || Boolean(context.sentenceHasAsciiTurkish);
1013
+ const typedHasMarks = hasTurkishMarks(word);
1014
+ const nextLow = next ? lowerTr(next.text) : "";
1015
+ const spans = [];
1016
+ // "oldu" / "öldü", "uç" / "üç": real words that differ only in Turkish marks (question particle harmony is deterministic).
1017
+ if (known(word) && !word.includes("'") && !QUESTION.test(word)) {
1018
+ const variants = markVariants(word)
1019
+ .filter(known)
1020
+ .sort((a, b) => this.lexicon.count(b) - this.lexicon.count(a))
1021
+ .slice(0, 3)
1022
+ .map((variant) => keepCase(typed, variant));
1023
+ if (variants.length > 0) {
1024
+ spans.push({ start: token.start, end: token.end, typed, alternatives: variants, kind: "marks", direction: "marks", asciiContext, typedHasMarks });
1025
+ }
1026
+ }
1027
+ // "bende" / "ben de", "evde" / "ev de", "evdeki" / "evde ki", "sevgimi" / "sevgi mi":
1028
+ // a real word that could be two. Never split TDK-fixed SOMBAHCEMI words ("oysaki", "illaki"), never split locative
1029
+ // -te/-ta into conjunction de/da ("ekte" is never "ek de"), never split Xde before another "de/da" ("bende de"),
1030
+ // and only propose splitting -mi when a question mark lies ahead without an existing question particle.
1031
+ if (known(word) && word.length >= 4 && !word.includes("'")) {
1032
+ const stem = word.slice(0, -2);
1033
+ const tail = word.slice(-2);
1034
+ if ((tail === "de" || tail === "da") && nextLow !== "de" && nextLow !== "da" && known(stem) && followsHarmony(stem, tail[1])) {
1035
+ spans.push({
1036
+ start: token.start,
1037
+ end: token.end,
1038
+ typed,
1039
+ alternatives: [`${typed.slice(0, -2)} ${typed.slice(-2)}`],
1040
+ kind: "de_da",
1041
+ direction: "split",
1042
+ asciiContext: false,
1043
+ typedHasMarks,
1044
+ });
1045
+ }
1046
+ else if (tail === "ki" && !FIXED_KI_WORDS.has(word) && !SOMBAHCEMI_KI.has(stem) && known(stem)) {
1047
+ spans.push({
1048
+ start: token.start,
1049
+ end: token.end,
1050
+ typed,
1051
+ alternatives: [`${typed.slice(0, -2)} ${typed.slice(-2)}`],
1052
+ kind: "ki",
1053
+ direction: "split",
1054
+ asciiContext: false,
1055
+ typedHasMarks,
1056
+ });
1057
+ }
1058
+ else if (/^m[ıiuü]$/.test(tail) &&
1059
+ stem.length >= 3 &&
1060
+ known(stem) &&
1061
+ followsHarmony(stem, tail[1])) {
1062
+ spans.push({
1063
+ start: token.start,
1064
+ end: token.end,
1065
+ typed,
1066
+ alternatives: [`${typed.slice(0, -2)} ${typed.slice(-2)}`],
1067
+ kind: "mi",
1068
+ direction: "split",
1069
+ asciiContext: false,
1070
+ typedHasMarks,
1071
+ });
1072
+ }
1073
+ }
1074
+ // "ben de" / "bende", "kitap da" / "kitapta", "evde ki" / "evdeki", "sevgi mi" / "sevgimi": two words that could be one.
1075
+ if (next && !isUpperInitial(next.text) && !isAllUpper(next.text) && !word.includes("'") && known(word)) {
1076
+ const second = nextLow;
1077
+ if (second === "de" || second === "da") {
1078
+ const gluedD = word + second;
1079
+ const gluedT = isVoicelessFinal(word) ? word + (second === "de" ? "te" : "ta") : "";
1080
+ const glued = known(gluedD) ? gluedD : gluedT && known(gluedT) ? gluedT : "";
1081
+ if (glued) {
1082
+ spans.push({
1083
+ start: token.start,
1084
+ end: next.end,
1085
+ typed: `${typed} ${next.text}`,
1086
+ alternatives: [keepCase(typed, glued)],
1087
+ kind: "de_da",
1088
+ direction: "join",
1089
+ asciiContext: false,
1090
+ typedHasMarks,
1091
+ });
1092
+ }
1093
+ }
1094
+ else if (second === "ki" && known(word + "ki")) {
1095
+ spans.push({
1096
+ start: token.start,
1097
+ end: next.end,
1098
+ typed: `${typed} ${next.text}`,
1099
+ alternatives: [typed + next.text],
1100
+ kind: "ki",
1101
+ direction: "join",
1102
+ asciiContext: false,
1103
+ typedHasMarks,
1104
+ });
1105
+ }
1106
+ else if (QUESTION.test(second) && !MUSIC_NOTES.has(word) && known(word + second)) {
1107
+ spans.push({
1108
+ start: token.start,
1109
+ end: next.end,
1110
+ typed: `${typed} ${next.text}`,
1111
+ alternatives: [typed + next.text],
1112
+ kind: "mi",
1113
+ direction: "join",
1114
+ asciiContext: false,
1115
+ typedHasMarks,
1116
+ });
1117
+ }
1118
+ }
1119
+ return spans;
1120
+ }
1121
+ /** True when a standalone question particle (mi/mı/mu/mü...) already appears later in the same sentence. */
1122
+ questionParticleAhead(tokens, index) {
1123
+ for (let ahead = index + 1; ahead < tokens.length; ahead++) {
1124
+ const tok = tokens[ahead];
1125
+ if (!tok.isWord) {
1126
+ if (SENTENCE_END.has(tok.text) || tok.text.includes("\n"))
1127
+ return false;
1128
+ continue;
1129
+ }
1130
+ const low = lowerTr(tok.text);
1131
+ if (QUESTION.test(low))
1132
+ return true;
1133
+ }
1134
+ return false;
1135
+ }
1136
+ /**
1137
+ * Words that were clearly typed without Turkish letters ("anlamadim", "sey"): unseen or nearly so as typed, but
1138
+ * common with marks. A sentence with one is treated as typed without Turkish letters, even when other words in the
1139
+ * text have them, so "hic" next to "anlamadim" still becomes "hiç".
1140
+ */
1141
+ asciiEvidence(tokens) {
1142
+ const asciiTyped = [];
1143
+ const sentenceOf = [];
1144
+ let sentence = 0;
1145
+ tokens.forEach((token, index) => {
1146
+ if (!token.isWord) {
1147
+ if (SENTENCE_END.has(token.text) || token.text.includes("\n"))
1148
+ sentence++;
1149
+ sentenceOf[index] = sentence;
1150
+ return;
1151
+ }
1152
+ sentenceOf[index] = sentence;
1153
+ const word = lowerTr(token.text);
1154
+ if (hasTurkishMarks(word) || this.lexicon.count(word) >= this.settings.knownWord || this.isRealWord(word))
1155
+ return;
1156
+ if (markVariants(word).some((variant) => this.lexicon.count(variant) >= ASCII_EVIDENCE_COUNT))
1157
+ asciiTyped.push(index);
1158
+ });
1159
+ return { asciiTyped, sentenceOf };
1160
+ }
1161
+ /** The next word when only a single space separates it from this one. */
1162
+ nextWord(tokens, index) {
1163
+ const space = tokens[index + 1];
1164
+ const word = tokens[index + 2];
1165
+ if (space?.text === " " && word?.isWord)
1166
+ return { token: word, index: index + 2 };
1167
+ return null;
1168
+ }
1169
+ questionAhead(tokens, index) {
1170
+ for (let ahead = index + 1; ahead < tokens.length; ahead++) {
1171
+ const text = tokens[ahead].text;
1172
+ if (text === "?")
1173
+ return true;
1174
+ if (SENTENCE_END.has(text) || text.includes("\n"))
1175
+ return false;
1176
+ }
1177
+ return false;
1178
+ }
1179
+ /** Words glued to "@", "/", digits or dots between letters are parts of addresses, handles or code. */
1180
+ isIsolated(tokens, index) {
1181
+ const before = tokens[index - 1]?.text ?? " ";
1182
+ const after = tokens[index + 1]?.text ?? " ";
1183
+ const afterNext = tokens[index + 2];
1184
+ if (/[@/#_\\\d-]/.test(before) || /[@/#_\\\d-]/.test(after))
1185
+ return false;
1186
+ // Part of a word with letters Turkish doesn't use ("skrælingi", Cyrillic): not ours to judge.
1187
+ if (/\p{L}/u.test(before) || /\p{L}/u.test(after))
1188
+ return false;
1189
+ if (after === "." && afterNext?.isWord) {
1190
+ // When sentenceCase is on, a missing space after a full stop ("gonderdim.bir", "yasiyor.her")
1191
+ // is NOT an address/domain when neither side is an abbreviation/TLD and there is no second dot.
1192
+ if (!this.settings.sentenceCase)
1193
+ return false;
1194
+ const cur = tokens[index];
1195
+ const curLow = lowerTr(cur.text);
1196
+ const nextLow = lowerTr(afterNext.text);
1197
+ const prevDot = before === "." || tokens[index - 2]?.text === ".";
1198
+ const nextDot = tokens[index + 3]?.text === ".";
1199
+ if (prevDot ||
1200
+ nextDot ||
1201
+ cur.text.length < 2 ||
1202
+ afterNext.text.length < 2 ||
1203
+ ABBREVIATIONS.has(curLow) ||
1204
+ NOT_A_SENTENCE_START.has(nextLow)) {
1205
+ return false;
1206
+ }
1207
+ return true;
1208
+ }
1209
+ return true;
1210
+ }
1211
+ /** Decides on one word, optionally joined with the next. Returns null to leave it alone. */
1212
+ check(typed, context, nextTyped) {
1213
+ if (isAllUpper(typed) || typed.length < 2)
1214
+ return null;
1215
+ const word = lowerTr(typed);
1216
+ if (this.isLowercaseProperForSentence(word, typed, context))
1217
+ return null;
1218
+ const typedCount = this.lexicon.count(word);
1219
+ const listed = this.knownFix(typed, word, context, nextTyped);
1220
+ if (listed === "keep")
1221
+ return null;
1222
+ if (listed)
1223
+ return listed;
1224
+ const pronoun = this.pronounAlso(typed, word, nextTyped);
1225
+ if (pronoun)
1226
+ return pronoun;
1227
+ const candidates = this.candidates(word, typed, context, typedCount, nextTyped);
1228
+ if (nextTyped && !isAllUpper(nextTyped) && !isUpperInitial(nextTyped) && !(isUpperInitial(typed) && !context.atSentenceStart)) {
1229
+ const joined = this.joinCandidate(word, lowerTr(nextTyped), typed, context.nextIsolated ?? true);
1230
+ if (joined)
1231
+ candidates.push(joined);
1232
+ }
1233
+ if (candidates.length === 0)
1234
+ return null;
1235
+ candidates.sort((first, second) => marginOf(second) - marginOf(first));
1236
+ const best = candidates[0];
1237
+ const runnerUp = candidates.find((candidate) => candidate.text !== best.text);
1238
+ const margin = marginOf(best);
1239
+ // A word nobody has seen that Turkish suffix rules also reject is almost surely a slip ("gelyorum"), so a fix for it
1240
+ // needs less of a margin.
1241
+ // Only for lowercase words: an unseen capitalized word is usually a name ("Kahireden" is "Kahire'den").
1242
+ const invalidTyped = best.kind === "typo" && this.morphology !== undefined && typedCount === 0 && typed === word && !this.isRealWord(word);
1243
+ const threshold = best.threshold ?? (invalidTyped ? this.settings.typoInvalidThreshold : this.settings.threshold[best.kind]);
1244
+ if (margin < threshold)
1245
+ return null;
1246
+ if (runnerUp && margin - marginOf(runnerUp) < this.settings.ambiguity)
1247
+ return null;
1248
+ if (best.kind === "marks" && context.prevWord && isAuxiliaryOl(context.prevWord, word, best.text))
1249
+ return null;
1250
+ const original = best.joinsNext ? `${typed} ${nextTyped}` : typed;
1251
+ const replacement = best.kind === "typo" ? matchCase(typed, best.text) : keepCase(original, best.text);
1252
+ return { replacement, kind: best.kind, margin, joinsNext: best.joinsNext };
1253
+ }
1254
+ /**
1255
+ * "bende geldim" -> "ben de geldim": a pronoun glued to "de" followed by a finite verb of the same person is the
1256
+ * conjunction, never the locative ("Kitap bende kaldı" keeps "bende": the verb there is third person).
1257
+ */
1258
+ pronounAlso(typed, word, nextTyped) {
1259
+ const person = PRONOUN_DE[word];
1260
+ if (!person || !nextTyped || !this.morphology?.analyze || isUpperInitial(nextTyped) && !isUpperInitial(typed))
1261
+ return null;
1262
+ const analyses = this.morphology.analyze(lowerTr(nextTyped));
1263
+ const finite = analyses.filter((a) => a.pos === "Verb" && a.morphemes.some((m) => FINITE_VERB_MORPHEMES.has(m)) && !a.morphemes.includes("Zero"));
1264
+ if (!finite.some((a) => a.morphemes.at(-1) === person))
1265
+ return null;
1266
+ if (analyses.some((a) => a.morphemes.at(-1) === "A3sg" && a.morphemes.some((m) => FINITE_VERB_MORPHEMES.has(m))))
1267
+ return null;
1268
+ return { replacement: `${typed.slice(0, -2)} ${typed.slice(-2)}`, kind: "split", margin: 5, joinsNext: false };
1269
+ }
1270
+ /** A listed misspelling wins over everything else when the fix is clearly more common than what was typed. */
1271
+ knownFix(typed, word, context, nextTyped) {
1272
+ if (!this.known || (isUpperInitial(typed) && !context.atSentenceStart))
1273
+ return null;
1274
+ const next = nextTyped && !isUpperInitial(nextTyped) ? lowerTr(nextTyped) : undefined;
1275
+ let best = null;
1276
+ const fixes = this.known.find(word, next, this.lexicon, !context.textHasMarks);
1277
+ // With contractions off, a single word matching one ("noldu") stays as typed: no other rule may take it for a slip.
1278
+ if (!this.settings.contractions && fixes.some((fix) => fix.contraction && !fix.joinsNext))
1279
+ return "keep";
1280
+ for (const fix of fixes) {
1281
+ if (fix.contraction && !this.settings.contractions)
1282
+ continue;
1283
+ const base = fix.joinsNext ? log(this.lexicon.pair(word, next)) : log(this.lexicon.count(word));
1284
+ const margin = log(fix.count) - this.settings.cost.known - base;
1285
+ if (margin < this.settings.threshold.known || (best && best.margin >= margin))
1286
+ continue;
1287
+ const original = fix.joinsNext ? `${typed} ${nextTyped}` : typed;
1288
+ best = { replacement: keepCase(original, fix.text), kind: fix.contraction ? "contraction" : "known", margin, joinsNext: fix.joinsNext };
1289
+ }
1290
+ return best;
1291
+ }
1292
+ candidates(word, typed, context, typedCount, nextTyped) {
1293
+ const { cost, knownWord, knownMarked, markedOverride } = this.settings;
1294
+ const typedScore = log(typedCount);
1295
+ const found = new Map();
1296
+ const add = (text, kind, score, base = typedScore, threshold, slipCost) => {
1297
+ if (!Number.isFinite(score) || !Number.isFinite(base) || text === word)
1298
+ return;
1299
+ const existing = found.get(text);
1300
+ // The same fix may come from two rules with different bars (plain mark restoration and the lower bar for a
1301
+ // unique morphologically valid variant). Keep the best margin and the lower bar of the two, or the lower bar
1302
+ // is lost whenever the other rule saw the same candidate first ("duzeltmiyor" -> "düzeltmiyor").
1303
+ const sameKind = existing?.kind === kind;
1304
+ const bar = (candidate) => candidate.threshold ?? this.settings.threshold[candidate.kind];
1305
+ if (!existing || score - base > marginOf(existing)) {
1306
+ const keepBar = sameKind && existing && bar(existing) < bar({ kind, threshold });
1307
+ found.set(text, { text, kind, score, base, joinsNext: false, threshold: keepBar ? existing.threshold : threshold, slipCost });
1308
+ }
1309
+ else if (sameKind && bar({ kind, threshold }) < bar(existing)) {
1310
+ existing.threshold = threshold;
1311
+ }
1312
+ };
1313
+ const capitalized = isUpperInitial(typed);
1314
+ const isName = capitalized && !context.atSentenceStart;
1315
+ const realTyped = this.isRealWord(word);
1316
+ const hasApostrophe = word.includes("'");
1317
+ const apostropheAt = hasApostrophe ? word.indexOf("'") : -1;
1318
+ const wordStem = hasApostrophe ? word.slice(0, apostropheAt) : "";
1319
+ const wordSuffix = hasApostrophe ? word.slice(apostropheAt + 1) : "";
1320
+ // In text that already uses Turkish marks, protect real Turkish words ("cabası", "oluyorduk", "basınız") with a
1321
+ // high override bar, while relaxing strict protection for low-count lowercase non-words ("yogurt", "yasam").
1322
+ const realMarked = context.textHasMarks && realTyped;
1323
+ const relaxStrict = this.morphology !== undefined &&
1324
+ typed === word &&
1325
+ !realTyped &&
1326
+ typedCount < 70 &&
1327
+ this.lexicon.capitalShare(word) < 0.55;
1328
+ const strict = context.textHasMarks && (realTyped || (typedCount >= knownMarked && !relaxStrict));
1329
+ const override = realMarked ? markedOverride + 0.5 : markedOverride;
1330
+ const variants = markVariants(word);
1331
+ const filterInvalidMarks = this.morphology !== undefined &&
1332
+ !isName &&
1333
+ !strict &&
1334
+ !realTyped &&
1335
+ !hasApostrophe &&
1336
+ variants.some((variant) => this.lexicon.count(variant) > 0 && this.isRealWord(variant));
1337
+ const forms = [word, ...variants];
1338
+ const typedLowerCount = Math.round(typedCount * (1 - this.lexicon.capitalShare(word)));
1339
+ let morphParticleHit = false;
1340
+ let strongAsciiMarkHit = false;
1341
+ for (const form of forms) {
1342
+ const markCost = form === word ? 0 : cost.marks;
1343
+ if (form !== word) {
1344
+ let blockMark = false;
1345
+ let sameApostropheStem = false;
1346
+ if (hasApostrophe) {
1347
+ const formQuote = form.indexOf("'");
1348
+ const formStem = form.slice(0, formQuote);
1349
+ const formSuffix = form.slice(formQuote + 1);
1350
+ sameApostropheStem = formStem === wordStem;
1351
+ const onlyLeadingCapitalI = typed[0] === "I" && wordStem[0] === "ı" && formStem[0] === "i" && wordStem.slice(1) === formStem.slice(1);
1352
+ if (context.textHasMarks &&
1353
+ !sameApostropheStem &&
1354
+ !onlyLeadingCapitalI &&
1355
+ (this.lexicon.count(wordStem) >= knownMarked || this.isRealWord(wordStem))) {
1356
+ blockMark = true;
1357
+ }
1358
+ if (!blockMark && formSuffix !== wordSuffix) {
1359
+ const isInverseStem = this.morphology !== undefined && this.hasFrontLocative(formStem) && !this.hasBackLocative(formStem);
1360
+ if (!isHarmoniousApostropheMarkChange(formStem, wordSuffix, formSuffix, isInverseStem)) {
1361
+ blockMark = true;
1362
+ }
1363
+ }
1364
+ }
1365
+ if (!blockMark && !(filterInvalidMarks && !this.isRealWord(form))) {
1366
+ const count = this.lexicon.count(form);
1367
+ const score = log(count) - cost.marks;
1368
+ const formValid = this.morphology !== undefined && this.isRealWord(form);
1369
+ if (count > 0 && (!strict || score - typedScore >= override)) {
1370
+ const suffixOnlyApostrophe = hasApostrophe && typedCount === 0 && !strict && count >= 7 && sameApostropheStem;
1371
+ let threshold = suffixOnlyApostrophe ? Math.max(1.5, this.settings.threshold.marks - 1.0) : undefined;
1372
+ // In sentences proven to be typed in ASCII Turkish, an invalid lowercase form ("yuku", "super", "dali")
1373
+ // restoring to a valid Turkish word needs less log-frequency gap than in normal marked text.
1374
+ if (threshold === undefined &&
1375
+ !context.textHasMarks &&
1376
+ context.sentenceHasAsciiTurkish &&
1377
+ !realTyped) {
1378
+ if (typed === word && formValid && word.length >= 3 && count >= 10) {
1379
+ threshold = Math.max(0.7, this.settings.threshold.marks - 1.8);
1380
+ }
1381
+ else if (typedCount === 0 && count >= 5 && (!capitalized || !hasApostrophe || sameApostropheStem || this.lexicon.capitalShare(form) >= 0.5)) {
1382
+ // Unseen word in an ASCII-typed Turkish sentence with an attested mark variant ("Gülruh", "Çapari", "Divanı'ndan").
1383
+ threshold = Math.max(1.2, this.settings.threshold.marks - 1.3);
1384
+ }
1385
+ }
1386
+ add(form, "marks", score, typedScore, threshold);
1387
+ // Lowercase-vs-lowercase count comparison when the typed lowercase word's corpus count is dominated by a
1388
+ // capitalized proper name ("egrisi", "dali", "makasi", "avi", "karin").
1389
+ if (!strict && typed === word && this.lexicon.capitalShare(word) >= 0.5 && formValid) {
1390
+ const candLower = Math.round(count * (1 - this.lexicon.capitalShare(form)));
1391
+ if (candLower >= 10) {
1392
+ add(form, "marks", log(candLower) - cost.marks, log(typedLowerCount), threshold);
1393
+ }
1394
+ }
1395
+ if (!context.textHasMarks &&
1396
+ !realTyped &&
1397
+ formValid &&
1398
+ score - typedScore >= (threshold ?? this.settings.threshold.marks)) {
1399
+ strongAsciiMarkHit = true;
1400
+ }
1401
+ }
1402
+ }
1403
+ if (strict)
1404
+ continue;
1405
+ }
1406
+ // A real word is never heuristically particle-split (guarded inside addSplits via formIsReal),
1407
+ // but strongly attested bigram splits (pair >> typedCount, e.g. "ihtimalide" -> "ihtimali de") still apply.
1408
+ const hit = this.addSplits(form, context, markCost, isName, capitalized, add);
1409
+ if (form === word && hit)
1410
+ morphParticleHit = true;
1411
+ if (!form.includes("'")) {
1412
+ if (isName) {
1413
+ this.addApostrophes(form, word, typedCount, typedScore, markCost, false, context.prevIsName ?? false, context.prevCapitalized ?? false, context.prevWord, add);
1414
+ }
1415
+ else if (capitalized && context.atSentenceStart) {
1416
+ this.addApostrophes(form, word, typedCount, typedScore, markCost, true, false, false, undefined, add);
1417
+ }
1418
+ }
1419
+ }
1420
+ // Unique morphologically valid mark restoration for unseen/rare lowercase invalid words ("yukleyince", "ezilmisti", "gidecegiz").
1421
+ if (this.morphology !== undefined &&
1422
+ !capitalized &&
1423
+ !strict &&
1424
+ !realTyped &&
1425
+ !hasApostrophe &&
1426
+ typedCount < 5 &&
1427
+ word.length >= 6 &&
1428
+ variants.length <= 128) {
1429
+ const validVariants = variants.filter((variant) => this.isRealWord(variant));
1430
+ const uniqueThreshold = Math.max(1.5, this.settings.threshold.marks - 1.0);
1431
+ if (validVariants.length === 1) {
1432
+ const only = validVariants[0];
1433
+ const vCount = this.lexicon.count(only);
1434
+ if (vCount > 0) {
1435
+ const score = typedCount === 0 ? Math.max(log(vCount), 2.5) - cost.marks : log(vCount) - cost.marks;
1436
+ add(only, "marks", score, typedScore, uniqueThreshold);
1437
+ }
1438
+ else if (typedCount === 0 &&
1439
+ word.length >= 8 &&
1440
+ !hasTurkishMarks(word) &&
1441
+ this.isSafeUnseenMarkVariant(word, only, context)) {
1442
+ add(only, "marks", 2.5 - cost.marks, typedScore, uniqueThreshold);
1443
+ }
1444
+ }
1445
+ else if (typedCount === 0 && word.length >= 7 && validVariants.length > 1) {
1446
+ // When multiple theoretical morph variants exist ("ısınmadır" vs "ışınmadır", "eşleşmiyorsa" vs "esleşmiyorsa"),
1447
+ // pick the unique one actually attested in the lexicon (count >= 3).
1448
+ const seenValid = validVariants.filter((variant) => this.lexicon.count(variant) >= 3);
1449
+ if (seenValid.length === 1) {
1450
+ const only = seenValid[0];
1451
+ const vCount = this.lexicon.count(only);
1452
+ add(only, "marks", Math.max(log(vCount), 2.5) - cost.marks, typedScore, uniqueThreshold);
1453
+ }
1454
+ }
1455
+ }
1456
+ // Unambiguous internal vowel disharmony inside an apostrophe suffix ("Ukrayna'sinda" -> "Ukrayna'sında").
1457
+ if (hasApostrophe && typedCount === 0 && !strict) {
1458
+ const fixedSuffix = fixDisharmoniousApostropheSuffix(word);
1459
+ if (fixedSuffix) {
1460
+ add(fixedSuffix, "marks", Math.max(log(this.lexicon.count(fixedSuffix)), 3.0) - cost.marks, typedScore, Math.max(1.5, this.settings.threshold.marks - 1.0));
1461
+ }
1462
+ }
1463
+ // Standalone question particle harmony in ASCII-typed sentences ("var mi" -> "var mı", "gördü mu" -> "gördü mü").
1464
+ if (!context.textHasMarks && context.prevWord && !context.prevIsName && context.prevWord.length >= 2) {
1465
+ this.addQuestionHarmony(word, context, typedScore, nextTyped, add);
1466
+ }
1467
+ // All-caps acronyms or mixed-case brands glued to a Turkish suffix ("HEXIMden" -> "HEXIM'den", "ABDde" -> "ABD'de", "MacOSdaki" -> "MacOS'daki").
1468
+ if (typedCount < 10 && !realTyped && !hasApostrophe) {
1469
+ const acronym = matchAcronymApostrophe(typed);
1470
+ if (acronym) {
1471
+ const prefixLower = lowerTr(acronym.prefix);
1472
+ if (this.lexicon.count(prefixLower) < 500 ||
1473
+ this.lexicon.capitalShare(prefixLower) >= 0.5 ||
1474
+ (this.morphology !== undefined && !this.isRealWord(prefixLower))) {
1475
+ add(acronym.withMark, "apostrophe", Math.max(3.5, typedScore + this.settings.threshold.apostrophe + 0.6) - cost.apostrophe, typedScore);
1476
+ }
1477
+ }
1478
+ }
1479
+ // Two-error / compound recoveries for unseen lowercase invalid words:
1480
+ // 1. Question particle + 1-edit slip ("biliyormusunm?" -> "biliyor musun?").
1481
+ // 2. Two glued words with optional missing Turkish marks ("yapmıyorsunanlamadim" -> "yapmıyorsun anlamadım").
1482
+ // Never compete with an already-passing single-word mark restoration ("muzikevinde" -> "müzikevinde").
1483
+ const hasInternalUpper = typed.slice(1) !== word.slice(1);
1484
+ const hasPassingMark = [...found.values()].some((cand) => cand.kind === "marks" && marginOf(cand) >= (cand.threshold ?? this.settings.threshold.marks));
1485
+ if (this.morphology !== undefined &&
1486
+ typedCount === 0 &&
1487
+ !realTyped &&
1488
+ !isName &&
1489
+ !hasApostrophe &&
1490
+ !hasInternalUpper &&
1491
+ !morphParticleHit &&
1492
+ !strongAsciiMarkHit &&
1493
+ !hasPassingMark) {
1494
+ if (word.length >= 6) {
1495
+ this.addQuestionParticleTypoSplits(word, context, typedScore, add);
1496
+ }
1497
+ if (word.length >= 10) {
1498
+ this.addTwoWordGluedSplits(word, typedScore, add);
1499
+ }
1500
+ }
1501
+ // Short 3-letter typo recovery ("bne" -> "ben", "ane" -> "anne") under strict morphology + frequency guards.
1502
+ // Never compete with words that already have a valid Turkish mark variant ("goz" -> "göz", "guc" -> "güç").
1503
+ if (this.morphology !== undefined &&
1504
+ word.length === 3 &&
1505
+ !realTyped &&
1506
+ !isName &&
1507
+ !hasApostrophe &&
1508
+ !hasInternalUpper &&
1509
+ !morphParticleHit &&
1510
+ !strongAsciiMarkHit &&
1511
+ typedCount <= 120 &&
1512
+ (typed === word || (context.atSentenceStart && this.lexicon.capitalShare(word) < 0.5)) &&
1513
+ !variants.some((v) => this.lexicon.exactCount(v) >= 50 && this.isRealWord(v))) {
1514
+ this.addShortWordTypos(word, context, typedCount, typedScore, typedLowerCount, nextTyped, add);
1515
+ }
1516
+ // Slips of the fingers are only considered for rare or unseen words that aren't names.
1517
+ // A rare form that Turkish suffix rules accept is a real word, not a slip ("getirsek" is not "getirmek").
1518
+ // Do not let single-edit typos hijack or tie a morphologically proven particle split ("boyunuda" -> "boyunu da")
1519
+ // or a clear mark restoration in an ASCII-typed sentence ("gecenleri" -> "geçenleri" vs "geceleri").
1520
+ // A lowercase word that Turkish rules reject and that is only seen as a rare misspelling in the corpus ("brada" 13
1521
+ // times, "burada" 33,000) is still a slip: it may be fixed, but only into a word seen 200 times as often.
1522
+ const rareInvalidSlip = this.morphology !== undefined && typed === word && typedCount < 50 && !realTyped && this.lexicon.capitalShare(word) < 0.5;
1523
+ if ((typedCount < knownWord || rareInvalidSlip) &&
1524
+ word.length >= 4 &&
1525
+ !isName &&
1526
+ !hasApostrophe &&
1527
+ !hasInternalUpper &&
1528
+ !realTyped &&
1529
+ !morphParticleHit &&
1530
+ !strongAsciiMarkHit) {
1531
+ // Do not let single-edit typos mangle an unsplit harmonized question particle ("olurmu", "yaparmı", "varmı").
1532
+ const qMatch = /^(.{3,})(m[iıuü](?:y?[iıuü]m|s[iıuü]n|y?[iıuü]z|s[iıuü]n[iıuü]z|d[iıuü]r|d[iıuü]|ym[iıuü]ş|ys[ae]|yd[iıuü]|yken)?)$/.exec(word);
1533
+ const unsplitQuestion = qMatch !== null &&
1534
+ followsHarmony(qMatch[1], qMatch[2][1]) &&
1535
+ sameHighVowels(qMatch[2]) &&
1536
+ this.isRealWord(qMatch[1]) &&
1537
+ this.lexicon.count(qMatch[1]) >= 5;
1538
+ if (!unsplitQuestion) {
1539
+ const unseenLowerInvalid = this.morphology !== undefined && typedCount === 0 && typed === word;
1540
+ const prevIsAcc = unseenLowerInvalid && context.prevWord ? this.isUnambiguousAccusative(context.prevWord) : false;
1541
+ for (const [text, slipCost] of this.oneEdit(word, unseenLowerInvalid)) {
1542
+ let count = this.lexicon.exactCount(text);
1543
+ if (unseenLowerInvalid && this.settings.typoStemShare > 0 && text.length >= 7 && this.isRealWord(text)) {
1544
+ count = Math.max(count, this.stemCount(text) * this.settings.typoStemShare);
1545
+ }
1546
+ const morphValid = this.morphology !== undefined && (count >= 1 ? this.isRealWord(text) : false);
1547
+ // For attested-but-rare valid forms (e.g. "gönderdim" obs=20, "beğendim" obs=24) in long unseen words,
1548
+ // allow a capped morphological prior boost (never boosting consonant->vowel substitutions like "göstermdn"->"göstermen").
1549
+ if (unseenLowerInvalid &&
1550
+ morphValid &&
1551
+ word.length >= 8 &&
1552
+ count >= 10 &&
1553
+ slipCost <= 1.25) {
1554
+ count = Math.max(count, this.effectiveCount(text, "autofix"));
1555
+ }
1556
+ if (count < 1)
1557
+ continue;
1558
+ if (typedCount >= knownWord && (count < 200 * typedCount || !this.isRealWord(text)))
1559
+ continue;
1560
+ // Never rewrite a word into a vowelless interjection/abbreviation ("Hımm" -> "Hmm", "km", "vb").
1561
+ if (!/[aeıioöuüâîû]/.test(text))
1562
+ continue;
1563
+ // A lowercase slip shouldn't rewrite into a mostly-capitalized proper name ("krate" -> "kate", "lmre" -> "emre").
1564
+ if (typed === word && this.lexicon.capitalShare(text) >= 0.6)
1565
+ continue;
1566
+ const morphPenalty = this.morphology !== undefined && !morphValid ? 1.5 : 0;
1567
+ const voicePenalty = prevIsAcc && morphValid && this.isPurelyPassiveVerb(text) ? 1.4 : 0;
1568
+ // For long unseen lowercase invalid words, a morphologically valid high-confidence keyboard edit
1569
+ // (swap, near-key sub/extra, or missed key) needs less frequency evidence ("gönderdim", "yoğunluklarında").
1570
+ let threshold;
1571
+ if (unseenLowerInvalid && morphValid && word.length >= 7 && slipCost <= 1.25 && count >= 20) {
1572
+ threshold = 0.6;
1573
+ }
1574
+ add(text, "typo", log(count) - cost.typo - slipCost - morphPenalty - voicePenalty, typedScore, threshold, slipCost);
1575
+ }
1576
+ // Principled generative-prior + mark-loss-plus-1-edit recovery for long unseen lowercase invalid words
1577
+ // ("duzenblemiyor" -> "düzenlemiyor", "kullandğımda" -> "kullandığımda", "puanlrım" -> "puanlarım").
1578
+ // Only fires when 1-edit lexicon search didn't already find a passing fix; strictly requires length >= 8,
1579
+ // non-substitution edit when combining with mark restoration (prevents "suhenin" -> "şubenin"), and capped prior
1580
+ // (prevents zero-count rare verb forms like "gerektin" from hijacking double omissions like "gerektn").
1581
+ if (unseenLowerInvalid && word.length >= 8 && this.morphology?.fuzzySearch) {
1582
+ const hasPassing1 = [...found.values()].some((cand) => marginOf(cand) >= (cand.threshold ?? this.settings.threshold[cand.kind]));
1583
+ if (!hasPassing1) {
1584
+ for (const f of this.morphology.fuzzySearch(word, 1, 15)) {
1585
+ if (f.editCost > 1.25)
1586
+ continue;
1587
+ if (this.lexicon.capitalShare(f.word) >= 0.6)
1588
+ continue;
1589
+ // If restoring Turkish marks AND editing a char, require length >= 9 and length change or transposition
1590
+ // (blocks 2-consonant substitutions like "suhenin" -> "şubenin" while keeping "duzenblemiyor" -> "düzenlemiyor").
1591
+ const marksChanged = foldTr(f.word) !== f.word && foldTr(word) !== f.word && f.word.length === word.length;
1592
+ if (marksChanged && f.editCost > 1.1)
1593
+ continue;
1594
+ const eff = this.effectiveCount(f.word, "autofix");
1595
+ if (eff < 20)
1596
+ continue;
1597
+ const voicePenalty = prevIsAcc && this.isPurelyPassiveVerb(f.word) ? 1.4 : 0;
1598
+ const threshold = word.length >= 9 && eff >= 28 ? 0.6 : 1.5;
1599
+ add(f.word, "typo", log(eff) - cost.typo - f.editCost - voicePenalty, typedScore, threshold, f.editCost);
1600
+ }
1601
+ }
1602
+ }
1603
+ // Cautious 2-vowel-drop recovery ("gelyorm" -> "geliyorum", "çalışıyrm" -> "çalışıyorum") when 1-edit finds nothing strong.
1604
+ if (unseenLowerInvalid && word.length >= 6) {
1605
+ const hasPassing = [...found.values()].some((cand) => marginOf(cand) >= (cand.threshold ?? this.settings.threshold[cand.kind]));
1606
+ if (!hasPassing) {
1607
+ this.addDoubleVowelDrops(word, typedScore, add);
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+ return [...found.values()];
1613
+ }
1614
+ /** Strict 3-letter typo recovery ("bne" -> "ben", "ane" -> "anne"): requires invalid stem, valid very frequent target. */
1615
+ addShortWordTypos(word, context, typedCount, typedScore, typedLowerCount, nextTyped, add) {
1616
+ const nextLower = nextTyped && !isAllUpper(nextTyped) ? lowerTr(nextTyped) : undefined;
1617
+ // Protect attested foreign/phrase tokens ("van der", "de la", "los angeles").
1618
+ if (context.prevWord && this.lexicon.pair(context.prevWord, word) > 0)
1619
+ return;
1620
+ if (nextLower && this.lexicon.pair(word, nextLower) > 0)
1621
+ return;
1622
+ const edits = new Map();
1623
+ const put = (cand, slip) => {
1624
+ if (cand !== word && (edits.get(cand) ?? Infinity) > slip)
1625
+ edits.set(cand, slip);
1626
+ };
1627
+ // Adjacent swaps ("bne" -> "ben")
1628
+ const swaps = new Set([word[1] + word[0] + word[2], word[0] + word[2] + word[1]]);
1629
+ for (const swap of swaps)
1630
+ put(swap, 0.7);
1631
+ // Single letter insertions (doubled consonant like "ane" -> "anne" is cheapest; leading insert heavily penalized)
1632
+ for (let i = 0; i <= word.length; i++) {
1633
+ const before = word.slice(0, i);
1634
+ const after = word.slice(i);
1635
+ const prev = word[i - 1];
1636
+ const at = word[i];
1637
+ for (const letter of ALPHABET) {
1638
+ const isDouble = letter === prev || letter === at;
1639
+ const slip = i === 0 ? (isDouble ? 1.8 : 2.3) : isDouble ? 0.8 : 1.2;
1640
+ put(before + letter + after, slip);
1641
+ }
1642
+ }
1643
+ // Near-key substitutions only for completely unseen 3-letter words ("bwn" -> "ben", "vqr" -> "var")
1644
+ if (typedCount === 0) {
1645
+ for (let i = 0; i < word.length; i++) {
1646
+ const at = word[i];
1647
+ for (const letter of ALPHABET) {
1648
+ if (letter !== at && areNearKeys(letter, at)) {
1649
+ put(word.slice(0, i) + letter + word.slice(i + 1), i === 0 ? 2.0 : 1.0);
1650
+ }
1651
+ }
1652
+ }
1653
+ }
1654
+ const { cost } = this.settings;
1655
+ const base = Math.min(typedScore, log(typedLowerCount));
1656
+ for (const [cand, slip] of edits) {
1657
+ const count = this.lexicon.exactCount(cand);
1658
+ // A swap is the commonest 3-letter slip ("bka" -> "bak"): it needs less frequency evidence than an insertion.
1659
+ const minCount = swaps.has(cand) ? Math.min(1500, this.settings.shortSwapMinCount) : 1500;
1660
+ const ratio = swaps.has(cand) && this.settings.shortSwapMinCount < 1500 ? 20 : 50;
1661
+ if (count < minCount || count < typedCount * ratio)
1662
+ continue;
1663
+ if (this.lexicon.capitalShare(cand) >= 0.5 || !this.isRealWord(cand))
1664
+ continue;
1665
+ const pairBonus = (context.prevWord && this.lexicon.pair(context.prevWord, cand) > 0) ||
1666
+ (nextLower && this.lexicon.pair(cand, nextLower) > 0)
1667
+ ? 0.8
1668
+ : 0;
1669
+ add(cand, "typo", log(count) - cost.typo - slip + pairBonus, base, 1.5);
1670
+ }
1671
+ }
1672
+ /** Recovers glued question particles with a 1-edit slip ("biliyormusunm?" -> "biliyor musun?"). */
1673
+ addQuestionParticleTypoSplits(word, context, typedScore, add) {
1674
+ const { cost } = this.settings;
1675
+ for (let cut = 3; cut <= word.length - 3; cut++) {
1676
+ const first = word.slice(0, cut);
1677
+ const second = word.slice(cut);
1678
+ if (second[0] !== "m" || second.length < 3 || second.length > 10 || QUESTION.test(second))
1679
+ continue;
1680
+ const firstCount = this.lexicon.exactCount(first);
1681
+ if (firstCount < 10 || this.lexicon.capitalShare(first) >= 0.5 || !this.isRealWord(first))
1682
+ continue;
1683
+ // Direct 1-edit candidates on the question particle (without word-final suffix-deletion penalties).
1684
+ const qEdits = new Map();
1685
+ const putQ = (cand, slip) => {
1686
+ if (cand.length >= 2 && (qEdits.get(cand) ?? Infinity) > slip)
1687
+ qEdits.set(cand, slip);
1688
+ };
1689
+ for (let i = 1; i < second.length; i++) {
1690
+ const at = second[i];
1691
+ const prev = second[i - 1];
1692
+ const next = second[i + 1];
1693
+ const nearExtra = (prev !== undefined && (at === prev || areNearKeys(at, prev))) ||
1694
+ (next !== undefined && (at === next || areNearKeys(at, next)));
1695
+ if (nearExtra)
1696
+ putQ(second.slice(0, i) + second.slice(i + 1), 0.9);
1697
+ if (next !== undefined)
1698
+ putQ(second.slice(0, i) + next + at + second.slice(i + 2), 0.7);
1699
+ for (const ch of "ıiuümnsyzdrke") {
1700
+ if (ch !== at && areNearKeys(ch, at))
1701
+ putQ(second.slice(0, i) + ch + second.slice(i + 1), 0.9);
1702
+ putQ(second.slice(0, i) + ch + second.slice(i), 1.0);
1703
+ }
1704
+ }
1705
+ for (const [cand, slip] of qEdits) {
1706
+ const checks = [cand];
1707
+ if (!context.textHasMarks && !hasTurkishMarks(cand)) {
1708
+ for (const v of markVariants(cand, 16))
1709
+ checks.push(v);
1710
+ }
1711
+ for (const q of checks) {
1712
+ if (QUESTION.test(q) &&
1713
+ sameHighVowels(q) &&
1714
+ followsHarmony(first, q[1]) &&
1715
+ (context.questionAhead || q.length >= 4)) {
1716
+ const markPen = q === cand ? 0 : cost.marks;
1717
+ add(`${first} ${q}`, "split", log(firstCount) - cost.split - slip - markPen, typedScore, 2.5);
1718
+ }
1719
+ }
1720
+ }
1721
+ }
1722
+ }
1723
+ /** Resolves one half of a long glued two-word error (optionally restoring missing Turkish marks). */
1724
+ resolveGluedPart(part) {
1725
+ if (part.length < 4)
1726
+ return null;
1727
+ if (this.isRealWord(part)) {
1728
+ const count = this.lexicon.exactCount(part);
1729
+ if (count >= 100 && this.lexicon.capitalShare(part) < 0.45) {
1730
+ return { text: part, count, marked: false };
1731
+ }
1732
+ }
1733
+ let best = null;
1734
+ let secondBest = 0;
1735
+ for (const v of markVariants(part, 128)) {
1736
+ const c = this.lexicon.exactCount(v);
1737
+ if (c < 100 || this.lexicon.capitalShare(v) >= 0.45 || !this.isRealWord(v))
1738
+ continue;
1739
+ if (!best || c > best.count) {
1740
+ if (best)
1741
+ secondBest = Math.max(secondBest, best.count);
1742
+ best = { text: v, count: c };
1743
+ }
1744
+ else {
1745
+ secondBest = Math.max(secondBest, c);
1746
+ }
1747
+ }
1748
+ if (best && (secondBest === 0 || best.count >= secondBest * 10)) {
1749
+ return { text: best.text, count: best.count, marked: true };
1750
+ }
1751
+ return null;
1752
+ }
1753
+ /** Splits two glued words (even with missing Turkish marks: "yapmıyorsunanlamadim" -> "yapmıyorsun anlamadım"). */
1754
+ addTwoWordGluedSplits(word, typedScore, add) {
1755
+ const { cost } = this.settings;
1756
+ for (let cut = 4; cut <= word.length - 4; cut++) {
1757
+ // A doubled tail is a repeated suffix ("değil-dirdir"), not a second word ("dırdır").
1758
+ const tail = word.slice(cut);
1759
+ if (tail.length % 2 === 0 && tail.slice(0, tail.length / 2) === tail.slice(tail.length / 2))
1760
+ continue;
1761
+ const left = this.resolveGluedPart(word.slice(0, cut));
1762
+ if (!left)
1763
+ continue;
1764
+ const right = this.resolveGluedPart(word.slice(cut));
1765
+ if (!right)
1766
+ continue;
1767
+ // Require a finite verb on either side (never forms an OOV noun compound) or an attested bigram.
1768
+ if (!this.isFiniteVerb(left.text) && !this.isFiniteVerb(right.text) && this.lexicon.pair(left.text, right.text) < 5) {
1769
+ continue;
1770
+ }
1771
+ const markPen = (left.marked ? cost.marks : 0) + (right.marked ? cost.marks : 0);
1772
+ const score = Math.min(log(left.count), log(right.count)) - cost.split - markPen - 0.8;
1773
+ add(`${left.text} ${right.text}`, "split", score, typedScore, 2.5);
1774
+ }
1775
+ }
1776
+ /** Cautious 2-vowel-drop recovery between consonant clusters ("gelyorm" -> "geliyorum", "çalışıyrm" -> "çalışıyorum"). */
1777
+ addDoubleVowelDrops(word, typedScore, add) {
1778
+ const gaps = [];
1779
+ for (let i = 1; i < word.length; i++) {
1780
+ if (!VOWELS.has(word[i - 1]) && !VOWELS.has(word[i]))
1781
+ gaps.push(i);
1782
+ }
1783
+ if (gaps.length < 2 || gaps.length > 5)
1784
+ return;
1785
+ const vowels = ["a", "e", "ı", "i", "o", "u", "ü"];
1786
+ const { cost } = this.settings;
1787
+ for (let a = 0; a < gaps.length; a++) {
1788
+ const p1 = gaps[a];
1789
+ for (let b = a + 1; b < gaps.length; b++) {
1790
+ const p2 = gaps[b];
1791
+ const s0 = word.slice(0, p1);
1792
+ const s1 = word.slice(p1, p2);
1793
+ const s2 = word.slice(p2);
1794
+ for (const v1 of vowels) {
1795
+ for (const v2 of vowels) {
1796
+ const cand = s0 + v1 + s1 + v2 + s2;
1797
+ const count = this.lexicon.exactCount(cand);
1798
+ if (count < 50 || this.lexicon.capitalShare(cand) >= 0.5 || !this.isRealWord(cand))
1799
+ continue;
1800
+ add(cand, "typo", log(count) - cost.typo - 0.8, typedScore, 1.5, 0.8);
1801
+ }
1802
+ }
1803
+ }
1804
+ }
1805
+ }
1806
+ /** Restores "mi/mu/misin/..." marks from the preceding word's vowels in ASCII-typed sentences. */
1807
+ addQuestionHarmony(word, context, typedScore, nextTyped, add) {
1808
+ const prev = context.prevWord;
1809
+ if (!prev || MUSIC_NOTES.has(prev) || !QUESTION.test(word))
1810
+ return;
1811
+ if (nextTyped && MUSIC_AFTER.has(lowerTr(nextTyped)))
1812
+ return;
1813
+ const prevValid = this.morphology !== undefined ? this.isRealWord(prev) : this.lexicon.count(prev) >= 5;
1814
+ if (!prevValid || this.lexicon.capitalShare(prev) >= 0.55)
1815
+ return;
1816
+ const frontLoc = this.hasFrontLocative(prev);
1817
+ const backLoc = this.hasBackLocative(prev);
1818
+ if (frontLoc && backLoc)
1819
+ return;
1820
+ const lexFront = this.lexicon.count(prev + "de") + this.lexicon.count(prev + "te");
1821
+ const lexBack = this.lexicon.count(prev + "da") + this.lexicon.count(prev + "ta");
1822
+ const isInverse = frontLoc || (this.morphology === undefined && lexFront >= 3 && lexFront > lexBack);
1823
+ const target = harmonizeQuestionParticle(word, prev, isInverse);
1824
+ if (!target)
1825
+ return;
1826
+ const typedPair = this.lexicon.pair(prev, word);
1827
+ const targetPair = this.lexicon.pair(prev, target);
1828
+ if (typedPair > 0 && typedPair >= targetPair)
1829
+ return;
1830
+ const hasClue = context.questionAhead || QUESTION.exec(word)?.[2] !== undefined || targetPair > 0;
1831
+ if (!hasClue)
1832
+ return;
1833
+ add(target, "marks", typedScore + Math.max(this.settings.threshold.marks, 3.0), typedScore);
1834
+ }
1835
+ /** "birsey" -> "bir şey" from how often the pair is seen; "geldinmi", "arenasıda", "diyorki" from grammar and stem. */
1836
+ addSplits(form, context, markCost, isName, capitalized, add) {
1837
+ const { cost } = this.settings;
1838
+ const glued = this.lexicon.count(form);
1839
+ const formIsReal = this.morphology !== undefined && this.isRealWord(form);
1840
+ const isProperAtStart = capitalized && this.lexicon.capitalShare(form) >= 0.5;
1841
+ let morphParticleHit = false;
1842
+ for (let cut = 2; cut <= form.length - 2; cut++) {
1843
+ const first = form.slice(0, cut);
1844
+ const second = form.slice(cut);
1845
+ if (second.includes("'") || NEVER_ALONE.has(second))
1846
+ continue;
1847
+ const pair = this.lexicon.pair(first, second);
1848
+ const foreignProperSplit = isName && this.morphology !== undefined && (!this.isRealWord(first) || !this.isRealWord(second));
1849
+ if (pair > 0 && !foreignProperSplit)
1850
+ add(`${first} ${second}`, "split", log(pair) - cost.split - markCost);
1851
+ // Glued particles after an apostrophe-inflected proper name ("Çin'dirki", "Ankara'dada", "İstanbul'damı?").
1852
+ if (first.includes("'")) {
1853
+ if (glued === 0 && !formIsReal && this.lexicon.count(first) > 0) {
1854
+ const quoteIdx = first.indexOf("'");
1855
+ const suf = first.slice(quoteIdx + 1);
1856
+ if (second === "ki" && /^(?:[dt][ıiuü]r|y?d[ıiuü])$/.test(suf)) {
1857
+ add(`${first} ${second}`, "split", Math.max(log(this.lexicon.count(first)), 3.2) - cost.split - markCost);
1858
+ }
1859
+ else if (ALSO.test(second) &&
1860
+ followsHarmony(first, second[1]) &&
1861
+ /^(?:[dt][ae]n?|n[ıiuü]n|y[aeıiuü]|y?l[ae])$/.test(suf)) {
1862
+ add(`${first} ${second}`, "split", Math.max(log(this.lexicon.count(first)), 3.2) - cost.split - markCost);
1863
+ }
1864
+ else {
1865
+ const q = QUESTION.exec(second);
1866
+ if (q && followsHarmony(first, q[1][1]) && sameHighVowels(second) && (context.questionAhead || q[2] !== undefined)) {
1867
+ add(`${first} ${second}`, "split", Math.max(log(this.lexicon.count(first)), 3.2) - cost.split - markCost);
1868
+ }
1869
+ }
1870
+ }
1871
+ continue;
1872
+ }
1873
+ // TDK rule: Noun + etmek compound verbs without sound drop/doubling are always written separate
1874
+ // ("farkettim" -> "fark ettim", "terketti" -> "terk etti", "kabuledildi" -> "kabul edildi", "devamediyor" -> "devam ediyor").
1875
+ // Guarded by !formIsReal (so genuine joined verbs like "affettim", "hissettim", "kaybettim" are never touched).
1876
+ if (!formIsReal &&
1877
+ !isName &&
1878
+ !isProperAtStart &&
1879
+ this.morphology !== undefined &&
1880
+ (second.startsWith("et") || second.startsWith("ed")) &&
1881
+ !JOINED_ETMEK_STEMS.has(first) &&
1882
+ ((second.length >= 4 && (first.length >= 4 || SEPARATE_ETMEK_SHORT.has(first))) ||
1883
+ (second === "et" && SEPARATE_ETMEK_BARE_IMPERATIVE.has(first))) &&
1884
+ this.lexicon.count(first) >= 50 &&
1885
+ this.lexicon.capitalShare(first) < 0.5 &&
1886
+ this.isBareNominalRoot(first) &&
1887
+ this.isVerbFormOf(second, "et")) {
1888
+ const base = log(glued);
1889
+ const targetScore = Math.max(log(this.lexicon.count(first)), base + this.settings.threshold.split + cost.split + 0.1);
1890
+ add(`${first} ${second}`, "split", targetScore - cost.split - markCost, base);
1891
+ morphParticleHit = true;
1892
+ continue;
1893
+ }
1894
+ // A morphologically valid word ("giyside", "güveninde", "kitabımı", "evdeki") is never particle-split.
1895
+ if (formIsReal || glued >= this.settings.knownMarked || first.length < 3)
1896
+ continue;
1897
+ const stem = this.lexicon.count(first);
1898
+ const morphProven = this.morphology !== undefined && this.isRealWord(first);
1899
+ const question = QUESTION.exec(second);
1900
+ if (question && followsHarmony(first, question[1][1]) && sameHighVowels(second)) {
1901
+ const hasQuestionClue = context.questionAhead || question[2] !== undefined;
1902
+ if (hasQuestionClue) {
1903
+ if (morphProven &&
1904
+ (stem > 0 || first.length >= 6) &&
1905
+ (!isName || this.lexicon.capitalShare(first) < 0.5) &&
1906
+ !isProperAtStart) {
1907
+ const score = (glued === 0 ? Math.max(log(stem), 3.2) : log(stem)) - cost.split - markCost;
1908
+ add(`${first} ${second}`, "split", score);
1909
+ if (first.length >= 4)
1910
+ morphParticleHit = true;
1911
+ }
1912
+ else if (stem > 0 && !isName) {
1913
+ add(`${first} ${second}`, "split", log(stem) - cost.split - markCost - 1);
1914
+ }
1915
+ }
1916
+ else if (morphProven &&
1917
+ !isName &&
1918
+ !isProperAtStart &&
1919
+ first.length >= 4 &&
1920
+ glued < this.settings.knownWord &&
1921
+ stem > 0 &&
1922
+ this.lexicon.capitalShare(first) < 0.5) {
1923
+ add(`${first} ${second}`, "split", log(stem) - cost.split - markCost);
1924
+ morphParticleHit = true;
1925
+ }
1926
+ continue;
1927
+ }
1928
+ if (ALSO.test(second) && followsHarmony(first, second[1]) && !isName && !isProperAtStart) {
1929
+ if (capitalized && this.isDerivedLanguageStem(first))
1930
+ continue;
1931
+ const voicingTypo = this.morphology !== undefined &&
1932
+ isVoicelessFinal(first) &&
1933
+ this.isRealWord(first + (second === "de" ? "te" : "ta"));
1934
+ const inverseHarmonyTypo = this.morphology !== undefined &&
1935
+ second === "da" &&
1936
+ this.hasFrontLocative(first);
1937
+ const collapsed = collapsedDoubledLocative(first, second);
1938
+ const doubledLocativeTypo = collapsed !== null &&
1939
+ this.lexicon.count(collapsed) >= 20 &&
1940
+ this.lexicon.count(collapsed) >= Math.max(stem, 1) * 10 &&
1941
+ (this.morphology === undefined || this.isRealWord(collapsed));
1942
+ if (voicingTypo || inverseHarmonyTypo || doubledLocativeTypo)
1943
+ continue;
1944
+ if (morphProven && (stem > 0 || first.length >= 6)) {
1945
+ const score = (glued === 0 ? Math.max(log(stem), 3.2) : log(stem)) - cost.split - markCost;
1946
+ // Morphologically impossible verb/conditional + de/da glues ("üzülsede", "istemesede") with low corpus noise.
1947
+ const impossibleVerbGlue = glued > 0 &&
1948
+ glued < this.settings.knownMarked &&
1949
+ ((pair >= 5 && pair >= glued * 3) || (stem >= glued * 4 && /(?:s[ae]|yor|m[ıiuü]ş|[ae]c[ae]k)$/.test(first)));
1950
+ const threshold = impossibleVerbGlue ? Math.max(0.7, this.settings.threshold.split - 1.8) : undefined;
1951
+ add(`${first} ${second}`, "split", score, undefined, threshold);
1952
+ if (first.length >= 4)
1953
+ morphParticleHit = true;
1954
+ }
1955
+ else if ((stem > 0 && NO_LOCATIVE_AFTER.test(first)) || (this.morphology !== undefined && glued === 0 && first.length >= 8 && /l[ae]r[ıi]$/.test(first))) {
1956
+ const score = this.morphology !== undefined &&
1957
+ glued === 0 &&
1958
+ ((stem >= 3 && STRONG_NO_LOCATIVE_AFTER.test(first)) || (first.length >= 8 && /l[ae]r[ıi]$/.test(first)))
1959
+ ? Math.max(log(stem), 3.2) - cost.split - markCost
1960
+ : log(stem) - cost.split - markCost - 1;
1961
+ add(`${first} ${second}`, "split", score);
1962
+ }
1963
+ continue;
1964
+ }
1965
+ if (second === "ki" && first.length >= 4 && !isName && !isProperAtStart) {
1966
+ if (morphProven && (stem > 0 || first.length >= 6)) {
1967
+ const score = (glued === 0 ? Math.max(log(stem), 3.2) : log(stem)) - cost.split - markCost;
1968
+ add(`${first} ${second}`, "split", score);
1969
+ morphParticleHit = true;
1970
+ }
1971
+ else if (stem > 0 && FINITE.test(first)) {
1972
+ add(`${first} ${second}`, "split", log(stem) - cost.split - markCost - 1);
1973
+ }
1974
+ }
1975
+ }
1976
+ return morphParticleHit;
1977
+ }
1978
+ /** "Ankaraya" -> "Ankara'ya" when the form is seen, or when "ankara" is a name and "ya" a suffix that takes one. */
1979
+ addApostrophes(form, word, typedCount, typedScore, markCost, atSentenceStart, prevIsName, prevCapitalized, prevWord, add) {
1980
+ const { cost, minName } = this.settings;
1981
+ const hasMorph = this.morphology !== undefined;
1982
+ const formCount = form === word ? typedCount : this.lexicon.count(form);
1983
+ const typedCaps = Math.round(typedCount * this.lexicon.capitalShare(word));
1984
+ const realWord = this.isRealWord(word);
1985
+ for (let cut = 2; cut < form.length; cut++) {
1986
+ const stem = form.slice(0, cut);
1987
+ const suffix = form.slice(cut);
1988
+ const withMark = `${stem}'${suffix}`;
1989
+ const seen = this.lexicon.count(withMark);
1990
+ const placeHead = !atSentenceStart && prevCapitalized && isPlaceApostropheHead(stem, prevWord);
1991
+ let blockedCached;
1992
+ const isBlocked = () => (blockedCached ??=
1993
+ this.isBlockedApostropheStem(stem, placeHead) ||
1994
+ (!placeHead && this.isInflectedApostropheStem(stem)));
1995
+ // TDK geographic/place/state P3sg head words preceded by a capitalized name ("Marmara Denizi'nin",
1996
+ // "Türkiye Cumhuriyeti'nin", "Kadıköy Mahallesi'nde", "Büyük Okyanus'ta", "Osmanlı Devleti'nin").
1997
+ // Institution head words ("Üniversitesi", "Partisi", "Kurumu") are excluded from PLACE_APOSTROPHE_HEADS.
1998
+ if (placeHead && markCost === 0 && suffix === word.slice(cut) && isValidPlaceApostrophe(stem, suffix)) {
1999
+ const markCap = seen > 0 ? this.lexicon.capitalShare(withMark) : 0;
2000
+ const seenCaps = Math.round(seen * markCap);
2001
+ if (seen >= 5 && markCap >= 0.65 && seenCaps >= typedCaps * 3) {
2002
+ add(withMark, "apostrophe", Math.max(log(seenCaps), log(typedCaps) + this.settings.threshold.apostrophe + 0.5) - cost.apostrophe, log(typedCaps), Math.max(1.5, this.settings.threshold.apostrophe - 1.0));
2003
+ continue;
2004
+ }
2005
+ if (seen === 0 && typedCaps === 0) {
2006
+ add(withMark, "apostrophe", this.settings.threshold.apostrophe + 0.5, 0);
2007
+ continue;
2008
+ }
2009
+ }
2010
+ if (seen > 0) {
2011
+ const markCap = this.lexicon.capitalShare(withMark);
2012
+ const stemCap = this.lexicon.capitalShare(stem);
2013
+ if (atSentenceStart) {
2014
+ if (markCap >= 0.7 &&
2015
+ stemCap >= 0.55 &&
2016
+ !TIME_NAMES_NO_START_APOSTROPHE.has(stem) &&
2017
+ !isBlocked()) {
2018
+ add(withMark, "apostrophe", log(seen) - cost.apostrophe - markCost, typedScore);
2019
+ }
2020
+ continue;
2021
+ }
2022
+ // Do not inject an apostrophe onto a blocked/inflected stem during mark restoration ("Odullerinde" -> "Ödüllerinde").
2023
+ if (markCost === 0 || !isBlocked()) {
2024
+ let threshold;
2025
+ // Unseen mid-sentence proper name with an attested high-cap apostrophe form ("Discord'u", "Arsenal'ı", "Karaca'dan").
2026
+ if (suffix === word.slice(cut) &&
2027
+ markCap >= 0.8 &&
2028
+ typedCount === 0 &&
2029
+ seen >= 7 &&
2030
+ !isBlocked()) {
2031
+ threshold = Math.max(1.5, this.settings.threshold.apostrophe - 1.0);
2032
+ }
2033
+ else if (!realWord &&
2034
+ suffix === word.slice(cut) &&
2035
+ markCap >= 0.8 &&
2036
+ typedCount > 0 &&
2037
+ typedCount <= 5 &&
2038
+ seen >= 8 &&
2039
+ seen >= typedCount * 4 &&
2040
+ this.lexicon.count(stem) >= 20 &&
2041
+ stemCap >= 0.55 &&
2042
+ !isBlocked()) {
2043
+ // Non-Turkish word with tiny typo count in corpus ("Malatyaspora" 5 vs "Malatyaspor'a" 96, "Hessin" 5 vs 64).
2044
+ threshold = Math.max(1.2, this.settings.threshold.apostrophe - 1.3);
2045
+ }
2046
+ add(withMark, "apostrophe", log(seen) - cost.apostrophe - markCost, typedScore, threshold);
2047
+ }
2048
+ // Mid-sentence, compare capitalized-mid-sentence counts too so a lowercase homograph ("elifin", "ekimde",
2049
+ // "aşilin") does not hide a clear proper-name apostrophe.
2050
+ const seenCaps = Math.round(seen * markCap);
2051
+ if (seenCaps >= 10 && seenCaps / seen >= 0.5 && stemCap >= 0.5 && !isBlocked()) {
2052
+ // Honorific titles after a mid-sentence proper name ("Aclan Bey'in", "Ayşe Hanım'a") take an apostrophe per TDK.
2053
+ const honorificThreshold = prevIsName && HONORIFIC_TITLES.has(stem) ? Math.max(1.2, this.settings.threshold.apostrophe - 1.3) : undefined;
2054
+ add(withMark, "apostrophe", log(seenCaps) - cost.apostrophe - markCost, log(typedCaps), honorificThreshold);
2055
+ }
2056
+ }
2057
+ if (atSentenceStart)
2058
+ continue;
2059
+ // The generic rule applies to unseen forms (or tiny Bloom-only non-word noise when attested) of clear names,
2060
+ // keeping the suffix as typed so a mark variant cannot compete with itself ("Weeknd'in" vs fake "Weeknd'ın").
2061
+ const effectiveUnseen = formCount === 0 || (formCount <= 2 && !realWord && seen >= 7);
2062
+ if (!effectiveUnseen || stem.length < 3 || suffix !== word.slice(cut))
2063
+ continue;
2064
+ const stemCount = this.lexicon.count(stem);
2065
+ if (stemCount < 5 || !isValidGenericApostrophe(stem, suffix, hasMorph) || isBlocked())
2066
+ continue;
2067
+ const share = this.lexicon.capitalShare(stem);
2068
+ if (stemCount >= minName) {
2069
+ if (suffix.length >= 2 && share >= 0.58) {
2070
+ add(withMark, "apostrophe", log(stemCount) - cost.apostrophe - markCost - 0.2, typedScore);
2071
+ }
2072
+ else if (suffix.length === 1 && share >= 0.75) {
2073
+ add(withMark, "apostrophe", log(stemCount) - cost.apostrophe - markCost - 1.2, typedScore);
2074
+ }
2075
+ else if (hasMorph &&
2076
+ !realWord &&
2077
+ !this.isRealWord(stem) &&
2078
+ stem.length >= 4 &&
2079
+ stemCount >= 25 &&
2080
+ share >= 0.2 &&
2081
+ suffix.length >= 3) {
2082
+ // Unseen foreign/brand stem with lower cap share + unambiguous 3+ letter Turkish suffix ("Calypso'dan", "Fonte'nin", "Equestria'daki").
2083
+ add(withMark, "apostrophe", log(stemCount) - cost.apostrophe - markCost - 0.2, typedScore);
2084
+ }
2085
+ }
2086
+ else if (hasMorph &&
2087
+ formCount === 0 &&
2088
+ !realWord &&
2089
+ !this.isRealWord(stem) &&
2090
+ stem.length >= 4 &&
2091
+ share >= 0.55 &&
2092
+ suffix.length >= 2) {
2093
+ // Rare foreign proper name (count 5..19, high cap share) with harmonized 2+ or 3+ letter Turkish suffix
2094
+ // ("Tevet'te", "Salayev'dir", "Tatikios'un", "Morgane'nın", "Tsvangirai'ye").
2095
+ const firstSuffixVowel = [...suffix].find((ch) => "aeıioöuü".includes(ch));
2096
+ if (suffix.length >= 3 || !firstSuffixVowel || followsHarmony(stem, firstSuffixVowel)) {
2097
+ add(withMark, "apostrophe", Math.max(log(stemCount), 3.2) - cost.apostrophe - markCost - 0.2, typedScore);
2098
+ }
2099
+ }
2100
+ }
2101
+ }
2102
+ /** "hiç bir" -> "hiçbir", "oysa ki" -> "oysaki", "ev de" -> "evde", "vaz geçtim" -> "vazgeçtim", "ann e" -> "anne". */
2103
+ joinCandidate(word, next, typed = word, nextIsolated = true) {
2104
+ if (word.includes("'") || next.includes("'"))
2105
+ return null;
2106
+ // Misplaced space inside a single word ("ann e" -> "anne"): requires lowercase first token (protects proper
2107
+ // name "Ann"), at least one morphologically invalid part (protects "ne de", "o da"), and a frequent valid join.
2108
+ if (this.morphology !== undefined && typed === word && nextIsolated && !JOIN_SECOND.has(next) && !QUESTION.test(next)) {
2109
+ const wInvalid = !this.isRealWord(word);
2110
+ const nInvalid = !this.isRealWord(next);
2111
+ if ((wInvalid || (nInvalid && next.length >= 2)) && (next.length >= 2 || wInvalid)) {
2112
+ const joined = word + next;
2113
+ if (joined.length >= 4 && this.lexicon.capitalShare(joined) < 0.5 && this.isRealWord(joined)) {
2114
+ const count = this.lexicon.exactCount(joined);
2115
+ const pair = this.lexicon.pair(word, next);
2116
+ if (count >= 50 && count >= Math.max(pair, 1) * 50) {
2117
+ const wLower = Math.round(this.lexicon.count(word) * (1 - this.lexicon.capitalShare(word)));
2118
+ const nLower = Math.round(this.lexicon.count(next) * (1 - this.lexicon.capitalShare(next)));
2119
+ if ((!wInvalid || wLower * 5 < count) && (!nInvalid || nLower * 5 < count)) {
2120
+ return {
2121
+ text: joined,
2122
+ kind: "join",
2123
+ score: log(count) - this.settings.cost.join,
2124
+ base: log(pair),
2125
+ joinsNext: true,
2126
+ threshold: 2.5,
2127
+ };
2128
+ }
2129
+ }
2130
+ }
2131
+ }
2132
+ }
2133
+ // TDK joined compound verbs across all conjugations ("vaz geçtim" -> "vazgeçtim", "kayıp ettim" -> "kaybettim",
2134
+ // "his ediyorum" -> "hissediyorum", "baş vurdum" -> "başvurdum").
2135
+ const verbRules = COMPOUND_VERB_JOINS.get(word);
2136
+ if (verbRules && this.morphology !== undefined) {
2137
+ for (const rule of verbRules) {
2138
+ const startsAux = next.startsWith(rule.auxStem) || (rule.auxStem === "et" && next.startsWith("ed"));
2139
+ if (!startsAux || !this.isVerbFormOf(next, rule.auxStem))
2140
+ continue;
2141
+ const joined = rule.prefix + next;
2142
+ if (!this.isRealWord(joined))
2143
+ continue;
2144
+ const pair = this.lexicon.pair(word, next);
2145
+ if (rule.strictZeroPair ? pair > 0 : pair > 5)
2146
+ continue;
2147
+ const count = this.lexicon.count(joined);
2148
+ if (count === 0)
2149
+ continue;
2150
+ return {
2151
+ text: joined,
2152
+ kind: "join",
2153
+ score: Math.max(log(count), log(pair) + this.settings.threshold.join + 0.5) - this.settings.cost.join,
2154
+ base: log(pair),
2155
+ joinsNext: true,
2156
+ };
2157
+ }
2158
+ }
2159
+ if (word === "her" && next !== "hangi" && next !== "kes")
2160
+ return null;
2161
+ if (!JOIN_FIRST.has(word) && !JOIN_SECOND.has(next))
2162
+ return null;
2163
+ const joined = word + next;
2164
+ const count = this.lexicon.count(joined);
2165
+ if (count === 0)
2166
+ return null;
2167
+ // Lowercase joins must not accidentally form a proper noun ("bu şehr" -> "buşehr", "o dile" -> "odile").
2168
+ if (this.lexicon.capitalShare(joined) >= 0.5)
2169
+ return null;
2170
+ const isSombahcemi = next === "ki" && SOMBAHCEMI_KI.has(word);
2171
+ // Do not join into a morphologically invalid word ("İkinizin de" -> "İkinizinde", "Her neyse" -> "Herneyse").
2172
+ if (this.morphology !== undefined && this.isRealWord(word) && !this.isRealWord(joined) && !isSombahcemi)
2173
+ return null;
2174
+ if (ALSO.test(next)) {
2175
+ if (isVoicelessFinal(word) || /(?:[ıiuü]n[ıiuü]z|[ıiuü]m[ıiuü]z)[ıiuü]n$/.test(word))
2176
+ return null;
2177
+ if (this.morphology === undefined && !followsHarmony(word, next[1]))
2178
+ return null;
2179
+ }
2180
+ if ((next === "te" || next === "ta") && TE_TA_SKIP.has(word))
2181
+ return null;
2182
+ const pair = this.lexicon.pair(word, next);
2183
+ // "de/da" after a word is far more often the conjunction in everyday writing than a misplaced locative, so
2184
+ // joining it needs a clearer case than other joins.
2185
+ const extra = ALSO.test(next) ? this.settings.deDaJoinCost : 0;
2186
+ let threshold;
2187
+ if (isSombahcemi && pair === 0) {
2188
+ threshold = Math.max(1.0, this.settings.threshold.join - 1.5);
2189
+ }
2190
+ else if (next === "ki" && /[dt][ae]$/.test(word) && pair <= 1 && (this.morphology === undefined || this.isRealWord(joined))) {
2191
+ threshold = Math.max(1.8, this.settings.threshold.join - 0.7);
2192
+ }
2193
+ else if ((next === "te" || next === "ta") && pair === 0 && (this.morphology !== undefined ? this.isRealWord(joined) : isVoicelessFinal(word))) {
2194
+ threshold = Math.max(2.0, this.settings.threshold.join - 0.5);
2195
+ }
2196
+ return {
2197
+ text: joined,
2198
+ kind: "join",
2199
+ score: log(count) - this.settings.cost.join - extra,
2200
+ base: log(pair),
2201
+ joinsNext: true,
2202
+ threshold,
2203
+ };
2204
+ }
2205
+ /** Count of the longest shorter prefix (4+ letters) that is itself a seen real word: "arkadaşlarım" for "arkadaşlarımla". */
2206
+ stemCount(text) {
2207
+ for (let end = text.length - 1; end >= 4; end--) {
2208
+ const stem = text.slice(0, end);
2209
+ const count = this.lexicon.exactCount(stem);
2210
+ if (count > 0 && this.isRealWord(stem))
2211
+ return count;
2212
+ }
2213
+ return 0;
2214
+ }
2215
+ /**
2216
+ * Empirical-Bayes effective frequency combining observed corpus count with the principled morphological
2217
+ * generative prior `C(lemma, pos) * P(morphemes | pos)` so unseen/rare valid inflections ("düzenlemiyor",
2218
+ * "kullandığımda") rank accurately without inflating bizarre stacked derivations.
2219
+ */
2220
+ effectiveCount(cand, mode) {
2221
+ const obs = this.lexicon.exactCount(cand);
2222
+ const prior = this.morphology?.priorCount?.(cand) ?? 0;
2223
+ if (prior <= 0)
2224
+ return obs;
2225
+ if (mode === "rank") {
2226
+ const priorEst = 0.65 * Math.pow(prior, 0.78);
2227
+ return Math.max(obs, priorEst) + Math.min(obs, priorEst) * 0.25;
2228
+ }
2229
+ // Cap unseen-form prior in auto-fix so a corpus-absent inflection ("gerektin") cannot pretend to
2230
+ // have count 3,000, while strong unseen forms ("düzenlemiyor", "kullandığımda") still pass cleanly.
2231
+ const rawPrior = 0.5 * Math.pow(prior, 0.82);
2232
+ const cappedPrior = obs === 0 ? Math.min(45, rawPrior) : Math.min(120, rawPrior);
2233
+ return Math.max(obs, cappedPrior);
2234
+ }
2235
+ /** True when every morphological reading of `word` is accusative ("hatalarını", "arabayı", "kitabını"). */
2236
+ isUnambiguousAccusative(word) {
2237
+ const analyses = this.morphology?.analyze?.(word);
2238
+ if (!analyses || analyses.length === 0)
2239
+ return false;
2240
+ return analyses.every((a) => a.morphemes.includes("Acc"));
2241
+ }
2242
+ /** True when every finite verb reading of `word` is passive or intransitive -lAn ("düzenleniyor"). */
2243
+ isPurelyPassiveVerb(word) {
2244
+ const analyses = this.morphology?.analyze?.(word);
2245
+ if (!analyses || analyses.length === 0)
2246
+ return false;
2247
+ const finite = analyses.filter((a) => a.pos === "Verb" || a.morphemes.some((m) => FINITE_VERB_MORPHEMES.has(m)));
2248
+ if (finite.length === 0)
2249
+ return false;
2250
+ return finite.every((a) => a.morphemes.includes("Pass") || a.morphemes.includes("Acquire"));
2251
+ }
2252
+ /**
2253
+ * True when `word` is a productive, harmonized nominal inflection of a corpus-attested noun/loanword
2254
+ * root missing from Zemberek's static dictionary (e.g. "özgeçmişimi" = "özgeçmiş"+"imi", "tripodlar" = "tripod"+"lar").
2255
+ * Never activates for roots Zemberek already knows, so real Turkish root typos are never shielded.
2256
+ */
2257
+ isAttestedOovInflection(word) {
2258
+ if (this.morphology === undefined || word.length < 6)
2259
+ return false;
2260
+ for (let cut = word.length - 1; cut >= 4; cut--) {
2261
+ const root = word.slice(0, cut);
2262
+ const suffix = word.slice(cut);
2263
+ if (!OOV_NOMINAL_SUFFIX.test(suffix))
2264
+ continue;
2265
+ if (this.lexicon.exactCount(root) < 12 || this.lexicon.capitalShare(root) >= 0.5)
2266
+ continue;
2267
+ if (this.isRealWord(root))
2268
+ continue;
2269
+ // Check consonant assimilation & vowel harmony on suffix boundary.
2270
+ if (suffix.startsWith("d") && isVoicelessFinal(root))
2271
+ continue;
2272
+ if (suffix.startsWith("t") && !isVoicelessFinal(root))
2273
+ continue;
2274
+ const firstSuffixVowel = [...suffix].find((ch) => VOWELS.has(ch));
2275
+ if (firstSuffixVowel && !followsHarmony(root, firstSuffixVowel))
2276
+ continue;
2277
+ // Also verify internal suffix vowels harmonize with each other (except invariant -ki).
2278
+ const checkCore = suffix.endsWith("ki") ? suffix.slice(0, -2) : suffix;
2279
+ let prevV = root;
2280
+ let harmOk = true;
2281
+ for (let i = 0; i < checkCore.length; i++) {
2282
+ const ch = checkCore[i];
2283
+ if (VOWELS.has(ch)) {
2284
+ if (!followsHarmony(prevV, ch)) {
2285
+ harmOk = false;
2286
+ break;
2287
+ }
2288
+ prevV = ch;
2289
+ }
2290
+ }
2291
+ if (harmOk)
2292
+ return true;
2293
+ }
2294
+ return false;
2295
+ }
2296
+ /** Detects whether an untouched token should be flagged, returning the SpellFlag or null. */
2297
+ detectFlag(token, context, nextTyped) {
2298
+ return this.detectFlagDetailed(token, context, nextTyped)?.flag ?? null;
2299
+ }
2300
+ /**
2301
+ * Procedural misspelling detector for words not auto-fixed by `check()`.
2302
+ * Separates `invalid` (rejected by morphology & unseen) from `rare` (rejected by morphology, very rare,
2303
+ * and close to a much stronger valid Turkish word) while protecting proper names, acronyms, foreign/scientific
2304
+ * words, apostrophe forms, contractions, and productive inflections of attested OOV nouns.
2305
+ */
2306
+ detectFlagDetailed(token, context, nextTyped) {
2307
+ const typed = token.text;
2308
+ if (isAllUpper(typed) || typed.length < 2)
2309
+ return null;
2310
+ const word = lowerTr(typed);
2311
+ if (word.includes("'"))
2312
+ return null;
2313
+ // Mixed/internal uppercase ("MacOS", "OpenAI", "HAProxy", "iPhone"): brand/code, not a spelling flag.
2314
+ if (typed.slice(1) !== word.slice(1))
2315
+ return null;
2316
+ const capitalized = isUpperInitial(typed);
2317
+ // Mid-sentence capitalized words are proper names.
2318
+ if (capitalized && !context.atSentenceStart)
2319
+ return null;
2320
+ // Respect contractions: when contractions are off, known contractions stay untouched and unflagged.
2321
+ if (this.knownFix(typed, word, context, nextTyped) === "keep")
2322
+ return null;
2323
+ const hasMorph = this.morphology !== undefined;
2324
+ if (hasMorph && this.isRealWord(word))
2325
+ return null;
2326
+ const typedCount = this.lexicon.count(word);
2327
+ // Common words in the corpus (modern loanwords, proper names, terms missing from Zemberek) are not flagged.
2328
+ if (typedCount >= 50)
2329
+ return null;
2330
+ const capShare = this.lexicon.capitalShare(word);
2331
+ // Capitalized sentence-start words that are mostly capitalized in the corpus are proper names.
2332
+ // Lowercase words whose corpus occurrences are capitalized proper names ("beek" vs "Beek", "sebz" vs "Sebz")
2333
+ // have very low lowercase count and ARE checked as rare typos!
2334
+ if (capitalized && typedCount >= 2 && capShare >= 0.45)
2335
+ return null;
2336
+ const typedLowerCount = Math.round(typedCount * (1 - capShare));
2337
+ // Without morphology, only flag completely unseen lowercase words that have strong lexicon suggestions.
2338
+ if (!hasMorph && (typedCount > 0 || capitalized))
2339
+ return null;
2340
+ const ranked = this.rankedSuggestionsFor(typed, word, context, typedCount, nextTyped);
2341
+ const top = ranked[0];
2342
+ // Protect productive harmonized inflections of attested OOV nouns ("özgeçmişimi", "tripodlar", "stabilitesinden")
2343
+ // unless a very close high-frequency valid Turkish word competes.
2344
+ if (typedCount === 0 && hasMorph && this.isAttestedOovInflection(word)) {
2345
+ const strongComp = top !== undefined && top.morphValid && top.editCost <= 0.85 && top.effCount >= 50;
2346
+ if (!strongComp)
2347
+ return null;
2348
+ }
2349
+ if (typedCount === 0) {
2350
+ // Sentence-start capitalized words (Wikipedia / subtitles) are very often proper names ("Maniwaki", "Ruluka").
2351
+ // Flag them ONLY when there is a plausible valid Turkish candidate (e.g. "Hoxam" -> "Hocam", "Tikım" -> "Takım",
2352
+ // "Maalledek" -> "Mahalledeki"). Allow up to capShare < 0.8 for morph-valid forms of address ("Hocam").
2353
+ if (capitalized) {
2354
+ if (!top)
2355
+ return null;
2356
+ const plausibleAtStart = top.kind === "split" ||
2357
+ top.kind === "apostrophe" ||
2358
+ (top.morphValid &&
2359
+ this.lexicon.capitalShare(top.text) < 0.8 &&
2360
+ ((top.editCost <= 1.2 && top.effCount >= 1) ||
2361
+ (top.editCost <= 1.75 && top.effCount >= 5) ||
2362
+ (top.editCost <= 1.95 && top.effCount >= 50)));
2363
+ if (!plausibleAtStart)
2364
+ return null;
2365
+ }
2366
+ else {
2367
+ // Lowercase unseen word rejected by morphology: suppress foreign/scientific/Latin terms that have NO close
2368
+ // Turkish candidate ("scapiflora", "neurophyllus", "psychoanalytischer", "milicenton", "dârayî").
2369
+ // A word containing Turkish diacritics ("klasöwe" -> "klasöre") or within 1 edit of an attested Turkish word
2370
+ // is kept even when a typo hits q/w/x.
2371
+ const hasCloseTurkish = top !== undefined &&
2372
+ (top.kind === "split" ||
2373
+ top.kind === "marks" ||
2374
+ (top.morphValid &&
2375
+ ((top.editCost <= 1.75 && (top.effCount >= 0.5 || top.obsCount >= 1)) ||
2376
+ (top.editCost <= 1.9 && top.obsCount >= 15 && hasTurkishMarks(word)))));
2377
+ if (!hasCloseTurkish) {
2378
+ if (/[qwxâîû]/.test(word) || FOREIGN_TAXONOMIC_SUFFIX.test(word))
2379
+ return null;
2380
+ if (ranked.length === 0)
2381
+ return null;
2382
+ }
2383
+ }
2384
+ const selected = ranked.slice(0, 5);
2385
+ const suggestions = selected.map((c) => c.display);
2386
+ const meta = [
2387
+ { coreMargin: 0, slipCost: 0, isMarkVariant: false },
2388
+ ...selected.map((c) => ({
2389
+ coreMargin: c.rankScore,
2390
+ slipCost: c.editCost,
2391
+ isMarkVariant: c.isMarkVariant,
2392
+ })),
2393
+ ];
2394
+ return {
2395
+ flag: { start: token.start, end: token.end, original: typed, suggestions, reason: "invalid" },
2396
+ meta,
2397
+ coreScores: selected.map((c) => c.rankScore),
2398
+ };
2399
+ }
2400
+ // Rare-but-seen (0 < typedCount < 50) morph-rejected word: flag as "rare" only when very close to a
2401
+ // much stronger valid Turkish word ("bka" -> "bak", "aşam" -> "akşam", "gedi" -> "geldi", "beek" -> "bebek",
2402
+ // "sebz" -> "sebze", "Afedersiniz" -> "Affedersiniz").
2403
+ if (!top)
2404
+ return null;
2405
+ // Sentence-start capitalized words already seen in the lexicon (e.g. "Yaghi", "Şeyhhasan", "Kilittaşı") are
2406
+ // usually proper names/compounds; only flag them when a massive 1-edit Turkish word dominates ("Afedersiniz").
2407
+ if (capitalized) {
2408
+ const hugeAtStart = top.morphValid &&
2409
+ this.lexicon.capitalShare(top.text) < 0.5 &&
2410
+ top.editCost <= 0.85 &&
2411
+ top.effCount >= Math.max(500, typedCount * 200);
2412
+ if (!hugeAtStart)
2413
+ return null;
2414
+ }
2415
+ else {
2416
+ if (this.lexicon.capitalShare(top.text) >= 0.5)
2417
+ return null;
2418
+ const effectiveTyped = Math.max(typedLowerCount, 1);
2419
+ const isStrongSplit = top.kind === "split" && top.effCount >= Math.max(80, effectiveTyped * 20);
2420
+ const isCloseTypo = ranked.slice(0, 3).some((cand) => cand.morphValid &&
2421
+ this.lexicon.capitalShare(cand.text) < 0.5 &&
2422
+ ((cand.editCost <= 1.25 && cand.effCount >= Math.max(typedCount <= 3 ? 45 : 80, effectiveTyped * 18)) ||
2423
+ (typedCount <= 3 && cand.editCost <= 1.65 && cand.effCount >= 200)));
2424
+ if (!isStrongSplit && !isCloseTypo)
2425
+ return null;
2426
+ }
2427
+ // Protect attested phrase tokens in bigrams ("van der", "de la") from rare flagging.
2428
+ const nextLower = nextTyped && !isAllUpper(nextTyped) ? lowerTr(nextTyped) : undefined;
2429
+ if (typedCount >= 5 && word.length <= 3) {
2430
+ if (context.prevWord && this.lexicon.pair(context.prevWord, word) > 0)
2431
+ return null;
2432
+ if (nextLower && this.lexicon.pair(word, nextLower) > 0)
2433
+ return null;
2434
+ }
2435
+ const selected = ranked.slice(0, 5);
2436
+ const suggestions = selected.map((c) => c.display);
2437
+ const meta = [
2438
+ { coreMargin: 0, slipCost: 0, isMarkVariant: false },
2439
+ ...selected.map((c) => ({
2440
+ coreMargin: c.rankScore,
2441
+ slipCost: c.editCost,
2442
+ isMarkVariant: c.isMarkVariant,
2443
+ })),
2444
+ ];
2445
+ return {
2446
+ flag: { start: token.start, end: token.end, original: typed, suggestions, reason: "rare" },
2447
+ meta,
2448
+ coreScores: selected.map((c) => c.rankScore),
2449
+ };
2450
+ }
2451
+ /**
2452
+ * Builds and ranks up to 5 suggestions for a suspicious word using:
2453
+ * 1. Existing rule candidates (marks, splits, apostrophes, short typos, 1-edit lexicon typos, double vowel drops),
2454
+ * 2. Fast 1-edit mark-folded fuzzy morphological search (catches unseen valid forms + mark-loss + 1 typo),
2455
+ * 3. 2-edit mark-folded fuzzy morphological search when 1-edit doesn't yield strong candidates (double omissions / 2 typos),
2456
+ * 4. Principled scoring with empirical-Bayes morphological prior, Turkish keyboard edit cost, bigram support,
2457
+ * and Turkish accusative-passive case-voice agreement.
2458
+ */
2459
+ rankedSuggestionsFor(typed, word, context, typedCount, nextTyped) {
2460
+ const foldedWord = foldTr(word);
2461
+ const nextLower = nextTyped && !isAllUpper(nextTyped) ? lowerTr(nextTyped) : undefined;
2462
+ const prevIsAcc = context.prevWord ? this.isUnambiguousAccusative(context.prevWord) : false;
2463
+ const pool = new Map();
2464
+ const consider = (candText, kind, editCost, knownMorphValid, foldedEdits = 1) => {
2465
+ if (!candText || candText === word)
2466
+ return;
2467
+ const isMulti = candText.includes(" ");
2468
+ if (!isMulti) {
2469
+ if (!/[aeıioöuüâîû]/.test(candText))
2470
+ return;
2471
+ if (typed === word && this.lexicon.capitalShare(candText) >= 0.65)
2472
+ return;
2473
+ }
2474
+ const existing = pool.get(candText);
2475
+ if (existing && existing.editCost <= editCost) {
2476
+ if (foldedEdits < existing.foldedEdits)
2477
+ existing.foldedEdits = foldedEdits;
2478
+ return;
2479
+ }
2480
+ const morphValid = knownMorphValid ??
2481
+ (isMulti
2482
+ ? candText.split(" ").every((p) => this.isRealWord(p) || QUESTION.test(p) || ALSO.test(p) || p === "ki")
2483
+ : this.morphology !== undefined && this.isRealWord(candText));
2484
+ let obsCount;
2485
+ let effCount;
2486
+ if (isMulti) {
2487
+ const [p1, p2] = candText.split(" ");
2488
+ const pairC = this.lexicon.pair(p1, p2);
2489
+ const minC = Math.min(this.lexicon.exactCount(p1), this.lexicon.exactCount(p2));
2490
+ obsCount = Math.max(pairC, minC);
2491
+ effCount = Math.max(pairC, Math.min(this.effectiveCount(p1, "rank"), Math.max(this.lexicon.count(p2), 50)));
2492
+ }
2493
+ else {
2494
+ obsCount = this.lexicon.exactCount(candText);
2495
+ effCount = morphValid ? this.effectiveCount(candText, "rank") : obsCount;
2496
+ }
2497
+ // Require either corpus attestation or morphological validity with non-trivial generative prior.
2498
+ if (obsCount < 1 && (!morphValid || (this.morphology?.priorCount && effCount < 0.03)))
2499
+ return;
2500
+ pool.set(candText, { text: candText, kind, editCost, foldedEdits, morphValid, obsCount, effCount });
2501
+ };
2502
+ // 1. Existing rule/lexicon candidates (marks, splits, apostrophes, short 3-letter typos, 1-edit lexicon typos).
2503
+ const existingCands = this.candidates(word, typed, context, typedCount, nextTyped);
2504
+ for (const c of existingCands) {
2505
+ if (c.joinsNext)
2506
+ continue;
2507
+ let ec;
2508
+ let fe = 1;
2509
+ if (c.kind === "split")
2510
+ ec = 0.85;
2511
+ else if (c.kind === "apostrophe")
2512
+ ec = 0.75;
2513
+ else {
2514
+ ec = turkishEditCost(word, c.text);
2515
+ if (foldTr(c.text) === foldedWord)
2516
+ fe = 0;
2517
+ }
2518
+ consider(c.text, c.kind, ec, undefined, fe);
2519
+ }
2520
+ // 2. Short 3-letter words: allow swaps, insertions, and near-key substitutions to valid Turkish words ("bka" -> "bak").
2521
+ if (word.length === 3 && this.morphology !== undefined) {
2522
+ for (const swap of [word[1] + word[0] + word[2], word[0] + word[2] + word[1]]) {
2523
+ if (this.isRealWord(swap))
2524
+ consider(swap, "typo", turkishEditCost(word, swap), true, 1);
2525
+ }
2526
+ for (let i = 0; i <= 3; i++) {
2527
+ const before = word.slice(0, i);
2528
+ const after = word.slice(i);
2529
+ for (const ch of ALPHABET) {
2530
+ const ins = before + ch + after;
2531
+ if (this.lexicon.exactCount(ins) >= 20 && this.isRealWord(ins)) {
2532
+ consider(ins, "typo", turkishEditCost(word, ins), true, 1);
2533
+ }
2534
+ }
2535
+ }
2536
+ for (let i = 0; i < 3; i++) {
2537
+ const at = word[i];
2538
+ for (const ch of ALPHABET) {
2539
+ if (ch !== at && (areNearKeys(ch, at) || (VOWELS.has(ch) && VOWELS.has(at)))) {
2540
+ const sub = word.slice(0, i) + ch + word.slice(i + 1);
2541
+ if (this.lexicon.exactCount(sub) >= 20 && this.isRealWord(sub)) {
2542
+ consider(sub, "typo", turkishEditCost(word, sub), true, 1);
2543
+ }
2544
+ }
2545
+ }
2546
+ }
2547
+ }
2548
+ // 3. Fast 1-edit mark-folded morphological search (handles unseen valid forms + mark-loss + 1 typo).
2549
+ if (this.morphology?.fuzzySearch && word.length >= 4 && word.length <= 28) {
2550
+ const fuzzy1 = this.morphology.fuzzySearch(word, 1, 30);
2551
+ for (const f of fuzzy1) {
2552
+ consider(f.word, f.foldedEdits === 0 ? "marks" : "typo", f.editCost, true, f.foldedEdits);
2553
+ }
2554
+ // 4. Escalate to 2-edit mark-folded morphological search when 1-edit doesn't produce a strong high-confidence
2555
+ // candidate (or leaves a single candidate on medium words), catching double omissions like "grkli" -> "gerekli",
2556
+ // "gerektn" -> "gerçekten", "frmuar" -> "fermuarı", "palıcanlar" -> "patlıcanları", "mahalemize" -> "mahallemizde".
2557
+ let veryStrongD1 = 0;
2558
+ let cleanTranspositionD1 = 0;
2559
+ for (const item of pool.values()) {
2560
+ if (item.morphValid && item.foldedEdits <= 1) {
2561
+ if (item.editCost <= 1.1 && item.effCount >= 120)
2562
+ veryStrongD1++;
2563
+ if (item.editCost <= 0.75 && item.effCount >= 1)
2564
+ cleanTranspositionD1++;
2565
+ }
2566
+ }
2567
+ if ((veryStrongD1 === 0 || (pool.size < 2 && cleanTranspositionD1 === 0)) && word.length >= 4 && word.length <= 18) {
2568
+ const fuzzy2 = this.morphology.fuzzySearch(word, 2, 40);
2569
+ for (const f of fuzzy2) {
2570
+ consider(f.word, "typo", f.editCost, true, f.foldedEdits);
2571
+ }
2572
+ }
2573
+ }
2574
+ // 5. Also include direct 1-edit lexicon matches for words with low count (e.g. non-Zemberek words like "caspius").
2575
+ if (word.length >= 4 && pool.size < 3) {
2576
+ for (const [cand, slip] of this.oneEdit(word, true)) {
2577
+ const c = this.lexicon.exactCount(cand);
2578
+ if (c >= 5)
2579
+ consider(cand, "typo", Math.min(slip, turkishEditCost(word, cand)), undefined, 1);
2580
+ }
2581
+ }
2582
+ const scored = [];
2583
+ for (const item of pool.values()) {
2584
+ const isMulti = item.text.includes(" ");
2585
+ let pairBonus = 0;
2586
+ if (!isMulti) {
2587
+ if (context.prevWord && this.lexicon.pair(context.prevWord, item.text) > 0)
2588
+ pairBonus += 1.2;
2589
+ if (nextLower && this.lexicon.pair(item.text, nextLower) > 0)
2590
+ pairBonus += 1.0;
2591
+ }
2592
+ const morphPenalty = item.morphValid ? 0 : -1.8;
2593
+ // Universal Turkish grammar: an unambiguously accusative direct object ("hatalarını") does not govern a
2594
+ // purely passive/intransitive verb ("düzenleniyor"), favoring active transitive readings ("düzenlemiyor").
2595
+ const voicePenalty = prevIsAcc && !isMulti && item.morphValid && this.isPurelyPassiveVerb(item.text) ? -1.6 : 0;
2596
+ // Bayes channel penalty: 1 keyboard edit is far likelier than 2 edits, so 1-edit transpositions/omissions
2597
+ // ("göndredim" -> "gönderdim", "kalelmerimi" -> "kalemlerimi") stay #1 over common 2-edit words while
2598
+ // genuine double omissions ("gerektn" -> "gerçekten") still surface cleanly.
2599
+ const extraEditPenalty = item.foldedEdits >= 2 ? 1.8 : 0;
2600
+ const rankScore = log(item.effCount) - 3.6 * item.editCost - extraEditPenalty + pairBonus + morphPenalty + voicePenalty;
2601
+ const display = item.kind === "typo" ? matchCase(typed, item.text) : keepCase(typed, item.text);
2602
+ scored.push({
2603
+ text: item.text,
2604
+ display,
2605
+ kind: item.kind,
2606
+ editCost: item.editCost,
2607
+ obsCount: item.obsCount,
2608
+ effCount: item.effCount,
2609
+ morphValid: item.morphValid,
2610
+ rankScore,
2611
+ isMarkVariant: !isMulti && foldTr(item.text) === foldedWord,
2612
+ });
2613
+ }
2614
+ scored.sort((a, b) => b.rankScore - a.rankScore || a.editCost - b.editCost);
2615
+ // Deduplicate by display string while keeping highest-ranked entry.
2616
+ const seenDisplay = new Set();
2617
+ const deduped = [];
2618
+ for (const s of scored) {
2619
+ if (seenDisplay.has(s.display))
2620
+ continue;
2621
+ seenDisplay.add(s.display);
2622
+ deduped.push(s);
2623
+ }
2624
+ return deduped;
2625
+ }
2626
+ /** Words one edit away, with a cost for edits that are unlikely on a Turkish Q keyboard. */
2627
+ oneEdit(word, unseenLowerInvalid = false) {
2628
+ const edits = new Map();
2629
+ const endCost = unseenLowerInvalid ? Math.min(this.settings.typoEndCost, 0.5) : this.settings.typoEndCost;
2630
+ const put = (text, slip, position, finalDelPenalty = 0) => {
2631
+ // Changing the end of a word often swaps one real suffix for another ("öyküsüz" is not "öyküsü", "benzeyene"
2632
+ // is not "benzeyen"), so edits there cost more.
2633
+ const atEnd = position >= word.length - this.settings.typoEndWindow ? endCost : 0;
2634
+ // Without morphology (or for capitalized/seen words), block edits on the last letter of 6+ letter words.
2635
+ // With morphology on unseen lowercase invalid words, valid inflections are already excluded via !realTyped.
2636
+ if (!unseenLowerInvalid && word.length >= 6 && position >= word.length - 1)
2637
+ return;
2638
+ const atStart = position === 0 ? 1.5 : 0;
2639
+ const total = slip + atEnd + atStart + finalDelPenalty;
2640
+ if (text.length > 0 && (edits.get(text) ?? Infinity) > total)
2641
+ edits.set(text, total);
2642
+ };
2643
+ for (let i = 0; i <= word.length; i++) {
2644
+ const before = word.slice(0, i);
2645
+ const at = word[i];
2646
+ const after = word.slice(i + 1);
2647
+ const previous = word[i - 1];
2648
+ if (at !== undefined) {
2649
+ const following = word[i + 1];
2650
+ // An extra key is almost always a duplicate or keyboard neighbor of an adjacent key ("fat-finger").
2651
+ const nearExtra = (previous !== undefined && (at === previous || areNearKeys(at, previous))) ||
2652
+ (following !== undefined && (at === following || areNearKeys(at, following)));
2653
+ const isFinalNonDupDelete = i === word.length - 1 && at !== previous;
2654
+ // A Turkish letter is typed on purpose; in a word Turkish rules reject it is not a stray key ("çalşıyorum" is
2655
+ // a missed "ı" in "çalışıyorum", not an extra "ş" in "çalıyorum").
2656
+ const deliberate = unseenLowerInvalid && "çğışöü".includes(at) && at !== previous && at !== following;
2657
+ // Deleting a non-duplicate final character (especially a distant key like "m" after "r" in "geliyorm") risks
2658
+ // chopping a real person suffix ("geliyorm" -> "geliyor" instead of "geliyorum").
2659
+ const finalDelPen = isFinalNonDupDelete && word.length >= 6 ? (nearExtra ? 1.4 : 2.5) : 0;
2660
+ const farExtra = unseenLowerInvalid ? this.settings.typoFarExtra : 2.3;
2661
+ put(before + after, deliberate ? Math.max(farExtra, 5) : nearExtra ? 0.9 : farExtra, i, finalDelPen); // an extra key
2662
+ if (following !== undefined)
2663
+ put(before + following + at + word.slice(i + 2), 0.7, i); // two keys swapped
2664
+ }
2665
+ const betweenConsonants = previous !== undefined && at !== undefined && !VOWELS.has(previous) && !VOWELS.has(at);
2666
+ for (const letter of ALPHABET) {
2667
+ if (at !== undefined && letter !== at) {
2668
+ if (areNearKeys(letter, at))
2669
+ put(before + letter + after, 0.8, i);
2670
+ else if (VOICING_PAIRS.has(at + letter))
2671
+ put(before + letter + after, 1.8, i);
2672
+ else if (unseenLowerInvalid && this.settings.typoVowelSwap > 0 && VOWELS.has(at) && VOWELS.has(letter)) {
2673
+ put(before + letter + after, this.settings.typoVowelSwap, i);
2674
+ }
2675
+ }
2676
+ // Omitting a vowel inside a consonant cluster ("geliyorm", "yapabilirm", "gönderdm") is very common in Turkish.
2677
+ const insertSlip = betweenConsonants && VOWELS.has(letter) ? 0.6 : 1.0;
2678
+ put(before + letter + word.slice(i), insertSlip, i);
2679
+ }
2680
+ }
2681
+ edits.delete(word);
2682
+ return edits;
2683
+ }
2684
+ }