wobble-bibble 1.1.0 → 1.2.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/dist/index.d.ts +109 -63
- package/dist/index.js +127 -66
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -31,68 +31,6 @@ declare const TRANSLATION_MARKER_PARTS: {
|
|
|
31
31
|
*/
|
|
32
32
|
declare const MARKER_ID_PATTERN: string;
|
|
33
33
|
//#endregion
|
|
34
|
-
//#region src/types.d.ts
|
|
35
|
-
/**
|
|
36
|
-
* A single segment (Arabic source excerpt) identified by an ID.
|
|
37
|
-
*
|
|
38
|
-
* Canonical shape (breaking change): `{ id, text }`.
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* const seg: Segment = { id: 'P1', text: 'نص عربي...' };
|
|
42
|
-
*/
|
|
43
|
-
type Segment = {
|
|
44
|
-
id: string;
|
|
45
|
-
text: string;
|
|
46
|
-
};
|
|
47
|
-
/**
|
|
48
|
-
* Machine-readable error types emitted by the validator.
|
|
49
|
-
* Keep these stable: clients may map them to UI severities.
|
|
50
|
-
*/
|
|
51
|
-
type ValidationErrorType = 'invalid_marker_format' | 'no_valid_markers' | 'newline_after_id' | 'duplicate_id' | 'invented_id' | 'missing_id_gap' | 'mismatched_colons' | 'truncated_segment' | 'implicit_continuation' | 'meta_talk' | 'arabic_leak' | 'wrong_diacritics' | 'empty_parentheses' | 'length_mismatch' | 'all_caps' | 'archaic_register' | 'multiword_translit_without_gloss';
|
|
52
|
-
/**
|
|
53
|
-
* A single validation error.
|
|
54
|
-
*/
|
|
55
|
-
type ValidationError = {
|
|
56
|
-
type: ValidationErrorType;
|
|
57
|
-
message: string;
|
|
58
|
-
id?: string;
|
|
59
|
-
match?: string;
|
|
60
|
-
};
|
|
61
|
-
/**
|
|
62
|
-
* Result of validating an LLM translation response against a set of source segments.
|
|
63
|
-
*/
|
|
64
|
-
type ValidationResponseResult = {
|
|
65
|
-
normalizedResponse: string;
|
|
66
|
-
parsedIds: string[];
|
|
67
|
-
errors: ValidationError[];
|
|
68
|
-
};
|
|
69
|
-
//#endregion
|
|
70
|
-
//#region src/textUtils.d.ts
|
|
71
|
-
/**
|
|
72
|
-
* Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.
|
|
73
|
-
* Each segment is formatted as "ID - Text" and separated by double newlines.
|
|
74
|
-
*
|
|
75
|
-
* @param segments - Array of segments to format
|
|
76
|
-
* @param prompt - The instruction/system prompt to prepend
|
|
77
|
-
* @returns Combined prompt and formatted text
|
|
78
|
-
*/
|
|
79
|
-
declare const formatExcerptsForPrompt: (segments: Segment[], prompt: string) => string;
|
|
80
|
-
/**
|
|
81
|
-
* Normalize line endings and split merged markers onto separate lines.
|
|
82
|
-
*
|
|
83
|
-
* @example
|
|
84
|
-
* // "helloP1 - ..." becomes split onto a new line before "P1 -"
|
|
85
|
-
* normalizeTranslationText('helloP1 - x').includes('\\nP1 -') === true
|
|
86
|
-
*/
|
|
87
|
-
declare const normalizeTranslationText: (content: string) => string;
|
|
88
|
-
/**
|
|
89
|
-
* Extract translation IDs from normalized response, in order.
|
|
90
|
-
*
|
|
91
|
-
* @example
|
|
92
|
-
* extractTranslationIds('P1 - a\\nP2b - b') // => ['P1', 'P2b']
|
|
93
|
-
*/
|
|
94
|
-
declare const extractTranslationIds: (text: string) => string[];
|
|
95
|
-
//#endregion
|
|
96
34
|
//#region .generated/prompts.d.ts
|
|
97
35
|
type PromptId = 'master_prompt' | 'encyclopedia_mixed' | 'fatawa' | 'fiqh' | 'hadith' | 'jarh_wa_tadil' | 'tafsir' | 'usul_al_fiqh';
|
|
98
36
|
declare const PROMPTS: readonly [{
|
|
@@ -187,6 +125,114 @@ declare const getPromptIds: () => PromptId[];
|
|
|
187
125
|
*/
|
|
188
126
|
declare const getMasterPrompt: () => string;
|
|
189
127
|
//#endregion
|
|
128
|
+
//#region src/types.d.ts
|
|
129
|
+
/**
|
|
130
|
+
* A single segment (Arabic source excerpt) identified by an ID.
|
|
131
|
+
*
|
|
132
|
+
* Canonical shape (breaking change): `{ id, text }`.
|
|
133
|
+
*
|
|
134
|
+
* @example
|
|
135
|
+
* const seg: Segment = { id: 'P1', text: 'نص عربي...' };
|
|
136
|
+
*/
|
|
137
|
+
type Segment = {
|
|
138
|
+
id: string;
|
|
139
|
+
text: string;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Machine-readable error types emitted by the validator.
|
|
143
|
+
* Keep these stable: clients may map them to UI severities.
|
|
144
|
+
*/
|
|
145
|
+
type ValidationErrorType = 'invalid_marker_format' | 'no_valid_markers' | 'newline_after_id' | 'duplicate_id' | 'invented_id' | 'missing_id_gap' | 'mismatched_colons' | 'truncated_segment' | 'implicit_continuation' | 'meta_talk' | 'arabic_leak' | 'wrong_diacritics' | 'empty_parentheses' | 'length_mismatch' | 'all_caps' | 'archaic_register' | 'multiword_translit_without_gloss';
|
|
146
|
+
/**
|
|
147
|
+
* A single validation error.
|
|
148
|
+
*/
|
|
149
|
+
type ValidationError = {
|
|
150
|
+
type: ValidationErrorType;
|
|
151
|
+
message: string;
|
|
152
|
+
id?: string;
|
|
153
|
+
match?: string;
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* Result of validating an LLM translation response against a set of source segments.
|
|
157
|
+
*/
|
|
158
|
+
type ValidationResponseResult = {
|
|
159
|
+
normalizedResponse: string;
|
|
160
|
+
parsedIds: string[];
|
|
161
|
+
errors: ValidationError[];
|
|
162
|
+
};
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/textUtils.d.ts
|
|
165
|
+
/**
|
|
166
|
+
* Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.
|
|
167
|
+
* Each segment is formatted as "ID - Text" and separated by double newlines.
|
|
168
|
+
*
|
|
169
|
+
* @param segments - Array of segments to format
|
|
170
|
+
* @param prompt - The instruction/system prompt to prepend
|
|
171
|
+
* @returns Combined prompt and formatted text
|
|
172
|
+
*/
|
|
173
|
+
declare const formatExcerptsForPrompt: (segments: Segment[], prompt: string) => string;
|
|
174
|
+
/**
|
|
175
|
+
* Normalize line endings and split merged markers onto separate lines.
|
|
176
|
+
*
|
|
177
|
+
* @example
|
|
178
|
+
* // "helloP1 - ..." becomes split onto a new line before "P1 -"
|
|
179
|
+
* normalizeTranslationText('helloP1 - x').includes('\\nP1 -') === true
|
|
180
|
+
*/
|
|
181
|
+
declare const normalizeTranslationText: (content: string) => string;
|
|
182
|
+
/**
|
|
183
|
+
* Extract translation IDs from normalized response, in order.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* extractTranslationIds('P1 - a\\nP2b - b') // => ['P1', 'P2b']
|
|
187
|
+
*/
|
|
188
|
+
declare const extractTranslationIds: (text: string) => string[];
|
|
189
|
+
/**
|
|
190
|
+
* Parse a single translation line in the form "ID - translation".
|
|
191
|
+
*
|
|
192
|
+
* Note: This returns a translation entry shape, not an Arabic source `Segment`.
|
|
193
|
+
*
|
|
194
|
+
* @param line - Single line to parse
|
|
195
|
+
* @returns `{ id, translation }` when valid; otherwise `null`
|
|
196
|
+
*
|
|
197
|
+
* @example
|
|
198
|
+
* parseTranslationLine('P1 - Hello')?.id === 'P1'
|
|
199
|
+
*/
|
|
200
|
+
declare const parseTranslationLine: (line: string) => {
|
|
201
|
+
id: string;
|
|
202
|
+
translation: string;
|
|
203
|
+
} | null;
|
|
204
|
+
/**
|
|
205
|
+
* Parses bulk translation text into a Map for efficient O(1) lookup.
|
|
206
|
+
*
|
|
207
|
+
* Handles multi-line translations: subsequent non-marker lines belong to the previous ID.
|
|
208
|
+
*
|
|
209
|
+
* @param rawText - Raw text containing translations in format "ID - Translation text"
|
|
210
|
+
* @returns An object with `count` and `translationMap`
|
|
211
|
+
*
|
|
212
|
+
* @example
|
|
213
|
+
* parseTranslations('P1 - a\\nP2 - b').count === 2
|
|
214
|
+
*/
|
|
215
|
+
declare const parseTranslations: (rawText: string) => {
|
|
216
|
+
count: number;
|
|
217
|
+
translationMap: Map<string, string>;
|
|
218
|
+
};
|
|
219
|
+
/**
|
|
220
|
+
* Parse translations into an ordered array (preserving the original response order).
|
|
221
|
+
*
|
|
222
|
+
* This differs from `parseTranslations()` which returns a Map and therefore cannot represent
|
|
223
|
+
* duplicates as separate entries.
|
|
224
|
+
*
|
|
225
|
+
* @param rawText - Raw text containing translations in format "ID - Translation text"
|
|
226
|
+
* @returns Array of `{ id, translation }` entries in appearance order
|
|
227
|
+
*
|
|
228
|
+
* @example
|
|
229
|
+
* parseTranslationsInOrder('P1 - a\\nP2 - b').map((e) => e.id) // => ['P1', 'P2']
|
|
230
|
+
*/
|
|
231
|
+
declare const parseTranslationsInOrder: (rawText: string) => {
|
|
232
|
+
id: string;
|
|
233
|
+
translation: string;
|
|
234
|
+
}[];
|
|
235
|
+
//#endregion
|
|
190
236
|
//#region src/validation.d.ts
|
|
191
237
|
/**
|
|
192
238
|
* Human-readable descriptions for each `ValidationErrorType`, intended for client UIs and logs.
|
|
@@ -283,5 +329,5 @@ declare const validateTranslationResponse: (segments: Segment[], response: strin
|
|
|
283
329
|
parsedIds: string[];
|
|
284
330
|
};
|
|
285
331
|
//#endregion
|
|
286
|
-
export { MARKER_ID_PATTERN, Markers, type PromptId, type PromptMetadata, type Segment, type StackedPrompt, TRANSLATION_MARKER_PARTS, VALIDATION_ERROR_TYPE_INFO, type ValidationError, type ValidationErrorType, type ValidationResponseResult, extractTranslationIds, formatExcerptsForPrompt, getMasterPrompt, getPrompt, getPromptIds, getPrompts, getStackedPrompt, normalizeTranslationText, stackPrompts, validateTranslationResponse };
|
|
332
|
+
export { MARKER_ID_PATTERN, Markers, type PromptId, type PromptMetadata, type Segment, type StackedPrompt, TRANSLATION_MARKER_PARTS, VALIDATION_ERROR_TYPE_INFO, type ValidationError, type ValidationErrorType, type ValidationResponseResult, extractTranslationIds, formatExcerptsForPrompt, getMasterPrompt, getPrompt, getPromptIds, getPrompts, getStackedPrompt, normalizeTranslationText, parseTranslationLine, parseTranslations, parseTranslationsInOrder, stackPrompts, validateTranslationResponse };
|
|
287
333
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -52,71 +52,6 @@ const MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK = 50;
|
|
|
52
52
|
const MIN_TRANSLATION_RATIO = .25;
|
|
53
53
|
const COLON_PATTERN = /[::]/g;
|
|
54
54
|
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region src/textUtils.ts
|
|
57
|
-
/**
|
|
58
|
-
* Segment type is shared across the library.
|
|
59
|
-
*/
|
|
60
|
-
/**
|
|
61
|
-
* Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.
|
|
62
|
-
* Each segment is formatted as "ID - Text" and separated by double newlines.
|
|
63
|
-
*
|
|
64
|
-
* @param segments - Array of segments to format
|
|
65
|
-
* @param prompt - The instruction/system prompt to prepend
|
|
66
|
-
* @returns Combined prompt and formatted text
|
|
67
|
-
*/
|
|
68
|
-
const formatExcerptsForPrompt = (segments, prompt) => {
|
|
69
|
-
return [prompt, segments.map((e) => `${e.id} - ${e.text}`).join("\n\n")].join("\n\n");
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* Normalize line endings and split merged markers onto separate lines.
|
|
73
|
-
*
|
|
74
|
-
* @example
|
|
75
|
-
* // "helloP1 - ..." becomes split onto a new line before "P1 -"
|
|
76
|
-
* normalizeTranslationText('helloP1 - x').includes('\\nP1 -') === true
|
|
77
|
-
*/
|
|
78
|
-
const normalizeTranslationText = (content) => {
|
|
79
|
-
const normalizedLineEndings = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
80
|
-
const mergedMarkerWithSpacePattern = new RegExp(` (${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`, "gm");
|
|
81
|
-
const mergedMarkerNoSpacePattern = new RegExp(`([^\\s\\n])(${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`, "gm");
|
|
82
|
-
return normalizedLineEndings.replace(mergedMarkerWithSpacePattern, "\n$1").replace(mergedMarkerNoSpacePattern, "$1\n$2").replace(/\\\[/gm, "[");
|
|
83
|
-
};
|
|
84
|
-
/**
|
|
85
|
-
* Extract translation IDs from normalized response, in order.
|
|
86
|
-
*
|
|
87
|
-
* @example
|
|
88
|
-
* extractTranslationIds('P1 - a\\nP2b - b') // => ['P1', 'P2b']
|
|
89
|
-
*/
|
|
90
|
-
const extractTranslationIds = (text) => {
|
|
91
|
-
const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;
|
|
92
|
-
const pattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}`, "gm");
|
|
93
|
-
const ids = [];
|
|
94
|
-
for (const match of text.matchAll(pattern)) ids.push(match[1]);
|
|
95
|
-
return ids;
|
|
96
|
-
};
|
|
97
|
-
/**
|
|
98
|
-
* Split the response into a per-ID map. Values contain translation content only (prefix removed).
|
|
99
|
-
*
|
|
100
|
-
* @example
|
|
101
|
-
* splitResponseById('P1 - a\\nP2 - b').get('P1') === 'a'
|
|
102
|
-
*/
|
|
103
|
-
const splitResponseById = (text) => {
|
|
104
|
-
const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;
|
|
105
|
-
const headerPattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}\\s*`, "gm");
|
|
106
|
-
const matches = [...text.matchAll(headerPattern)];
|
|
107
|
-
const map = /* @__PURE__ */ new Map();
|
|
108
|
-
for (let i = 0; i < matches.length; i++) {
|
|
109
|
-
const id = matches[i][1];
|
|
110
|
-
const start = matches[i].index ?? 0;
|
|
111
|
-
const nextStart = i + 1 < matches.length ? matches[i + 1].index ?? text.length : text.length;
|
|
112
|
-
const chunk = text.slice(start, nextStart).trimEnd();
|
|
113
|
-
const prefixPattern = /* @__PURE__ */ new RegExp(`^${id}${optionalSpace}${dashes}\\s*`);
|
|
114
|
-
map.set(id, chunk.replace(prefixPattern, "").trim());
|
|
115
|
-
}
|
|
116
|
-
return map;
|
|
117
|
-
};
|
|
118
|
-
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
119
|
-
|
|
120
55
|
//#endregion
|
|
121
56
|
//#region .generated/prompts.ts
|
|
122
57
|
const MASTER_PROMPT = "ROLE: Expert academic translator of Classical Islamic texts; prioritize accuracy and structure over fluency.\nCRITICAL NEGATIONS: 1. NO SANITIZATION (Do not soften polemics). 2. NO META-TALK (Output translation only). 3. NO MARKDOWN (Plain text only). 4. NO EMENDATION. 5. NO INFERENCE. 6. NO RESTRUCTURING. 7. NO OPAQUE TRANSLITERATION (Must translate phrases). 8. NO INVENTED SEGMENTS (Do not create, modify, or \"continue\" segment IDs. Output IDs verbatim exactly as they appear in the source input/metadata. Alphabetic suffixes (e.g., P5511a) are allowed IF AND ONLY IF that exact ID appears in the source. Any ID not present verbatim in the source is INVENTED. EXAMPLE: If P5803b ends with a questioner line, that line stays under P5803b — do NOT invent P5803c. If an expected ID is missing from the source, output: \"ID - [MISSING]\".)\nRULES: NO ARABIC SCRIPT (Except ﷺ). Plain text only. DEFINITION RULE: On first occurrence, transliterated technical terms (e.g., bidʿah) MUST be defined: \"translit (English)\". Preserve Segment ID. Translate meaning/intent. No inference. No extra fields. Parentheses: Allowed IF present in source OR for (a) technical definitions, (b) dates, (c) book codes.\nARABIC LEAK (Hard ban):\n- SCRIPT LOCK: Output must be 100% Latin script (ASCII + ALA-LC diacritics like ā ī ū ḥ ṣ ḍ ṭ ẓ ʿ ʾ). These diacritics are allowed/required and are NOT Arabic script.\n- STRICT BAN: Arabic script codepoints (letters, Arabic-Indic numerals ٠-٩, punctuation like ، ؟ ؛ « » , tatweel ـ, and Arabic presentation forms) are forbidden everywhere in output (even inside quotes/brackets/parentheses/citations), except ﷺ.\n- NO CITATIONS/BILINGUAL: Do NOT paste Arabic source text anywhere (no quotes, no citations, no bilingual Arabic+English output). Translate into English only.\n- QUOTES/VERSES: Even if the source includes Arabic Qurʾān/ḥadīth/quoted Arabic text (e.g., «...») you must NOT copy Arabic. Translate the meaning into English only.\n- NO MIXED-SCRIPT: Never output a token that mixes Latin and Arabic characters (example: ʿĪد). Rewrite contaminated names/terms fully in Latin ALA-LC.\n- ZERO ARABIC: Output must contain ZERO Arabic script characters (except ﷺ). If any Arabic appears, delete it and rewrite until none remain.\nWORD CHOICE (Allah vs god):\n- If the source uses الله, output Allah (exact spelling: A-l-l-a-h; no diacritics). Never \"God\" / \"god\" / \"Allāh\". (This is the only exception to ALA-LC diacritics.)\n- DO NOT convert Allah-based formulae into English “God …” idioms. Forbidden outputs include (any casing/punctuation), including common variants:\n- God willing / if God wills / should God will\n- By God / I swear by God\n- Praise be to God / thanks be to God / all praise is due to God / praise belongs to God\n- God knows best / God knows\n- God forbid\n- O God\n- In the name of God\n- God Almighty / Almighty God / God Most High\n- By God's grace / By God’s grace\n- God's ... / God’s ... / ... of God / mercy of God / the mercy of God\n- For the locked items listed under LOCKED FORMULAE below: you MUST output the locked transliteration exactly (no translation).\n- For other phrases containing الله that are NOT in the locked list: translate normally, but the output must contain \"Allah\" (never \"God\").\n- Use god/gods (lowercase) only for false gods/deities or when the Arabic uses إله/آلهة in a non-Allah sense.\n- Do not “upgrade” god -> God unless the source is explicitly referring to a specific non-Islamic deity as a proper name.\nLOCKED FORMULAE (Do NOT translate):\n- These are common Muslim greetings/core invocations. Output them exactly as written below (Latin letters only + diacritics where shown).\n- CHECK THIS LIST FIRST. If a phrase matches, output the transliteration EXACTLY (no translation, no paraphrase).\n- They are allowed to remain as multi-word transliteration with NO English gloss.\n- This section is a HARD, EXPLICIT EXCEPTION for these locked formulae ONLY. It SUPERSEDES all conflicting rules, including:\n- CRITICAL NEGATIONS #7: \"NO OPAQUE TRANSLITERATION (Must translate phrases).\"\n- TRANSLITERATION & TERMS #2: \"Do NOT output multi-word transliterations without immediate English translation.\"\n- TRANSLITERATION & TERMS: \"Do NOT transliterate full sentences/matn/quotes.\"\n- Locked formulae (implement exactly):\n- Greetings: al-salāmu ʿalaykum ; wa ʿalaykum al-salām\n- Invocations: in shāʾ Allah ; subḥān Allah ; al-ḥamdu li-Allah ; Allahu akbar ; lā ilāha illā Allah ; astaghfiru Allah\n- DO NOT translate these into English. Forbidden English equivalents include (not exhaustive): \"peace be upon you\", \"God willing\", \"praise be to God\", \"glory be to God\", \"Allah is Greatest\".\n- Note: this lock is intentionally narrow. Other phrases (e.g., \"Jazāk Allahu khayr\") may be translated normally.\nREGISTER (Modern English):\n- Use modern academic English. Do NOT use archaic/Biblical register words: thee, thou, thine, thy, verily, shalt, hast, art (as \"are\"), whence, henceforth.\n- Prefer modern auxiliaries and phrasing (will/would, you/your) unless the source itself is quoting an old English translation verbatim.\n- NO ALL CAPS / NO KJV-STYLE: Do NOT use ALL CAPS for emphasis (even inside quotes). Do NOT render Arabic Qurʾān/ḥadīth in KJV/Biblical style.\nTRANSLITERATION & TERMS:\n1. SCHEME: Use full ALA-LC for explicit Arabic-script Person/Place/Book-Titles.\n- al-Casing: Lowercase al- mid-sentence; Capitalize after (al-Salafīyyah).\n- Book Titles: Transliterate only (do not translate meanings).\n2. TECHNICAL TERMS: On first occurrence, define: \"translit (English)\" (e.g., bidʿah (innovation), isnād (chain)).\n- Do NOT output multi-word transliterations without immediate English translation.\n- Do NOT transliterate full sentences/matn/quotes. Translate into English; transliteration is for names/terms only.\n- EXCEPTION (Duʿāʾ/Supplications): If the source contains a specific duʿāʾ/supplication phrase and you choose to preserve its wording for pronunciation, you MAY output transliteration BUT you MUST also translate it immediately (same line or next) as: \"translit (English translation)\". Do NOT output Arabic script.\n- Example Allowed: Allāhumma innī asʾaluka al-ʿāfiyah (O Allah, I ask You for well-being).\n- Example Forbidden: Transliterate a long multi-sentence duʿāʾ paragraph without translating it.\n- LOCKED FORMULAE are the only exception allowed to remain multi-word transliteration with NO English gloss.\n- If you use any other multi-word transliteration (not locked), it MUST be immediately glossed: \"translit (English)\". Prefer full English translation for phrases.\n- Do NOT leave common nouns/objects/roles as transliteration (e.g., tools, foods, occupations). Translate them into English. If you must transliterate a non-name, you MUST immediately gloss it: \"translit (English)\".\n3. STANDARDIZED TERMS: Use standard academic spellings: Muḥammad, Shaykh, Qurʾān, Islām, ḥadīth.\n- Sunnah (Capitalized) = The Corpus/Prophetic Tradition. sunnah (lowercase) = legal status/recommended.\n4. PROPER NAMES: Transliterate only (no parentheses).\n5. UNICODE: Latin + Latin Extended (āīūḥʿḍṣṭẓʾ) + punctuation. NO Arabic script (except ﷺ). NO emoji.\n- DIACRITIC FALLBACK: If you cannot produce correct ALA-LC diacritics, output English only. Do NOT use substitute accents (â/ã/á).\n6. SALUTATION: Replace all Prophet salutations with ﷺ.\n7. HONORIFICS: Expand common phrases (do not transliterate):\n- Allah ʿazza wa-jall -> Allah, the Mighty and Majestic\n- rahimahu Allah -> may Allah have mercy on him\n8. AMBIGUITY: Use contextual meaning from tafsir for theological terms. Do not sanitise polemics (e.g. Rāfiḍah).\nOUTPUT FORMAT: Segment_ID - English translation.\nCRITICAL: You must use the ASCII hyphen separator \" - \" (space+hyphen+space) immediately after the ID. Do NOT use em-dash or en-dash. Do NOT use a newline after the ID.\nID INTEGRITY (Check First):\n- PREPASS (Silent closed set): Internally identify the exact ordered list of Segment_IDs present in the source. Treat this list as a CLOSED SET. Do not output this list.\n- REQUIRED (Exact match): Your output must contain EXACTLY those Segment_IDs, in the EXACT same order, each appearing EXACTLY ONCE as an \"ID - ...\" prefix. FORBIDDEN: re-outputting an ID prefix you already used (even in long segments).\n- BAN (No new IDs): Do NOT invent ANY IDs or ID-like labels not present verbatim in the source (including \"(continued)\", \"cont.\", \"part 2\", or invented suffixes like P123c). Suffix IDs are allowed ONLY if that exact ID appears in the source.\n- BOUNDARY (No bleed): Translate ONLY the text that belongs to the current Segment_ID (from its header to the next Segment_ID header, or to end-of-input for the last segment). Do NOT move lines across IDs and do NOT merge segments.\n- INCOMPLETE (Strict): Use \"ID - [INCOMPLETE]\" ONLY if the provided source text under that ID is truly unreadable/untranslatable. NEVER use \"[INCOMPLETE]\" for ellipses (…) or long segments. Translate all available text.\nMULTI-LINE SEGMENTS (e.g., internal Q&A): Output the Segment_ID and \" - \" ONLY ONCE on the first line. Do NOT repeat the Segment_ID on subsequent lines; subsequent lines must start directly with the speaker label/text (no \"ID - \" prefix).\nSEGMENT BOUNDARIES (Anti-hallucination): Start a NEW segment ONLY when the source explicitly provides a Segment_ID. If the source continues with extra lines (including speaker labels like \"Questioner:\"/\"The Shaykh:\"/\"السائل:\"/\"الشيخ:\") WITHOUT a new Segment_ID, treat them as part of the CURRENT segment (multi-line under the current Segment_ID). Do NOT invent a new ID (including alphabetic suffixes like \"P5803c\") to label such continuation.\nOUTPUT COMPLETENESS: Translate ALL content in EVERY segment. Do not truncate, summarize, or skip content. The \"…\" symbol in the source indicates an audio gap in the original recording — it is NOT an instruction to omit content. Every segment must be fully translated. If you cannot complete a segment, output \"ID - [INCOMPLETE]\" instead of just \"…\".\nOUTPUT UNIQUENESS: Each Segment_ID from the source must appear in your output EXACTLY ONCE as an \"ID - ...\" prefix. Do NOT output the same Segment_ID header twice. If a segment is long or has multiple speaker turns, continue translating under that single ID header without re-stating it.\nNEGATIVE CONSTRAINTS: Do NOT output \"implicit continuation\", summaries, or extra paragraphs. Output only the text present in the source segment.\nExample: P1234 - Translation text... (Correct) vs P1234\\nTranslation... (Forbidden).\nEXAMPLE: Input: P405 - حدثنا عبد الله بن يوسف... Output: P405 - ʿAbd Allāh b. Yūsuf narrated to us...";
|
|
@@ -245,6 +180,132 @@ const getMasterPrompt = () => {
|
|
|
245
180
|
return MASTER_PROMPT;
|
|
246
181
|
};
|
|
247
182
|
|
|
183
|
+
//#endregion
|
|
184
|
+
//#region src/textUtils.ts
|
|
185
|
+
/**
|
|
186
|
+
* Segment type is shared across the library.
|
|
187
|
+
*/
|
|
188
|
+
/**
|
|
189
|
+
* Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.
|
|
190
|
+
* Each segment is formatted as "ID - Text" and separated by double newlines.
|
|
191
|
+
*
|
|
192
|
+
* @param segments - Array of segments to format
|
|
193
|
+
* @param prompt - The instruction/system prompt to prepend
|
|
194
|
+
* @returns Combined prompt and formatted text
|
|
195
|
+
*/
|
|
196
|
+
const formatExcerptsForPrompt = (segments, prompt) => {
|
|
197
|
+
return [prompt, segments.map((e) => `${e.id} - ${e.text}`).join("\n\n")].join("\n\n");
|
|
198
|
+
};
|
|
199
|
+
/**
|
|
200
|
+
* Normalize line endings and split merged markers onto separate lines.
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* // "helloP1 - ..." becomes split onto a new line before "P1 -"
|
|
204
|
+
* normalizeTranslationText('helloP1 - x').includes('\\nP1 -') === true
|
|
205
|
+
*/
|
|
206
|
+
const normalizeTranslationText = (content) => {
|
|
207
|
+
const normalizedLineEndings = content.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
208
|
+
const mergedMarkerWithSpacePattern = new RegExp(` (${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`, "gm");
|
|
209
|
+
const mergedMarkerNoSpacePattern = new RegExp(`([^\\s\\n])(${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`, "gm");
|
|
210
|
+
return normalizedLineEndings.replace(mergedMarkerWithSpacePattern, "\n$1").replace(mergedMarkerNoSpacePattern, "$1\n$2").replace(/\\\[/gm, "[");
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* Extract translation IDs from normalized response, in order.
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* extractTranslationIds('P1 - a\\nP2b - b') // => ['P1', 'P2b']
|
|
217
|
+
*/
|
|
218
|
+
const extractTranslationIds = (text) => {
|
|
219
|
+
const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;
|
|
220
|
+
const pattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}`, "gm");
|
|
221
|
+
const ids = [];
|
|
222
|
+
for (const match of text.matchAll(pattern)) ids.push(match[1]);
|
|
223
|
+
return ids;
|
|
224
|
+
};
|
|
225
|
+
/**
|
|
226
|
+
* Parse a single translation line in the form "ID - translation".
|
|
227
|
+
*
|
|
228
|
+
* Note: This returns a translation entry shape, not an Arabic source `Segment`.
|
|
229
|
+
*
|
|
230
|
+
* @param line - Single line to parse
|
|
231
|
+
* @returns `{ id, translation }` when valid; otherwise `null`
|
|
232
|
+
*
|
|
233
|
+
* @example
|
|
234
|
+
* parseTranslationLine('P1 - Hello')?.id === 'P1'
|
|
235
|
+
*/
|
|
236
|
+
const parseTranslationLine = (line) => {
|
|
237
|
+
const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;
|
|
238
|
+
const pattern = /* @__PURE__ */ new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}(.*)$`);
|
|
239
|
+
const [, id, rest] = line.match(pattern) || [];
|
|
240
|
+
const translation = typeof rest === "string" ? rest.trim() : "";
|
|
241
|
+
return id && translation ? {
|
|
242
|
+
id,
|
|
243
|
+
translation
|
|
244
|
+
} : null;
|
|
245
|
+
};
|
|
246
|
+
/**
|
|
247
|
+
* Parses bulk translation text into a Map for efficient O(1) lookup.
|
|
248
|
+
*
|
|
249
|
+
* Handles multi-line translations: subsequent non-marker lines belong to the previous ID.
|
|
250
|
+
*
|
|
251
|
+
* @param rawText - Raw text containing translations in format "ID - Translation text"
|
|
252
|
+
* @returns An object with `count` and `translationMap`
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* parseTranslations('P1 - a\\nP2 - b').count === 2
|
|
256
|
+
*/
|
|
257
|
+
const parseTranslations = (rawText) => {
|
|
258
|
+
const translationMap = splitResponseById(normalizeTranslationText(rawText));
|
|
259
|
+
return {
|
|
260
|
+
count: translationMap.size,
|
|
261
|
+
translationMap
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
/**
|
|
265
|
+
* Parse translations into an ordered array (preserving the original response order).
|
|
266
|
+
*
|
|
267
|
+
* This differs from `parseTranslations()` which returns a Map and therefore cannot represent
|
|
268
|
+
* duplicates as separate entries.
|
|
269
|
+
*
|
|
270
|
+
* @param rawText - Raw text containing translations in format "ID - Translation text"
|
|
271
|
+
* @returns Array of `{ id, translation }` entries in appearance order
|
|
272
|
+
*
|
|
273
|
+
* @example
|
|
274
|
+
* parseTranslationsInOrder('P1 - a\\nP2 - b').map((e) => e.id) // => ['P1', 'P2']
|
|
275
|
+
*/
|
|
276
|
+
const parseTranslationsInOrder = (rawText) => {
|
|
277
|
+
const normalized = normalizeTranslationText(rawText);
|
|
278
|
+
const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;
|
|
279
|
+
const headerPattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}\\s*`, "gm");
|
|
280
|
+
const matches = [...normalized.matchAll(headerPattern)];
|
|
281
|
+
const entries = [];
|
|
282
|
+
for (let i = 0; i < matches.length; i++) {
|
|
283
|
+
const id = matches[i][1];
|
|
284
|
+
const start = matches[i].index ?? 0;
|
|
285
|
+
const nextStart = i + 1 < matches.length ? matches[i + 1].index ?? normalized.length : normalized.length;
|
|
286
|
+
const chunk = normalized.slice(start, nextStart).trimEnd();
|
|
287
|
+
const prefixPattern = /* @__PURE__ */ new RegExp(`^${id}${optionalSpace}${dashes}\\s*`);
|
|
288
|
+
const translation = chunk.replace(prefixPattern, "").trim();
|
|
289
|
+
entries.push({
|
|
290
|
+
id,
|
|
291
|
+
translation
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
return entries;
|
|
295
|
+
};
|
|
296
|
+
/**
|
|
297
|
+
* Split the response into a per-ID map. Values contain translation content only (prefix removed).
|
|
298
|
+
*
|
|
299
|
+
* @example
|
|
300
|
+
* splitResponseById('P1 - a\\nP2 - b').get('P1') === 'a'
|
|
301
|
+
*/
|
|
302
|
+
const splitResponseById = (text) => {
|
|
303
|
+
const map = /* @__PURE__ */ new Map();
|
|
304
|
+
for (const entry of parseTranslationsInOrder(text)) map.set(entry.id, entry.translation);
|
|
305
|
+
return map;
|
|
306
|
+
};
|
|
307
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
308
|
+
|
|
248
309
|
//#endregion
|
|
249
310
|
//#region src/validation.ts
|
|
250
311
|
/**
|
|
@@ -692,5 +753,5 @@ const validateMultiwordTranslitWithoutGloss = (parsedIds, responseById) => {
|
|
|
692
753
|
};
|
|
693
754
|
|
|
694
755
|
//#endregion
|
|
695
|
-
export { MARKER_ID_PATTERN, Markers, TRANSLATION_MARKER_PARTS, VALIDATION_ERROR_TYPE_INFO, extractTranslationIds, formatExcerptsForPrompt, getMasterPrompt, getPrompt, getPromptIds, getPrompts, getStackedPrompt, normalizeTranslationText, stackPrompts, validateTranslationResponse };
|
|
756
|
+
export { MARKER_ID_PATTERN, Markers, TRANSLATION_MARKER_PARTS, VALIDATION_ERROR_TYPE_INFO, extractTranslationIds, formatExcerptsForPrompt, getMasterPrompt, getPrompt, getPromptIds, getPrompts, getStackedPrompt, normalizeTranslationText, parseTranslationLine, parseTranslations, parseTranslationsInOrder, stackPrompts, validateTranslationResponse };
|
|
696
757
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/constants.ts","../src/textUtils.ts","../.generated/prompts.ts","../src/prompts.ts","../src/validation.ts"],"sourcesContent":["/**\n * Supported marker types for segments.\n */\nexport enum Markers {\n /** B - Book reference */\n Book = 'B',\n /** F - Footnote reference */\n Footnote = 'F',\n /** T - Heading reference */\n Heading = 'T',\n /** C - Chapter reference */\n Chapter = 'C',\n /** N - Note reference */\n Note = 'N',\n /** P - Translation/Plain segment */\n Plain = 'P',\n}\n\n/**\n * Regex parts for building translation marker patterns.\n */\nexport const TRANSLATION_MARKER_PARTS = {\n /** Dash variations (hyphen, en dash, em dash) */\n dashes: '[-–—]',\n /** Numeric portion of the reference */\n digits: '\\\\d+',\n /** Valid marker prefixes (Book, Chapter, Footnote, Translation, Page) */\n markers: `[${Markers.Book}${Markers.Chapter}${Markers.Footnote}${Markers.Heading}${Markers.Plain}${Markers.Note}]`,\n /** Optional whitespace before dash */\n optionalSpace: '\\\\s?',\n /** Valid single-letter suffixes */\n suffix: '[a-z]',\n} as const;\n\n/**\n * Pattern for a segment ID (e.g., P1234, B45a).\n */\nexport const MARKER_ID_PATTERN = `${TRANSLATION_MARKER_PARTS.markers}${TRANSLATION_MARKER_PARTS.digits}${TRANSLATION_MARKER_PARTS.suffix}?`;\n\n/**\n * English tokens that indicate archaic/Biblical register and should be flagged.\n */\nexport const ARCHAIC_WORDS = [\n 'thee',\n 'thou',\n 'thine',\n 'thy',\n 'verily',\n 'shalt',\n 'hast',\n 'whence',\n 'henceforth',\n 'saith',\n 'behold',\n] as const;\n\nexport const MAX_EMPTY_PARENTHESES = 3;\nexport const MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK = 50;\nexport const MIN_TRANSLATION_RATIO = 0.25;\n\nexport const COLON_PATTERN = /[::]/g;\n","/**\n * Segment type is shared across the library.\n */\nimport { MARKER_ID_PATTERN, TRANSLATION_MARKER_PARTS } from './constants';\nimport type { Segment } from './types';\n\n/**\n * Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.\n * Each segment is formatted as \"ID - Text\" and separated by double newlines.\n *\n * @param segments - Array of segments to format\n * @param prompt - The instruction/system prompt to prepend\n * @returns Combined prompt and formatted text\n */\nexport const formatExcerptsForPrompt = (segments: Segment[], prompt: string) => {\n const formatted = segments.map((e) => `${e.id} - ${e.text}`).join('\\n\\n');\n return [prompt, formatted].join('\\n\\n');\n};\n\n/**\n * Normalize line endings and split merged markers onto separate lines.\n *\n * @example\n * // \"helloP1 - ...\" becomes split onto a new line before \"P1 -\"\n * normalizeTranslationText('helloP1 - x').includes('\\\\nP1 -') === true\n */\nexport const normalizeTranslationText = (content: string) => {\n const normalizedLineEndings = content.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n const mergedMarkerWithSpacePattern = new RegExp(\n ` (${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`,\n 'gm',\n );\n\n const mergedMarkerNoSpacePattern = new RegExp(\n `([^\\\\s\\\\n])(${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`,\n 'gm',\n );\n\n return normalizedLineEndings\n .replace(mergedMarkerWithSpacePattern, '\\n$1')\n .replace(mergedMarkerNoSpacePattern, '$1\\n$2')\n .replace(/\\\\\\[/gm, '[');\n};\n\n/**\n * Extract translation IDs from normalized response, in order.\n *\n * @example\n * extractTranslationIds('P1 - a\\\\nP2b - b') // => ['P1', 'P2b']\n */\nexport const extractTranslationIds = (text: string) => {\n const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n const pattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}`, 'gm');\n const ids: string[] = [];\n for (const match of text.matchAll(pattern)) {\n ids.push(match[1]);\n }\n return ids;\n};\n\n/**\n * Split the response into a per-ID map. Values contain translation content only (prefix removed).\n *\n * @example\n * splitResponseById('P1 - a\\\\nP2 - b').get('P1') === 'a'\n */\nexport const splitResponseById = (text: string) => {\n const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n const headerPattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}\\\\s*`, 'gm');\n const matches = [...text.matchAll(headerPattern)];\n\n const map = new Map<string, string>();\n for (let i = 0; i < matches.length; i++) {\n const id = matches[i][1];\n const start = matches[i].index ?? 0;\n const nextStart = i + 1 < matches.length ? (matches[i + 1].index ?? text.length) : text.length;\n const chunk = text.slice(start, nextStart).trimEnd();\n const prefixPattern = new RegExp(`^${id}${optionalSpace}${dashes}\\\\s*`);\n map.set(id, chunk.replace(prefixPattern, '').trim());\n }\n return map;\n};\n\nexport const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n","// AUTO-GENERATED FILE - DO NOT EDIT\n// Generated from prompts/*.md by scripts/generate-prompts.ts\n\n// =============================================================================\n// PROMPT TYPE\n// =============================================================================\n\nexport type PromptId = 'master_prompt' | 'encyclopedia_mixed' | 'fatawa' | 'fiqh' | 'hadith' | 'jarh_wa_tadil' | 'tafsir' | 'usul_al_fiqh';\n\n// =============================================================================\n// RAW PROMPT CONTENT\n// =============================================================================\n\nexport const MASTER_PROMPT = \"ROLE: Expert academic translator of Classical Islamic texts; prioritize accuracy and structure over fluency.\\nCRITICAL NEGATIONS: 1. NO SANITIZATION (Do not soften polemics). 2. NO META-TALK (Output translation only). 3. NO MARKDOWN (Plain text only). 4. NO EMENDATION. 5. NO INFERENCE. 6. NO RESTRUCTURING. 7. NO OPAQUE TRANSLITERATION (Must translate phrases). 8. NO INVENTED SEGMENTS (Do not create, modify, or \\\"continue\\\" segment IDs. Output IDs verbatim exactly as they appear in the source input/metadata. Alphabetic suffixes (e.g., P5511a) are allowed IF AND ONLY IF that exact ID appears in the source. Any ID not present verbatim in the source is INVENTED. EXAMPLE: If P5803b ends with a questioner line, that line stays under P5803b — do NOT invent P5803c. If an expected ID is missing from the source, output: \\\"ID - [MISSING]\\\".)\\nRULES: NO ARABIC SCRIPT (Except ﷺ). Plain text only. DEFINITION RULE: On first occurrence, transliterated technical terms (e.g., bidʿah) MUST be defined: \\\"translit (English)\\\". Preserve Segment ID. Translate meaning/intent. No inference. No extra fields. Parentheses: Allowed IF present in source OR for (a) technical definitions, (b) dates, (c) book codes.\\nARABIC LEAK (Hard ban):\\n- SCRIPT LOCK: Output must be 100% Latin script (ASCII + ALA-LC diacritics like ā ī ū ḥ ṣ ḍ ṭ ẓ ʿ ʾ). These diacritics are allowed/required and are NOT Arabic script.\\n- STRICT BAN: Arabic script codepoints (letters, Arabic-Indic numerals ٠-٩, punctuation like ، ؟ ؛ « » , tatweel ـ, and Arabic presentation forms) are forbidden everywhere in output (even inside quotes/brackets/parentheses/citations), except ﷺ.\\n- NO CITATIONS/BILINGUAL: Do NOT paste Arabic source text anywhere (no quotes, no citations, no bilingual Arabic+English output). Translate into English only.\\n- QUOTES/VERSES: Even if the source includes Arabic Qurʾān/ḥadīth/quoted Arabic text (e.g., «...») you must NOT copy Arabic. Translate the meaning into English only.\\n- NO MIXED-SCRIPT: Never output a token that mixes Latin and Arabic characters (example: ʿĪد). Rewrite contaminated names/terms fully in Latin ALA-LC.\\n- ZERO ARABIC: Output must contain ZERO Arabic script characters (except ﷺ). If any Arabic appears, delete it and rewrite until none remain.\\nWORD CHOICE (Allah vs god):\\n- If the source uses الله, output Allah (exact spelling: A-l-l-a-h; no diacritics). Never \\\"God\\\" / \\\"god\\\" / \\\"Allāh\\\". (This is the only exception to ALA-LC diacritics.)\\n- DO NOT convert Allah-based formulae into English “God …” idioms. Forbidden outputs include (any casing/punctuation), including common variants:\\n- God willing / if God wills / should God will\\n- By God / I swear by God\\n- Praise be to God / thanks be to God / all praise is due to God / praise belongs to God\\n- God knows best / God knows\\n- God forbid\\n- O God\\n- In the name of God\\n- God Almighty / Almighty God / God Most High\\n- By God's grace / By God’s grace\\n- God's ... / God’s ... / ... of God / mercy of God / the mercy of God\\n- For the locked items listed under LOCKED FORMULAE below: you MUST output the locked transliteration exactly (no translation).\\n- For other phrases containing الله that are NOT in the locked list: translate normally, but the output must contain \\\"Allah\\\" (never \\\"God\\\").\\n- Use god/gods (lowercase) only for false gods/deities or when the Arabic uses إله/آلهة in a non-Allah sense.\\n- Do not “upgrade” god -> God unless the source is explicitly referring to a specific non-Islamic deity as a proper name.\\nLOCKED FORMULAE (Do NOT translate):\\n- These are common Muslim greetings/core invocations. Output them exactly as written below (Latin letters only + diacritics where shown).\\n- CHECK THIS LIST FIRST. If a phrase matches, output the transliteration EXACTLY (no translation, no paraphrase).\\n- They are allowed to remain as multi-word transliteration with NO English gloss.\\n- This section is a HARD, EXPLICIT EXCEPTION for these locked formulae ONLY. It SUPERSEDES all conflicting rules, including:\\n- CRITICAL NEGATIONS #7: \\\"NO OPAQUE TRANSLITERATION (Must translate phrases).\\\"\\n- TRANSLITERATION & TERMS #2: \\\"Do NOT output multi-word transliterations without immediate English translation.\\\"\\n- TRANSLITERATION & TERMS: \\\"Do NOT transliterate full sentences/matn/quotes.\\\"\\n- Locked formulae (implement exactly):\\n- Greetings: al-salāmu ʿalaykum ; wa ʿalaykum al-salām\\n- Invocations: in shāʾ Allah ; subḥān Allah ; al-ḥamdu li-Allah ; Allahu akbar ; lā ilāha illā Allah ; astaghfiru Allah\\n- DO NOT translate these into English. Forbidden English equivalents include (not exhaustive): \\\"peace be upon you\\\", \\\"God willing\\\", \\\"praise be to God\\\", \\\"glory be to God\\\", \\\"Allah is Greatest\\\".\\n- Note: this lock is intentionally narrow. Other phrases (e.g., \\\"Jazāk Allahu khayr\\\") may be translated normally.\\nREGISTER (Modern English):\\n- Use modern academic English. Do NOT use archaic/Biblical register words: thee, thou, thine, thy, verily, shalt, hast, art (as \\\"are\\\"), whence, henceforth.\\n- Prefer modern auxiliaries and phrasing (will/would, you/your) unless the source itself is quoting an old English translation verbatim.\\n- NO ALL CAPS / NO KJV-STYLE: Do NOT use ALL CAPS for emphasis (even inside quotes). Do NOT render Arabic Qurʾān/ḥadīth in KJV/Biblical style.\\nTRANSLITERATION & TERMS:\\n1. SCHEME: Use full ALA-LC for explicit Arabic-script Person/Place/Book-Titles.\\n- al-Casing: Lowercase al- mid-sentence; Capitalize after (al-Salafīyyah).\\n- Book Titles: Transliterate only (do not translate meanings).\\n2. TECHNICAL TERMS: On first occurrence, define: \\\"translit (English)\\\" (e.g., bidʿah (innovation), isnād (chain)).\\n- Do NOT output multi-word transliterations without immediate English translation.\\n- Do NOT transliterate full sentences/matn/quotes. Translate into English; transliteration is for names/terms only.\\n- EXCEPTION (Duʿāʾ/Supplications): If the source contains a specific duʿāʾ/supplication phrase and you choose to preserve its wording for pronunciation, you MAY output transliteration BUT you MUST also translate it immediately (same line or next) as: \\\"translit (English translation)\\\". Do NOT output Arabic script.\\n- Example Allowed: Allāhumma innī asʾaluka al-ʿāfiyah (O Allah, I ask You for well-being).\\n- Example Forbidden: Transliterate a long multi-sentence duʿāʾ paragraph without translating it.\\n- LOCKED FORMULAE are the only exception allowed to remain multi-word transliteration with NO English gloss.\\n- If you use any other multi-word transliteration (not locked), it MUST be immediately glossed: \\\"translit (English)\\\". Prefer full English translation for phrases.\\n- Do NOT leave common nouns/objects/roles as transliteration (e.g., tools, foods, occupations). Translate them into English. If you must transliterate a non-name, you MUST immediately gloss it: \\\"translit (English)\\\".\\n3. STANDARDIZED TERMS: Use standard academic spellings: Muḥammad, Shaykh, Qurʾān, Islām, ḥadīth.\\n- Sunnah (Capitalized) = The Corpus/Prophetic Tradition. sunnah (lowercase) = legal status/recommended.\\n4. PROPER NAMES: Transliterate only (no parentheses).\\n5. UNICODE: Latin + Latin Extended (āīūḥʿḍṣṭẓʾ) + punctuation. NO Arabic script (except ﷺ). NO emoji.\\n- DIACRITIC FALLBACK: If you cannot produce correct ALA-LC diacritics, output English only. Do NOT use substitute accents (â/ã/á).\\n6. SALUTATION: Replace all Prophet salutations with ﷺ.\\n7. HONORIFICS: Expand common phrases (do not transliterate):\\n- Allah ʿazza wa-jall -> Allah, the Mighty and Majestic\\n- rahimahu Allah -> may Allah have mercy on him\\n8. AMBIGUITY: Use contextual meaning from tafsir for theological terms. Do not sanitise polemics (e.g. Rāfiḍah).\\nOUTPUT FORMAT: Segment_ID - English translation.\\nCRITICAL: You must use the ASCII hyphen separator \\\" - \\\" (space+hyphen+space) immediately after the ID. Do NOT use em-dash or en-dash. Do NOT use a newline after the ID.\\nID INTEGRITY (Check First):\\n- PREPASS (Silent closed set): Internally identify the exact ordered list of Segment_IDs present in the source. Treat this list as a CLOSED SET. Do not output this list.\\n- REQUIRED (Exact match): Your output must contain EXACTLY those Segment_IDs, in the EXACT same order, each appearing EXACTLY ONCE as an \\\"ID - ...\\\" prefix. FORBIDDEN: re-outputting an ID prefix you already used (even in long segments).\\n- BAN (No new IDs): Do NOT invent ANY IDs or ID-like labels not present verbatim in the source (including \\\"(continued)\\\", \\\"cont.\\\", \\\"part 2\\\", or invented suffixes like P123c). Suffix IDs are allowed ONLY if that exact ID appears in the source.\\n- BOUNDARY (No bleed): Translate ONLY the text that belongs to the current Segment_ID (from its header to the next Segment_ID header, or to end-of-input for the last segment). Do NOT move lines across IDs and do NOT merge segments.\\n- INCOMPLETE (Strict): Use \\\"ID - [INCOMPLETE]\\\" ONLY if the provided source text under that ID is truly unreadable/untranslatable. NEVER use \\\"[INCOMPLETE]\\\" for ellipses (…) or long segments. Translate all available text.\\nMULTI-LINE SEGMENTS (e.g., internal Q&A): Output the Segment_ID and \\\" - \\\" ONLY ONCE on the first line. Do NOT repeat the Segment_ID on subsequent lines; subsequent lines must start directly with the speaker label/text (no \\\"ID - \\\" prefix).\\nSEGMENT BOUNDARIES (Anti-hallucination): Start a NEW segment ONLY when the source explicitly provides a Segment_ID. If the source continues with extra lines (including speaker labels like \\\"Questioner:\\\"/\\\"The Shaykh:\\\"/\\\"السائل:\\\"/\\\"الشيخ:\\\") WITHOUT a new Segment_ID, treat them as part of the CURRENT segment (multi-line under the current Segment_ID). Do NOT invent a new ID (including alphabetic suffixes like \\\"P5803c\\\") to label such continuation.\\nOUTPUT COMPLETENESS: Translate ALL content in EVERY segment. Do not truncate, summarize, or skip content. The \\\"…\\\" symbol in the source indicates an audio gap in the original recording — it is NOT an instruction to omit content. Every segment must be fully translated. If you cannot complete a segment, output \\\"ID - [INCOMPLETE]\\\" instead of just \\\"…\\\".\\nOUTPUT UNIQUENESS: Each Segment_ID from the source must appear in your output EXACTLY ONCE as an \\\"ID - ...\\\" prefix. Do NOT output the same Segment_ID header twice. If a segment is long or has multiple speaker turns, continue translating under that single ID header without re-stating it.\\nNEGATIVE CONSTRAINTS: Do NOT output \\\"implicit continuation\\\", summaries, or extra paragraphs. Output only the text present in the source segment.\\nExample: P1234 - Translation text... (Correct) vs P1234\\\\nTranslation... (Forbidden).\\nEXAMPLE: Input: P405 - حدثنا عبد الله بن يوسف... Output: P405 - ʿAbd Allāh b. Yūsuf narrated to us...\";\n\nexport const ENCYCLOPEDIA_MIXED = \"NO MODE TAGS: Do not output any mode labels or bracket tags.\\nSTRUCTURE (Apply First):\\n- Q&A: Whenever \\\"Al-Sāʾil:\\\"/\\\"Al-Shaykh:\\\" appear: Start NEW LINE for speaker. Keep Label+Text on SAME LINE.\\n- EXCEPTION: If the speaker label is the VERY FIRST token after the \\\"ID - \\\" prefix, keep it on the same line. (Correct: P5455 - Questioner: Text...) (Wrong: P5455 \\\\n Questioner: Text...).\\n- INTERNAL Q&A: If segment has multiple turns, use new lines for speakers. Output Segment ID ONLY ONCE at the start of the first line. Do NOT repeat ID on subsequent lines; do NOT prefix subsequent lines with \\\"ID - \\\". (e.g. P5455 - Questioner: ... \\\\n The Shaykh: ...).\\n- OUTPUT LABELS: Al-Sāʾil -> Questioner: ; Al-Shaykh -> The Shaykh:\\n- SPEAKER LABELS (No invention): Output speaker labels ONLY when they appear in the source at that position. Do NOT add \\\"Questioner:\\\"/\\\"The Shaykh:\\\" to unlabeled text. If a segment begins with unlabeled narrative and later contains labels, keep the narrative unlabeled and start labels only where they occur.\\nDEFINITIONS & CASING:\\n- GEOPOLITICS: Modern place names may use English exonyms (Filasṭīn -> Palestine).\\n- PLURALS: Do not pluralize term-pairs by appending \\\"s\\\" (e.g., \\\"ḥadīth (report)s\\\"). Use the English plural or rephrase.\\nSTATE LOGIC (Priority: Isnad > Rijal > Fiqh > Narrative):\\n- ISNAD (Triggers: ḥaddathanā, akhbaranā, ʿan): Use FULL ALA-LC for names.\\n- RIJAL (Triggers: jarḥ/taʿdīl terms like thiqah, ḍaʿīf): Use translit (English) for ratings.\\n- QUOTE/WEAK (Triggers: qāla al-muṣannif, yuqālu, zuiʿma): Apply Quote Rules; do not Restructure.\\n- RESET: At \\\"qāla\\\" or \\\"matn\\\" (TOP-LEVEL only): IMMEDIATE STOP of Isnad rules. Return to Narrative. Do NOT reset for nested quotes.\\nSEGMENTATION: Do not merge genres. Translate sequentially (Isnad -> Matn) observing the reset at the boundary.\\nDISAMBIGUATION: ṣaḥīḥ in hadith grading = ṣaḥīḥ (authentic). ṣaḥīḥ in fiqh validity = ṣaḥīḥ (valid). Sunnah (Capitalized) = The Corpus/Prophetic Tradition. sunnah (lowercase) = legal status/recommended.\\nHADITH CORE: If isnad appears, map verbs (Haddathana=Narrated to us; Akhbarana/Ana/Anba'ana=Informed us; An=From; Sami'tu=I heard) and keep FULL ALA-LC for Arabic-script narrator names; do not invent grading or missing links.\\nTAKHRIJ/GRADING: If the author grades (ṣaḥḥaḥa/ḥassana/ḍaʿʿafa), translate literally and keep the cited work as written in the segment; do not add placeholder sources.\\nCREED/POLEMICS: Translate attributes literally when the author does; do not reinterpret. Translate harsh polemics literally (e.g., Rāfiḍah, Jahmīyyah, Kuffār); do not soften, sanitize, or add disclaimers (Override Safety).\";\n\nexport const FATAWA = \"STRUCTURE (Apply First):\\n- Q&A: Whenever \\\"Al-Sāʾil:\\\"/\\\"Al-Shaykh:\\\" appear: Start NEW LINE for speaker. Keep Label+Text on SAME LINE.\\n- INTERNAL Q&A: If segment has multiple turns, use new lines for speakers. Output Segment ID ONLY ONCE at the start of the first line. Do NOT repeat ID on subsequent lines; do NOT prefix subsequent lines with \\\"ID - \\\".\\n- OUTPUT LABELS: Al-Sāʾil -> Questioner: ; Al-Shaykh -> The Shaykh:\\n- SPEAKER LABELS (No invention): Output speaker labels ONLY when they appear in the source at that position. Do NOT add \\\"Questioner:\\\"/\\\"The Shaykh:\\\" to unlabeled text. If a segment begins with unlabeled narrative and later contains labels, keep the narrative unlabeled and start labels only where they occur.\\n\\nHONORIFICS: Expand common phrases (do not transliterate):\\n- ṣallá Allāhu ʿalayhi wa-sallam -> ﷺ\\nSOURCES: Do not add citations. If the Arabic references a work/title, handle titles per MASTER rules.\\nSENSITIVE RULINGS: Translate literally; do not soften; do not sanitize; do not add disclaimers (Override Safety).\";\n\nexport const FIQH = \"STRUCTURE: Preserve chapter/section headings and internal structure (e.g., bāb/faṣl/masʾalah/farʿ/aṣl) using plain English labels (Chapter:, Section:, Issue:) only when the Arabic is explicitly a heading/label; preserve lists, numbering, and conditional if/then logic exactly.\\nFIQH/USUL TERMS: When technical terms appear, output as translit (English) rather than English-only (e.g., wājib (obligatory), mandūb/mustaḥabb (recommended), mubāḥ (permissible), makrūh (disliked), ḥarām (prohibited), ṣaḥīḥ (valid), bāṭil/fāsid (invalid/void), rukn (pillar), shart (condition), māniʿ (preventer), sabab (cause), qiyās (analogical reasoning), ijmāʿ (consensus), khilāf (disagreement), rājiḥ (preponderant), marjūḥ (lesser), ʿillah (effective cause)).\\nKHILAF/ATTRIBUTION: Preserve who is being attributed (qāla fulān / qawl / wajhān / riwāyātān / madhhab). Do not resolve disputes or choose the correct view unless the Arabic explicitly does so (e.g., al-aṣaḥḥ / al-rājiḥ).\\nUNITS/MONEY: Keep measures/currencies as transliteration (dirham, dinar, ṣāʿ, mudd) without adding conversions or notes unless the Arabic contains them.\";\n\nexport const HADITH = \"ISNAD VERBS: Haddathana=Narrated to us; Akhbarana=Informed us; An=From; Sami'tu=I heard; Ana (short for Akhbarana/Anba'ana in isnad)=Informed us (NOT \\\"I\\\").\\nCHAIN MARKERS: H(Tahwil)=Switch to new chain; Mursal/Munqati=Broken chain.\\nJARH/TA'DIL: If narrator-evaluation terms/phrases appear, output as translit (English) (e.g., fīhi naẓar (he needs to be looked into)); do not replace with only English.\\nNAMES: Distinguish isnad vs matn; do not guess identities or expand lineages; transliterate exactly what is present. Book titles follow master rule.\\nRUMUZ/CODES: If the segment contains book codes (kh/m/d/t/s/q/4), preserve them exactly; do not expand to book names.\";\n\nexport const JARH_WA_TADIL = \"GLOSSARY: When a jarh/ta'dil term/phrase appears, output as translit (English) (e.g., thiqah (trustworthy), ṣadūq (truthful), layyin (soft/lenient), ḍaʿīf (weak), matrūk (abandoned), kadhdhāb (liar), dajjāl (imposter), munkar al-ḥadīth (narrates denounced hadith)).\\nRUMUZ: Preserve book codes in Latin exactly as in the segment (e.g., (kh) (m) (d t q) (4) (a)); do not expand unless the Arabic segment itself expands them.\\nQALA: Translate as \\\"He said:\\\" and start a new line for each new critic.\\nDATES: Use (d. 256 AH) or (born 194 AH).\\nNO HARM: Translate \\\"There is no harm in him\\\"; no notes.\\nPOLEMICS: Harsh terms (e.g., dajjāl, khabīth, rāfiḍī) must be translated literally; do not soften.\";\n\nexport const TAFSIR = \"AYAH CITES: Do not output surah names unless the Arabic includes the name. Use [2:255]. If the segment contains quoted Qur'an text, translate it in braces: {…} [2:255].\\nATTRIBUTES: Translate Allah’s attributes as the author intends; if the author is literal, keep literal (e.g., Hand, Face); do not add metaphorical reinterpretation unless the author does; mirror the author’s theology (Ash'ari vs Salafi) exactly.\\nI'RAB TERMS: Mubtada=Subject; Khabar=Predicate; Fa'il=Agent/Doer; Maf'ul=Object.\\nPROPHET NAMES: Use Arabic equivalents with ALA-LC diacritics (e.g., Mūsá, ʿĪsá, Dāwūd, Yūsuf).\\nPOETRY: Preserve line breaks (one English line per Arabic line); no bullets; prioritize literal structure/grammar over rhyme.\";\n\nexport const USUL_AL_FIQH = \"STRUCTURE: Preserve the argument structure (claims, objections \\\"if it is said...\\\", replies \\\"we say...\\\", evidences, counter-evidences). Preserve explicit labels (faṣl, masʾalah, qāla, qīla, qulna) as plain English equivalents only when the Arabic is explicitly a label.\\nUSUL TERMS: When technical terms appear, output as translit (English) (e.g., ʿāmm (general), khāṣṣ (specific), muṭlaq (absolute), muqayyad (restricted), amr (command), nahy (prohibition), ḥaqīqah (literal), majāz (figurative), mujmal (ambiguous), mubayyan (clarified), naṣṣ (explicit text), ẓāhir (apparent), mafhūm (implication), manṭūq (stated meaning), dalīl (evidence), qiyās (analogical reasoning), ʿillah (effective cause), sabab (cause), shart (condition), māniʿ (preventer), ijmāʿ (consensus), naskh (abrogation)).\\nDISPUTE HANDLING: Do not resolve methodological disputes or harmonize schools unless the Arabic explicitly chooses (e.g., al-rājiḥ / al-aṣaḥḥ / ṣaḥīḥ). Preserve attribution to the madhhab/scholars as written.\\nQUR'AN/HADITH: Keep verse references in the segment’s style; do not invent references. If a hadith isnad appears, follow MASTER isnad/name rules.\";\n\n// =============================================================================\n// PROMPT METADATA\n// =============================================================================\n\nexport const PROMPTS = [\n {\n id: 'master_prompt' as const,\n name: 'Master Prompt',\n content: MASTER_PROMPT,\n },\n {\n id: 'encyclopedia_mixed' as const,\n name: 'Encyclopedia Mixed',\n content: ENCYCLOPEDIA_MIXED,\n },\n {\n id: 'fatawa' as const,\n name: 'Fatawa',\n content: FATAWA,\n },\n {\n id: 'fiqh' as const,\n name: 'Fiqh',\n content: FIQH,\n },\n {\n id: 'hadith' as const,\n name: 'Hadith',\n content: HADITH,\n },\n {\n id: 'jarh_wa_tadil' as const,\n name: 'Jarh Wa Tadil',\n content: JARH_WA_TADIL,\n },\n {\n id: 'tafsir' as const,\n name: 'Tafsir',\n content: TAFSIR,\n },\n {\n id: 'usul_al_fiqh' as const,\n name: 'Usul Al Fiqh',\n content: USUL_AL_FIQH,\n },\n] as const;\n\nexport type PromptMetadata = (typeof PROMPTS)[number];\n","import { MASTER_PROMPT, PROMPTS, type PromptId, type PromptMetadata } from '@generated/prompts';\n\nexport type { PromptId, PromptMetadata };\n\n/**\n * A stacked prompt ready for use with an LLM.\n */\nexport type StackedPrompt = {\n /** Unique identifier */\n id: PromptId;\n /** Human-readable name */\n name: string;\n /** The full prompt content (master + addon if applicable) */\n content: string;\n /** Whether this is the master prompt (not stacked) */\n isMaster: boolean;\n};\n\n/**\n * Stacks a master prompt with a specialized addon prompt.\n *\n * @param master - The master/base prompt\n * @param addon - The specialized addon prompt\n * @returns Combined prompt text\n */\nexport const stackPrompts = (master: string, addon: string): string => {\n if (!master) {\n return addon;\n }\n if (!addon) {\n return master;\n }\n return `${master}\\n${addon}`;\n};\n\n/**\n * Gets all available prompts as stacked prompts (master + addon combined).\n * Master prompt is returned as-is, addon prompts are stacked with master.\n *\n * @returns Array of all stacked prompts\n */\nexport const getPrompts = (): StackedPrompt[] => {\n return PROMPTS.map((prompt) => ({\n content: prompt.id === 'master_prompt' ? prompt.content : stackPrompts(MASTER_PROMPT, prompt.content),\n id: prompt.id,\n isMaster: prompt.id === 'master_prompt',\n name: prompt.name,\n }));\n};\n\n/**\n * Gets a specific prompt by ID (strongly typed).\n * Returns the stacked version (master + addon) for addon prompts.\n *\n * @param id - The prompt ID to retrieve\n * @returns The stacked prompt\n * @throws Error if prompt ID is not found\n */\nexport const getPrompt = (id: PromptId): StackedPrompt => {\n const prompt = PROMPTS.find((p) => p.id === id);\n if (!prompt) {\n throw new Error(`Prompt not found: ${id}`);\n }\n\n return {\n content: prompt.id === 'master_prompt' ? prompt.content : stackPrompts(MASTER_PROMPT, prompt.content),\n id: prompt.id,\n isMaster: prompt.id === 'master_prompt',\n name: prompt.name,\n };\n};\n\n/**\n * Gets the raw stacked prompt text for a specific prompt ID.\n * Convenience method for when you just need the text.\n *\n * @param id - The prompt ID\n * @returns The stacked prompt content string\n */\nexport const getStackedPrompt = (id: PromptId): string => {\n return getPrompt(id).content;\n};\n\n/**\n * Gets the list of available prompt IDs.\n * Useful for UI dropdowns or validation.\n *\n * @returns Array of prompt IDs\n */\nexport const getPromptIds = (): PromptId[] => {\n return PROMPTS.map((p) => p.id);\n};\n\n/**\n * Gets just the master prompt content.\n * Useful when you need to use a custom addon.\n *\n * @returns The master prompt content\n */\nexport const getMasterPrompt = (): string => {\n return MASTER_PROMPT;\n};\n","import {\n ARCHAIC_WORDS,\n COLON_PATTERN,\n MARKER_ID_PATTERN,\n MAX_EMPTY_PARENTHESES,\n MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK,\n MIN_TRANSLATION_RATIO,\n TRANSLATION_MARKER_PARTS,\n} from './constants';\nimport { escapeRegExp, extractTranslationIds, normalizeTranslationText, splitResponseById } from './textUtils';\nimport type { Segment, ValidationError, ValidationErrorType } from './types';\n\n/**\n * Human-readable descriptions for each `ValidationErrorType`, intended for client UIs and logs.\n *\n * @example\n * VALIDATION_ERROR_TYPE_INFO.arabic_leak.description\n */\nexport const VALIDATION_ERROR_TYPE_INFO = {\n all_caps: {\n description: 'ALL CAPS “shouting” word detected (5+ letters).',\n },\n arabic_leak: {\n description: 'Arabic script was detected in output (except ﷺ).',\n },\n archaic_register: {\n description: 'Archaic/Biblical English detected (e.g., thou, verily, shalt).',\n },\n duplicate_id: {\n description: 'The same segment ID appears more than once in the response.',\n },\n empty_parentheses: {\n description: 'Excessive \"()\" patterns detected, often indicating failed/empty term-pairs.',\n },\n implicit_continuation: {\n description: 'The response includes continuation/meta phrasing (e.g., \"continued:\", \"implicit continuation\").',\n },\n invalid_marker_format: {\n description: 'A segment marker line is malformed (e.g., wrong ID shape or missing content after the dash).',\n },\n invented_id: {\n description: 'The response contains a segment ID that does not exist in the provided source corpus.',\n },\n length_mismatch: {\n description: 'Translation appears too short relative to Arabic source (heuristic truncation check).',\n },\n meta_talk: {\n description: 'The response includes translator/editor notes instead of pure translation.',\n },\n mismatched_colons: {\n description:\n 'Per-segment colon count mismatch between Arabic segment text and its translation chunk (counts \":\" and \":\").',\n },\n missing_id_gap: {\n description:\n 'A gap was detected: the response includes two IDs whose corpus order implies one or more intermediate IDs are missing.',\n },\n multiword_translit_without_gloss: {\n description: 'A multi-word transliteration phrase was detected without an immediate parenthetical gloss.',\n },\n newline_after_id: {\n description: 'The response used \"ID -\\\\nText\" instead of \"ID - Text\" (newline immediately after the marker).',\n },\n no_valid_markers: {\n description: 'No valid \"ID - ...\" markers were found anywhere in the response.',\n },\n truncated_segment: {\n description: 'A segment appears truncated (e.g., only \"…\", \"...\", or \"[INCOMPLETE]\").',\n },\n wrong_diacritics: {\n description: 'Wrong diacritics like â/ã/á were detected (should use macrons like ā ī ū).',\n },\n} as const satisfies Record<ValidationErrorType, { description: string }>;\n\nconst ARCHAIC_PATTERNS = ARCHAIC_WORDS.map((w) => new RegExp(`\\\\b${escapeRegExp(w)}\\\\b`, 'i'));\n\n/**\n * Validate an LLM translation response against a set of Arabic source segments.\n *\n * Rules are expressed as a list of typed errors. The caller decides severity.\n * The validator normalizes the response first (marker splitting + line endings).\n *\n * Important: `segments` may be the full corpus. The validator reduces to only\n * those IDs parsed from the response (plus detects missing-ID gaps between IDs).\n *\n * @example\n * // Pass (no errors)\n * validateTranslationResponse(\n * [{ id: 'P1', text: 'نص عربي طويل...' }],\n * 'P1 - A complete translation.'\n * ).errors.length === 0\n *\n * @example\n * // Fail (invented ID)\n * validateTranslationResponse(\n * [{ id: 'P1', text: 'نص عربي طويل...' }],\n * 'P2 - This ID is not in the corpus.'\n * ).errors.some(e => e.type === 'invented_id') === true\n */\nexport const validateTranslationResponse = (segments: Segment[], response: string) => {\n const normalizedResponse = normalizeTranslationText(response);\n const parsedIds = extractTranslationIds(normalizedResponse);\n\n if (parsedIds.length === 0) {\n return {\n errors: [{ message: 'No valid translation markers found', type: 'no_valid_markers' }],\n normalizedResponse,\n parsedIds: [],\n };\n }\n\n const segmentById = new Map<string, Segment>();\n for (const s of segments) {\n segmentById.set(s.id, s);\n }\n\n const responseById = splitResponseById(normalizedResponse);\n\n const errors: ValidationError[] = [\n ...validateMarkerFormat(normalizedResponse),\n ...validateNewlineAfterId(normalizedResponse),\n ...validateTruncatedSegments(normalizedResponse),\n ...validateImplicitContinuation(normalizedResponse),\n ...validateMetaTalk(normalizedResponse),\n ...validateDuplicateIds(parsedIds),\n ...validateInventedIds(parsedIds, segmentById),\n ...validateMissingIdGaps(parsedIds, segmentById, segments),\n ...validateArabicLeak(normalizedResponse),\n ...validateWrongDiacritics(normalizedResponse),\n ...validateEmptyParentheses(normalizedResponse),\n ...validateTranslationLengthsForResponse(parsedIds, segmentById, responseById),\n ...validateAllCaps(normalizedResponse),\n ...validateArchaicRegister(normalizedResponse),\n ...validateMismatchedColons(parsedIds, segmentById, responseById),\n ...validateMultiwordTranslitWithoutGloss(parsedIds, responseById),\n ];\n\n return { errors, normalizedResponse, parsedIds };\n};\n\n/**\n * Validate translation marker format (single-line errors).\n *\n * @example\n * // Fail: malformed marker\n * validateMarkerFormat('B1234$5 - x')[0]?.type === 'invalid_marker_format'\n */\nconst validateMarkerFormat = (text: string): ValidationError[] => {\n const { markers, digits, suffix, dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n\n const invalidRefPattern = new RegExp(\n `^${markers}(?=${digits})(?=.*${dashes})(?!${digits}${suffix}*${optionalSpace}${dashes})[^\\\\s-–—]+${optionalSpace}${dashes}`,\n 'm',\n );\n const invalidRef = text.match(invalidRefPattern);\n if (invalidRef) {\n return [\n {\n message: `Invalid reference format \"${invalidRef[0].trim()}\" - expected format is letter + numbers + optional suffix (a-j) + dash`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const spaceBeforePattern = new RegExp(` ${markers}${digits}${suffix}+${optionalSpace}${dashes}`, 'm');\n const suffixNoDashPattern = new RegExp(`^${markers}${digits}${suffix}(?! ${dashes})`, 'm');\n const suspicious = text.match(spaceBeforePattern) || text.match(suffixNoDashPattern);\n if (suspicious) {\n return [\n {\n match: suspicious[0],\n message: `Suspicious reference found: \"${suspicious[0]}\"`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const emptyAfterDashPattern = new RegExp(`^${MARKER_ID_PATTERN}${optionalSpace}${dashes}\\\\s*$`, 'm');\n const emptyAfterDash = text.match(emptyAfterDashPattern);\n if (emptyAfterDash) {\n return [\n {\n match: emptyAfterDash[0].trim(),\n message: `Reference \"${emptyAfterDash[0].trim()}\" has dash but no content after it`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const dollarSignPattern = new RegExp(`^${markers}${digits}\\\\$${digits}`, 'm');\n const dollarSignRef = text.match(dollarSignPattern);\n if (dollarSignRef) {\n return [\n {\n match: dollarSignRef[0],\n message: `Invalid reference format \"${dollarSignRef[0]}\" - contains $ character`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n return [];\n};\n\n/**\n * Detect newline after an ID line (formatting bug).\n *\n * @example\n * // Fail: newline after \"P1 -\"\n * validateNewlineAfterId('P1 -\\\\nText')[0]?.type === 'newline_after_id'\n */\nconst validateNewlineAfterId = (text: string): ValidationError[] => {\n const pattern = new RegExp(\n `^${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes}\\\\s*\\\\n`,\n 'm',\n );\n const match = text.match(pattern);\n return match\n ? [\n {\n match: match[0].trim(),\n message: `Invalid format: newline after ID \"${match[0].trim()}\" - use \"ID - Text\" format`,\n type: 'newline_after_id',\n },\n ]\n : [];\n};\n\n/**\n * Detect duplicated IDs in the parsed ID list.\n *\n * @example\n * validateDuplicateIds(['P1','P1'])[0]?.type === 'duplicate_id'\n */\nconst validateDuplicateIds = (ids: string[]): ValidationError[] => {\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const id of ids) {\n if (seen.has(id)) {\n duplicates.add(id);\n }\n seen.add(id);\n }\n return [...duplicates].map((id) => ({\n id,\n message: `Duplicate ID \"${id}\" detected - each segment should appear only once`,\n type: 'duplicate_id',\n }));\n};\n\n/**\n * Detect IDs in the response that do not exist in the passed segment corpus.\n *\n * @example\n * validateInventedIds(['P1','P2'], new Map([['P1',{id:'P1',text:'x'}]]) )[0]?.type === 'invented_id'\n */\nconst validateInventedIds = (outputIds: string[], segmentById: Map<string, Segment>): ValidationError[] => {\n const invented = outputIds.filter((id) => !segmentById.has(id));\n return invented.length > 0\n ? [\n {\n match: invented.join(','),\n message: `Invented ID(s) detected: ${invented.map((id) => `\"${id}\"`).join(', ')} - these IDs do not exist in the source`,\n type: 'invented_id',\n },\n ]\n : [];\n};\n\n/**\n * Detect a “gap”: response contains IDs A and C, but the corpus order includes B between them.\n * This only checks for missing IDs between consecutive IDs within each response-ordered block.\n *\n * @example\n * // Corpus: P1, P2, P3. Response: P1, P3 => missing_id_gap includes P2\n */\nconst validateMissingIdGaps = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n segments: Segment[],\n): ValidationError[] => {\n const indexById = new Map<string, number>();\n for (let i = 0; i < segments.length; i++) {\n indexById.set(segments[i].id, i);\n }\n\n const parsedIdSet = new Set(parsedIds);\n const missing = new Set<string>();\n\n const collectMissingBetween = (startIdx: number, endIdx: number) => {\n for (let j = startIdx + 1; j < endIdx; j++) {\n const midId = segments[j]?.id;\n if (midId && segmentById.has(midId) && !parsedIdSet.has(midId)) {\n missing.add(midId);\n }\n }\n };\n\n for (let i = 0; i < parsedIds.length - 1; i++) {\n const a = parsedIds[i];\n const b = parsedIds[i + 1];\n if (!segmentById.has(a) || !segmentById.has(b)) {\n continue;\n }\n\n const ia = indexById.get(a);\n const ib = indexById.get(b);\n if (ia == null || ib == null) {\n continue;\n }\n\n // Reset blocks when order goes backwards (block pasting)\n if (ib < ia) {\n continue;\n }\n\n collectMissingBetween(ia, ib);\n }\n\n const uniqueMissing = [...missing];\n return uniqueMissing.length > 0\n ? [\n {\n match: uniqueMissing.join(','),\n message: `Missing segment ID(s) detected between translated IDs: ${uniqueMissing.map((id) => `\"${id}\"`).join(', ')}`,\n type: 'missing_id_gap',\n },\n ]\n : [];\n};\n\n/**\n * Detect segments that appear truncated (just \"…\" / \"...\" / \"[INCOMPLETE]\").\n *\n * @example\n * validateTruncatedSegments('P1 - …')[0]?.type === 'truncated_segment'\n */\nconst validateTruncatedSegments = (text: string): ValidationError[] => {\n const segmentPattern = /^([A-Z]\\d+[a-j]?)\\s*[-–—]\\s*(.*)$/gm;\n const truncated: string[] = [];\n for (const match of text.matchAll(segmentPattern)) {\n const id = match[1];\n const content = match[2].trim();\n if (!content || content === '…' || content === '...' || content === '[INCOMPLETE]') {\n truncated.push(id);\n }\n }\n return truncated.length > 0\n ? [\n {\n match: truncated.join(','),\n message: `Truncated segment(s) detected: ${truncated.map((id) => `\"${id}\"`).join(', ')} - segments must be fully translated`,\n type: 'truncated_segment',\n },\n ]\n : [];\n};\n\n/**\n * Detect implicit continuation markers.\n *\n * @example\n * validateImplicitContinuation('P1 - continued: ...')[0]?.type === 'implicit_continuation'\n */\nconst validateImplicitContinuation = (text: string): ValidationError[] => {\n const patterns = [/implicit continuation/i, /\\bcontinuation:/i, /\\bcontinued:/i];\n for (const pattern of patterns) {\n const match = text.match(pattern);\n if (match) {\n return [\n {\n match: match[0],\n message: `Detected \"${match[0]}\" - do not add implicit continuation text`,\n type: 'implicit_continuation',\n },\n ];\n }\n }\n return [];\n};\n\n/**\n * Detect meta-talk (translator/editor notes).\n *\n * @example\n * validateMetaTalk(\"P1 - (Translator's note: ...)\")[0]?.type === 'meta_talk'\n */\nconst validateMetaTalk = (text: string): ValidationError[] => {\n const patterns = [/\\(note:/i, /\\(translator'?s? note:/i, /\\[editor:/i, /\\[note:/i, /\\(ed\\.:/i, /\\(trans\\.:/i];\n for (const pattern of patterns) {\n const match = text.match(pattern);\n if (match) {\n return [\n {\n match: match[0],\n message: `Detected meta-talk \"${match[0]}\" - output translation only, no translator/editor notes`,\n type: 'meta_talk',\n },\n ];\n }\n }\n return [];\n};\n\n/**\n * Detect Arabic script characters (except ﷺ).\n *\n * @example\n * validateArabicLeak('P1 - الله')[0]?.type === 'arabic_leak'\n *\n * @example\n * // Pass: ﷺ allowed\n * validateArabicLeak('P1 - Muḥammad ﷺ said...').length === 0\n */\nconst validateArabicLeak = (text: string): ValidationError[] => {\n const arabicPattern = /[\\u0600-\\u06FF\\u0750-\\u077F\\uFB50-\\uFDF9\\uFDFB-\\uFDFF\\uFE70-\\uFEFF]+/g;\n const matches = text.match(arabicPattern) ?? [];\n\n // Allow ﷺ (U+FDFD) as an explicit exception.\n const normalized = matches\n .map((m) => m.replace(/ﷺ/g, ''))\n .map((m) => m.trim())\n .filter((m) => m.length > 0);\n\n return normalized.map((match) => ({ match, message: `Arabic script detected: \"${match}\"`, type: 'arabic_leak' }));\n};\n\n/**\n * Detect wrong diacritics (â/ã/á) that indicate failed ALA-LC macrons.\n *\n * @example\n * validateWrongDiacritics('kâfir')[0]?.type === 'wrong_diacritics'\n */\nconst validateWrongDiacritics = (text: string): ValidationError[] => {\n const wrongPattern = /[âêîôûãñáéíóú]/gi;\n const matches = text.match(wrongPattern) ?? [];\n const unique = [...new Set(matches)];\n return unique.map((m) => ({\n match: m,\n message: `Wrong diacritic \"${m}\" detected - use macrons (ā, ī, ū) instead`,\n type: 'wrong_diacritics',\n }));\n};\n\n/**\n * Detect excessive empty parentheses \"()\" which often indicates failed transliterations.\n *\n * @example\n * // Fail: too many \"()\"\n * validateEmptyParentheses('() () () ()')[0]?.type === 'empty_parentheses'\n */\nconst validateEmptyParentheses = (text: string): ValidationError[] => {\n const count = text.match(/\\(\\)/g)?.length ?? 0;\n return count > MAX_EMPTY_PARENTHESES\n ? [\n {\n message: `Found ${count} empty parentheses \"()\" - this usually indicates failed transliterations. Please check if the LLM omitted Arabic/transliterated terms.`,\n type: 'empty_parentheses',\n },\n ]\n : [];\n};\n\n/**\n * Detect truncated translation vs Arabic source (ratio-based).\n *\n * @example\n * // Fail: long Arabic + very short translation\n * detectTruncatedTranslation('نص عربي طويل ... (50+ chars)', 'Short') !== undefined\n */\nconst detectTruncatedTranslation = (arabicText: string, translationText: string) => {\n const arabic = (arabicText || '').trim();\n const translation = (translationText || '').trim();\n\n if (arabic.length < MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK) {\n return;\n }\n if (translation.length === 0) {\n return `Translation appears empty but Arabic text has ${arabic.length} characters`;\n }\n\n const ratio = translation.length / arabic.length;\n if (ratio < MIN_TRANSLATION_RATIO) {\n const expectedMinLength = Math.round(arabic.length * MIN_TRANSLATION_RATIO);\n return `Translation appears truncated: ${translation.length} chars for ${arabic.length} char Arabic text (expected at least ~${expectedMinLength} chars)`;\n }\n};\n\n/**\n * Validate per-ID translation lengths (response subset only).\n *\n * @example\n * // Produces a length_mismatch error for the first truncated segment found\n */\nconst validateTranslationLengthsForResponse = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n responseById: Map<string, string>,\n) => {\n for (const id of parsedIds) {\n const seg = segmentById.get(id);\n const translation = responseById.get(id);\n if (!seg || translation == null) {\n continue;\n }\n const error = detectTruncatedTranslation(seg.text, translation);\n if (error) {\n const e = {\n id,\n message: `Translation for \"${id}\" ${error.replace('Translation ', '').toLowerCase()}`,\n type: 'length_mismatch',\n } as const satisfies ValidationError;\n return [e];\n }\n }\n return [] as ValidationError[];\n};\n\n/**\n * Detect “shouting” ALL CAPS words.\n *\n * @example\n * validateAllCaps('THIS IS LOUD')[0]?.type === 'all_caps'\n */\nconst validateAllCaps = (text: string): ValidationError[] => {\n const matches = text.match(/\\b[A-Z]{5,}\\b/g) ?? [];\n const unique = [...new Set(matches)];\n return unique.map((m) => ({ match: m, message: `ALL CAPS detected: \"${m}\"`, type: 'all_caps' }));\n};\n\n/**\n * Detect archaic/Biblical register tokens.\n *\n * @example\n * validateArchaicRegister('verily thou shalt')[0]?.type === 'archaic_register'\n */\nconst validateArchaicRegister = (text: string): ValidationError[] => {\n const found: string[] = [];\n for (const re of ARCHAIC_PATTERNS) {\n const m = text.match(re);\n if (m) {\n found.push(m[0]);\n }\n }\n return [...new Set(found)].map((m) => ({\n match: m,\n message: `Archaic/Biblical register word detected: \"${m}\"`,\n type: 'archaic_register',\n }));\n};\n\n/**\n * Detect per-segment mismatch in colon counts between Arabic segment text and its translation chunk.\n *\n * This is intentionally heuristic and avoids hardcoding speaker label tokens.\n *\n * @example\n * // Arabic: \"الشيخ: ... السائل: ...\" => 2 colons\n * // Translation: \"The Shaykh: ...\" => 1 colon => mismatched_colons\n */\nconst validateMismatchedColons = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n responseById: Map<string, string>,\n): ValidationError[] => {\n const errors: ValidationError[] = [];\n\n for (const id of parsedIds) {\n const seg = segmentById.get(id);\n const translation = responseById.get(id);\n if (!seg || !translation) {\n continue;\n }\n\n const arabicCount = seg.text.match(COLON_PATTERN)?.length ?? 0;\n const englishCount = translation.match(COLON_PATTERN)?.length ?? 0;\n\n if (arabicCount === englishCount) {\n continue;\n }\n\n errors.push({\n id,\n match: `${arabicCount} vs ${englishCount}`,\n message: `Colon count mismatch in \"${id}\": Arabic has ${arabicCount} \":\" but translation has ${englishCount}. This may indicate dropped/moved speaker turns or formatting drift.`,\n type: 'mismatched_colons',\n });\n }\n\n return errors;\n};\n\n/**\n * Detect multi-word transliteration patterns without immediate parenthetical gloss.\n *\n * @example\n * // Fail: \"al-hajr fi al-madajīʿ\" without \"(English ...)\" nearby\n * // => multiword_translit_without_gloss\n */\nconst validateMultiwordTranslitWithoutGloss = (\n parsedIds: string[],\n responseById: Map<string, string>,\n): ValidationError[] => {\n const errors: ValidationError[] = [];\n const phrasePattern = /\\b(al-[a-zʿʾāīūḥṣḍṭẓ-]+)\\s+fi\\s+(al-[a-zʿʾāīūḥṣḍṭẓ-]+)\\b/gi;\n\n for (const id of parsedIds) {\n const text = responseById.get(id);\n if (!text) {\n continue;\n }\n\n for (const m of text.matchAll(phrasePattern)) {\n const phrase = `${m[1]} fi ${m[2]}`;\n const idx = m.index ?? -1;\n if (idx >= 0) {\n const after = text.slice(idx, Math.min(text.length, idx + phrase.length + 25));\n if (!after.includes('(')) {\n errors.push({\n id,\n match: phrase,\n message: `Multi-word transliteration without immediate gloss in \"${id}\": \"${phrase}\"`,\n type: 'multiword_translit_without_gloss',\n });\n }\n }\n }\n }\n\n return errors;\n};\n"],"mappings":";;;;AAGA,IAAY,4CAAL;;AAEH;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;;;;;AAMJ,MAAa,2BAA2B;CAEpC,QAAQ;CAER,QAAQ;CAER,SAAS,IAAI,QAAQ,OAAO,QAAQ,UAAU,QAAQ,WAAW,QAAQ,UAAU,QAAQ,QAAQ,QAA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jE,MAAI,gBAAgB,aAChB;AAGJ,SAAO,KAAK;GACR;GACA,OAAO,GAAG,YAAY,MAAM;GAC5B,SAAS,4BAA4B,GAAG,gBAAgB,YAAY,2BAA2B,aAAa;GAC5G,MAAM;GACT,CAAC;;AAGN,QAAO;;;;;;;;;AAUX,MAAM,yCACF,WACA,iBACoB;CACpB,MAAM,SAA4B,EAAE;CACpC,MAAM,gBAAgB;AAEtB,MAAK,MAAM,MAAM,WAAW;EACxB,MAAM,OAAO,aAAa,IAAI,GAAG;AACjC,MAAI,CAAC,KACD;AAGJ,OAAK,MAAM,KAAK,KAAK,SAAS,cAAc,EAAE;GAC1C,MAAM,SAAS,GAAG,EAAE,GAAG,MAAM,EAAE;GAC/B,MAAM,MAAM,EAAE,SAAS;AACvB,OAAI,OAAO,GAEP;QAAI,CADU,KAAK,MAAM,KAAK,KAAK,IAAI,KAAK,QAAQ,MAAM,OAAO,SAAS,GAAG,CAAC,CACnE,SAAS,IAAI,CACpB,QAAO,KAAK;KACR;KACA,OAAO;KACP,SAAS,0DAA0D,GAAG,MAAM,OAAO;KACnF,MAAM;KACT,CAAC;;;;AAMlB,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/constants.ts","../.generated/prompts.ts","../src/prompts.ts","../src/textUtils.ts","../src/validation.ts"],"sourcesContent":["/**\n * Supported marker types for segments.\n */\nexport enum Markers {\n /** B - Book reference */\n Book = 'B',\n /** F - Footnote reference */\n Footnote = 'F',\n /** T - Heading reference */\n Heading = 'T',\n /** C - Chapter reference */\n Chapter = 'C',\n /** N - Note reference */\n Note = 'N',\n /** P - Translation/Plain segment */\n Plain = 'P',\n}\n\n/**\n * Regex parts for building translation marker patterns.\n */\nexport const TRANSLATION_MARKER_PARTS = {\n /** Dash variations (hyphen, en dash, em dash) */\n dashes: '[-–—]',\n /** Numeric portion of the reference */\n digits: '\\\\d+',\n /** Valid marker prefixes (Book, Chapter, Footnote, Translation, Page) */\n markers: `[${Markers.Book}${Markers.Chapter}${Markers.Footnote}${Markers.Heading}${Markers.Plain}${Markers.Note}]`,\n /** Optional whitespace before dash */\n optionalSpace: '\\\\s?',\n /** Valid single-letter suffixes */\n suffix: '[a-z]',\n} as const;\n\n/**\n * Pattern for a segment ID (e.g., P1234, B45a).\n */\nexport const MARKER_ID_PATTERN = `${TRANSLATION_MARKER_PARTS.markers}${TRANSLATION_MARKER_PARTS.digits}${TRANSLATION_MARKER_PARTS.suffix}?`;\n\n/**\n * English tokens that indicate archaic/Biblical register and should be flagged.\n */\nexport const ARCHAIC_WORDS = [\n 'thee',\n 'thou',\n 'thine',\n 'thy',\n 'verily',\n 'shalt',\n 'hast',\n 'whence',\n 'henceforth',\n 'saith',\n 'behold',\n] as const;\n\nexport const MAX_EMPTY_PARENTHESES = 3;\nexport const MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK = 50;\nexport const MIN_TRANSLATION_RATIO = 0.25;\n\nexport const COLON_PATTERN = /[::]/g;\n","// AUTO-GENERATED FILE - DO NOT EDIT\n// Generated from prompts/*.md by scripts/generate-prompts.ts\n\n// =============================================================================\n// PROMPT TYPE\n// =============================================================================\n\nexport type PromptId = 'master_prompt' | 'encyclopedia_mixed' | 'fatawa' | 'fiqh' | 'hadith' | 'jarh_wa_tadil' | 'tafsir' | 'usul_al_fiqh';\n\n// =============================================================================\n// RAW PROMPT CONTENT\n// =============================================================================\n\nexport const MASTER_PROMPT = \"ROLE: Expert academic translator of Classical Islamic texts; prioritize accuracy and structure over fluency.\\nCRITICAL NEGATIONS: 1. NO SANITIZATION (Do not soften polemics). 2. NO META-TALK (Output translation only). 3. NO MARKDOWN (Plain text only). 4. NO EMENDATION. 5. NO INFERENCE. 6. NO RESTRUCTURING. 7. NO OPAQUE TRANSLITERATION (Must translate phrases). 8. NO INVENTED SEGMENTS (Do not create, modify, or \\\"continue\\\" segment IDs. Output IDs verbatim exactly as they appear in the source input/metadata. Alphabetic suffixes (e.g., P5511a) are allowed IF AND ONLY IF that exact ID appears in the source. Any ID not present verbatim in the source is INVENTED. EXAMPLE: If P5803b ends with a questioner line, that line stays under P5803b — do NOT invent P5803c. If an expected ID is missing from the source, output: \\\"ID - [MISSING]\\\".)\\nRULES: NO ARABIC SCRIPT (Except ﷺ). Plain text only. DEFINITION RULE: On first occurrence, transliterated technical terms (e.g., bidʿah) MUST be defined: \\\"translit (English)\\\". Preserve Segment ID. Translate meaning/intent. No inference. No extra fields. Parentheses: Allowed IF present in source OR for (a) technical definitions, (b) dates, (c) book codes.\\nARABIC LEAK (Hard ban):\\n- SCRIPT LOCK: Output must be 100% Latin script (ASCII + ALA-LC diacritics like ā ī ū ḥ ṣ ḍ ṭ ẓ ʿ ʾ). These diacritics are allowed/required and are NOT Arabic script.\\n- STRICT BAN: Arabic script codepoints (letters, Arabic-Indic numerals ٠-٩, punctuation like ، ؟ ؛ « » , tatweel ـ, and Arabic presentation forms) are forbidden everywhere in output (even inside quotes/brackets/parentheses/citations), except ﷺ.\\n- NO CITATIONS/BILINGUAL: Do NOT paste Arabic source text anywhere (no quotes, no citations, no bilingual Arabic+English output). Translate into English only.\\n- QUOTES/VERSES: Even if the source includes Arabic Qurʾān/ḥadīth/quoted Arabic text (e.g., «...») you must NOT copy Arabic. Translate the meaning into English only.\\n- NO MIXED-SCRIPT: Never output a token that mixes Latin and Arabic characters (example: ʿĪد). Rewrite contaminated names/terms fully in Latin ALA-LC.\\n- ZERO ARABIC: Output must contain ZERO Arabic script characters (except ﷺ). If any Arabic appears, delete it and rewrite until none remain.\\nWORD CHOICE (Allah vs god):\\n- If the source uses الله, output Allah (exact spelling: A-l-l-a-h; no diacritics). Never \\\"God\\\" / \\\"god\\\" / \\\"Allāh\\\". (This is the only exception to ALA-LC diacritics.)\\n- DO NOT convert Allah-based formulae into English “God …” idioms. Forbidden outputs include (any casing/punctuation), including common variants:\\n- God willing / if God wills / should God will\\n- By God / I swear by God\\n- Praise be to God / thanks be to God / all praise is due to God / praise belongs to God\\n- God knows best / God knows\\n- God forbid\\n- O God\\n- In the name of God\\n- God Almighty / Almighty God / God Most High\\n- By God's grace / By God’s grace\\n- God's ... / God’s ... / ... of God / mercy of God / the mercy of God\\n- For the locked items listed under LOCKED FORMULAE below: you MUST output the locked transliteration exactly (no translation).\\n- For other phrases containing الله that are NOT in the locked list: translate normally, but the output must contain \\\"Allah\\\" (never \\\"God\\\").\\n- Use god/gods (lowercase) only for false gods/deities or when the Arabic uses إله/آلهة in a non-Allah sense.\\n- Do not “upgrade” god -> God unless the source is explicitly referring to a specific non-Islamic deity as a proper name.\\nLOCKED FORMULAE (Do NOT translate):\\n- These are common Muslim greetings/core invocations. Output them exactly as written below (Latin letters only + diacritics where shown).\\n- CHECK THIS LIST FIRST. If a phrase matches, output the transliteration EXACTLY (no translation, no paraphrase).\\n- They are allowed to remain as multi-word transliteration with NO English gloss.\\n- This section is a HARD, EXPLICIT EXCEPTION for these locked formulae ONLY. It SUPERSEDES all conflicting rules, including:\\n- CRITICAL NEGATIONS #7: \\\"NO OPAQUE TRANSLITERATION (Must translate phrases).\\\"\\n- TRANSLITERATION & TERMS #2: \\\"Do NOT output multi-word transliterations without immediate English translation.\\\"\\n- TRANSLITERATION & TERMS: \\\"Do NOT transliterate full sentences/matn/quotes.\\\"\\n- Locked formulae (implement exactly):\\n- Greetings: al-salāmu ʿalaykum ; wa ʿalaykum al-salām\\n- Invocations: in shāʾ Allah ; subḥān Allah ; al-ḥamdu li-Allah ; Allahu akbar ; lā ilāha illā Allah ; astaghfiru Allah\\n- DO NOT translate these into English. Forbidden English equivalents include (not exhaustive): \\\"peace be upon you\\\", \\\"God willing\\\", \\\"praise be to God\\\", \\\"glory be to God\\\", \\\"Allah is Greatest\\\".\\n- Note: this lock is intentionally narrow. Other phrases (e.g., \\\"Jazāk Allahu khayr\\\") may be translated normally.\\nREGISTER (Modern English):\\n- Use modern academic English. Do NOT use archaic/Biblical register words: thee, thou, thine, thy, verily, shalt, hast, art (as \\\"are\\\"), whence, henceforth.\\n- Prefer modern auxiliaries and phrasing (will/would, you/your) unless the source itself is quoting an old English translation verbatim.\\n- NO ALL CAPS / NO KJV-STYLE: Do NOT use ALL CAPS for emphasis (even inside quotes). Do NOT render Arabic Qurʾān/ḥadīth in KJV/Biblical style.\\nTRANSLITERATION & TERMS:\\n1. SCHEME: Use full ALA-LC for explicit Arabic-script Person/Place/Book-Titles.\\n- al-Casing: Lowercase al- mid-sentence; Capitalize after (al-Salafīyyah).\\n- Book Titles: Transliterate only (do not translate meanings).\\n2. TECHNICAL TERMS: On first occurrence, define: \\\"translit (English)\\\" (e.g., bidʿah (innovation), isnād (chain)).\\n- Do NOT output multi-word transliterations without immediate English translation.\\n- Do NOT transliterate full sentences/matn/quotes. Translate into English; transliteration is for names/terms only.\\n- EXCEPTION (Duʿāʾ/Supplications): If the source contains a specific duʿāʾ/supplication phrase and you choose to preserve its wording for pronunciation, you MAY output transliteration BUT you MUST also translate it immediately (same line or next) as: \\\"translit (English translation)\\\". Do NOT output Arabic script.\\n- Example Allowed: Allāhumma innī asʾaluka al-ʿāfiyah (O Allah, I ask You for well-being).\\n- Example Forbidden: Transliterate a long multi-sentence duʿāʾ paragraph without translating it.\\n- LOCKED FORMULAE are the only exception allowed to remain multi-word transliteration with NO English gloss.\\n- If you use any other multi-word transliteration (not locked), it MUST be immediately glossed: \\\"translit (English)\\\". Prefer full English translation for phrases.\\n- Do NOT leave common nouns/objects/roles as transliteration (e.g., tools, foods, occupations). Translate them into English. If you must transliterate a non-name, you MUST immediately gloss it: \\\"translit (English)\\\".\\n3. STANDARDIZED TERMS: Use standard academic spellings: Muḥammad, Shaykh, Qurʾān, Islām, ḥadīth.\\n- Sunnah (Capitalized) = The Corpus/Prophetic Tradition. sunnah (lowercase) = legal status/recommended.\\n4. PROPER NAMES: Transliterate only (no parentheses).\\n5. UNICODE: Latin + Latin Extended (āīūḥʿḍṣṭẓʾ) + punctuation. NO Arabic script (except ﷺ). NO emoji.\\n- DIACRITIC FALLBACK: If you cannot produce correct ALA-LC diacritics, output English only. Do NOT use substitute accents (â/ã/á).\\n6. SALUTATION: Replace all Prophet salutations with ﷺ.\\n7. HONORIFICS: Expand common phrases (do not transliterate):\\n- Allah ʿazza wa-jall -> Allah, the Mighty and Majestic\\n- rahimahu Allah -> may Allah have mercy on him\\n8. AMBIGUITY: Use contextual meaning from tafsir for theological terms. Do not sanitise polemics (e.g. Rāfiḍah).\\nOUTPUT FORMAT: Segment_ID - English translation.\\nCRITICAL: You must use the ASCII hyphen separator \\\" - \\\" (space+hyphen+space) immediately after the ID. Do NOT use em-dash or en-dash. Do NOT use a newline after the ID.\\nID INTEGRITY (Check First):\\n- PREPASS (Silent closed set): Internally identify the exact ordered list of Segment_IDs present in the source. Treat this list as a CLOSED SET. Do not output this list.\\n- REQUIRED (Exact match): Your output must contain EXACTLY those Segment_IDs, in the EXACT same order, each appearing EXACTLY ONCE as an \\\"ID - ...\\\" prefix. FORBIDDEN: re-outputting an ID prefix you already used (even in long segments).\\n- BAN (No new IDs): Do NOT invent ANY IDs or ID-like labels not present verbatim in the source (including \\\"(continued)\\\", \\\"cont.\\\", \\\"part 2\\\", or invented suffixes like P123c). Suffix IDs are allowed ONLY if that exact ID appears in the source.\\n- BOUNDARY (No bleed): Translate ONLY the text that belongs to the current Segment_ID (from its header to the next Segment_ID header, or to end-of-input for the last segment). Do NOT move lines across IDs and do NOT merge segments.\\n- INCOMPLETE (Strict): Use \\\"ID - [INCOMPLETE]\\\" ONLY if the provided source text under that ID is truly unreadable/untranslatable. NEVER use \\\"[INCOMPLETE]\\\" for ellipses (…) or long segments. Translate all available text.\\nMULTI-LINE SEGMENTS (e.g., internal Q&A): Output the Segment_ID and \\\" - \\\" ONLY ONCE on the first line. Do NOT repeat the Segment_ID on subsequent lines; subsequent lines must start directly with the speaker label/text (no \\\"ID - \\\" prefix).\\nSEGMENT BOUNDARIES (Anti-hallucination): Start a NEW segment ONLY when the source explicitly provides a Segment_ID. If the source continues with extra lines (including speaker labels like \\\"Questioner:\\\"/\\\"The Shaykh:\\\"/\\\"السائل:\\\"/\\\"الشيخ:\\\") WITHOUT a new Segment_ID, treat them as part of the CURRENT segment (multi-line under the current Segment_ID). Do NOT invent a new ID (including alphabetic suffixes like \\\"P5803c\\\") to label such continuation.\\nOUTPUT COMPLETENESS: Translate ALL content in EVERY segment. Do not truncate, summarize, or skip content. The \\\"…\\\" symbol in the source indicates an audio gap in the original recording — it is NOT an instruction to omit content. Every segment must be fully translated. If you cannot complete a segment, output \\\"ID - [INCOMPLETE]\\\" instead of just \\\"…\\\".\\nOUTPUT UNIQUENESS: Each Segment_ID from the source must appear in your output EXACTLY ONCE as an \\\"ID - ...\\\" prefix. Do NOT output the same Segment_ID header twice. If a segment is long or has multiple speaker turns, continue translating under that single ID header without re-stating it.\\nNEGATIVE CONSTRAINTS: Do NOT output \\\"implicit continuation\\\", summaries, or extra paragraphs. Output only the text present in the source segment.\\nExample: P1234 - Translation text... (Correct) vs P1234\\\\nTranslation... (Forbidden).\\nEXAMPLE: Input: P405 - حدثنا عبد الله بن يوسف... Output: P405 - ʿAbd Allāh b. Yūsuf narrated to us...\";\n\nexport const ENCYCLOPEDIA_MIXED = \"NO MODE TAGS: Do not output any mode labels or bracket tags.\\nSTRUCTURE (Apply First):\\n- Q&A: Whenever \\\"Al-Sāʾil:\\\"/\\\"Al-Shaykh:\\\" appear: Start NEW LINE for speaker. Keep Label+Text on SAME LINE.\\n- EXCEPTION: If the speaker label is the VERY FIRST token after the \\\"ID - \\\" prefix, keep it on the same line. (Correct: P5455 - Questioner: Text...) (Wrong: P5455 \\\\n Questioner: Text...).\\n- INTERNAL Q&A: If segment has multiple turns, use new lines for speakers. Output Segment ID ONLY ONCE at the start of the first line. Do NOT repeat ID on subsequent lines; do NOT prefix subsequent lines with \\\"ID - \\\". (e.g. P5455 - Questioner: ... \\\\n The Shaykh: ...).\\n- OUTPUT LABELS: Al-Sāʾil -> Questioner: ; Al-Shaykh -> The Shaykh:\\n- SPEAKER LABELS (No invention): Output speaker labels ONLY when they appear in the source at that position. Do NOT add \\\"Questioner:\\\"/\\\"The Shaykh:\\\" to unlabeled text. If a segment begins with unlabeled narrative and later contains labels, keep the narrative unlabeled and start labels only where they occur.\\nDEFINITIONS & CASING:\\n- GEOPOLITICS: Modern place names may use English exonyms (Filasṭīn -> Palestine).\\n- PLURALS: Do not pluralize term-pairs by appending \\\"s\\\" (e.g., \\\"ḥadīth (report)s\\\"). Use the English plural or rephrase.\\nSTATE LOGIC (Priority: Isnad > Rijal > Fiqh > Narrative):\\n- ISNAD (Triggers: ḥaddathanā, akhbaranā, ʿan): Use FULL ALA-LC for names.\\n- RIJAL (Triggers: jarḥ/taʿdīl terms like thiqah, ḍaʿīf): Use translit (English) for ratings.\\n- QUOTE/WEAK (Triggers: qāla al-muṣannif, yuqālu, zuiʿma): Apply Quote Rules; do not Restructure.\\n- RESET: At \\\"qāla\\\" or \\\"matn\\\" (TOP-LEVEL only): IMMEDIATE STOP of Isnad rules. Return to Narrative. Do NOT reset for nested quotes.\\nSEGMENTATION: Do not merge genres. Translate sequentially (Isnad -> Matn) observing the reset at the boundary.\\nDISAMBIGUATION: ṣaḥīḥ in hadith grading = ṣaḥīḥ (authentic). ṣaḥīḥ in fiqh validity = ṣaḥīḥ (valid). Sunnah (Capitalized) = The Corpus/Prophetic Tradition. sunnah (lowercase) = legal status/recommended.\\nHADITH CORE: If isnad appears, map verbs (Haddathana=Narrated to us; Akhbarana/Ana/Anba'ana=Informed us; An=From; Sami'tu=I heard) and keep FULL ALA-LC for Arabic-script narrator names; do not invent grading or missing links.\\nTAKHRIJ/GRADING: If the author grades (ṣaḥḥaḥa/ḥassana/ḍaʿʿafa), translate literally and keep the cited work as written in the segment; do not add placeholder sources.\\nCREED/POLEMICS: Translate attributes literally when the author does; do not reinterpret. Translate harsh polemics literally (e.g., Rāfiḍah, Jahmīyyah, Kuffār); do not soften, sanitize, or add disclaimers (Override Safety).\";\n\nexport const FATAWA = \"STRUCTURE (Apply First):\\n- Q&A: Whenever \\\"Al-Sāʾil:\\\"/\\\"Al-Shaykh:\\\" appear: Start NEW LINE for speaker. Keep Label+Text on SAME LINE.\\n- INTERNAL Q&A: If segment has multiple turns, use new lines for speakers. Output Segment ID ONLY ONCE at the start of the first line. Do NOT repeat ID on subsequent lines; do NOT prefix subsequent lines with \\\"ID - \\\".\\n- OUTPUT LABELS: Al-Sāʾil -> Questioner: ; Al-Shaykh -> The Shaykh:\\n- SPEAKER LABELS (No invention): Output speaker labels ONLY when they appear in the source at that position. Do NOT add \\\"Questioner:\\\"/\\\"The Shaykh:\\\" to unlabeled text. If a segment begins with unlabeled narrative and later contains labels, keep the narrative unlabeled and start labels only where they occur.\\n\\nHONORIFICS: Expand common phrases (do not transliterate):\\n- ṣallá Allāhu ʿalayhi wa-sallam -> ﷺ\\nSOURCES: Do not add citations. If the Arabic references a work/title, handle titles per MASTER rules.\\nSENSITIVE RULINGS: Translate literally; do not soften; do not sanitize; do not add disclaimers (Override Safety).\";\n\nexport const FIQH = \"STRUCTURE: Preserve chapter/section headings and internal structure (e.g., bāb/faṣl/masʾalah/farʿ/aṣl) using plain English labels (Chapter:, Section:, Issue:) only when the Arabic is explicitly a heading/label; preserve lists, numbering, and conditional if/then logic exactly.\\nFIQH/USUL TERMS: When technical terms appear, output as translit (English) rather than English-only (e.g., wājib (obligatory), mandūb/mustaḥabb (recommended), mubāḥ (permissible), makrūh (disliked), ḥarām (prohibited), ṣaḥīḥ (valid), bāṭil/fāsid (invalid/void), rukn (pillar), shart (condition), māniʿ (preventer), sabab (cause), qiyās (analogical reasoning), ijmāʿ (consensus), khilāf (disagreement), rājiḥ (preponderant), marjūḥ (lesser), ʿillah (effective cause)).\\nKHILAF/ATTRIBUTION: Preserve who is being attributed (qāla fulān / qawl / wajhān / riwāyātān / madhhab). Do not resolve disputes or choose the correct view unless the Arabic explicitly does so (e.g., al-aṣaḥḥ / al-rājiḥ).\\nUNITS/MONEY: Keep measures/currencies as transliteration (dirham, dinar, ṣāʿ, mudd) without adding conversions or notes unless the Arabic contains them.\";\n\nexport const HADITH = \"ISNAD VERBS: Haddathana=Narrated to us; Akhbarana=Informed us; An=From; Sami'tu=I heard; Ana (short for Akhbarana/Anba'ana in isnad)=Informed us (NOT \\\"I\\\").\\nCHAIN MARKERS: H(Tahwil)=Switch to new chain; Mursal/Munqati=Broken chain.\\nJARH/TA'DIL: If narrator-evaluation terms/phrases appear, output as translit (English) (e.g., fīhi naẓar (he needs to be looked into)); do not replace with only English.\\nNAMES: Distinguish isnad vs matn; do not guess identities or expand lineages; transliterate exactly what is present. Book titles follow master rule.\\nRUMUZ/CODES: If the segment contains book codes (kh/m/d/t/s/q/4), preserve them exactly; do not expand to book names.\";\n\nexport const JARH_WA_TADIL = \"GLOSSARY: When a jarh/ta'dil term/phrase appears, output as translit (English) (e.g., thiqah (trustworthy), ṣadūq (truthful), layyin (soft/lenient), ḍaʿīf (weak), matrūk (abandoned), kadhdhāb (liar), dajjāl (imposter), munkar al-ḥadīth (narrates denounced hadith)).\\nRUMUZ: Preserve book codes in Latin exactly as in the segment (e.g., (kh) (m) (d t q) (4) (a)); do not expand unless the Arabic segment itself expands them.\\nQALA: Translate as \\\"He said:\\\" and start a new line for each new critic.\\nDATES: Use (d. 256 AH) or (born 194 AH).\\nNO HARM: Translate \\\"There is no harm in him\\\"; no notes.\\nPOLEMICS: Harsh terms (e.g., dajjāl, khabīth, rāfiḍī) must be translated literally; do not soften.\";\n\nexport const TAFSIR = \"AYAH CITES: Do not output surah names unless the Arabic includes the name. Use [2:255]. If the segment contains quoted Qur'an text, translate it in braces: {…} [2:255].\\nATTRIBUTES: Translate Allah’s attributes as the author intends; if the author is literal, keep literal (e.g., Hand, Face); do not add metaphorical reinterpretation unless the author does; mirror the author’s theology (Ash'ari vs Salafi) exactly.\\nI'RAB TERMS: Mubtada=Subject; Khabar=Predicate; Fa'il=Agent/Doer; Maf'ul=Object.\\nPROPHET NAMES: Use Arabic equivalents with ALA-LC diacritics (e.g., Mūsá, ʿĪsá, Dāwūd, Yūsuf).\\nPOETRY: Preserve line breaks (one English line per Arabic line); no bullets; prioritize literal structure/grammar over rhyme.\";\n\nexport const USUL_AL_FIQH = \"STRUCTURE: Preserve the argument structure (claims, objections \\\"if it is said...\\\", replies \\\"we say...\\\", evidences, counter-evidences). Preserve explicit labels (faṣl, masʾalah, qāla, qīla, qulna) as plain English equivalents only when the Arabic is explicitly a label.\\nUSUL TERMS: When technical terms appear, output as translit (English) (e.g., ʿāmm (general), khāṣṣ (specific), muṭlaq (absolute), muqayyad (restricted), amr (command), nahy (prohibition), ḥaqīqah (literal), majāz (figurative), mujmal (ambiguous), mubayyan (clarified), naṣṣ (explicit text), ẓāhir (apparent), mafhūm (implication), manṭūq (stated meaning), dalīl (evidence), qiyās (analogical reasoning), ʿillah (effective cause), sabab (cause), shart (condition), māniʿ (preventer), ijmāʿ (consensus), naskh (abrogation)).\\nDISPUTE HANDLING: Do not resolve methodological disputes or harmonize schools unless the Arabic explicitly chooses (e.g., al-rājiḥ / al-aṣaḥḥ / ṣaḥīḥ). Preserve attribution to the madhhab/scholars as written.\\nQUR'AN/HADITH: Keep verse references in the segment’s style; do not invent references. If a hadith isnad appears, follow MASTER isnad/name rules.\";\n\n// =============================================================================\n// PROMPT METADATA\n// =============================================================================\n\nexport const PROMPTS = [\n {\n id: 'master_prompt' as const,\n name: 'Master Prompt',\n content: MASTER_PROMPT,\n },\n {\n id: 'encyclopedia_mixed' as const,\n name: 'Encyclopedia Mixed',\n content: ENCYCLOPEDIA_MIXED,\n },\n {\n id: 'fatawa' as const,\n name: 'Fatawa',\n content: FATAWA,\n },\n {\n id: 'fiqh' as const,\n name: 'Fiqh',\n content: FIQH,\n },\n {\n id: 'hadith' as const,\n name: 'Hadith',\n content: HADITH,\n },\n {\n id: 'jarh_wa_tadil' as const,\n name: 'Jarh Wa Tadil',\n content: JARH_WA_TADIL,\n },\n {\n id: 'tafsir' as const,\n name: 'Tafsir',\n content: TAFSIR,\n },\n {\n id: 'usul_al_fiqh' as const,\n name: 'Usul Al Fiqh',\n content: USUL_AL_FIQH,\n },\n] as const;\n\nexport type PromptMetadata = (typeof PROMPTS)[number];\n","import { MASTER_PROMPT, PROMPTS, type PromptId, type PromptMetadata } from '@generated/prompts';\n\nexport type { PromptId, PromptMetadata };\n\n/**\n * A stacked prompt ready for use with an LLM.\n */\nexport type StackedPrompt = {\n /** Unique identifier */\n id: PromptId;\n /** Human-readable name */\n name: string;\n /** The full prompt content (master + addon if applicable) */\n content: string;\n /** Whether this is the master prompt (not stacked) */\n isMaster: boolean;\n};\n\n/**\n * Stacks a master prompt with a specialized addon prompt.\n *\n * @param master - The master/base prompt\n * @param addon - The specialized addon prompt\n * @returns Combined prompt text\n */\nexport const stackPrompts = (master: string, addon: string): string => {\n if (!master) {\n return addon;\n }\n if (!addon) {\n return master;\n }\n return `${master}\\n${addon}`;\n};\n\n/**\n * Gets all available prompts as stacked prompts (master + addon combined).\n * Master prompt is returned as-is, addon prompts are stacked with master.\n *\n * @returns Array of all stacked prompts\n */\nexport const getPrompts = (): StackedPrompt[] => {\n return PROMPTS.map((prompt) => ({\n content: prompt.id === 'master_prompt' ? prompt.content : stackPrompts(MASTER_PROMPT, prompt.content),\n id: prompt.id,\n isMaster: prompt.id === 'master_prompt',\n name: prompt.name,\n }));\n};\n\n/**\n * Gets a specific prompt by ID (strongly typed).\n * Returns the stacked version (master + addon) for addon prompts.\n *\n * @param id - The prompt ID to retrieve\n * @returns The stacked prompt\n * @throws Error if prompt ID is not found\n */\nexport const getPrompt = (id: PromptId): StackedPrompt => {\n const prompt = PROMPTS.find((p) => p.id === id);\n if (!prompt) {\n throw new Error(`Prompt not found: ${id}`);\n }\n\n return {\n content: prompt.id === 'master_prompt' ? prompt.content : stackPrompts(MASTER_PROMPT, prompt.content),\n id: prompt.id,\n isMaster: prompt.id === 'master_prompt',\n name: prompt.name,\n };\n};\n\n/**\n * Gets the raw stacked prompt text for a specific prompt ID.\n * Convenience method for when you just need the text.\n *\n * @param id - The prompt ID\n * @returns The stacked prompt content string\n */\nexport const getStackedPrompt = (id: PromptId): string => {\n return getPrompt(id).content;\n};\n\n/**\n * Gets the list of available prompt IDs.\n * Useful for UI dropdowns or validation.\n *\n * @returns Array of prompt IDs\n */\nexport const getPromptIds = (): PromptId[] => {\n return PROMPTS.map((p) => p.id);\n};\n\n/**\n * Gets just the master prompt content.\n * Useful when you need to use a custom addon.\n *\n * @returns The master prompt content\n */\nexport const getMasterPrompt = (): string => {\n return MASTER_PROMPT;\n};\n","/**\n * Segment type is shared across the library.\n */\nimport { MARKER_ID_PATTERN, TRANSLATION_MARKER_PARTS } from './constants';\nimport type { Segment } from './types';\n\n/**\n * Formats excerpts for an LLM prompt by combining the prompt rules with the segment text.\n * Each segment is formatted as \"ID - Text\" and separated by double newlines.\n *\n * @param segments - Array of segments to format\n * @param prompt - The instruction/system prompt to prepend\n * @returns Combined prompt and formatted text\n */\nexport const formatExcerptsForPrompt = (segments: Segment[], prompt: string) => {\n const formatted = segments.map((e) => `${e.id} - ${e.text}`).join('\\n\\n');\n return [prompt, formatted].join('\\n\\n');\n};\n\n/**\n * Normalize line endings and split merged markers onto separate lines.\n *\n * @example\n * // \"helloP1 - ...\" becomes split onto a new line before \"P1 -\"\n * normalizeTranslationText('helloP1 - x').includes('\\\\nP1 -') === true\n */\nexport const normalizeTranslationText = (content: string) => {\n const normalizedLineEndings = content.replace(/\\r\\n/g, '\\n').replace(/\\r/g, '\\n');\n\n const mergedMarkerWithSpacePattern = new RegExp(\n ` (${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`,\n 'gm',\n );\n\n const mergedMarkerNoSpacePattern = new RegExp(\n `([^\\\\s\\\\n])(${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes})`,\n 'gm',\n );\n\n return normalizedLineEndings\n .replace(mergedMarkerWithSpacePattern, '\\n$1')\n .replace(mergedMarkerNoSpacePattern, '$1\\n$2')\n .replace(/\\\\\\[/gm, '[');\n};\n\n/**\n * Extract translation IDs from normalized response, in order.\n *\n * @example\n * extractTranslationIds('P1 - a\\\\nP2b - b') // => ['P1', 'P2b']\n */\nexport const extractTranslationIds = (text: string) => {\n const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n const pattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}`, 'gm');\n const ids: string[] = [];\n for (const match of text.matchAll(pattern)) {\n ids.push(match[1]);\n }\n return ids;\n};\n\n/**\n * Parse a single translation line in the form \"ID - translation\".\n *\n * Note: This returns a translation entry shape, not an Arabic source `Segment`.\n *\n * @param line - Single line to parse\n * @returns `{ id, translation }` when valid; otherwise `null`\n *\n * @example\n * parseTranslationLine('P1 - Hello')?.id === 'P1'\n */\nexport const parseTranslationLine = (line: string) => {\n const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n const pattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}(.*)$`);\n const match = line.match(pattern);\n const [, id, rest] = match || [];\n const translation = typeof rest === 'string' ? rest.trim() : '';\n return id && translation ? { id, translation } : null;\n};\n\n/**\n * Parses bulk translation text into a Map for efficient O(1) lookup.\n *\n * Handles multi-line translations: subsequent non-marker lines belong to the previous ID.\n *\n * @param rawText - Raw text containing translations in format \"ID - Translation text\"\n * @returns An object with `count` and `translationMap`\n *\n * @example\n * parseTranslations('P1 - a\\\\nP2 - b').count === 2\n */\nexport const parseTranslations = (rawText: string) => {\n const normalized = normalizeTranslationText(rawText);\n const translationMap = splitResponseById(normalized);\n return { count: translationMap.size, translationMap };\n};\n\n/**\n * Parse translations into an ordered array (preserving the original response order).\n *\n * This differs from `parseTranslations()` which returns a Map and therefore cannot represent\n * duplicates as separate entries.\n *\n * @param rawText - Raw text containing translations in format \"ID - Translation text\"\n * @returns Array of `{ id, translation }` entries in appearance order\n *\n * @example\n * parseTranslationsInOrder('P1 - a\\\\nP2 - b').map((e) => e.id) // => ['P1', 'P2']\n */\nexport const parseTranslationsInOrder = (rawText: string) => {\n const normalized = normalizeTranslationText(rawText);\n const { dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n const headerPattern = new RegExp(`^(${MARKER_ID_PATTERN})${optionalSpace}${dashes}\\\\s*`, 'gm');\n const matches = [...normalized.matchAll(headerPattern)];\n\n const entries: Array<{ id: string; translation: string }> = [];\n for (let i = 0; i < matches.length; i++) {\n const id = matches[i][1];\n const start = matches[i].index ?? 0;\n const nextStart = i + 1 < matches.length ? (matches[i + 1].index ?? normalized.length) : normalized.length;\n const chunk = normalized.slice(start, nextStart).trimEnd();\n const prefixPattern = new RegExp(`^${id}${optionalSpace}${dashes}\\\\s*`);\n const translation = chunk.replace(prefixPattern, '').trim();\n entries.push({ id, translation });\n }\n return entries;\n};\n\n/**\n * Split the response into a per-ID map. Values contain translation content only (prefix removed).\n *\n * @example\n * splitResponseById('P1 - a\\\\nP2 - b').get('P1') === 'a'\n */\nexport const splitResponseById = (text: string) => {\n const map = new Map<string, string>();\n for (const entry of parseTranslationsInOrder(text)) {\n map.set(entry.id, entry.translation);\n }\n return map;\n};\n\nexport const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n","import {\n ARCHAIC_WORDS,\n COLON_PATTERN,\n MARKER_ID_PATTERN,\n MAX_EMPTY_PARENTHESES,\n MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK,\n MIN_TRANSLATION_RATIO,\n TRANSLATION_MARKER_PARTS,\n} from './constants';\nimport { escapeRegExp, extractTranslationIds, normalizeTranslationText, splitResponseById } from './textUtils';\nimport type { Segment, ValidationError, ValidationErrorType } from './types';\n\n/**\n * Human-readable descriptions for each `ValidationErrorType`, intended for client UIs and logs.\n *\n * @example\n * VALIDATION_ERROR_TYPE_INFO.arabic_leak.description\n */\nexport const VALIDATION_ERROR_TYPE_INFO = {\n all_caps: {\n description: 'ALL CAPS “shouting” word detected (5+ letters).',\n },\n arabic_leak: {\n description: 'Arabic script was detected in output (except ﷺ).',\n },\n archaic_register: {\n description: 'Archaic/Biblical English detected (e.g., thou, verily, shalt).',\n },\n duplicate_id: {\n description: 'The same segment ID appears more than once in the response.',\n },\n empty_parentheses: {\n description: 'Excessive \"()\" patterns detected, often indicating failed/empty term-pairs.',\n },\n implicit_continuation: {\n description: 'The response includes continuation/meta phrasing (e.g., \"continued:\", \"implicit continuation\").',\n },\n invalid_marker_format: {\n description: 'A segment marker line is malformed (e.g., wrong ID shape or missing content after the dash).',\n },\n invented_id: {\n description: 'The response contains a segment ID that does not exist in the provided source corpus.',\n },\n length_mismatch: {\n description: 'Translation appears too short relative to Arabic source (heuristic truncation check).',\n },\n meta_talk: {\n description: 'The response includes translator/editor notes instead of pure translation.',\n },\n mismatched_colons: {\n description:\n 'Per-segment colon count mismatch between Arabic segment text and its translation chunk (counts \":\" and \":\").',\n },\n missing_id_gap: {\n description:\n 'A gap was detected: the response includes two IDs whose corpus order implies one or more intermediate IDs are missing.',\n },\n multiword_translit_without_gloss: {\n description: 'A multi-word transliteration phrase was detected without an immediate parenthetical gloss.',\n },\n newline_after_id: {\n description: 'The response used \"ID -\\\\nText\" instead of \"ID - Text\" (newline immediately after the marker).',\n },\n no_valid_markers: {\n description: 'No valid \"ID - ...\" markers were found anywhere in the response.',\n },\n truncated_segment: {\n description: 'A segment appears truncated (e.g., only \"…\", \"...\", or \"[INCOMPLETE]\").',\n },\n wrong_diacritics: {\n description: 'Wrong diacritics like â/ã/á were detected (should use macrons like ā ī ū).',\n },\n} as const satisfies Record<ValidationErrorType, { description: string }>;\n\nconst ARCHAIC_PATTERNS = ARCHAIC_WORDS.map((w) => new RegExp(`\\\\b${escapeRegExp(w)}\\\\b`, 'i'));\n\n/**\n * Validate an LLM translation response against a set of Arabic source segments.\n *\n * Rules are expressed as a list of typed errors. The caller decides severity.\n * The validator normalizes the response first (marker splitting + line endings).\n *\n * Important: `segments` may be the full corpus. The validator reduces to only\n * those IDs parsed from the response (plus detects missing-ID gaps between IDs).\n *\n * @example\n * // Pass (no errors)\n * validateTranslationResponse(\n * [{ id: 'P1', text: 'نص عربي طويل...' }],\n * 'P1 - A complete translation.'\n * ).errors.length === 0\n *\n * @example\n * // Fail (invented ID)\n * validateTranslationResponse(\n * [{ id: 'P1', text: 'نص عربي طويل...' }],\n * 'P2 - This ID is not in the corpus.'\n * ).errors.some(e => e.type === 'invented_id') === true\n */\nexport const validateTranslationResponse = (segments: Segment[], response: string) => {\n const normalizedResponse = normalizeTranslationText(response);\n const parsedIds = extractTranslationIds(normalizedResponse);\n\n if (parsedIds.length === 0) {\n return {\n errors: [{ message: 'No valid translation markers found', type: 'no_valid_markers' }],\n normalizedResponse,\n parsedIds: [],\n };\n }\n\n const segmentById = new Map<string, Segment>();\n for (const s of segments) {\n segmentById.set(s.id, s);\n }\n\n const responseById = splitResponseById(normalizedResponse);\n\n const errors: ValidationError[] = [\n ...validateMarkerFormat(normalizedResponse),\n ...validateNewlineAfterId(normalizedResponse),\n ...validateTruncatedSegments(normalizedResponse),\n ...validateImplicitContinuation(normalizedResponse),\n ...validateMetaTalk(normalizedResponse),\n ...validateDuplicateIds(parsedIds),\n ...validateInventedIds(parsedIds, segmentById),\n ...validateMissingIdGaps(parsedIds, segmentById, segments),\n ...validateArabicLeak(normalizedResponse),\n ...validateWrongDiacritics(normalizedResponse),\n ...validateEmptyParentheses(normalizedResponse),\n ...validateTranslationLengthsForResponse(parsedIds, segmentById, responseById),\n ...validateAllCaps(normalizedResponse),\n ...validateArchaicRegister(normalizedResponse),\n ...validateMismatchedColons(parsedIds, segmentById, responseById),\n ...validateMultiwordTranslitWithoutGloss(parsedIds, responseById),\n ];\n\n return { errors, normalizedResponse, parsedIds };\n};\n\n/**\n * Validate translation marker format (single-line errors).\n *\n * @example\n * // Fail: malformed marker\n * validateMarkerFormat('B1234$5 - x')[0]?.type === 'invalid_marker_format'\n */\nconst validateMarkerFormat = (text: string): ValidationError[] => {\n const { markers, digits, suffix, dashes, optionalSpace } = TRANSLATION_MARKER_PARTS;\n\n const invalidRefPattern = new RegExp(\n `^${markers}(?=${digits})(?=.*${dashes})(?!${digits}${suffix}*${optionalSpace}${dashes})[^\\\\s-–—]+${optionalSpace}${dashes}`,\n 'm',\n );\n const invalidRef = text.match(invalidRefPattern);\n if (invalidRef) {\n return [\n {\n message: `Invalid reference format \"${invalidRef[0].trim()}\" - expected format is letter + numbers + optional suffix (a-j) + dash`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const spaceBeforePattern = new RegExp(` ${markers}${digits}${suffix}+${optionalSpace}${dashes}`, 'm');\n const suffixNoDashPattern = new RegExp(`^${markers}${digits}${suffix}(?! ${dashes})`, 'm');\n const suspicious = text.match(spaceBeforePattern) || text.match(suffixNoDashPattern);\n if (suspicious) {\n return [\n {\n match: suspicious[0],\n message: `Suspicious reference found: \"${suspicious[0]}\"`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const emptyAfterDashPattern = new RegExp(`^${MARKER_ID_PATTERN}${optionalSpace}${dashes}\\\\s*$`, 'm');\n const emptyAfterDash = text.match(emptyAfterDashPattern);\n if (emptyAfterDash) {\n return [\n {\n match: emptyAfterDash[0].trim(),\n message: `Reference \"${emptyAfterDash[0].trim()}\" has dash but no content after it`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n const dollarSignPattern = new RegExp(`^${markers}${digits}\\\\$${digits}`, 'm');\n const dollarSignRef = text.match(dollarSignPattern);\n if (dollarSignRef) {\n return [\n {\n match: dollarSignRef[0],\n message: `Invalid reference format \"${dollarSignRef[0]}\" - contains $ character`,\n type: 'invalid_marker_format',\n },\n ];\n }\n\n return [];\n};\n\n/**\n * Detect newline after an ID line (formatting bug).\n *\n * @example\n * // Fail: newline after \"P1 -\"\n * validateNewlineAfterId('P1 -\\\\nText')[0]?.type === 'newline_after_id'\n */\nconst validateNewlineAfterId = (text: string): ValidationError[] => {\n const pattern = new RegExp(\n `^${MARKER_ID_PATTERN}${TRANSLATION_MARKER_PARTS.optionalSpace}${TRANSLATION_MARKER_PARTS.dashes}\\\\s*\\\\n`,\n 'm',\n );\n const match = text.match(pattern);\n return match\n ? [\n {\n match: match[0].trim(),\n message: `Invalid format: newline after ID \"${match[0].trim()}\" - use \"ID - Text\" format`,\n type: 'newline_after_id',\n },\n ]\n : [];\n};\n\n/**\n * Detect duplicated IDs in the parsed ID list.\n *\n * @example\n * validateDuplicateIds(['P1','P1'])[0]?.type === 'duplicate_id'\n */\nconst validateDuplicateIds = (ids: string[]): ValidationError[] => {\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const id of ids) {\n if (seen.has(id)) {\n duplicates.add(id);\n }\n seen.add(id);\n }\n return [...duplicates].map((id) => ({\n id,\n message: `Duplicate ID \"${id}\" detected - each segment should appear only once`,\n type: 'duplicate_id',\n }));\n};\n\n/**\n * Detect IDs in the response that do not exist in the passed segment corpus.\n *\n * @example\n * validateInventedIds(['P1','P2'], new Map([['P1',{id:'P1',text:'x'}]]) )[0]?.type === 'invented_id'\n */\nconst validateInventedIds = (outputIds: string[], segmentById: Map<string, Segment>): ValidationError[] => {\n const invented = outputIds.filter((id) => !segmentById.has(id));\n return invented.length > 0\n ? [\n {\n match: invented.join(','),\n message: `Invented ID(s) detected: ${invented.map((id) => `\"${id}\"`).join(', ')} - these IDs do not exist in the source`,\n type: 'invented_id',\n },\n ]\n : [];\n};\n\n/**\n * Detect a “gap”: response contains IDs A and C, but the corpus order includes B between them.\n * This only checks for missing IDs between consecutive IDs within each response-ordered block.\n *\n * @example\n * // Corpus: P1, P2, P3. Response: P1, P3 => missing_id_gap includes P2\n */\nconst validateMissingIdGaps = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n segments: Segment[],\n): ValidationError[] => {\n const indexById = new Map<string, number>();\n for (let i = 0; i < segments.length; i++) {\n indexById.set(segments[i].id, i);\n }\n\n const parsedIdSet = new Set(parsedIds);\n const missing = new Set<string>();\n\n const collectMissingBetween = (startIdx: number, endIdx: number) => {\n for (let j = startIdx + 1; j < endIdx; j++) {\n const midId = segments[j]?.id;\n if (midId && segmentById.has(midId) && !parsedIdSet.has(midId)) {\n missing.add(midId);\n }\n }\n };\n\n for (let i = 0; i < parsedIds.length - 1; i++) {\n const a = parsedIds[i];\n const b = parsedIds[i + 1];\n if (!segmentById.has(a) || !segmentById.has(b)) {\n continue;\n }\n\n const ia = indexById.get(a);\n const ib = indexById.get(b);\n if (ia == null || ib == null) {\n continue;\n }\n\n // Reset blocks when order goes backwards (block pasting)\n if (ib < ia) {\n continue;\n }\n\n collectMissingBetween(ia, ib);\n }\n\n const uniqueMissing = [...missing];\n return uniqueMissing.length > 0\n ? [\n {\n match: uniqueMissing.join(','),\n message: `Missing segment ID(s) detected between translated IDs: ${uniqueMissing.map((id) => `\"${id}\"`).join(', ')}`,\n type: 'missing_id_gap',\n },\n ]\n : [];\n};\n\n/**\n * Detect segments that appear truncated (just \"…\" / \"...\" / \"[INCOMPLETE]\").\n *\n * @example\n * validateTruncatedSegments('P1 - …')[0]?.type === 'truncated_segment'\n */\nconst validateTruncatedSegments = (text: string): ValidationError[] => {\n const segmentPattern = /^([A-Z]\\d+[a-j]?)\\s*[-–—]\\s*(.*)$/gm;\n const truncated: string[] = [];\n for (const match of text.matchAll(segmentPattern)) {\n const id = match[1];\n const content = match[2].trim();\n if (!content || content === '…' || content === '...' || content === '[INCOMPLETE]') {\n truncated.push(id);\n }\n }\n return truncated.length > 0\n ? [\n {\n match: truncated.join(','),\n message: `Truncated segment(s) detected: ${truncated.map((id) => `\"${id}\"`).join(', ')} - segments must be fully translated`,\n type: 'truncated_segment',\n },\n ]\n : [];\n};\n\n/**\n * Detect implicit continuation markers.\n *\n * @example\n * validateImplicitContinuation('P1 - continued: ...')[0]?.type === 'implicit_continuation'\n */\nconst validateImplicitContinuation = (text: string): ValidationError[] => {\n const patterns = [/implicit continuation/i, /\\bcontinuation:/i, /\\bcontinued:/i];\n for (const pattern of patterns) {\n const match = text.match(pattern);\n if (match) {\n return [\n {\n match: match[0],\n message: `Detected \"${match[0]}\" - do not add implicit continuation text`,\n type: 'implicit_continuation',\n },\n ];\n }\n }\n return [];\n};\n\n/**\n * Detect meta-talk (translator/editor notes).\n *\n * @example\n * validateMetaTalk(\"P1 - (Translator's note: ...)\")[0]?.type === 'meta_talk'\n */\nconst validateMetaTalk = (text: string): ValidationError[] => {\n const patterns = [/\\(note:/i, /\\(translator'?s? note:/i, /\\[editor:/i, /\\[note:/i, /\\(ed\\.:/i, /\\(trans\\.:/i];\n for (const pattern of patterns) {\n const match = text.match(pattern);\n if (match) {\n return [\n {\n match: match[0],\n message: `Detected meta-talk \"${match[0]}\" - output translation only, no translator/editor notes`,\n type: 'meta_talk',\n },\n ];\n }\n }\n return [];\n};\n\n/**\n * Detect Arabic script characters (except ﷺ).\n *\n * @example\n * validateArabicLeak('P1 - الله')[0]?.type === 'arabic_leak'\n *\n * @example\n * // Pass: ﷺ allowed\n * validateArabicLeak('P1 - Muḥammad ﷺ said...').length === 0\n */\nconst validateArabicLeak = (text: string): ValidationError[] => {\n const arabicPattern = /[\\u0600-\\u06FF\\u0750-\\u077F\\uFB50-\\uFDF9\\uFDFB-\\uFDFF\\uFE70-\\uFEFF]+/g;\n const matches = text.match(arabicPattern) ?? [];\n\n // Allow ﷺ (U+FDFD) as an explicit exception.\n const normalized = matches\n .map((m) => m.replace(/ﷺ/g, ''))\n .map((m) => m.trim())\n .filter((m) => m.length > 0);\n\n return normalized.map((match) => ({ match, message: `Arabic script detected: \"${match}\"`, type: 'arabic_leak' }));\n};\n\n/**\n * Detect wrong diacritics (â/ã/á) that indicate failed ALA-LC macrons.\n *\n * @example\n * validateWrongDiacritics('kâfir')[0]?.type === 'wrong_diacritics'\n */\nconst validateWrongDiacritics = (text: string): ValidationError[] => {\n const wrongPattern = /[âêîôûãñáéíóú]/gi;\n const matches = text.match(wrongPattern) ?? [];\n const unique = [...new Set(matches)];\n return unique.map((m) => ({\n match: m,\n message: `Wrong diacritic \"${m}\" detected - use macrons (ā, ī, ū) instead`,\n type: 'wrong_diacritics',\n }));\n};\n\n/**\n * Detect excessive empty parentheses \"()\" which often indicates failed transliterations.\n *\n * @example\n * // Fail: too many \"()\"\n * validateEmptyParentheses('() () () ()')[0]?.type === 'empty_parentheses'\n */\nconst validateEmptyParentheses = (text: string): ValidationError[] => {\n const count = text.match(/\\(\\)/g)?.length ?? 0;\n return count > MAX_EMPTY_PARENTHESES\n ? [\n {\n message: `Found ${count} empty parentheses \"()\" - this usually indicates failed transliterations. Please check if the LLM omitted Arabic/transliterated terms.`,\n type: 'empty_parentheses',\n },\n ]\n : [];\n};\n\n/**\n * Detect truncated translation vs Arabic source (ratio-based).\n *\n * @example\n * // Fail: long Arabic + very short translation\n * detectTruncatedTranslation('نص عربي طويل ... (50+ chars)', 'Short') !== undefined\n */\nconst detectTruncatedTranslation = (arabicText: string, translationText: string) => {\n const arabic = (arabicText || '').trim();\n const translation = (translationText || '').trim();\n\n if (arabic.length < MIN_ARABIC_LENGTH_FOR_TRUNCATION_CHECK) {\n return;\n }\n if (translation.length === 0) {\n return `Translation appears empty but Arabic text has ${arabic.length} characters`;\n }\n\n const ratio = translation.length / arabic.length;\n if (ratio < MIN_TRANSLATION_RATIO) {\n const expectedMinLength = Math.round(arabic.length * MIN_TRANSLATION_RATIO);\n return `Translation appears truncated: ${translation.length} chars for ${arabic.length} char Arabic text (expected at least ~${expectedMinLength} chars)`;\n }\n};\n\n/**\n * Validate per-ID translation lengths (response subset only).\n *\n * @example\n * // Produces a length_mismatch error for the first truncated segment found\n */\nconst validateTranslationLengthsForResponse = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n responseById: Map<string, string>,\n) => {\n for (const id of parsedIds) {\n const seg = segmentById.get(id);\n const translation = responseById.get(id);\n if (!seg || translation == null) {\n continue;\n }\n const error = detectTruncatedTranslation(seg.text, translation);\n if (error) {\n const e = {\n id,\n message: `Translation for \"${id}\" ${error.replace('Translation ', '').toLowerCase()}`,\n type: 'length_mismatch',\n } as const satisfies ValidationError;\n return [e];\n }\n }\n return [] as ValidationError[];\n};\n\n/**\n * Detect “shouting” ALL CAPS words.\n *\n * @example\n * validateAllCaps('THIS IS LOUD')[0]?.type === 'all_caps'\n */\nconst validateAllCaps = (text: string): ValidationError[] => {\n const matches = text.match(/\\b[A-Z]{5,}\\b/g) ?? [];\n const unique = [...new Set(matches)];\n return unique.map((m) => ({ match: m, message: `ALL CAPS detected: \"${m}\"`, type: 'all_caps' }));\n};\n\n/**\n * Detect archaic/Biblical register tokens.\n *\n * @example\n * validateArchaicRegister('verily thou shalt')[0]?.type === 'archaic_register'\n */\nconst validateArchaicRegister = (text: string): ValidationError[] => {\n const found: string[] = [];\n for (const re of ARCHAIC_PATTERNS) {\n const m = text.match(re);\n if (m) {\n found.push(m[0]);\n }\n }\n return [...new Set(found)].map((m) => ({\n match: m,\n message: `Archaic/Biblical register word detected: \"${m}\"`,\n type: 'archaic_register',\n }));\n};\n\n/**\n * Detect per-segment mismatch in colon counts between Arabic segment text and its translation chunk.\n *\n * This is intentionally heuristic and avoids hardcoding speaker label tokens.\n *\n * @example\n * // Arabic: \"الشيخ: ... السائل: ...\" => 2 colons\n * // Translation: \"The Shaykh: ...\" => 1 colon => mismatched_colons\n */\nconst validateMismatchedColons = (\n parsedIds: string[],\n segmentById: Map<string, Segment>,\n responseById: Map<string, string>,\n): ValidationError[] => {\n const errors: ValidationError[] = [];\n\n for (const id of parsedIds) {\n const seg = segmentById.get(id);\n const translation = responseById.get(id);\n if (!seg || !translation) {\n continue;\n }\n\n const arabicCount = seg.text.match(COLON_PATTERN)?.length ?? 0;\n const englishCount = translation.match(COLON_PATTERN)?.length ?? 0;\n\n if (arabicCount === englishCount) {\n continue;\n }\n\n errors.push({\n id,\n match: `${arabicCount} vs ${englishCount}`,\n message: `Colon count mismatch in \"${id}\": Arabic has ${arabicCount} \":\" but translation has ${englishCount}. This may indicate dropped/moved speaker turns or formatting drift.`,\n type: 'mismatched_colons',\n });\n }\n\n return errors;\n};\n\n/**\n * Detect multi-word transliteration patterns without immediate parenthetical gloss.\n *\n * @example\n * // Fail: \"al-hajr fi al-madajīʿ\" without \"(English ...)\" nearby\n * // => multiword_translit_without_gloss\n */\nconst validateMultiwordTranslitWithoutGloss = (\n parsedIds: string[],\n responseById: Map<string, string>,\n): ValidationError[] => {\n const errors: ValidationError[] = [];\n const phrasePattern = /\\b(al-[a-zʿʾāīūḥṣḍṭẓ-]+)\\s+fi\\s+(al-[a-zʿʾāīūḥṣḍṭẓ-]+)\\b/gi;\n\n for (const id of parsedIds) {\n const text = responseById.get(id);\n if (!text) {\n continue;\n }\n\n for (const m of text.matchAll(phrasePattern)) {\n const phrase = `${m[1]} fi ${m[2]}`;\n const idx = m.index ?? -1;\n if (idx >= 0) {\n const after = text.slice(idx, Math.min(text.length, idx + phrase.length + 25));\n if (!after.includes('(')) {\n errors.push({\n id,\n match: phrase,\n message: `Multi-word transliteration without immediate gloss in \"${id}\": \"${phrase}\"`,\n type: 'multiword_translit_without_gloss',\n });\n }\n }\n }\n }\n\n return errors;\n};\n"],"mappings":";;;;AAGA,IAAY,4CAAL;;AAEH;;AAEA;;AAEA;;AAEA;;AAEA;;AAEA;;;;;;AAMJ,MAAa,2BAA2B;CAEpC,QAAQ;CAER,QAAQ;CAER,SAAS,IAAI,QAAQ,OAAO,QAAQ,UAAU,QAAQ,WAAW,QAAQ,UAAU,QAAQ,QAAQ,QAAQ,KAAK;CAEhH,eAAe;CAEf,QAAQ;CACX;;;;AAKD,MAAa,oBAAoB,GAAG,yBAAyB,UAAU,yBAAyB,SAAS,yBAAyB,OAAO;;;;AAKzI,MAAa,gBAAgB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACH;AAED,MAAa,wBAAwB;AACrC,MAAa,yCAAyC;AACtD,MAAa,wBAAwB;AAErC,MAAa,gBAAgB;;;;AC/C7B,MAAa,gBAAgB;AAE7B,MAAa,qBAAqB;AAElC,MAA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