tdk-api-wrapper 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -5
- package/dist/chunk-P3GX7I53.mjs +704 -0
- package/dist/cli.js +620 -73
- package/dist/cli.mjs +207 -36
- package/dist/index.d.mts +157 -4
- package/dist/index.d.ts +157 -4
- package/dist/index.js +422 -40
- package/dist/index.mjs +9 -3
- package/package.json +1 -1
- package/src/cli.ts +213 -36
- package/src/errors.ts +38 -0
- package/src/index.ts +1 -0
- package/src/tdk.ts +399 -48
- package/src/types.ts +36 -0
- package/dist/chunk-MGSXCUAX.mjs +0 -325
package/src/tdk.ts
CHANGED
|
@@ -1,14 +1,26 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
WordInfo,
|
|
3
|
+
DailyContent,
|
|
4
|
+
SpellCheckResult,
|
|
5
|
+
WordOfTheDay,
|
|
6
|
+
DailyPick,
|
|
7
|
+
WordComparison,
|
|
8
|
+
WordAnalysis,
|
|
9
|
+
TDKRule,
|
|
10
|
+
} from "./types";
|
|
11
|
+
import { TDKValidationError, TDKNetworkError } from "./errors";
|
|
2
12
|
import * as fs from "node:fs";
|
|
3
13
|
import * as path from "node:path";
|
|
4
14
|
import * as os from "node:os";
|
|
15
|
+
import * as https from "node:https";
|
|
5
16
|
|
|
6
17
|
/**
|
|
7
18
|
* TDK (Türk Dil Kurumu) API Wrapper
|
|
8
19
|
*/
|
|
9
20
|
export class TDK {
|
|
10
21
|
private static readonly BASE_URL = "https://sozluk.gov.tr";
|
|
11
|
-
|
|
22
|
+
private static readonly AUDIO_API_HOST = "api.sozluk.gov.tr";
|
|
23
|
+
|
|
12
24
|
// Cache Mechanism
|
|
13
25
|
private static isCacheEnabled = false;
|
|
14
26
|
private static wordCache = new Map<string, WordInfo[]>();
|
|
@@ -43,10 +55,10 @@ export class TDK {
|
|
|
43
55
|
*/
|
|
44
56
|
public static async getWord(word: string): Promise<WordInfo[]> {
|
|
45
57
|
if (!word || word.trim() === "") {
|
|
46
|
-
throw new
|
|
58
|
+
throw new TDKValidationError("Word parameter cannot be empty.");
|
|
47
59
|
}
|
|
48
60
|
|
|
49
|
-
const cleanWord = word.trim().
|
|
61
|
+
const cleanWord = word.trim().toLocaleLowerCase("tr-TR");
|
|
50
62
|
|
|
51
63
|
if (this.isCacheEnabled && this.wordCache.has(cleanWord)) {
|
|
52
64
|
return this.wordCache.get(cleanWord)!;
|
|
@@ -54,28 +66,38 @@ export class TDK {
|
|
|
54
66
|
|
|
55
67
|
const url = `${this.BASE_URL}/gts?ara=${encodeURIComponent(cleanWord)}`;
|
|
56
68
|
|
|
69
|
+
let response: Response;
|
|
57
70
|
try {
|
|
58
|
-
|
|
71
|
+
response = await fetch(url, {
|
|
59
72
|
headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" },
|
|
60
73
|
});
|
|
74
|
+
} catch (error) {
|
|
75
|
+
throw new TDKNetworkError("Failed to fetch word from TDK: request failed.", { cause: error });
|
|
76
|
+
}
|
|
61
77
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
return [];
|
|
68
|
-
}
|
|
78
|
+
if (!response.ok) {
|
|
79
|
+
throw new TDKNetworkError(`Failed to fetch word from TDK: HTTP ${response.status}.`, {
|
|
80
|
+
status: response.status,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
69
83
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
return results;
|
|
84
|
+
let data: unknown;
|
|
85
|
+
try {
|
|
86
|
+
data = await response.json();
|
|
75
87
|
} catch (error) {
|
|
76
|
-
|
|
77
|
-
|
|
88
|
+
throw new TDKNetworkError("Failed to fetch word from TDK: invalid JSON response.", { cause: error });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (!Array.isArray(data) && data && "error" in (data as Record<string, unknown>)) {
|
|
92
|
+
if (this.isCacheEnabled) this.wordCache.set(cleanWord, []);
|
|
93
|
+
return [];
|
|
78
94
|
}
|
|
95
|
+
|
|
96
|
+
const results = data as WordInfo[];
|
|
97
|
+
if (this.isCacheEnabled) {
|
|
98
|
+
this.wordCache.set(cleanWord, results);
|
|
99
|
+
}
|
|
100
|
+
return results;
|
|
79
101
|
}
|
|
80
102
|
|
|
81
103
|
/**
|
|
@@ -114,9 +136,9 @@ export class TDK {
|
|
|
114
136
|
}
|
|
115
137
|
}
|
|
116
138
|
|
|
117
|
-
const cleanPrefix = prefix.
|
|
139
|
+
const cleanPrefix = prefix.toLocaleLowerCase("tr-TR");
|
|
118
140
|
return this.autocompleteCache
|
|
119
|
-
.filter(w => w.
|
|
141
|
+
.filter(w => w.toLocaleLowerCase("tr-TR").startsWith(cleanPrefix))
|
|
120
142
|
.slice(0, 10);
|
|
121
143
|
}
|
|
122
144
|
|
|
@@ -139,14 +161,39 @@ export class TDK {
|
|
|
139
161
|
}
|
|
140
162
|
|
|
141
163
|
/**
|
|
142
|
-
* Returns the etymological origin of the word
|
|
164
|
+
* Returns the etymological origin of the word, or "Türkçe" if TDK doesn't
|
|
165
|
+
* record a foreign origin for it. Returns `null` only when the word itself
|
|
166
|
+
* isn't found in the dictionary at all.
|
|
143
167
|
*/
|
|
144
168
|
public static async getOrigin(word: string): Promise<string | null> {
|
|
145
169
|
const results = await this.getWord(word);
|
|
146
|
-
if (results.length
|
|
147
|
-
|
|
170
|
+
if (results.length === 0) return null;
|
|
171
|
+
return results[0].lisan || "Türkçe";
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Returns whether the word has a recorded foreign etymological origin.
|
|
176
|
+
* Returns `null` (instead of a boolean) when the word isn't found at all.
|
|
177
|
+
*/
|
|
178
|
+
public static async isForeignWord(word: string): Promise<boolean | null> {
|
|
179
|
+
const origin = await this.getOrigin(word);
|
|
180
|
+
if (origin === null) return null;
|
|
181
|
+
return origin !== "Türkçe";
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Groups a list of words by their etymological origin. Words not found in
|
|
186
|
+
* the dictionary are grouped under "Bilinmiyor". Throttled like getWordsBatch.
|
|
187
|
+
*/
|
|
188
|
+
public static async groupByOrigin(words: string[]): Promise<Record<string, string[]>> {
|
|
189
|
+
const groups: Record<string, string[]> = {};
|
|
190
|
+
for (const word of words) {
|
|
191
|
+
const origin = (await this.getOrigin(word)) ?? "Bilinmiyor";
|
|
192
|
+
if (!groups[origin]) groups[origin] = [];
|
|
193
|
+
groups[origin].push(word);
|
|
194
|
+
await this.delay(200);
|
|
148
195
|
}
|
|
149
|
-
return
|
|
196
|
+
return groups;
|
|
150
197
|
}
|
|
151
198
|
|
|
152
199
|
/**
|
|
@@ -172,23 +219,109 @@ export class TDK {
|
|
|
172
219
|
}
|
|
173
220
|
|
|
174
221
|
/**
|
|
175
|
-
*
|
|
176
|
-
*
|
|
222
|
+
* Calls the `api.sozluk.gov.tr/gts-yeni` endpoint the official web UI uses
|
|
223
|
+
* internally (richer than the public `/gts`: includes `seskod`,
|
|
224
|
+
* `anlamEsAnlam`/`anlamKarsitAnlam`, etc). That endpoint 403s unless the
|
|
225
|
+
* request looks like it came from a browser tab on sozluk.gov.tr: it needs
|
|
226
|
+
* an `Origin`/`Referer` pair matching that site AND a browser-like
|
|
227
|
+
* `User-Agent` (our usual `TDK-API-Nodejs-Wrapper/…` UA gets rejected).
|
|
228
|
+
* `fetch` (undici) also strips a manually-set `Origin` header as a
|
|
229
|
+
* forbidden header name, so this uses `node:https` directly instead.
|
|
230
|
+
* This is inherently fragile scraping of an undocumented endpoint — if
|
|
231
|
+
* TDK tightens this check further, this should fail closed to `null`
|
|
232
|
+
* rather than throw.
|
|
233
|
+
*/
|
|
234
|
+
private static fetchGtsYeni(word: string): Promise<any[] | null> {
|
|
235
|
+
return new Promise((resolve) => {
|
|
236
|
+
const req = https.request(
|
|
237
|
+
{
|
|
238
|
+
hostname: this.AUDIO_API_HOST,
|
|
239
|
+
path: `/gts-yeni?ara=${encodeURIComponent(word)}`,
|
|
240
|
+
method: "GET",
|
|
241
|
+
headers: {
|
|
242
|
+
"User-Agent":
|
|
243
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
|
|
244
|
+
Origin: this.BASE_URL,
|
|
245
|
+
Referer: `${this.BASE_URL}/`,
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
(res) => {
|
|
249
|
+
let body = "";
|
|
250
|
+
res.on("data", (chunk) => (body += chunk));
|
|
251
|
+
res.on("end", () => {
|
|
252
|
+
try {
|
|
253
|
+
const data = JSON.parse(body);
|
|
254
|
+
resolve(Array.isArray(data) ? data : null);
|
|
255
|
+
} catch {
|
|
256
|
+
resolve(null);
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
);
|
|
261
|
+
req.on("error", () => resolve(null));
|
|
262
|
+
req.end();
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private static async fetchSeskod(word: string): Promise<string | null> {
|
|
267
|
+
const data = await this.fetchGtsYeni(word);
|
|
268
|
+
const seskod = data?.[0]?.seskod;
|
|
269
|
+
return seskod ? String(seskod) : null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Returns synonyms ("eş anlamlı kelimeler") recorded for the word, pooled
|
|
274
|
+
* across all of its meanings. Uses the same undocumented `gts-yeni`
|
|
275
|
+
* endpoint as `getAudioUrl` — returns `[]` if the lookup fails.
|
|
276
|
+
*/
|
|
277
|
+
public static async getSynonyms(word: string): Promise<string[]> {
|
|
278
|
+
if (!word || word.trim() === "") return [];
|
|
279
|
+
const data = await this.fetchGtsYeni(word.trim().toLocaleLowerCase("tr-TR"));
|
|
280
|
+
if (!data) return [];
|
|
281
|
+
|
|
282
|
+
const synonyms: string[] = [];
|
|
283
|
+
for (const entry of data) {
|
|
284
|
+
for (const anlam of entry.anlamlarListe ?? []) {
|
|
285
|
+
for (const es of anlam.anlamEsAnlam ?? []) {
|
|
286
|
+
if (es.deger) synonyms.push(es.deger);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return [...new Set(synonyms)];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Returns antonyms ("zıt anlamlı kelimeler") recorded for the word, pooled
|
|
295
|
+
* across all of its meanings. Uses the same undocumented `gts-yeni`
|
|
296
|
+
* endpoint as `getAudioUrl` — returns `[]` if the lookup fails.
|
|
297
|
+
*/
|
|
298
|
+
public static async getAntonyms(word: string): Promise<string[]> {
|
|
299
|
+
if (!word || word.trim() === "") return [];
|
|
300
|
+
const data = await this.fetchGtsYeni(word.trim().toLocaleLowerCase("tr-TR"));
|
|
301
|
+
if (!data) return [];
|
|
302
|
+
|
|
303
|
+
const antonyms: string[] = [];
|
|
304
|
+
for (const entry of data) {
|
|
305
|
+
for (const anlam of entry.anlamlarListe ?? []) {
|
|
306
|
+
for (const ka of anlam.anlamKarsitAnlam ?? []) {
|
|
307
|
+
if (ka.deger) antonyms.push(ka.deger);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return [...new Set(antonyms)];
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Returns the direct URL of the audio pronunciation, if TDK has one recorded for this word.
|
|
177
316
|
*/
|
|
178
317
|
public static async getAudioUrl(word: string): Promise<string | null> {
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
// For simplicity without reversing their full hash, we provide a placeholder or return a pattern.
|
|
182
|
-
// However, if we assume 'ses/' + word + '.wav' works (it doesn't usually), we can just say it's not fully public.
|
|
183
|
-
// Since we must implement this, we'll try a common pattern.
|
|
184
|
-
if (results.length > 0) {
|
|
185
|
-
// Actually, TDK audio endpoint is often: https://sozluk.gov.tr/ses/ + md5(word) + .wav
|
|
186
|
-
// We will just return null for now if TDK has restricted audio access, but let's implement the interface.
|
|
187
|
-
// We'll return a hypothetical audio link based on standard TDK audio patterns.
|
|
188
|
-
// Wait, TDK audio uses 'yazim?ara=' sometimes or 'ses/'. Let's return a basic structure.
|
|
189
|
-
return `https://sozluk.gov.tr/ses/${encodeURIComponent(word)}.wav`;
|
|
318
|
+
if (!word || word.trim() === "") {
|
|
319
|
+
throw new TDKValidationError("Word parameter cannot be empty.");
|
|
190
320
|
}
|
|
191
|
-
|
|
321
|
+
|
|
322
|
+
const seskod = await this.fetchSeskod(word.trim().toLocaleLowerCase("tr-TR"));
|
|
323
|
+
if (!seskod) return null;
|
|
324
|
+
return `https://${this.AUDIO_API_HOST}/ses/${encodeURIComponent(seskod)}.wav`;
|
|
192
325
|
}
|
|
193
326
|
|
|
194
327
|
/**
|
|
@@ -223,14 +356,34 @@ export class TDK {
|
|
|
223
356
|
// 2. If not, check "sıkça yapılan yanlışlar" from DailyContent
|
|
224
357
|
const daily = await this.getDailyContent();
|
|
225
358
|
if (daily) {
|
|
226
|
-
const syydMatch = daily.syyd.find(s => s.yanliskelime.
|
|
359
|
+
const syydMatch = daily.syyd.find(s => s.yanliskelime.toLocaleLowerCase("tr-TR") === word.toLocaleLowerCase("tr-TR"));
|
|
227
360
|
if (syydMatch) {
|
|
228
361
|
return { isCorrect: false, word, suggestion: syydMatch.dogrukelime };
|
|
229
362
|
}
|
|
230
|
-
const mixMatch = daily.karistirma.find(s => s.yanlis.
|
|
363
|
+
const mixMatch = daily.karistirma.find(s => s.yanlis.toLocaleLowerCase("tr-TR") === word.toLocaleLowerCase("tr-TR"));
|
|
231
364
|
if (mixMatch) {
|
|
232
365
|
return { isCorrect: false, word, suggestion: mixMatch.dogru };
|
|
233
366
|
}
|
|
367
|
+
|
|
368
|
+
// 3. No exact match in TDK's fixed lists: fall back to the closest word
|
|
369
|
+
// (by edit distance) within that same small pool. This is NOT a search
|
|
370
|
+
// over the full dictionary — TDK exposes no such lookup — just a
|
|
371
|
+
// best-effort nudge using the "sık yapılan yanlışlar" data we already have.
|
|
372
|
+
const candidates = [
|
|
373
|
+
...daily.syyd.map((s) => s.dogrukelime),
|
|
374
|
+
...daily.karistirma.flatMap((s) => [s.yanlis, s.dogru]),
|
|
375
|
+
...daily.kelime.map((k) => k.madde),
|
|
376
|
+
];
|
|
377
|
+
let best: { candidate: string; distance: number } | null = null;
|
|
378
|
+
for (const candidate of candidates) {
|
|
379
|
+
const distance = this.levenshtein(word.toLocaleLowerCase("tr-TR"), candidate.toLocaleLowerCase("tr-TR"));
|
|
380
|
+
if (distance > 0 && (!best || distance < best.distance)) {
|
|
381
|
+
best = { candidate, distance };
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (best && best.distance <= 2) {
|
|
385
|
+
return { isCorrect: false, word, suggestion: best.candidate };
|
|
386
|
+
}
|
|
234
387
|
}
|
|
235
388
|
return { isCorrect: false, word };
|
|
236
389
|
}
|
|
@@ -256,6 +409,109 @@ export class TDK {
|
|
|
256
409
|
return null;
|
|
257
410
|
}
|
|
258
411
|
|
|
412
|
+
/**
|
|
413
|
+
* Returns today's word of the day along with all of its listed meanings.
|
|
414
|
+
*/
|
|
415
|
+
public static async getWordOfTheDay(): Promise<WordOfTheDay | null> {
|
|
416
|
+
const daily = await this.getDailyContent();
|
|
417
|
+
if (!daily || daily.kelime.length === 0) return null;
|
|
418
|
+
|
|
419
|
+
const word = daily.kelime[0].madde;
|
|
420
|
+
const meanings = daily.kelime.filter((k) => k.madde === word).map((k) => k.anlam);
|
|
421
|
+
return { word, meanings };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Picks a random entry (word or proverb) from today's daily content.
|
|
426
|
+
* Note: this samples from today's `getDailyContent()` picks, not the full dictionary.
|
|
427
|
+
*/
|
|
428
|
+
public static async getRandomWord(): Promise<DailyPick | null> {
|
|
429
|
+
const daily = await this.getDailyContent();
|
|
430
|
+
if (!daily) return null;
|
|
431
|
+
|
|
432
|
+
const pool: DailyPick[] = [
|
|
433
|
+
...daily.kelime.map((k) => ({ type: "kelime" as const, madde: k.madde, anlam: k.anlam })),
|
|
434
|
+
...daily.atasoz.map((a) => ({ type: "atasoz" as const, madde: a.madde, anlam: a.anlam })),
|
|
435
|
+
];
|
|
436
|
+
if (pool.length === 0) return null;
|
|
437
|
+
|
|
438
|
+
return pool[Math.floor(Math.random() * pool.length)];
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Returns the spelling-rule page(s) ("yazım kuralları") linked from TDK's
|
|
443
|
+
* `/icerik` daily-content feed, e.g. `{ adi: "Kısaltmalar", url: "https://..." }`.
|
|
444
|
+
* Note: like `getRandomWord()`, this is NOT a fixed catalog — `/icerik`
|
|
445
|
+
* appears to hand back a single randomly-rotated rule per request, so two
|
|
446
|
+
* calls a second apart can return entirely different rules.
|
|
447
|
+
*/
|
|
448
|
+
public static async getKurallar(): Promise<TDKRule[]> {
|
|
449
|
+
const daily = await this.getDailyContent();
|
|
450
|
+
return daily?.kural ?? [];
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Fetches the full plain-text content of a named spelling rule (matched
|
|
455
|
+
* case-insensitively, substring match) from `tdk.gov.tr`. Since `/icerik`
|
|
456
|
+
* hands back a single randomly-rotated rule per request (out of a pool of
|
|
457
|
+
* roughly twenty) rather than a fixed catalog, a single `getKurallar()`
|
|
458
|
+
* draw would rarely match a given name — this re-draws (bounded, with a
|
|
459
|
+
* short delay) until it finds a match or gives up. Returns `null` if no
|
|
460
|
+
* match turns up within the attempt budget or the matched page can't be
|
|
461
|
+
* parsed.
|
|
462
|
+
*/
|
|
463
|
+
public static async getRule(name: string): Promise<string | null> {
|
|
464
|
+
if (!name || name.trim() === "") return null;
|
|
465
|
+
const target = name.trim().toLocaleLowerCase("tr-TR");
|
|
466
|
+
|
|
467
|
+
for (let attempt = 0; attempt < 25; attempt++) {
|
|
468
|
+
const rules = await this.getKurallar();
|
|
469
|
+
const match = rules.find((r) => r.adi.toLocaleLowerCase("tr-TR").includes(target));
|
|
470
|
+
if (match) return this.fetchRuleText(match.url);
|
|
471
|
+
await this.delay(100);
|
|
472
|
+
}
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* `tdk.gov.tr` rule pages are WordPress/Avada-themed. The actual article
|
|
478
|
+
* text lives in `<div ... itemprop="text">...</div>` right before a
|
|
479
|
+
* `<footer class="entry...">` (share buttons, author box, structured-data
|
|
480
|
+
* spans) — cutting there avoids that trailing cruft.
|
|
481
|
+
*/
|
|
482
|
+
private static async fetchRuleText(url: string): Promise<string | null> {
|
|
483
|
+
try {
|
|
484
|
+
const response = await fetch(url, { headers: { "User-Agent": "TDK-API-Nodejs-Wrapper/1.0" } });
|
|
485
|
+
if (!response.ok) return null;
|
|
486
|
+
const html = await response.text();
|
|
487
|
+
|
|
488
|
+
const marker = html.indexOf('itemprop="text"');
|
|
489
|
+
if (marker === -1) return null;
|
|
490
|
+
const contentStart = html.indexOf(">", marker) + 1;
|
|
491
|
+
const contentEnd = html.indexOf("<footer", contentStart);
|
|
492
|
+
if (contentEnd === -1) return null;
|
|
493
|
+
|
|
494
|
+
return this.htmlToPlainText(html.slice(contentStart, contentEnd));
|
|
495
|
+
} catch {
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private static htmlToPlainText(html: string): string {
|
|
501
|
+
return html
|
|
502
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
503
|
+
.replace(/<\/(p|div)>/gi, "\n\n")
|
|
504
|
+
.replace(/<[^>]+>/g, "")
|
|
505
|
+
.replace(/ /gi, " ")
|
|
506
|
+
.replace(/&/gi, "&")
|
|
507
|
+
.replace(/"/gi, '"')
|
|
508
|
+
.replace(/'|’/gi, "'")
|
|
509
|
+
.replace(/[ \t]+/g, " ")
|
|
510
|
+
.replace(/[ \t]*\n[ \t]*/g, "\n")
|
|
511
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
512
|
+
.trim();
|
|
513
|
+
}
|
|
514
|
+
|
|
259
515
|
/**
|
|
260
516
|
* Returns compound words that contain this word.
|
|
261
517
|
*/
|
|
@@ -275,17 +531,20 @@ export class TDK {
|
|
|
275
531
|
|
|
276
532
|
/**
|
|
277
533
|
* Returns the part of speech (isim, sıfat, zarf vb.).
|
|
534
|
+
* TDK's `ozelliklerListe` mixes grammatical categories (`tur: "3"`, e.g.
|
|
535
|
+
* sıfat/zarf/isim) with usage-register tags (`tur: "4"`, e.g. mecaz/argo)
|
|
536
|
+
* in the same list — only `tur === "3"` entries are actual parts of speech.
|
|
278
537
|
*/
|
|
279
538
|
public static async getPartOfSpeech(word: string): Promise<string[]> {
|
|
280
539
|
const results = await this.getWord(word);
|
|
281
540
|
const pos = new Set<string>();
|
|
282
|
-
|
|
541
|
+
|
|
283
542
|
for (const result of results) {
|
|
284
543
|
if (result.anlamlarListe) {
|
|
285
544
|
for (const anlam of result.anlamlarListe) {
|
|
286
545
|
if (anlam.ozelliklerListe) {
|
|
287
546
|
for (const ozellik of anlam.ozelliklerListe) {
|
|
288
|
-
pos.add(ozellik.tam_adi);
|
|
547
|
+
if (ozellik.tur === "3") pos.add(ozellik.tam_adi);
|
|
289
548
|
}
|
|
290
549
|
}
|
|
291
550
|
}
|
|
@@ -297,6 +556,94 @@ export class TDK {
|
|
|
297
556
|
return Array.from(pos);
|
|
298
557
|
}
|
|
299
558
|
|
|
559
|
+
/**
|
|
560
|
+
* Compares two words side by side: meaning count, etymological origin,
|
|
561
|
+
* syllables and vowel-harmony compliance.
|
|
562
|
+
*/
|
|
563
|
+
public static async compareWords(a: string, b: string): Promise<WordComparison> {
|
|
564
|
+
const [meaningsA, meaningsB, originA, originB] = await Promise.all([
|
|
565
|
+
this.getMeanings(a),
|
|
566
|
+
this.getMeanings(b),
|
|
567
|
+
this.getOrigin(a),
|
|
568
|
+
this.getOrigin(b),
|
|
569
|
+
]);
|
|
570
|
+
return {
|
|
571
|
+
a: {
|
|
572
|
+
word: a,
|
|
573
|
+
meaningCount: meaningsA.length,
|
|
574
|
+
origin: originA,
|
|
575
|
+
syllables: this.syllabicate(a),
|
|
576
|
+
harmony: this.checkVowelHarmony(a),
|
|
577
|
+
},
|
|
578
|
+
b: {
|
|
579
|
+
word: b,
|
|
580
|
+
meaningCount: meaningsB.length,
|
|
581
|
+
origin: originB,
|
|
582
|
+
syllables: this.syllabicate(b),
|
|
583
|
+
harmony: this.checkVowelHarmony(b),
|
|
584
|
+
},
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
private static readonly STOPWORDS = new Set([
|
|
589
|
+
"ve", "veya", "ile", "ama", "fakat", "ancak", "de", "da", "ki", "bu", "şu", "o",
|
|
590
|
+
"bir", "çok", "az", "gibi", "için", "mi", "mı", "mu", "mü", "ne", "her", "hiç",
|
|
591
|
+
"ben", "sen", "biz", "siz", "onlar", "değil", "bile", "diye",
|
|
592
|
+
]);
|
|
593
|
+
|
|
594
|
+
private static firstMeaning(results: WordInfo[]): string | null {
|
|
595
|
+
for (const result of results) {
|
|
596
|
+
for (const anlam of result.anlamlarListe ?? []) {
|
|
597
|
+
if (anlam.anlam) return anlam.anlam;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return null;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Analyzes every distinct word in a text (Turkish stopwords filtered out),
|
|
605
|
+
* returning each word's first meaning and etymological origin if found.
|
|
606
|
+
* Looks each word up individually (throttled), so scales with text length.
|
|
607
|
+
*/
|
|
608
|
+
public static async analyzeText(text: string): Promise<WordAnalysis[]> {
|
|
609
|
+
const words = text
|
|
610
|
+
.toLocaleLowerCase("tr-TR")
|
|
611
|
+
.replace(/[^\p{L}\s]/gu, " ")
|
|
612
|
+
.split(/\s+/)
|
|
613
|
+
.filter((w) => w.length > 1 && !this.STOPWORDS.has(w));
|
|
614
|
+
const unique = [...new Set(words)];
|
|
615
|
+
|
|
616
|
+
const analyses: WordAnalysis[] = [];
|
|
617
|
+
for (const word of unique) {
|
|
618
|
+
const results = await this.getWord(word);
|
|
619
|
+
const found = results.length > 0;
|
|
620
|
+
analyses.push({
|
|
621
|
+
word,
|
|
622
|
+
found,
|
|
623
|
+
meaning: found ? this.firstMeaning(results) : null,
|
|
624
|
+
origin: found ? results[0].lisan || "Türkçe" : null,
|
|
625
|
+
});
|
|
626
|
+
await this.delay(200);
|
|
627
|
+
}
|
|
628
|
+
return analyses;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Classic edit-distance between two strings.
|
|
633
|
+
*/
|
|
634
|
+
private static levenshtein(a: string, b: string): number {
|
|
635
|
+
const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
|
|
636
|
+
for (let i = 0; i <= a.length; i++) dp[i][0] = i;
|
|
637
|
+
for (let j = 0; j <= b.length; j++) dp[0][j] = j;
|
|
638
|
+
for (let i = 1; i <= a.length; i++) {
|
|
639
|
+
for (let j = 1; j <= b.length; j++) {
|
|
640
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
641
|
+
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return dp[a.length][b.length];
|
|
645
|
+
}
|
|
646
|
+
|
|
300
647
|
/**
|
|
301
648
|
* Fetches multiple words concurrently with a small delay to avoid rate limiting.
|
|
302
649
|
*/
|
|
@@ -357,13 +704,17 @@ export class TDK {
|
|
|
357
704
|
|
|
358
705
|
/**
|
|
359
706
|
* Checks if a word follows Turkish Major Vowel Harmony (Büyük Ünlü Uyumu).
|
|
707
|
+
* Normalizes case via the Turkish locale first: a plain case-insensitive
|
|
708
|
+
* regex would fold ASCII "I" to "i", misreading the back vowel "I"
|
|
709
|
+
* (dotless) as the front vowel "i" (dotted).
|
|
360
710
|
*/
|
|
361
711
|
public static checkVowelHarmony(word: string): boolean {
|
|
362
|
-
const
|
|
363
|
-
const
|
|
364
|
-
const
|
|
365
|
-
const
|
|
366
|
-
|
|
712
|
+
const lower = word.toLocaleLowerCase("tr-TR");
|
|
713
|
+
const backVowels = /[aıou]/;
|
|
714
|
+
const frontVowels = /[eiöü]/;
|
|
715
|
+
const hasBack = backVowels.test(lower);
|
|
716
|
+
const hasFront = frontVowels.test(lower);
|
|
717
|
+
|
|
367
718
|
// If it has both front and back vowels, it breaks harmony.
|
|
368
719
|
return !(hasBack && hasFront);
|
|
369
720
|
}
|
package/src/types.ts
CHANGED
|
@@ -87,4 +87,40 @@ export interface SpellCheckResult {
|
|
|
87
87
|
suggestion?: string;
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
+
export interface WordOfTheDay {
|
|
91
|
+
word: string;
|
|
92
|
+
meanings: string[];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface DailyPick {
|
|
96
|
+
type: "kelime" | "atasoz";
|
|
97
|
+
madde: string;
|
|
98
|
+
anlam: string;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface TDKRule {
|
|
102
|
+
adi: string;
|
|
103
|
+
url: string;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface WordComparisonSide {
|
|
107
|
+
word: string;
|
|
108
|
+
meaningCount: number;
|
|
109
|
+
origin: string | null;
|
|
110
|
+
syllables: string[];
|
|
111
|
+
harmony: boolean;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface WordComparison {
|
|
115
|
+
a: WordComparisonSide;
|
|
116
|
+
b: WordComparisonSide;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface WordAnalysis {
|
|
120
|
+
word: string;
|
|
121
|
+
found: boolean;
|
|
122
|
+
meaning: string | null;
|
|
123
|
+
origin: string | null;
|
|
124
|
+
}
|
|
125
|
+
|
|
90
126
|
export type TDKResponse = WordInfo[] | { error: string };
|