tdk-api-wrapper 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tdk.ts DELETED
@@ -1,2056 +0,0 @@
1
- import type {
2
- WordInfo,
3
- DailyContent,
4
- SpellCheckResult,
5
- StemResult,
6
- WordOfTheDay,
7
- DailyPick,
8
- WordComparison,
9
- WordAnalysis,
10
- TDKRule,
11
- KubbealtiEntry,
12
- WiktionaryEntry,
13
- ProofreadIssue,
14
- ProofreadResult,
15
- PatternSearchOptions,
16
- AnagramOptions,
17
- RhymeOptions,
18
- TDKConfig,
19
- } from "./types";
20
- import { TDKValidationError, TDKNetworkError } from "./errors";
21
- import { getStemCandidates } from "./morphology";
22
- import * as fs from "node:fs";
23
- import * as path from "node:path";
24
- import * as os from "node:os";
25
- import * as https from "node:https";
26
- import * as tls from "node:tls";
27
-
28
- /**
29
- * Known frequent Turkish misspellings, erroneously joined compound words,
30
- * and words where vowel dropping is prohibited by TDK (Yazım Kılavuzu).
31
- */
32
- export const COMMON_MISSPELLINGS: Record<string, string> = {
33
- // -şey ile biten ve ayrı yazılması zorunlu söz öbekleri
34
- herşey: "her şey",
35
- hersey: "her şey",
36
- birşey: "bir şey",
37
- birsey: "bir şey",
38
- hiçbirşey: "hiçbir şey",
39
- hicbirsey: "hiçbir şey",
40
- çokşey: "çok şey",
41
- coksey: "çok şey",
42
- şeyler: "şeyler",
43
- seyler: "şeyler",
44
- herhangibirşey: "herhangi bir şey",
45
- herhangibirsey: "herhangi bir şey",
46
-
47
- // Sıkça birleşik yazılan ama ayrı yazılması gereken sözler
48
- hergün: "her gün",
49
- hergun: "her gün",
50
- herzaman: "her zaman",
51
- heran: "her an",
52
- heryer: "her yer",
53
- herbiri: "her biri",
54
- pekçok: "pek çok",
55
- pekcok: "pek çok",
56
- pekaz: "pek az",
57
- yada: "ya da",
58
- tabiki: "tabii ki",
59
- tabiiki: "tabii ki",
60
- sağol: "sağ ol",
61
- sagol: "sağ ol",
62
- sağolun: "sağ olun",
63
- sagolun: "sağ olun",
64
- hoşçakal: "hoşça kal",
65
- hoscakal: "hoşça kal",
66
- hoşgeldin: "hoş geldin",
67
- hosgeldin: "hoş geldin",
68
- hoşgeldiniz: "hoş geldiniz",
69
- hosgeldiniz: "hoş geldiniz",
70
- hoşbulduk: "hoş bulduk",
71
- hosbulduk: "hoş bulduk",
72
- yanısıra: "yanı sıra",
73
- yanisira: "yanı sıra",
74
- peşisıra: "peşi sıra",
75
- pesisira: "peşi sıra",
76
- ardısıra: "ardı sıra",
77
- ardisira: "ardı sıra",
78
- artarda: "art arda",
79
- yüzyüze: "yüz yüze",
80
- yuzyuze: "yüz yüze",
81
- elele: "el ele",
82
- gözgöze: "göz göze",
83
- başbaşa: "baş başa",
84
- basbasa: "baş başa",
85
- yanyana: "yan yana",
86
- içiçe: "iç içe",
87
- icice: "iç içe",
88
- üstüste: "üst üste",
89
- ustuste: "üst üste",
90
- altalta: "alt alta",
91
- önsöz: "ön söz",
92
- onsoz: "ön söz",
93
- önyargı: "ön yargı",
94
- onyargi: "ön yargı",
95
- farketmek: "fark etmek",
96
- farketti: "fark etti",
97
- farkettim: "fark ettim",
98
- farkeder: "fark eder",
99
- farketmez: "fark etmez",
100
- terketmek: "terk etmek",
101
- terketti: "terk etti",
102
- ayırdetmek: "ayırt etmek",
103
- ayırtetmek: "ayırt etmek",
104
- arzetmek: "arz etmek",
105
- arzederim: "arz ederim",
106
- varolmak: "var olmak",
107
- yokolmak: "yok olmak",
108
- haketmek: "hak etmek",
109
- haketti: "hak etti",
110
- hakkaten: "hakikaten",
111
- hiçkimse: "hiç kimse",
112
- hickimse: "hiç kimse",
113
-
114
- // Ünlü düşmesi yapılmaması gereken yer bildiren sözler (TDK Kural 15)
115
- burda: "burada",
116
- burdan: "buradan",
117
- şurda: "şurada",
118
- surda: "şurada",
119
- şurdan: "şuradan",
120
- surdan: "şuradan",
121
- orda: "orada",
122
- ordan: "oradan",
123
- içerde: "içeride",
124
- icerde: "içeride",
125
- içerden: "içeriden",
126
- icerden: "içeriden",
127
- dışarda: "dışarıda",
128
- disarda: "dışarıda",
129
- dışardan: "dışarıdan",
130
- disardan: "dışarıdan",
131
- yukarda: "yukarıda",
132
- yukardan: "yukarıdan",
133
-
134
- // Sıkça yanlış yazılan sözcükler
135
- herkez: "herkes",
136
- yanlız: "yalnız",
137
- yalnış: "yanlış",
138
- orjinal: "orijinal",
139
- labaratuar: "laboratuvar",
140
- laboratuar: "laboratuvar",
141
- şöför: "şoför",
142
- sofor: "şoför",
143
- egzos: "egzoz",
144
- eksoz: "egzoz",
145
- ekzoz: "egzoz",
146
- kiprik: "kirpik",
147
- kirbit: "kibrit",
148
- klavuz: "kılavuz",
149
- kıravat: "kravat",
150
- süpriz: "sürpriz",
151
- supriz: "sürpriz",
152
- raslantı: "rastlantı",
153
- hastahane: "hastane",
154
- pastahane: "pastane",
155
- postahane: "postane",
156
- eczahane: "eczane",
157
- meyva: "meyve",
158
- sarmısak: "sarımsak",
159
- dinazor: "dinozor",
160
- pantalon: "pantolon",
161
- tesbih: "tespih",
162
- ahçı: "aşçı",
163
- matba: "matbaa",
164
- idda: "iddia",
165
- iddaa: "iddia",
166
- muhattap: "muhatap",
167
- traş: "tıraş",
168
- karnıbahar: "karnabahar",
169
- kareografi: "koreografi",
170
- poaça: "poğaça",
171
- pohaça: "poğaça",
172
- şarz: "şarj",
173
- sarj: "şarj",
174
- makina: "makine",
175
- müsade: "müsaade",
176
- entellektüel: "entelektüel",
177
- inisiyatif: "inisiyatif",
178
- insiyatif: "inisiyatif",
179
- sezeryan: "sezaryen",
180
- doküman: "doküman",
181
- döküman: "doküman",
182
- erozyon: "erozyon",
183
- erizyon: "erozyon",
184
- anane: "anneanne",
185
- babaanne: "babaanne",
186
- };
187
-
188
- export const SEY_EXCEPTIONS = new Set(["düşey", "eşey", "konsey", "jersey", "şey"]);
189
-
190
- /**
191
- * Turkish Q (QWERTY) keyboard geometry for the spell checker's closest-headword
192
- * fallback. Plain Damerau-Levenshtein treats every wrong letter as one full
193
- * edit, so it cannot tell that "arabs" is much more likely a slip for "araba"
194
- * (s and a sit next to each other) than for some equidistant headword, or that
195
- * "swlam" is "selam" (w next to e). These tables let a substitution cost a
196
- * fraction of an edit when the two keys are physically adjacent — or are the
197
- * ASCII/diacritic pair of one another (ı/i, ş/s, ö/o, …), the other dominant
198
- * class of Turkish typo — so the nearest *and* most plausible headword wins.
199
- * Everyone is assumed to be on a Turkish Q layout.
200
- */
201
- const KEYBOARD_ROWS: ReadonlyArray<readonly [string, number]> = [
202
- ["qwertyuıopğü", 0],
203
- ["asdfghjklşi", 0.5],
204
- ["zxcvbnmöç", 1],
205
- ];
206
- const KEYBOARD_COORDS: Readonly<Record<string, readonly [number, number]>> = (() => {
207
- const coords: Record<string, readonly [number, number]> = {};
208
- KEYBOARD_ROWS.forEach(([keys, offset], row) => {
209
- [...keys].forEach((key, col) => {
210
- coords[key] = [col + offset, row];
211
- });
212
- });
213
- return coords;
214
- })();
215
-
216
- /** ASCII <-> Turkish-diacritic siblings, treated as an almost-free substitution. */
217
- const DIACRITIC_SIBLINGS: Readonly<Record<string, string>> = {
218
- ı: "i", i: "ı", ö: "o", o: "ö", ü: "u", u: "ü",
219
- ş: "s", s: "ş", ç: "c", c: "ç", ğ: "g", g: "ğ", â: "a", a: "â",
220
- };
221
-
222
- /** Cost of substituting a key for its left/right neighbour on the same row. */
223
- const KEYBOARD_ROW_SUB_COST = 0.4;
224
- /** Cost of substituting a key for a diagonally adjacent one on the row above/below. */
225
- const KEYBOARD_DIAGONAL_SUB_COST = 0.55;
226
- /** Cost of confusing a letter with its diacritic/ASCII sibling. */
227
- const DIACRITIC_SUB_COST = 0.3;
228
- /** Cost of a transposition ("selam" <-> "selma"): a single wrong finger order. */
229
- const TRANSPOSITION_COST = 0.8;
230
-
231
- /**
232
- * Weighted substitution cost between two single characters: 0 if identical,
233
- * a small fraction if they are diacritic siblings or neighbouring keys on a
234
- * Turkish Q keyboard, otherwise a full 1.
235
- */
236
- function keyboardSubCost(a: string, b: string): number {
237
- if (a === b) return 0;
238
- if (DIACRITIC_SIBLINGS[a] === b) return DIACRITIC_SUB_COST;
239
- const pa = KEYBOARD_COORDS[a];
240
- const pb = KEYBOARD_COORDS[b];
241
- if (!pa || !pb) return 1;
242
- const dx = Math.abs(pa[0] - pb[0]);
243
- const dy = Math.abs(pa[1] - pb[1]);
244
- // Same row, immediate horizontal neighbour: the most common slip.
245
- if (dy === 0 && dx <= 1 + 1e-9) return KEYBOARD_ROW_SUB_COST;
246
- // One row up/down and within roughly one key horizontally: a diagonal slip.
247
- if (dy === 1 && dx <= 1 + 1e-9) return KEYBOARD_DIAGONAL_SUB_COST;
248
- return 1;
249
- }
250
-
251
- /**
252
- * TDK (Türk Dil Kurumu) API Wrapper
253
- */
254
- export class TDK {
255
- private static readonly BASE_URL = "https://sozluk.gov.tr";
256
- private static readonly AUDIO_API_HOST = "api.sozluk.gov.tr";
257
- private static readonly KUBBEALTI_HOST = "eski.lugatim.com";
258
-
259
- /**
260
- * `eski.lugatim.com` (Kubbealtı Lugatı's data API) sends only its leaf
261
- * certificate during the TLS handshake, omitting the intermediates a
262
- * correctly configured server would include — a server-side misconfiguration,
263
- * not something we should paper over by disabling verification. These are
264
- * the two certificates the server *should* be sending (fetched from the
265
- * leaf's own Authority Information Access URLs), supplied here so Node can
266
- * still build a full, properly verified chain up to a root it already
267
- * trusts (ISRG Root X1). If Let's Encrypt rotates this intermediate, this
268
- * stops working and every Kubbealtı call fails closed to `null` — same
269
- * fail-closed contract as the rest of this file's fragile integrations.
270
- */
271
- private static readonly KUBBEALTI_EXTRA_CA = [
272
- `-----BEGIN CERTIFICATE-----
273
- MIIE2jCCAsKgAwIBAgIQTr0klH4k05SALYSlL9WzGTANBgkqhkiG9w0BAQsFADAu
274
- MQswCQYDVQQGEwJVUzENMAsGA1UEChMESVNSRzEQMA4GA1UEAxMHUm9vdCBZUjAe
275
- Fw0yNTA5MDMwMDAwMDBaFw0yODA5MDIyMzU5NTlaMDMxCzAJBgNVBAYTAlVTMRYw
276
- FAYDVQQKEw1MZXQncyBFbmNyeXB0MQwwCgYDVQQDEwNZUjIwggEiMA0GCSqGSIb3
277
- DQEBAQUAA4IBDwAwggEKAoIBAQDZ0LxwBppqh84luqMerV/eeL/fXQ7mLQQv1Lnp
278
- WKZbyvGpx6wh6AfnslAnF6ewTkcHA+gSOoBvm3Dfm06AuGiF+KRut4fAcowqnAQQ
279
- CW98+QPP/eOv/wug7Iyk4NkOxf2I6g2f55T6nJoOTLFcukeRq80JGQEYan+dPFr9
280
- OGUgQK2hGKgNkW87pappsOAuUJcroYhRt5uUis4qaZireiseu32gzDJNBAiKtsvd
281
- 6HX4v25bpkRNcS/B/Gtc9kVbUpD+2PLPxdei3Tim55k4tfAEXwD2qyiPTxrTNq6l
282
- N+AMr5g2c1dNqkOTwjxeV6L5lpP1rGiYvLnRaPlOqyZRPW+5AgMBAAGjge4wgesw
283
- DgYDVR0PAQH/BAQDAgGGMBMGA1UdJQQMMAoGCCsGAQUFBwMBMBIGA1UdEwEB/wQI
284
- MAYBAf8CAQAwHQYDVR0OBBYEFEAVLSZ57TIgnt+ach3WMh+BDIEMMB8GA1UdIwQY
285
- MBaAFN7nW2DQIm1AKH0/DQH+pLVStFGUMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEF
286
- BQcwAoYWaHR0cDovL3lyLmkubGVuY3Iub3JnLzATBgNVHSAEDDAKMAgGBmeBDAEC
287
- ATAnBgNVHR8EIDAeMBygGqAYhhZodHRwOi8veXIuYy5sZW5jci5vcmcvMA0GCSqG
288
- SIb3DQEBCwUAA4ICAQB0ZUQWZ9/Yn9COEpo+JfecMnB0h0vwDm/M66IqXqw3LoaL
289
- mx9lZvRTeDIS67PUeI3yCA2W6PKRD0/FE/G57lOmS+Xy5AaaL00ICGOqjNcCaMWW
290
- 8o8nevHOd4i4lqgtznE/28QwlcdJyF8yBiWHpnyjhEpmNWJURgOCOg2xpwRMBCsj
291
- MScqYPtOhBeuYQvSwAEeTML2Ukh6uGuX4E14q65Ja8cdjF5bAldnP1eE4FBaAwsZ
292
- G2fOqqrKV03Y85Nw2btedP1AtliQuJZs/Jo/gXxXdc7LrH3McgnpnbTiAncX7yES
293
- hP6kzQejllqMCIt52HOjxDGWafS7Xw+DKwqmH+Eqy8dcbOuag/1AYlQoKNVK3F5q
294
- Hh6tEDiMqQcLIibGKteE6iHo4A/bIScbzrhXUYuism42ZYzmc48FMVIH3qy4L84E
295
- TdAH2gtxw0PAhvRVXp8HP7wfngpzsN/8xOTpeRSbM4+Qbc56G6+Bifmv6sk1ieQb
296
- NA3wJdl4DDUuQSV8hBgx6zoI1ZSGORprDFux7c6rhc77QZMSRrEgomBeklervEve
297
- 86ylWmZ3WWHV6RLMi8xNvjd71r4EPIGgY7BZU/VPBkq+uA7Gb6mbJnFgV43uh3xy
298
- LRFgxIAphIukwTGSMZZR+AI+Qnp0BYTWovHXozOf3H8r6hozEoT02JHn0AeTfA==
299
- -----END CERTIFICATE-----`,
300
- `-----BEGIN CERTIFICATE-----
301
- MIIF9DCCA9ygAwIBAgIRAPJLbRf52a18scn+p4eCaZ8wDQYJKoZIhvcNAQELBQAw
302
- TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
303
- cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjYwNTEzMDAwMDAw
304
- WhcNMzIwOTAyMjM1OTU5WjAuMQswCQYDVQQGEwJVUzENMAsGA1UEChMESVNSRzEQ
305
- MA4GA1UEAxMHUm9vdCBZUjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB
306
- ANvGJnN78CTJdWL3+eGfsLN5TrNBJs+VH9hRXqRbwxu9sGNiB0BD1fcOxbSUQCJI
307
- M1xE13Db+5Cw1w0s0EBYsvuIP/6joF0w8cuImbgR1OGgYbSQ4OpzI+DG8SGuTlcE
308
- 873OCS+kh3srlo6vl43M5OJg4Aeo1sfHp6kTJDoIiFBNJAY+OKfX/FUvYKuhjT+n
309
- o49lmqmupSBI5PkBQiqrEGtWU5uxU/cQWHGu8jSjFBznZqvbNPLMXMLFxCb3WTfr
310
- JBXXjqvWG+v4bjzxjjeAtOlU7qarRDvNOyAuQYLln904M+faKx8hnLCpJ15ZqaEg
311
- cNlY+9MMWcC5yvL2A2j3l9+2buggZX+dOE91zYmIdawTvSZuVvlbRrAlLxIB6pwM
312
- BjneXCjYQ8+3BCCjssbSNpZU3hTcBDdhfAlEDlYr6pEatnMdmDT5BqnKC92bd0Eh
313
- M1fbLHioLccLCuievT8ZkPhZrq7Mii7gNXAcUEAR8+lzYal+9zTg7C5DALyVOeG/
314
- CqfRAMn1KSHCR0NSA6P8tn/mGRlnCct5rtVCLnVySVpU6H1qGg3DgTOuskf8eahT
315
- MiYbI5ezPJmO5ertalskQ1utp74+eDy92PI4ftHKTbq9IWhH4YZKh3WnJEIt+oQv
316
- lYZbY8tpEroKrFB6PFGzrJIDRyts4HqvuH52RFj2zv/BAgMBAAGjgeswgegwDgYD
317
- VR0PAQH/BAQDAgEGMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA8GA1UdEwEB/wQFMAMB
318
- Af8wHQYDVR0OBBYEFN7nW2DQIm1AKH0/DQH+pLVStFGUMB8GA1UdIwQYMBaAFHm0
319
- WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcwAoYW
320
- aHR0cDovL3gxLmkubGVuY3Iub3JnLzATBgNVHSAEDDAKMAgGBmeBDAECATAnBgNV
321
- HR8EIDAeMBygGqAYhhZodHRwOi8veDEuYy5sZW5jci5vcmcvMA0GCSqGSIb3DQEB
322
- CwUAA4ICAQA8spSI95KKfn2W6GMmDpHBJSPaLbsS3W93cijJCRCYAc1fsJgL1FIL
323
- 7C0C9ecPOdcwB2fi0Dk2p94j9iTJCxmt5CFSKLRWwnXT2MMSXexVxqoVB79BdWPx
324
- VXETkVme/qYSAuKVHh5Ps+5BixgmwS1JkjSAc+MfrUbNssVEEnH0aEiAh+rotXAV
325
- JSP/Ye7LJPEwD9DWG72vVWbhAcuOf5OLjz57Ctk7MgQHynZ7+PlHJtajroCaIbtC
326
- r6tcZZaAwUQm+jQyeWdV+2hv9deOYFmKeQyjjcSrN5Nadrw+L9DZJLbA1HqeNvLh
327
- BgqpP0fvJq2N6EtD574N6eMI7uMsJTnji2UDz9el5XLSv9fqJMuDQtYVb2oTNoKp
328
- oUqhxPVC0aq4eG5MESaIdn8b5ZGSSeAJLMHXljEdlNza+ncfkviXk1POLnnFdvx8
329
- /gk6M374WbLWFXw8N141B/Rl/tINGfl1TxOIiqtiMYkL02RSGb1kq34BL9NPP27z
330
- RGMuHGnzS3hFIrRTfKxrzUZ9RzQWzEG3K6fJ3r2nqSltkeytis9DIBoFY9VmVyjL
331
- M71DMi+y1+TRSJVClEMwvA4yL++7q9XZx5r5wBRWB4kQTKH5qyoZnDw7iiuh1lID
332
- yDFx8r7i9vIJU5HS3moZLkYWAOilMaV9N56A9Bgb6dNcHkvg3NoaYA==
333
- -----END CERTIFICATE-----`,
334
- ];
335
-
336
- // Configuration
337
- private static defaultTimeoutMs = 8000;
338
- private static defaultRetries = 1;
339
- private static maxCacheSize = 1000;
340
-
341
- // Cache Mechanism
342
- private static isCacheEnabled = false;
343
- private static wordCache = new Map<string, WordInfo[]>();
344
- private static dailyContentCache: DailyContent | null = null;
345
- private static autocompleteCache: string[] = [];
346
- private static autocompleteSet: Set<string> = new Set<string>();
347
- private static stemCache = new Map<string, string | null>();
348
-
349
- /**
350
- * Configures global client options such as network timeout, retries, and cache size.
351
- */
352
- public static configure(config: TDKConfig): void {
353
- if (config.timeoutMs !== undefined) this.defaultTimeoutMs = Math.max(100, config.timeoutMs);
354
- if (config.retries !== undefined) this.defaultRetries = Math.max(0, config.retries);
355
- if (config.cache !== undefined) this.enableCache(config.cache);
356
- if (config.maxCacheSize !== undefined) this.maxCacheSize = Math.max(10, config.maxCacheSize);
357
- }
358
-
359
- /**
360
- * Enables or disables in-memory caching for API requests.
361
- */
362
- public static enableCache(status = true): void {
363
- this.isCacheEnabled = status;
364
- if (!status) {
365
- this.clearCache();
366
- }
367
- }
368
-
369
- /**
370
- * Clears the internal cache.
371
- */
372
- public static clearCache(): void {
373
- this.wordCache.clear();
374
- this.dailyContentCache = null;
375
- this.autocompleteCache = [];
376
- this.autocompleteSet.clear();
377
- this.stemCache.clear();
378
- }
379
-
380
- private static setBoundedCache<K, V>(map: Map<K, V>, key: K, value: V): void {
381
- if (map.size >= this.maxCacheSize) {
382
- const firstKey = map.keys().next().value;
383
- if (firstKey !== undefined) map.delete(firstKey);
384
- }
385
- map.set(key, value);
386
- }
387
-
388
- private static delay(ms: number) {
389
- return new Promise((resolve) => setTimeout(resolve, ms));
390
- }
391
-
392
- /**
393
- * Internal helper that performs HTTP fetch with timeout and automatic retry on network/5xx errors.
394
- */
395
- private static async fetchWithRetry(
396
- url: string,
397
- options: RequestInit = {},
398
- retries: number = this.defaultRetries,
399
- timeoutMs: number = this.defaultTimeoutMs
400
- ): Promise<Response> {
401
- let lastError: unknown;
402
- for (let attempt = 0; attempt <= retries; attempt++) {
403
- try {
404
- const signal = AbortSignal.timeout(timeoutMs);
405
- const headers = {
406
- "User-Agent": "TDK-API-Nodejs-Wrapper/1.0",
407
- ...((options.headers as Record<string, string>) || {}),
408
- };
409
- const res = await fetch(url, { ...options, headers, signal });
410
- if (res.ok || (res.status >= 400 && res.status < 500)) {
411
- return res;
412
- }
413
- // If 5xx server error, retry
414
- if (attempt < retries) {
415
- await this.delay(200 * (attempt + 1));
416
- continue;
417
- }
418
- return res;
419
- } catch (err) {
420
- lastError = err;
421
- if (attempt < retries) {
422
- await this.delay(200 * (attempt + 1));
423
- continue;
424
- }
425
- }
426
- }
427
- throw new TDKNetworkError(`Request to ${url} failed after ${retries + 1} attempts.`, {
428
- cause: lastError,
429
- });
430
- }
431
-
432
- /**
433
- * Fetches detailed information for a given word from the TDK Dictionary.
434
- */
435
- public static async getWord(word: string): Promise<WordInfo[]> {
436
- if (!word || word.trim() === "") {
437
- throw new TDKValidationError("Word parameter cannot be empty.");
438
- }
439
-
440
- const cleanWord = word.trim().toLocaleLowerCase("tr-TR");
441
-
442
- if (this.isCacheEnabled && this.wordCache.has(cleanWord)) {
443
- return this.wordCache.get(cleanWord)!;
444
- }
445
-
446
- const url = `${this.BASE_URL}/gts?ara=${encodeURIComponent(cleanWord)}`;
447
-
448
- let response: Response;
449
- try {
450
- response = await this.fetchWithRetry(url);
451
- } catch (error) {
452
- throw new TDKNetworkError("Failed to fetch word from TDK: request failed.", { cause: error });
453
- }
454
-
455
- if (!response.ok) {
456
- throw new TDKNetworkError(`Failed to fetch word from TDK: HTTP ${response.status}.`, {
457
- status: response.status,
458
- });
459
- }
460
-
461
- let data: unknown;
462
- try {
463
- data = await response.json();
464
- } catch (error) {
465
- throw new TDKNetworkError("Failed to fetch word from TDK: invalid JSON response.", { cause: error });
466
- }
467
-
468
- if (!Array.isArray(data) && data && "error" in (data as Record<string, unknown>)) {
469
- if (this.isCacheEnabled) this.setBoundedCache(this.wordCache, cleanWord, []);
470
- return [];
471
- }
472
-
473
- const results = data as WordInfo[];
474
- if (this.isCacheEnabled) {
475
- this.setBoundedCache(this.wordCache, cleanWord, results);
476
- }
477
- return results;
478
- }
479
-
480
- /**
481
- * Helper method to get only the meanings (definitions) of a word as a string array.
482
- */
483
- public static async getMeanings(word: string): Promise<string[]> {
484
- const results = await this.getWord(word);
485
- if (results.length === 0) return [];
486
-
487
- const meanings: string[] = [];
488
- for (const result of results) {
489
- if (result.anlamlarListe) {
490
- for (const anlam of result.anlamlarListe) {
491
- if (anlam.anlam) meanings.push(anlam.anlam);
492
- }
493
- }
494
- }
495
- return meanings;
496
- }
497
-
498
- /**
499
- * `sozluk.gov.tr`'s dedicated `/autocomplete.json` (and `/data/autocomplete.json`)
500
- * routes no longer serve JSON — they fall through to the SPA's `index.html`.
501
- * The full ~81k-word headword list the site's own autocomplete UI uses is
502
- * instead bundled directly into its main JS asset as a
503
- * `JSON.parse(\`[{"madde":"..."}]\`)` literal, so this fetches the home
504
- * page to find that asset's current hashed filename, downloads it (a few
505
- * MB, only once per process), and extracts the literal out of it. Fragile
506
- * scraping of an implementation detail — if TDK's build stops embedding
507
- * this, this fails closed to `[]` rather than throwing.
508
- */
509
- private static async fetchAutocompleteData(): Promise<string[]> {
510
- try {
511
- const homeResponse = await fetch(`${this.BASE_URL}/`, {
512
- headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" },
513
- });
514
- if (!homeResponse.ok) return [];
515
- const html = await homeResponse.text();
516
-
517
- const scriptMatch = html.match(/src="(\/assets\/index-[^"]+\.js)"/);
518
- if (!scriptMatch) return [];
519
-
520
- const bundleResponse = await fetch(`${this.BASE_URL}${scriptMatch[1]}`, {
521
- headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" },
522
- });
523
- if (!bundleResponse.ok) return [];
524
- const bundleJs = await bundleResponse.text();
525
-
526
- const startMarker = 'JSON.parse(`[{"madde":';
527
- const startIdx = bundleJs.indexOf(startMarker);
528
- if (startIdx === -1) return [];
529
- const jsonStart = startIdx + "JSON.parse(".length + 1;
530
- const jsonEnd = bundleJs.indexOf("`)", jsonStart);
531
- if (jsonEnd === -1) return [];
532
-
533
- const data = JSON.parse(bundleJs.slice(jsonStart, jsonEnd)) as { madde: string }[];
534
- return data.map((item) => item.madde).filter(Boolean);
535
- } catch {
536
- return [];
537
- }
538
- }
539
-
540
- /**
541
- * Ensures TDK's ~81k headword list is loaded in memory for fast O(1) set operations.
542
- */
543
- private static async ensureAutocompleteLoaded(): Promise<void> {
544
- if (this.autocompleteCache.length === 0) {
545
- this.autocompleteCache = await this.fetchAutocompleteData();
546
- this.autocompleteSet = new Set(
547
- this.autocompleteCache.map((w) => w.toLocaleLowerCase("tr-TR"))
548
- );
549
- }
550
- }
551
-
552
- /**
553
- * Returns autocomplete suggestions for a given prefix, searched over TDK's
554
- * full headword list (see `fetchAutocompleteData`). The list is fetched
555
- * and cached once per process regardless of `enableCache()` — the same
556
- * caching behavior as before — and only cleared by `clearCache()`.
557
- */
558
- public static async getSuggestions(prefix: string): Promise<string[]> {
559
- if (!prefix || prefix.trim() === "") return [];
560
-
561
- await this.ensureAutocompleteLoaded();
562
-
563
- const cleanPrefix = prefix.trim().toLocaleLowerCase("tr-TR");
564
- return this.autocompleteCache
565
- .filter(w => w.toLocaleLowerCase("tr-TR").startsWith(cleanPrefix))
566
- .slice(0, 10);
567
- }
568
-
569
- /**
570
- * Checks whether a word exists as a known headword in TDK dictionary.
571
- * Checks in-memory autocompleteSet (81k headwords) if loaded, or queries TDK API.
572
- */
573
- public static async isHeadword(word: string): Promise<boolean> {
574
- if (!word || word.trim() === "") return false;
575
- const clean = word.trim().toLocaleLowerCase("tr-TR");
576
-
577
- await this.ensureAutocompleteLoaded();
578
- if (this.autocompleteSet.size > 0) {
579
- return this.autocompleteSet.has(clean);
580
- }
581
-
582
- try {
583
- const results = await this.getWord(clean);
584
- return results.length > 0;
585
- } catch {
586
- return false;
587
- }
588
- }
589
-
590
- /**
591
- * Generates candidate roots for a given Turkish word using progressive BFS suffix stripping,
592
- * consonant mutation restoration, and vowel drop restoration.
593
- */
594
- public static getStemCandidates(word: string): string[] {
595
- return getStemCandidates(word);
596
- }
597
-
598
- /**
599
- * Finds the dictionary root (headword) of a word by checking direct existence
600
- * and evaluating candidate stems generated by morphological analysis.
601
- * Returns the root headword string if found, or null if no match in TDK.
602
- */
603
- public static async findRoot(word: string): Promise<string | null> {
604
- if (!word || word.trim() === "") return null;
605
- const clean = word.trim().toLocaleLowerCase("tr-TR");
606
-
607
- if (this.stemCache.has(clean)) {
608
- return this.stemCache.get(clean)!;
609
- }
610
-
611
- // 1. If the word itself is an exact headword, it is its own root
612
- if (await this.isHeadword(clean)) {
613
- this.setBoundedCache(this.stemCache, clean, clean);
614
- return clean;
615
- }
616
-
617
- // 2. Test morphological stem candidates
618
- const candidates = getStemCandidates(clean);
619
- for (const candidate of candidates) {
620
- if (await this.isHeadword(candidate)) {
621
- this.setBoundedCache(this.stemCache, clean, candidate);
622
- return candidate;
623
- }
624
- }
625
-
626
- this.setBoundedCache(this.stemCache, clean, null);
627
- return null;
628
- }
629
-
630
- /**
631
- * Performs morphological stemming on a Turkish word.
632
- * Returns a StemResult containing the original word, resolved root, and whether it is inflected.
633
- */
634
- public static async stem(word: string): Promise<StemResult | null> {
635
- if (!word || word.trim() === "") return null;
636
- const clean = word.trim().toLocaleLowerCase("tr-TR");
637
- const root = await this.findRoot(word);
638
-
639
- if (!root) {
640
- return null;
641
- }
642
-
643
- return {
644
- word,
645
- root,
646
- isInflected: root !== clean,
647
- candidates: getStemCandidates(word),
648
- };
649
- }
650
-
651
- /**
652
- * Returns a list of proverbs and idioms containing the word.
653
- */
654
- public static async getProverbs(word: string): Promise<string[]> {
655
- const results = await this.getWord(word);
656
- if (results.length === 0) return [];
657
-
658
- const proverbs: string[] = [];
659
- for (const result of results) {
660
- if (result.atasozu) {
661
- for (const atasoz of result.atasozu) {
662
- if (atasoz.madde) proverbs.push(atasoz.madde);
663
- }
664
- }
665
- }
666
- return proverbs;
667
- }
668
-
669
- /**
670
- * Returns the etymological origin of the word, or "Türkçe" if TDK doesn't
671
- * record a foreign origin for it. Returns `null` only when the word itself
672
- * isn't found in the dictionary at all.
673
- */
674
- public static async getOrigin(word: string): Promise<string | null> {
675
- const results = await this.getWord(word);
676
- if (results.length === 0) return null;
677
- return results[0].lisan || "Türkçe";
678
- }
679
-
680
- /**
681
- * Returns whether the word has a recorded foreign etymological origin.
682
- * Returns `null` (instead of a boolean) when the word isn't found at all.
683
- */
684
- public static async isForeignWord(word: string): Promise<boolean | null> {
685
- const origin = await this.getOrigin(word);
686
- if (origin === null) return null;
687
- return origin !== "Türkçe";
688
- }
689
-
690
- /**
691
- * Groups a list of words by their etymological origin. Words not found in
692
- * the dictionary are grouped under "Bilinmiyor". Throttled like getWordsBatch.
693
- */
694
- public static async groupByOrigin(words: string[]): Promise<Record<string, string[]>> {
695
- const groups: Record<string, string[]> = {};
696
- for (const word of words) {
697
- const origin = (await this.getOrigin(word)) ?? "Bilinmiyor";
698
- if (!groups[origin]) groups[origin] = [];
699
- groups[origin].push(word);
700
- await this.delay(200);
701
- }
702
- return groups;
703
- }
704
-
705
- /**
706
- * Returns literature examples containing the word.
707
- */
708
- public static async getExamples(word: string): Promise<{ sentence: string; author: string | null }[]> {
709
- const results = await this.getWord(word);
710
- const examples: { sentence: string; author: string | null }[] = [];
711
-
712
- for (const result of results) {
713
- if (result.anlamlarListe) {
714
- for (const anlam of result.anlamlarListe) {
715
- if (anlam.orneklerListe) {
716
- for (const ornek of anlam.orneklerListe) {
717
- const author = ornek.yazar && ornek.yazar.length > 0 ? ornek.yazar[0].tam_adi : null;
718
- examples.push({ sentence: ornek.ornek, author });
719
- }
720
- }
721
- }
722
- }
723
- }
724
- return examples;
725
- }
726
-
727
- /**
728
- * Calls the `api.sozluk.gov.tr/gts-yeni` endpoint the official web UI uses
729
- * internally (richer than the public `/gts`: includes `seskod`,
730
- * `anlamEsAnlam`/`anlamKarsitAnlam`, etc). That endpoint 403s unless the
731
- * request looks like it came from a browser tab on sozluk.gov.tr: it needs
732
- * an `Origin`/`Referer` pair matching that site AND a browser-like
733
- * `User-Agent` (our usual `TDK-API-Nodejs-Wrapper/…` UA gets rejected).
734
- * `fetch` (undici) also strips a manually-set `Origin` header as a
735
- * forbidden header name, so this uses `node:https` directly instead.
736
- * This is inherently fragile scraping of an undocumented endpoint — if
737
- * TDK tightens this check further, this should fail closed to `null`
738
- * rather than throw.
739
- */
740
- private static fetchGtsYeni(word: string): Promise<any[] | null> {
741
- return new Promise((resolve) => {
742
- const req = https.request(
743
- {
744
- hostname: this.AUDIO_API_HOST,
745
- path: `/gts-yeni?ara=${encodeURIComponent(word)}`,
746
- method: "GET",
747
- headers: {
748
- "User-Agent":
749
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
750
- Origin: this.BASE_URL,
751
- Referer: `${this.BASE_URL}/`,
752
- },
753
- },
754
- (res) => {
755
- let body = "";
756
- res.on("data", (chunk) => (body += chunk));
757
- res.on("end", () => {
758
- try {
759
- const data = JSON.parse(body);
760
- resolve(Array.isArray(data) ? data : null);
761
- } catch {
762
- resolve(null);
763
- }
764
- });
765
- }
766
- );
767
- req.on("error", () => resolve(null));
768
- req.end();
769
- });
770
- }
771
-
772
- private static async fetchSeskod(word: string): Promise<string | null> {
773
- const data = await this.fetchGtsYeni(word);
774
- const seskod = data?.[0]?.seskod;
775
- return seskod ? String(seskod) : null;
776
- }
777
-
778
- /**
779
- * Returns synonyms ("eş anlamlı kelimeler") recorded for the word, pooled
780
- * across all of its meanings. Uses the same undocumented `gts-yeni`
781
- * endpoint as `getAudioUrl` — returns `[]` if the lookup fails.
782
- */
783
- public static async getSynonyms(word: string): Promise<string[]> {
784
- if (!word || word.trim() === "") return [];
785
- const data = await this.fetchGtsYeni(word.trim().toLocaleLowerCase("tr-TR"));
786
- if (!data) return [];
787
-
788
- const synonyms: string[] = [];
789
- for (const entry of data) {
790
- for (const anlam of entry.anlamlarListe ?? []) {
791
- for (const es of anlam.anlamEsAnlam ?? []) {
792
- if (es.deger) synonyms.push(es.deger);
793
- }
794
- }
795
- }
796
- return [...new Set(synonyms)];
797
- }
798
-
799
- /**
800
- * Returns antonyms ("zıt anlamlı kelimeler") recorded for the word, pooled
801
- * across all of its meanings. Uses the same undocumented `gts-yeni`
802
- * endpoint as `getAudioUrl` — returns `[]` if the lookup fails.
803
- */
804
- public static async getAntonyms(word: string): Promise<string[]> {
805
- if (!word || word.trim() === "") return [];
806
- const data = await this.fetchGtsYeni(word.trim().toLocaleLowerCase("tr-TR"));
807
- if (!data) return [];
808
-
809
- const antonyms: string[] = [];
810
- for (const entry of data) {
811
- for (const anlam of entry.anlamlarListe ?? []) {
812
- for (const ka of anlam.anlamKarsitAnlam ?? []) {
813
- if (ka.deger) antonyms.push(ka.deger);
814
- }
815
- }
816
- }
817
- return [...new Set(antonyms)];
818
- }
819
-
820
- /**
821
- * Returns the direct URL of the audio pronunciation, if TDK has one recorded for this word.
822
- */
823
- public static async getAudioUrl(word: string): Promise<string | null> {
824
- if (!word || word.trim() === "") {
825
- throw new TDKValidationError("Word parameter cannot be empty.");
826
- }
827
-
828
- const seskod = await this.fetchSeskod(word.trim().toLocaleLowerCase("tr-TR"));
829
- if (!seskod) return null;
830
- return `https://${this.AUDIO_API_HOST}/ses/${encodeURIComponent(seskod)}.wav`;
831
- }
832
-
833
- /**
834
- * Downloads the audio pronunciation to the specified path.
835
- */
836
- public static async downloadAudio(word: string, destPath?: string): Promise<string | null> {
837
- const url = await this.getAudioUrl(word);
838
- if (!url) return null;
839
-
840
- const finalPath = destPath || path.join(os.tmpdir(), `${word}.wav`);
841
- try {
842
- const res = await fetch(url);
843
- if (!res.ok) return null;
844
- const buffer = await res.arrayBuffer();
845
- fs.writeFileSync(finalPath, Buffer.from(buffer));
846
- return finalPath;
847
- } catch {
848
- return null;
849
- }
850
- }
851
-
852
- /**
853
- * Checks spelling and returns suggestions if wrong.
854
- */
855
- public static async checkSpelling(word: string): Promise<SpellCheckResult> {
856
- if (!word || word.trim() === "") {
857
- return { isCorrect: false, word };
858
- }
859
-
860
- const cleanWord = word.trim().toLocaleLowerCase("tr-TR");
861
-
862
- // 1. Check if word exists in TDK dictionary
863
- const results = await this.getWord(word);
864
- if (results.length > 0) {
865
- return { isCorrect: true, word };
866
- }
867
-
868
- // 2. Common Turkish misspellings, erroneously joined compounds, and vowel drop errors
869
- if (COMMON_MISSPELLINGS[cleanWord]) {
870
- return { isCorrect: false, word, suggestion: COMMON_MISSPELLINGS[cleanWord] };
871
- }
872
-
873
- // 3. Dynamic -şey / -sey attached check:
874
- // In Turkish, 'şey' is an indefinite pronoun and is ALWAYS written separately from the preceding word
875
- // (e.g. her şey, bir şey, hiçbir şey, çok şey, her şeyi, bir şeyler).
876
- const seyMatch = cleanWord.match(/^(.+?)(?:şey|sey)([ıiuaeüodekmnl]+)?$/);
877
- if (seyMatch && !SEY_EXCEPTIONS.has(cleanWord)) {
878
- let prefix = seyMatch[1];
879
- const suffix = seyMatch[2] || "";
880
- if (prefix === "hicbir") prefix = "hiçbir";
881
- if (prefix === "cok") prefix = "çok";
882
- return {
883
- isCorrect: false,
884
- word,
885
- suggestion: `${prefix} şey${suffix}`,
886
- };
887
- }
888
-
889
- // 4. "Sıkça yapılan yanlışlar" from DailyContent
890
- const daily = await this.getDailyContent();
891
- if (daily) {
892
- const syydMatch = daily.syyd.find((s) => s.yanliskelime.toLocaleLowerCase("tr-TR") === cleanWord);
893
- if (syydMatch) {
894
- return { isCorrect: false, word, suggestion: syydMatch.dogrukelime };
895
- }
896
- const mixMatch = daily.karistirma.find((s) => s.yanlis.toLocaleLowerCase("tr-TR") === cleanWord);
897
- if (mixMatch) {
898
- return { isCorrect: false, word, suggestion: mixMatch.dogru };
899
- }
900
- }
901
-
902
- // 5. Morphology Fallback: Check if the word is an inflected form or bare verb imperative of a known headword
903
- // (e.g., "halılarımızın" -> "halı", "kitabımız" -> "kitap", "çocuğa" -> "çocuk", "söyle" -> "söylemek")
904
- const root = await this.findRoot(word);
905
- if (root) {
906
- const isInflected = root !== cleanWord;
907
- return {
908
- isCorrect: true,
909
- word,
910
- isInflected,
911
- root,
912
- };
913
- }
914
-
915
- // 6. Check if headwords with spaces match when space is removed (e.g. "ön yargı" for "önyargı")
916
- if (this.autocompleteCache.length === 0) {
917
- this.autocompleteCache = await this.fetchAutocompleteData();
918
- }
919
- for (const candidate of this.autocompleteCache) {
920
- if (candidate.includes(" ")) {
921
- const candidateNoSpace = candidate.replace(/\s+/g, "").toLocaleLowerCase("tr-TR");
922
- if (candidateNoSpace === cleanWord) {
923
- return { isCorrect: false, word, suggestion: candidate };
924
- }
925
- }
926
- }
927
-
928
- // 7. No exact match or morphology root: fall back to closest headword by edit distance.
929
- // Candidates are ranked by the keyboard-/diacritic-aware distance (so "arabs" picks
930
- // "araba" over an equidistant headword because s->a is a neighbouring-key slip, and
931
- // "swlam" picks "selam" because w->e is), while the plain integer Damerau-Levenshtein
932
- // still gates acceptance. Ties prefer matching first letter, then matching length, and
933
- // initial character mismatches are penalized so irrelevant foreign loanwords (like
934
- // 'jersey') do not beat Turkish roots.
935
- let best:
936
- | { candidate: string; score: number; rawDist: number; firstMismatch: number; lengthMismatch: number }
937
- | null = null;
938
- for (const candidate of this.autocompleteCache) {
939
- if (candidate.includes(" ") || candidate !== candidate.toLocaleLowerCase("tr-TR")) continue;
940
- if (Math.abs(candidate.length - cleanWord.length) > 2) continue;
941
-
942
- const rawDist = this.damerauLevenshtein(cleanWord, candidate);
943
- if (rawDist === 0 || rawDist > 2) continue;
944
-
945
- const firstMismatch = candidate[0] === cleanWord[0] ? 0 : 1;
946
- const lengthMismatch = candidate.length === cleanWord.length ? 0 : 1;
947
- const score = this.keyboardAwareDistance(cleanWord, candidate) + (firstMismatch > 0 ? 1.2 : 0);
948
-
949
- const better =
950
- !best ||
951
- score < best.score - 1e-9 ||
952
- (Math.abs(score - best.score) < 1e-9 && firstMismatch < best.firstMismatch) ||
953
- (Math.abs(score - best.score) < 1e-9 &&
954
- firstMismatch === best.firstMismatch &&
955
- lengthMismatch < best.lengthMismatch);
956
- if (better) {
957
- best = { candidate, score, rawDist, firstMismatch, lengthMismatch };
958
- }
959
- }
960
- if (best && best.rawDist <= 2 && (best.firstMismatch === 0 || best.rawDist <= 1)) {
961
- return { isCorrect: false, word, suggestion: best.candidate };
962
- }
963
- return { isCorrect: false, word };
964
- }
965
-
966
- /**
967
- * Fetches daily content (word of the day, proverbs, rules, etc).
968
- * `bypassCache` skips both reading and writing `dailyContentCache` even
969
- * when `enableCache(true)` is on — used by `getRule()`'s retry loop, which
970
- * needs a fresh random `/icerik` draw on every attempt; without it, once
971
- * caching is enabled the loop would just re-read the same cached response
972
- * 25 times and could never find a rule outside that first random draw.
973
- */
974
- public static async getDailyContent(bypassCache = false): Promise<DailyContent | null> {
975
- if (!bypassCache && this.isCacheEnabled && this.dailyContentCache) return this.dailyContentCache;
976
-
977
- try {
978
- const response = await fetch(`${this.BASE_URL}/icerik`, {
979
- headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" },
980
- });
981
- if (response.ok) {
982
- const data = await response.json() as DailyContent;
983
- if (!bypassCache && this.isCacheEnabled) this.dailyContentCache = data;
984
- return data;
985
- }
986
- } catch {
987
- return null;
988
- }
989
- return null;
990
- }
991
-
992
- /**
993
- * Returns today's word of the day along with all of its listed meanings.
994
- */
995
- public static async getWordOfTheDay(): Promise<WordOfTheDay | null> {
996
- const daily = await this.getDailyContent();
997
- if (!daily || daily.kelime.length === 0) return null;
998
-
999
- const word = daily.kelime[0].madde;
1000
- const meanings = daily.kelime.filter((k) => k.madde === word).map((k) => k.anlam);
1001
- return { word, meanings };
1002
- }
1003
-
1004
- /**
1005
- * Picks a random entry (word or proverb) from today's daily content.
1006
- * Note: this samples from today's `getDailyContent()` picks, not the full dictionary.
1007
- */
1008
- public static async getRandomWord(): Promise<DailyPick | null> {
1009
- const daily = await this.getDailyContent();
1010
- if (!daily) return null;
1011
-
1012
- const pool: DailyPick[] = [
1013
- ...daily.kelime.map((k) => ({ type: "kelime" as const, madde: k.madde, anlam: k.anlam })),
1014
- ...daily.atasoz.map((a) => ({ type: "atasoz" as const, madde: a.madde, anlam: a.anlam })),
1015
- ];
1016
- if (pool.length === 0) return null;
1017
-
1018
- return pool[Math.floor(Math.random() * pool.length)];
1019
- }
1020
-
1021
- /**
1022
- * Returns the spelling-rule page(s) ("yazım kuralları") linked from TDK's
1023
- * `/icerik` daily-content feed, e.g. `{ adi: "Kısaltmalar", url: "https://..." }`.
1024
- * Note: like `getRandomWord()`, this is NOT a fixed catalog — `/icerik`
1025
- * appears to hand back a single randomly-rotated rule per request, so two
1026
- * calls a second apart can return entirely different rules. `bypassCache`
1027
- * (used internally by `getRule()`'s retry loop) forces a fresh `/icerik`
1028
- * draw even when `enableCache(true)` is on.
1029
- */
1030
- public static async getKurallar(bypassCache = false): Promise<TDKRule[]> {
1031
- const daily = await this.getDailyContent(bypassCache);
1032
- return daily?.kural ?? [];
1033
- }
1034
-
1035
- /**
1036
- * Fetches the full plain-text content of a named spelling rule (matched
1037
- * case-insensitively, substring match) from `tdk.gov.tr`. Since `/icerik`
1038
- * hands back a single randomly-rotated rule per request (out of a pool of
1039
- * roughly twenty) rather than a fixed catalog, a single `getKurallar()`
1040
- * draw would rarely match a given name — this re-draws until it finds a
1041
- * match or gives up. Draws happen in concurrent batches (each `/icerik`
1042
- * request is independent and stateless) rather than one-at-a-time with a
1043
- * delay: same total sample size (25) and hit probability as a sequential
1044
- * loop, but bounded to a handful of round-trips instead of 25 of them, so
1045
- * a miss resolves in roughly one round-trip time instead of several
1046
- * seconds. Every draw bypasses `dailyContentCache` — without that, once
1047
- * `enableCache(true)` is on, every attempt would just re-read the same
1048
- * cached `/icerik` response and could never find a rule outside whatever
1049
- * the first draw happened to be. Returns `null` if no match turns up
1050
- * within the attempt budget or the matched page can't be parsed.
1051
- */
1052
- public static async getRule(name: string): Promise<string | null> {
1053
- if (!name || name.trim() === "") return null;
1054
- const target = name.trim().toLocaleLowerCase("tr-TR");
1055
-
1056
- const BATCH_SIZE = 5;
1057
- const ROUNDS = 5;
1058
- for (let round = 0; round < ROUNDS; round++) {
1059
- const batches = await Promise.all(
1060
- Array.from({ length: BATCH_SIZE }, () => this.getKurallar(true))
1061
- );
1062
- for (const rules of batches) {
1063
- const match = rules.find((r) => r.adi.toLocaleLowerCase("tr-TR").includes(target));
1064
- if (match) return this.fetchRuleText(match.url);
1065
- }
1066
- }
1067
- return null;
1068
- }
1069
-
1070
- /**
1071
- * `tdk.gov.tr` rule pages are WordPress/Avada-themed. The actual article
1072
- * text lives in `<div ... itemprop="text">...</div>` right before a
1073
- * `<footer class="entry...">` (share buttons, author box, structured-data
1074
- * spans) — cutting there avoids that trailing cruft.
1075
- */
1076
- private static async fetchRuleText(url: string): Promise<string | null> {
1077
- try {
1078
- const response = await fetch(url, { headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" } });
1079
- if (!response.ok) return null;
1080
- const html = await response.text();
1081
-
1082
- const marker = html.indexOf('itemprop="text"');
1083
- if (marker === -1) return null;
1084
- const contentStart = html.indexOf(">", marker) + 1;
1085
- const contentEnd = html.indexOf("<footer", contentStart);
1086
- if (contentEnd === -1) return null;
1087
-
1088
- return this.htmlToPlainText(html.slice(contentStart, contentEnd));
1089
- } catch {
1090
- return null;
1091
- }
1092
- }
1093
-
1094
- private static htmlToPlainText(html: string): string {
1095
- return html
1096
- .replace(/<br\s*\/?>/gi, "\n")
1097
- .replace(/<\/(p|div)>/gi, "\n\n")
1098
- .replace(/<[^>]+>/g, "")
1099
- .replace(/&nbsp;/gi, " ")
1100
- .replace(/&lt;/gi, "<")
1101
- .replace(/&gt;/gi, ">")
1102
- .replace(/&quot;/gi, '"')
1103
- .replace(/&#39;|&rsquo;/gi, "'")
1104
- .replace(/&amp;/gi, "&")
1105
- .replace(/[ \t]+/g, " ")
1106
- .replace(/[ \t]*\n[ \t]*/g, "\n")
1107
- .replace(/\n{3,}/g, "\n\n")
1108
- .trim();
1109
- }
1110
-
1111
- /**
1112
- * GETs a JSON path from Kubbealtı Lugatı's data API (`eski.lugatim.com`),
1113
- * supplying `KUBBEALTI_EXTRA_CA` to work around that host's incomplete
1114
- * certificate chain (see the constant's doc comment). Fails closed to
1115
- * `null` on any error — network, TLS, HTTP, or JSON parse.
1116
- */
1117
- private static fetchKubbealtiJson(path: string): Promise<any> {
1118
- return new Promise((resolve) => {
1119
- const req = https.request(
1120
- {
1121
- hostname: this.KUBBEALTI_HOST,
1122
- path,
1123
- method: "GET",
1124
- ca: [...tls.rootCertificates, ...this.KUBBEALTI_EXTRA_CA],
1125
- headers: {
1126
- "User-Agent":
1127
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
1128
- },
1129
- },
1130
- (res) => {
1131
- if (res.statusCode !== 200) {
1132
- res.resume();
1133
- resolve(null);
1134
- return;
1135
- }
1136
- let body = "";
1137
- res.on("data", (chunk) => (body += chunk));
1138
- res.on("end", () => {
1139
- try {
1140
- resolve(JSON.parse(body));
1141
- } catch {
1142
- resolve(null);
1143
- }
1144
- });
1145
- }
1146
- );
1147
- req.on("error", () => resolve(null));
1148
- req.end();
1149
- });
1150
- }
1151
-
1152
- /**
1153
- * Kubbealtı indexes headwords with full classical Turkish orthography,
1154
- * including letters that a plain-ASCII-ish query tends to drop — most
1155
- * commonly ü/ö/ç/ğ/ş, but also the circumflex ("düzeltme işareti") used in
1156
- * Arabic/Persian loanwords like "rüzgâr". A search for "ruzgar" misses
1157
- * entirely (verified: even "ruzgâr" alone still misses — it's the missing
1158
- * ü, not the missing â, that actually breaks the match). This generates
1159
- * single-letter-substitution variants to retry, one substitution per
1160
- * variant (not combinatorial) — covers the overwhelmingly common case of
1161
- * one "de-Turkished" letter without an explosion of API calls for words
1162
- * with several.
1163
- */
1164
- private static readonly TURKISH_DEASCII_MAP: Record<string, string[]> = {
1165
- a: ["â"],
1166
- i: ["ı", "î"],
1167
- o: ["ö"],
1168
- u: ["ü", "û"],
1169
- c: ["ç"],
1170
- g: ["ğ"],
1171
- s: ["ş"],
1172
- };
1173
-
1174
- private static generateTurkishVariants(word: string): string[] {
1175
- const lower = word.trim().toLocaleLowerCase("tr-TR");
1176
- const variants: string[] = [];
1177
- for (let i = 0; i < lower.length; i++) {
1178
- for (const replacement of this.TURKISH_DEASCII_MAP[lower[i]] ?? []) {
1179
- variants.push(lower.slice(0, i) + replacement + lower.slice(i + 1));
1180
- }
1181
- }
1182
- return variants;
1183
- }
1184
-
1185
- /**
1186
- * Returns Kubbealtı Lugatı ("Misalli Büyük Türkçe Sözlük") entries for a
1187
- * word, scraped from the site's own data API — undocumented, and Kubbealtı
1188
- * Lugatı is a commercial dictionary product, unlike TDK's or Wiktionary's
1189
- * openly-published data, so use this in line with their terms. `anlam` is
1190
- * raw HTML (rich typography markup); use `getKubbealtiMeanings()` for
1191
- * plain text. Falls back to `generateTurkishVariants()` if the exact query
1192
- * comes up empty (see its doc comment). Returns `null` on any fetch/parse
1193
- * failure, `[]` if no variant matches either.
1194
- */
1195
- public static async getKubbealti(word: string): Promise<KubbealtiEntry[] | null> {
1196
- if (!word || word.trim() === "") return null;
1197
-
1198
- const data = await this.fetchKubbealtiJson(`/rest/s/${encodeURIComponent(word.trim())}/`);
1199
- if (!data || !Array.isArray(data.content)) return null;
1200
- if (data.content.length > 0) {
1201
- return data.content.map((entry: any) => ({ kelime: entry.kelime, anlam: entry.anlam }));
1202
- }
1203
-
1204
- for (const variant of this.generateTurkishVariants(word)) {
1205
- const variantData = await this.fetchKubbealtiJson(`/rest/s/${encodeURIComponent(variant)}/`);
1206
- if (variantData && Array.isArray(variantData.content) && variantData.content.length > 0) {
1207
- return variantData.content.map((entry: any) => ({ kelime: entry.kelime, anlam: entry.anlam }));
1208
- }
1209
- }
1210
- return [];
1211
- }
1212
-
1213
- /**
1214
- * Same as `getKubbealti()` but with each entry's `anlam` HTML stripped to
1215
- * plain text via `htmlToPlainText()`.
1216
- */
1217
- public static async getKubbealtiMeanings(word: string): Promise<string[] | null> {
1218
- const entries = await this.getKubbealti(word);
1219
- if (!entries) return null;
1220
- return entries.map((e) => this.htmlToPlainText(e.anlam));
1221
- }
1222
-
1223
- /**
1224
- * Autocomplete suggestions from Kubbealtı Lugatı's own typeahead endpoint
1225
- * (separate from `getSuggestions()`, which uses TDK's data).
1226
- */
1227
- public static async getKubbealtiSuggestions(prefix: string): Promise<string[]> {
1228
- if (!prefix || prefix.trim() === "") return [];
1229
- const data = await this.fetchKubbealtiJson(`/rest/word-search/${encodeURIComponent(prefix.trim())}`);
1230
- if (!Array.isArray(data)) return [];
1231
- return data.map((item: any) => item.display).filter(Boolean);
1232
- }
1233
-
1234
- /**
1235
- * Returns the etymology paragraph for a word from Nişanyan Sözlük, scraped
1236
- * from that page's server-rendered `<meta name="description">` tag (the
1237
- * page already puts the full etymology text there for SEO, so no need to
1238
- * parse the site's internal SvelteKit data format). Returns `null` if the
1239
- * word isn't found (the page falls back to a generic site tagline in that
1240
- * case) or the request fails.
1241
- */
1242
- public static async getNisanyan(word: string): Promise<string | null> {
1243
- if (!word || word.trim() === "") return null;
1244
- try {
1245
- const response = await fetch(
1246
- `https://www.nisanyansozluk.com/kelime/${encodeURIComponent(word.trim().toLocaleLowerCase("tr-TR"))}`,
1247
- { headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" } }
1248
- );
1249
- if (!response.ok) return null;
1250
- const html = await response.text();
1251
- const match = html.match(/<meta name="description" content="([^"]*)"/);
1252
- if (!match) return null;
1253
- const description = this.htmlToPlainText(match[1]);
1254
- if (description === "Çağdaş Türkçenin Etimolojisi") return null;
1255
- return description;
1256
- } catch {
1257
- return null;
1258
- }
1259
- }
1260
-
1261
- private static async fetchWiktionaryEntry(title: string): Promise<WiktionaryEntry | null> {
1262
- try {
1263
- const url = `https://tr.wiktionary.org/w/api.php?action=query&prop=extracts&titles=${encodeURIComponent(
1264
- title
1265
- )}&format=json&explaintext=1&formatversion=2`;
1266
- const response = await fetch(url, { headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" } });
1267
- if (!response.ok) return null;
1268
- const data = await response.json();
1269
- const page = data?.query?.pages?.[0];
1270
- if (!page || page.missing || !page.extract) return null;
1271
-
1272
- const raw: string = page.extract;
1273
- const sections: Record<string, string> = {};
1274
- const parts = raw.split(/\n(={2,4})\s*(.+?)\s*\1\n/);
1275
- // parts[0] is text before the first heading (usually empty); after
1276
- // that, headings and their following text alternate in triples.
1277
- for (let i = 1; i < parts.length; i += 3) {
1278
- const title = parts[i + 1]?.trim();
1279
- const content = parts[i + 2]?.trim();
1280
- if (title) sections[title] = content ?? "";
1281
- }
1282
- return { raw, sections };
1283
- } catch {
1284
- return null;
1285
- }
1286
- }
1287
-
1288
- /**
1289
- * Returns the Turkish Wiktionary (`tr.wiktionary.org`) entry for a word,
1290
- * via MediaWiki's official Action API (`action=query&prop=extracts`) — no
1291
- * scraping involved, this is a stable, documented public API. `sections`
1292
- * splits the plain-text extract on its `== Heading ==`/`=== Heading ===`
1293
- * markers (e.g. "Köken", "Söyleniş", "Ad") for convenience; `raw` has the
1294
- * unsplit text. This wiki has title capitalization turned off
1295
- * ($wgCapitalLinks=false — common for Wiktionaries, since case is
1296
- * meaningful for a dictionary: "Türkiye" the country vs. a lowercase
1297
- * common word), so an exact-case miss retries with the first letter
1298
- * uppercased (Turkish-locale-aware, so "istanbul" tries "İstanbul", not
1299
- * "Istanbul") before giving up. Returns `null` if neither is found or the
1300
- * request fails.
1301
- */
1302
- public static async getWiktionary(word: string): Promise<WiktionaryEntry | null> {
1303
- if (!word || word.trim() === "") return null;
1304
- const trimmed = word.trim();
1305
-
1306
- const direct = await this.fetchWiktionaryEntry(trimmed);
1307
- if (direct) return direct;
1308
-
1309
- const capitalized = trimmed.charAt(0).toLocaleUpperCase("tr-TR") + trimmed.slice(1);
1310
- if (capitalized === trimmed) return null;
1311
- return this.fetchWiktionaryEntry(capitalized);
1312
- }
1313
-
1314
- /**
1315
- * Convenience filter over `getWiktionary()`: returns just one section's
1316
- * text (e.g. `getWiktionarySection(word, "Köken")` for etymology), matched
1317
- * case-insensitively. Returns `null` if the word or the section isn't found.
1318
- */
1319
- public static async getWiktionarySection(word: string, sectionName: string): Promise<string | null> {
1320
- const entry = await this.getWiktionary(word);
1321
- if (!entry) return null;
1322
- const key = Object.keys(entry.sections).find(
1323
- (k) => k.toLocaleLowerCase("tr-TR") === sectionName.trim().toLocaleLowerCase("tr-TR")
1324
- );
1325
- return key ? entry.sections[key] : null;
1326
- }
1327
-
1328
- /**
1329
- * Returns compound words that contain this word.
1330
- */
1331
- public static async getCompoundWords(word: string): Promise<string[]> {
1332
- const results = await this.getWord(word);
1333
- if (results.length === 0) return [];
1334
-
1335
- const compound: string[] = [];
1336
- for (const result of results) {
1337
- if (result.birlesikler) {
1338
- const words = result.birlesikler.split(',').map(w => w.trim());
1339
- compound.push(...words);
1340
- }
1341
- }
1342
- return [...new Set(compound)];
1343
- }
1344
-
1345
- /**
1346
- * Returns the part of speech (isim, sıfat, zarf vb.).
1347
- * TDK's `ozelliklerListe` mixes grammatical categories (`tur: "3"`, e.g.
1348
- * sıfat/zarf/isim) with usage-register tags (`tur: "4"`, e.g. mecaz/argo)
1349
- * in the same list — only `tur === "3"` entries are actual parts of speech.
1350
- */
1351
- public static async getPartOfSpeech(word: string): Promise<string[]> {
1352
- const results = await this.getWord(word);
1353
- const pos = new Set<string>();
1354
-
1355
- for (const result of results) {
1356
- if (result.anlamlarListe) {
1357
- for (const anlam of result.anlamlarListe) {
1358
- if (anlam.ozelliklerListe) {
1359
- for (const ozellik of anlam.ozelliklerListe) {
1360
- if (ozellik.tur === "3") pos.add(ozellik.tam_adi);
1361
- }
1362
- }
1363
- }
1364
- }
1365
- }
1366
- if (pos.size === 0 && results.length > 0) {
1367
- pos.add('isim'); // Default to noun if TDK doesn't specify
1368
- }
1369
- return Array.from(pos);
1370
- }
1371
-
1372
- /**
1373
- * Compares two words side by side: meaning count, etymological origin,
1374
- * syllables and vowel-harmony compliance.
1375
- */
1376
- public static async compareWords(a: string, b: string): Promise<WordComparison> {
1377
- const [meaningsA, meaningsB, originA, originB] = await Promise.all([
1378
- this.getMeanings(a),
1379
- this.getMeanings(b),
1380
- this.getOrigin(a),
1381
- this.getOrigin(b),
1382
- ]);
1383
- return {
1384
- a: {
1385
- word: a,
1386
- meaningCount: meaningsA.length,
1387
- origin: originA,
1388
- syllables: this.syllabicate(a),
1389
- harmony: this.checkVowelHarmony(a),
1390
- labialHarmony: this.checkLabialHarmony(a),
1391
- },
1392
- b: {
1393
- word: b,
1394
- meaningCount: meaningsB.length,
1395
- origin: originB,
1396
- syllables: this.syllabicate(b),
1397
- harmony: this.checkVowelHarmony(b),
1398
- labialHarmony: this.checkLabialHarmony(b),
1399
- },
1400
- };
1401
- }
1402
-
1403
- private static readonly STOPWORDS = new Set([
1404
- "ve", "veya", "ile", "ama", "fakat", "ancak", "de", "da", "ki", "bu", "şu", "o",
1405
- "bir", "çok", "az", "gibi", "için", "mi", "mı", "mu", "mü", "ne", "her", "hiç",
1406
- "ben", "sen", "biz", "siz", "onlar", "değil", "bile", "diye",
1407
- ]);
1408
-
1409
- private static firstMeaning(results: WordInfo[]): string | null {
1410
- for (const result of results) {
1411
- for (const anlam of result.anlamlarListe ?? []) {
1412
- if (anlam.anlam) return anlam.anlam;
1413
- }
1414
- }
1415
- return null;
1416
- }
1417
-
1418
- /**
1419
- * Analyzes every distinct word in a text (Turkish stopwords filtered out),
1420
- * returning each word's first meaning and etymological origin if found.
1421
- * Looks each word up individually (throttled), so scales with text length.
1422
- * TDK only indexes dictionary (dictionary/root) forms, not inflected ones —
1423
- * it does no morphological analysis, and neither does this method: a
1424
- * suffixed word like "evde" or "dildir" (root "ev"/"dil" plus a case/verb
1425
- * suffix) will come back `found: false` even though the root is a real
1426
- * headword. This is an inherent limitation of the data source, not a bug.
1427
- */
1428
- public static async analyzeText(text: string): Promise<WordAnalysis[]> {
1429
- const words = text
1430
- .toLocaleLowerCase("tr-TR")
1431
- .replace(/[^\p{L}\s]/gu, " ")
1432
- .split(/\s+/)
1433
- .filter((w) => w.length > 1 && !this.STOPWORDS.has(w));
1434
- const unique = [...new Set(words)];
1435
-
1436
- const analyses: WordAnalysis[] = [];
1437
- for (const word of unique) {
1438
- let results = await this.getWord(word);
1439
- let found = results.length > 0;
1440
- let root: string | undefined;
1441
- let isInflected: boolean | undefined;
1442
-
1443
- if (!found) {
1444
- const resolvedRoot = await this.findRoot(word);
1445
- if (resolvedRoot) {
1446
- results = await this.getWord(resolvedRoot);
1447
- if (results.length > 0) {
1448
- found = true;
1449
- root = resolvedRoot;
1450
- isInflected = true;
1451
- }
1452
- }
1453
- }
1454
-
1455
- analyses.push({
1456
- word,
1457
- found,
1458
- meaning: found ? this.firstMeaning(results) : null,
1459
- origin: found ? results[0].lisan || "Türkçe" : null,
1460
- root,
1461
- isInflected,
1462
- });
1463
- await this.delay(200);
1464
- }
1465
- return analyses;
1466
- }
1467
-
1468
- /**
1469
- * Damerau-Levenshtein edit-distance (optimal string alignment variant):
1470
- * like classic Levenshtein but also counts an adjacent-character
1471
- * transposition (e.g. "yanlız" -> "yalnız") as a single edit instead of
1472
- * two substitutions — a very common class of typo that plain Levenshtein
1473
- * otherwise misses.
1474
- */
1475
- private static damerauLevenshtein(a: string, b: string): number {
1476
- const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
1477
- for (let i = 0; i <= a.length; i++) dp[i][0] = i;
1478
- for (let j = 0; j <= b.length; j++) dp[0][j] = j;
1479
- for (let i = 1; i <= a.length; i++) {
1480
- for (let j = 1; j <= b.length; j++) {
1481
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
1482
- dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
1483
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1484
- dp[i][j] = Math.min(dp[i][j], dp[i - 2][j - 2] + cost);
1485
- }
1486
- }
1487
- }
1488
- return dp[a.length][b.length];
1489
- }
1490
-
1491
- /**
1492
- * Keyboard- and diacritic-aware edit distance: same optimal-string-alignment
1493
- * recurrence as {@link damerauLevenshtein}, but a substitution is charged by
1494
- * {@link keyboardSubCost} (a fraction of an edit when the two letters are
1495
- * adjacent on a Turkish Q keyboard or are ASCII/diacritic siblings) and a
1496
- * transposition costs {@link TRANSPOSITION_COST}. Insertions and deletions
1497
- * still cost a full 1. Used only to *rank* spelling candidates; the plain
1498
- * integer distance still gates whether a suggestion is offered at all.
1499
- */
1500
- private static keyboardAwareDistance(a: string, b: string): number {
1501
- const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
1502
- for (let i = 0; i <= a.length; i++) dp[i][0] = i;
1503
- for (let j = 0; j <= b.length; j++) dp[0][j] = j;
1504
- for (let i = 1; i <= a.length; i++) {
1505
- for (let j = 1; j <= b.length; j++) {
1506
- const cost = keyboardSubCost(a[i - 1], b[j - 1]);
1507
- dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
1508
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1509
- dp[i][j] = Math.min(dp[i][j], dp[i - 2][j - 2] + TRANSPOSITION_COST);
1510
- }
1511
- }
1512
- }
1513
- return dp[a.length][b.length];
1514
- }
1515
-
1516
- /**
1517
- * Fetches multiple words concurrently with a small delay to avoid rate limiting.
1518
- */
1519
- public static async getWordsBatch(words: string[]): Promise<WordInfo[][]> {
1520
- const results: WordInfo[][] = [];
1521
- for (const word of words) {
1522
- try {
1523
- const res = await this.getWord(word);
1524
- results.push(res);
1525
- } catch {
1526
- results.push([]);
1527
- }
1528
- await this.delay(200); // 200ms throttle
1529
- }
1530
- return results;
1531
- }
1532
-
1533
- /**
1534
- * Syllabicates a Turkish word based on general grammar rules.
1535
- * Handles syllable separation for vowels, single consonants, double consonants,
1536
- * and western loanword three-consonant clusters (e.g. e-lek-trik, kon-trol, or-kes-tra).
1537
- */
1538
- public static syllabicate(word: string): string[] {
1539
- const vowels = /[aeıioöuüAEIİOÖUÜ]/;
1540
- const ONSET_CLUSTERS = new Set(["tr", "pr", "kr", "gr", "br", "fr", "dr", "pl", "kl", "fl", "bl", "gl"]);
1541
- const result: string[] = [];
1542
- let currentSyllable = "";
1543
-
1544
- // Go from right to left.
1545
- for (let i = word.length - 1; i >= 0; i--) {
1546
- currentSyllable = word[i] + currentSyllable;
1547
- if (vowels.test(word[i])) {
1548
- // If the preceding char is a consonant and it's not the first char
1549
- // and the char before that is a vowel, then the consonant belongs to this syllable.
1550
- if (i - 1 >= 0 && !vowels.test(word[i - 1])) {
1551
- // It's a consonant.
1552
- if (i - 2 >= 0 && vowels.test(word[i - 2])) {
1553
- currentSyllable = word[i - 1] + currentSyllable;
1554
- i--; // skip the consonant
1555
- } else if (i - 2 >= 0 && !vowels.test(word[i - 2])) {
1556
- // Two consonants before this vowel. Check if three consonants exist and end in an onset cluster
1557
- if (i - 3 >= 0 && !vowels.test(word[i - 3]) && ONSET_CLUSTERS.has((word[i - 2] + word[i - 1]).toLowerCase())) {
1558
- currentSyllable = word[i - 2] + word[i - 1] + currentSyllable;
1559
- i -= 2;
1560
- } else {
1561
- currentSyllable = word[i - 1] + currentSyllable;
1562
- i--;
1563
- }
1564
- }
1565
- }
1566
- result.unshift(currentSyllable);
1567
- currentSyllable = "";
1568
- }
1569
- }
1570
- // If there is anything left (e.g. no vowels at the start like "tr"), add it to the first syllable
1571
- if (currentSyllable) {
1572
- if (result.length > 0) {
1573
- result[0] = currentSyllable + result[0];
1574
- } else {
1575
- result.push(currentSyllable);
1576
- }
1577
- }
1578
- return result;
1579
- }
1580
-
1581
- /**
1582
- * Checks if a word follows Turkish Major Vowel Harmony (Büyük Ünlü Uyumu).
1583
- * Normalizes case via the Turkish locale first: a plain case-insensitive
1584
- * regex would fold ASCII "I" to "i", misreading the back vowel "I"
1585
- * (dotless) as the front vowel "i" (dotted).
1586
- */
1587
- public static checkVowelHarmony(word: string): boolean {
1588
- const lower = word.toLocaleLowerCase("tr-TR");
1589
- const backVowels = /[aıou]/;
1590
- const frontVowels = /[eiöü]/;
1591
- const hasBack = backVowels.test(lower);
1592
- const hasFront = frontVowels.test(lower);
1593
-
1594
- // If it has both front and back vowels, it breaks harmony.
1595
- return !(hasBack && hasFront);
1596
- }
1597
-
1598
- /**
1599
- * Checks if a word follows Turkish Minor Vowel Harmony (Küçük Ünlü Uyumu / Labial Harmony).
1600
- * Rules:
1601
- * 1. After an unrounded vowel (a, e, ı, i), only unrounded vowels (a, e, ı, i) can follow.
1602
- * 2. After a rounded vowel (o, ö, u, ü), either an unrounded wide (a, e) or rounded narrow (u, ü) vowel can follow.
1603
- * Single-syllable words and words with <=1 vowel are considered compliant by convention.
1604
- */
1605
- public static checkLabialHarmony(word: string): boolean {
1606
- const lower = word.toLocaleLowerCase("tr-TR");
1607
- const vowels = lower.split("").filter((ch) => "aeıioöuü".includes(ch));
1608
- if (vowels.length <= 1) return true;
1609
-
1610
- for (let i = 0; i < vowels.length - 1; i++) {
1611
- const v1 = vowels[i];
1612
- const v2 = vowels[i + 1];
1613
-
1614
- if ("aeıi".includes(v1)) {
1615
- if (!"aeıi".includes(v2)) return false;
1616
- } else if ("oöuü".includes(v1)) {
1617
- if (!"aeuü".includes(v2)) return false;
1618
- }
1619
- }
1620
- return true;
1621
- }
1622
-
1623
- /**
1624
- * Searches TDK headwords using a wildcard / pattern string.
1625
- * Wildcards:
1626
- * '_' or '?' matches any single character
1627
- * '*' matches zero or more characters
1628
- * Example: "k_l_m" matches "kalem", "kelam", "kilim".
1629
- * Runs in-memory against TDK's 81k headword list.
1630
- */
1631
- public static async patternSearch(pattern: string, options?: PatternSearchOptions): Promise<string[]> {
1632
- if (!pattern || pattern.trim() === "") return [];
1633
- await this.ensureAutocompleteLoaded();
1634
-
1635
- const cleanPattern = pattern.trim().toLocaleLowerCase("tr-TR");
1636
- const escaped = cleanPattern
1637
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
1638
- .replace(/[_?]/g, "[\\p{L}]")
1639
- .replace(/\*/g, "[\\p{L}]*");
1640
- const regex = new RegExp(`^${escaped}$`, "u");
1641
-
1642
- const max = options?.maxResults ?? 50;
1643
- const matches: string[] = [];
1644
-
1645
- for (const headword of this.autocompleteCache) {
1646
- const lower = headword.toLocaleLowerCase("tr-TR");
1647
- if (regex.test(lower)) {
1648
- matches.push(headword);
1649
- if (matches.length >= max) break;
1650
- }
1651
- }
1652
- return matches;
1653
- }
1654
-
1655
- /**
1656
- * Finds headwords in TDK that can be formed from the given letters (anagrams).
1657
- * If exact-length anagrams exist, they are returned.
1658
- * If none exist (or exactLength is false), valid sub-anagrams (words using a subset of the letters,
1659
- * minimum 3 letters) are returned, sorted by length descending.
1660
- */
1661
- public static async findAnagrams(letters: string, options?: AnagramOptions): Promise<string[]> {
1662
- if (!letters || letters.trim() === "") return [];
1663
- await this.ensureAutocompleteLoaded();
1664
-
1665
- const clean = letters.trim().toLocaleLowerCase("tr-TR").replace(/[^a-zçğıöşüâîû]/gi, "");
1666
- if (clean.length === 0) return [];
1667
-
1668
- const forceExact = options?.exactLength === true;
1669
- const max = options?.maxResults ?? 50;
1670
-
1671
- const getFrequency = (str: string): Record<string, number> => {
1672
- const freq: Record<string, number> = {};
1673
- for (const ch of str) {
1674
- freq[ch] = (freq[ch] || 0) + 1;
1675
- }
1676
- return freq;
1677
- };
1678
-
1679
- const targetFreq = getFrequency(clean);
1680
- const exactMatches: string[] = [];
1681
- const subMatches: string[] = [];
1682
-
1683
- for (const headword of this.autocompleteCache) {
1684
- const lower = headword.toLocaleLowerCase("tr-TR");
1685
- if (lower.includes(" ") || lower.includes("-")) continue;
1686
- if (lower.length > clean.length || lower.length < 3) continue;
1687
-
1688
- const wordFreq = getFrequency(lower);
1689
- let isValid = true;
1690
- for (const [ch, count] of Object.entries(wordFreq)) {
1691
- if (!targetFreq[ch] || targetFreq[ch] < count) {
1692
- isValid = false;
1693
- break;
1694
- }
1695
- }
1696
-
1697
- if (isValid && lower !== clean) {
1698
- if (lower.length === clean.length) {
1699
- exactMatches.push(headword);
1700
- } else {
1701
- subMatches.push(headword);
1702
- }
1703
- }
1704
- }
1705
-
1706
- if (exactMatches.length > 0 || forceExact) {
1707
- return exactMatches.slice(0, max);
1708
- }
1709
-
1710
- subMatches.sort((a, b) => b.length - a.length || a.localeCompare(b, "tr-TR"));
1711
- return subMatches.slice(0, max);
1712
- }
1713
-
1714
- /**
1715
- * Finds words in TDK that rhyme with the given word (sharing the same ending suffix/letters).
1716
- * @param word The target word
1717
- * @param options.minLetters Minimum number of ending characters that must match (default: 3)
1718
- * @param options.maxResults Maximum number of rhyme results to return (default: 50)
1719
- */
1720
- public static async findRhymes(word: string, options?: RhymeOptions): Promise<string[]> {
1721
- if (!word || word.trim() === "") return [];
1722
- await this.ensureAutocompleteLoaded();
1723
-
1724
- const clean = word.trim().toLocaleLowerCase("tr-TR");
1725
- const minLetters = Math.min(options?.minLetters ?? 3, clean.length);
1726
- const max = options?.maxResults ?? 50;
1727
-
1728
- const suffix = clean.slice(-minLetters);
1729
- const results: string[] = [];
1730
-
1731
- for (const headword of this.autocompleteCache) {
1732
- const lower = headword.toLocaleLowerCase("tr-TR");
1733
- if (lower !== clean && lower.endsWith(suffix) && !lower.includes(" ")) {
1734
- results.push(headword);
1735
- if (results.length >= max) break;
1736
- }
1737
- }
1738
-
1739
- return results;
1740
- }
1741
-
1742
- /**
1743
- * Performs comprehensive spelling, grammar, and syntax proofreading on a Turkish text.
1744
- * Detects:
1745
- * 1. Conjunction 'da/de' erroneously joined to verbs or words (e.g. "gitsende" -> "gitsen de")
1746
- * 2. Conjunction 'ki' erroneously joined to verbs (e.g. "gördümki" -> "gördüm ki"), respecting SOMBAHÇEMİ exceptions
1747
- * 3. Question particle 'mi/mı/mu/mü' erroneously joined to words (e.g. "geldimi" -> "geldi mi")
1748
- * 4. Misspelled words with dictionary suggestions (via edit-distance & morphology)
1749
- */
1750
- public static async proofread(text: string): Promise<ProofreadResult> {
1751
- if (!text || text.trim() === "") {
1752
- return { text: text || "", issues: [], isCorrect: true };
1753
- }
1754
-
1755
- await this.ensureAutocompleteLoaded();
1756
- const issues: ProofreadIssue[] = [];
1757
-
1758
- const SOMBAHCEMI = new Set([
1759
- "sanki", "oysaki", "mademki", "belki", "halbuki", "çünkü", "meğerki", "illaki"
1760
- ]);
1761
-
1762
- // 1. Detect multi-word phrases that should be written as single compound words
1763
- const PHRASE_MISTAKES: {
1764
- regex: RegExp;
1765
- suggestion: string;
1766
- message: string;
1767
- type: ProofreadIssue["type"];
1768
- }[] = [
1769
- {
1770
- regex: /\bhiç\s+bir\b/gi,
1771
- suggestion: "hiçbir",
1772
- message: "'hiçbir' belgisiz sıfatı bitişik yazılmalıdır.",
1773
- type: "spelling",
1774
- },
1775
- {
1776
- regex: /\bbir\s+çok\b/gi,
1777
- suggestion: "birçok",
1778
- message: "'birçok' belgisiz sıfatı/zamiri bitişik yazılmalıdır.",
1779
- type: "spelling",
1780
- },
1781
- {
1782
- regex: /\bbir\s+kaç\b/gi,
1783
- suggestion: "birkaç",
1784
- message: "'birkaç' belgisiz sıfatı/zamiri bitişik yazılmalıdır.",
1785
- type: "spelling",
1786
- },
1787
- {
1788
- regex: /\bbir\s+az\b/gi,
1789
- suggestion: "biraz",
1790
- message: "'biraz' sözcüğü bitişik yazılmalıdır.",
1791
- type: "spelling",
1792
- },
1793
- {
1794
- regex: /\bher\s+hangi\b/gi,
1795
- suggestion: "herhangi",
1796
- message: "'herhangi' sözcüğü bitişik yazılmalıdır.",
1797
- type: "spelling",
1798
- },
1799
- {
1800
- regex: /\bgit\s+gide\b/gi,
1801
- suggestion: "gitgide",
1802
- message: "'gitgide' zarfı bitişik yazılmalıdır.",
1803
- type: "spelling",
1804
- },
1805
- {
1806
- regex: /\bbirden\s+bire\b/gi,
1807
- suggestion: "birdenbire",
1808
- message: "'birdenbire' zarfı bitişik yazılmalıdır.",
1809
- type: "spelling",
1810
- },
1811
- {
1812
- regex: /\brast\s+gele\b/gi,
1813
- suggestion: "rastgele",
1814
- message: "'rastgele' zarfı bitişik yazılmalıdır.",
1815
- type: "spelling",
1816
- },
1817
- ];
1818
-
1819
- const coveredRanges: { start: number; end: number }[] = [];
1820
- for (const pm of PHRASE_MISTAKES) {
1821
- let pmMatch: RegExpExecArray | null;
1822
- while ((pmMatch = pm.regex.exec(text)) !== null) {
1823
- const start = pmMatch.index;
1824
- const end = start + pmMatch[0].length;
1825
- coveredRanges.push({ start, end });
1826
- issues.push({
1827
- type: pm.type,
1828
- word: pmMatch[0],
1829
- startIndex: start,
1830
- endIndex: end,
1831
- suggestion: pm.suggestion,
1832
- message: pm.message,
1833
- });
1834
- }
1835
- }
1836
-
1837
- const tokenRegex = /[\p{L}0-9'’]+/gu;
1838
- let match: RegExpExecArray | null;
1839
-
1840
- while ((match = tokenRegex.exec(text)) !== null) {
1841
- const rawWord = match[0];
1842
- const startIndex = match.index;
1843
- const endIndex = startIndex + rawWord.length;
1844
- const lower = rawWord.toLocaleLowerCase("tr-TR");
1845
-
1846
- if (/^\d+$/.test(lower)) continue;
1847
- if (coveredRanges.some((r) => startIndex >= r.start && endIndex <= r.end)) continue;
1848
-
1849
- let flagged = false;
1850
-
1851
- // 1. Check Question Particle (mı, mi, mu, mü) erroneously attached
1852
- const questionMatch = lower.match(/^(.+?)(m[ıiuü](?:sin|sın|sun|sün|siniz|sınız|sunuz|sünüz|yiz|yız|yuz|yüz|m|k)?)$/);
1853
- if (questionMatch) {
1854
- const base = questionMatch[1];
1855
- const particle = questionMatch[2];
1856
- if (base.length >= 2 && (await this.isHeadword(base) || (await this.findRoot(base)) !== null)) {
1857
- if (!(await this.isHeadword(lower))) {
1858
- issues.push({
1859
- type: "question_particle",
1860
- word: rawWord,
1861
- startIndex,
1862
- endIndex,
1863
- suggestion: `${base} ${particle}`,
1864
- message: `'${particle}' soru eki kendinden önceki kelimeden ayrı yazılmalıdır.`,
1865
- });
1866
- flagged = true;
1867
- }
1868
- }
1869
- }
1870
-
1871
- const VERB_CONJUGATION_REGEX =
1872
- /(?:d[ıiuü][kmmn]?|t[ıiuü][kmmn]?|d[ıiuü]n[ıiuü]z?|t[ıiuü]n[ıiuü]z?|m[ıiuü]ş(?:[szn][ıiuü]z?|lar)?|yor(?:um|sun|uz|lar)?|ecek(?:sin|iz|ler)?|acak(?:sın|ız|lar)?|s[ae][mnk]|s[ae]n[ıiz]?|meli|malı|me[mz]|ma[mz])$/i;
1873
-
1874
- // 2. Check Conjunction 'ki' erroneously attached to verbs
1875
- if (!flagged && lower.endsWith("ki") && lower.length > 3) {
1876
- const base = lower.slice(0, -2);
1877
- if (!SOMBAHCEMI.has(lower)) {
1878
- if (!(await this.isHeadword(lower))) {
1879
- const root = await this.findRoot(base);
1880
- const isVerb =
1881
- (base === "demek" || base === "kaldı" || base === "yeter" || base === "bilmem" || VERB_CONJUGATION_REGEX.test(base)) &&
1882
- (root ? root.endsWith("mek") || root.endsWith("mak") : true);
1883
-
1884
- if (isVerb) {
1885
- issues.push({
1886
- type: "conjunction_ki",
1887
- word: rawWord,
1888
- startIndex,
1889
- endIndex,
1890
- suggestion: `${base} ki`,
1891
- message: `'ki' bağlacı ayrı yazılmalıdır.`,
1892
- });
1893
- flagged = true;
1894
- }
1895
- }
1896
- }
1897
- }
1898
-
1899
- // 3. Check Conjunction 'da/de/ta/te' erroneously attached to verbs
1900
- if (!flagged && (lower.endsWith("de") || lower.endsWith("da") || lower.endsWith("te") || lower.endsWith("ta")) && lower.length > 3) {
1901
- const base = lower.slice(0, -2);
1902
- const ending = lower.slice(-2);
1903
- if (!(await this.isHeadword(lower))) {
1904
- const root = await this.findRoot(base);
1905
- const isVerb =
1906
- VERB_CONJUGATION_REGEX.test(base) &&
1907
- (root ? root.endsWith("mek") || root.endsWith("mak") : false);
1908
-
1909
- if (isVerb) {
1910
- const correctEnding = ending.startsWith("t") ? (ending === "te" ? "de" : "da") : ending;
1911
- issues.push({
1912
- type: "conjunction_da",
1913
- word: rawWord,
1914
- startIndex,
1915
- endIndex,
1916
- suggestion: `${base} ${correctEnding}`,
1917
- message: `'da/de' bağlacı fiillerden sonra her zaman ayrı yazılır (bağlaç olan da/de sertleşmez).`,
1918
- });
1919
- flagged = true;
1920
- }
1921
- }
1922
- }
1923
-
1924
- // 4. Check -şey / -sey erroneously attached to preceding word
1925
- const seyMatch = lower.match(/^(.+?)(?:şey|sey)([ıiuaeüodekmnl]+)?$/);
1926
- if (!flagged && seyMatch && !SEY_EXCEPTIONS.has(lower)) {
1927
- let prefix = seyMatch[1];
1928
- const suffix = seyMatch[2] || "";
1929
- if (prefix === "hicbir") prefix = "hiçbir";
1930
- if (prefix === "cok") prefix = "çok";
1931
- issues.push({
1932
- type: "spelling",
1933
- word: rawWord,
1934
- startIndex,
1935
- endIndex,
1936
- suggestion: `${prefix} şey${suffix}`,
1937
- message: "'şey' sözcüğü kendinden önceki kelimeden ayrı yazılmalıdır.",
1938
- });
1939
- flagged = true;
1940
- }
1941
-
1942
- // 5. Check 'yada' conjunction mistake
1943
- if (!flagged && lower === "yada") {
1944
- issues.push({
1945
- type: "spelling",
1946
- word: rawWord,
1947
- startIndex,
1948
- endIndex,
1949
- suggestion: "ya da",
1950
- message: "'ya da' bağlacı her zaman ayrı yazılır.",
1951
- });
1952
- flagged = true;
1953
- }
1954
-
1955
- // 6. Check common vowel drop mistakes: burda, şurda, orda, vb. (TDK Kural 15)
1956
- if (!flagged && (lower === "burda" || lower === "şurda" || lower === "surda" || lower === "orda" || lower === "içerde" || lower === "icerde" || lower === "dışarda" || lower === "disarda" || lower === "yukarda")) {
1957
- const correct = COMMON_MISSPELLINGS[lower] || lower;
1958
- issues.push({
1959
- type: "spelling",
1960
- word: rawWord,
1961
- startIndex,
1962
- endIndex,
1963
- suggestion: correct,
1964
- message: `'${rawWord}' sözcüğünde ünlü düşmesi yapılmaz.`,
1965
- });
1966
- flagged = true;
1967
- }
1968
-
1969
- // 7. General Spell Check
1970
- if (!flagged) {
1971
- const check = await this.checkSpelling(rawWord);
1972
- if (!check.isCorrect) {
1973
- issues.push({
1974
- type: "spelling",
1975
- word: rawWord,
1976
- startIndex,
1977
- endIndex,
1978
- suggestion: check.suggestion,
1979
- message: check.suggestion
1980
- ? `'${rawWord}' yanlış yazılmış olabilir.`
1981
- : `'${rawWord}' sözlükte bulunamadı.`,
1982
- });
1983
- }
1984
- }
1985
- }
1986
-
1987
- issues.sort((a, b) => a.startIndex - b.startIndex);
1988
-
1989
- return {
1990
- text,
1991
- issues,
1992
- isCorrect: issues.length === 0,
1993
- };
1994
- }
1995
- }
1996
-
1997
- /**
1998
- * Configurable instance-based client for TDK API.
1999
- * Useful for multi-tenant applications or backend services requiring isolated configurations.
2000
- */
2001
- export class TDKClient {
2002
- constructor(config?: TDKConfig) {
2003
- if (config) {
2004
- TDK.configure(config);
2005
- }
2006
- }
2007
-
2008
- public getWord(word: string): Promise<WordInfo[]> {
2009
- return TDK.getWord(word);
2010
- }
2011
-
2012
- public getMeanings(word: string): Promise<string[]> {
2013
- return TDK.getMeanings(word);
2014
- }
2015
-
2016
- public checkSpelling(word: string): Promise<SpellCheckResult> {
2017
- return TDK.checkSpelling(word);
2018
- }
2019
-
2020
- public findRoot(word: string): Promise<string | null> {
2021
- return TDK.findRoot(word);
2022
- }
2023
-
2024
- public stem(word: string): Promise<StemResult | null> {
2025
- return TDK.stem(word);
2026
- }
2027
-
2028
- public proofread(text: string): Promise<ProofreadResult> {
2029
- return TDK.proofread(text);
2030
- }
2031
-
2032
- public patternSearch(pattern: string, options?: PatternSearchOptions): Promise<string[]> {
2033
- return TDK.patternSearch(pattern, options);
2034
- }
2035
-
2036
- public findAnagrams(letters: string, options?: AnagramOptions): Promise<string[]> {
2037
- return TDK.findAnagrams(letters, options);
2038
- }
2039
-
2040
- public findRhymes(word: string, options?: RhymeOptions): Promise<string[]> {
2041
- return TDK.findRhymes(word, options);
2042
- }
2043
-
2044
- public syllabicate(word: string): string[] {
2045
- return TDK.syllabicate(word);
2046
- }
2047
-
2048
- public checkVowelHarmony(word: string): boolean {
2049
- return TDK.checkVowelHarmony(word);
2050
- }
2051
-
2052
- public checkLabialHarmony(word: string): boolean {
2053
- return TDK.checkLabialHarmony(word);
2054
- }
2055
- }
2056
-