laratext 0.1.0

Laratext for Laravel Rust: translation keys with their source text, and auto-translation with OpenAI, Claude, Google Translate or Translatorio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use std::collections::HashSet;

use indexmap::IndexMap;

/// A call that could not be read, with the line it starts on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unreadable {
    /// The line of the call, starting at 1, or 0 when the whole file could not be read.
    pub line: usize,
    /// The start of the call.
    pub call: String,
}

/// What the scanner found in a script.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Extracted {
    /// `[key => source text]`.
    pub texts: IndexMap<String, String>,
    /// The calls whose key or text is not a literal string.
    pub unreadable: Vec<Unreadable>,
}

/// Finds `text('key', 'Source')` calls in JavaScript, TypeScript, Vue and Svelte files.
///
/// Each call is matched on its own, from its name to its second argument. The file is never
/// followed as a whole: JSX text and Vue or Svelte markup carry unescaped apostrophes (`l'Andorra`)
/// that would derail anything tracking strings across the file.
#[derive(Debug, Clone)]
pub struct ScriptTexts {
    functions: Vec<String>,
}

impl ScriptTexts {
    /// A scanner for calls to these names, such as `text` and `$text`.
    pub fn new(functions: impl IntoIterator<Item = impl Into<String>>) -> Self {
        Self {
            functions: functions.into_iter().map(Into::into).collect(),
        }
    }

    /// Read the calls in the bytes of a file. A file that is not valid UTF-8 is reported, not half
    /// read.
    pub fn extract_bytes(&self, content: &[u8]) -> Extracted {
        match std::str::from_utf8(content) {
            Ok(content) => self.extract(content),
            Err(_) => Extracted {
                texts: IndexMap::new(),
                unreadable: vec![Unreadable {
                    line: 0,
                    call: "Not valid UTF-8".to_owned(),
                }],
            },
        }
    }

    /// Read the calls in a file.
    pub fn extract(&self, content: &str) -> Extracted {
        let mut texts = IndexMap::new();
        let mut read: HashSet<usize> = HashSet::new();

        // The second argument has to end where the call does or at the next argument, which rules
        // out text('key', 'a' + b).
        let mut position = 0;

        while let Some((start, after_call)) = self.next_call(content, position) {
            match two_arguments(content, after_call) {
                Some(found) => {
                    position = found.end;

                    if is_interpolated(found.key_quote, found.key) || is_interpolated(found.value_quote, found.value) {
                        continue;
                    }

                    texts.insert(unescape(found.key), unescape(found.value));
                    read.insert(start);
                }
                None => position = next_char(content, start),
            }
        }

        let mut position = 0;

        while let Some((start, after_call)) = self.next_call(content, position) {
            match one_argument(content, after_call) {
                Some(found) => {
                    position = found.end;

                    if is_interpolated(found.key_quote, found.key) {
                        continue;
                    }

                    let key = unescape(found.key);

                    if !texts.contains_key(&key) {
                        let text = key_to_text(&key);

                        texts.insert(key, text);
                    }

                    read.insert(start);
                }
                None => position = next_char(content, start),
            }
        }

        Extracted {
            unreadable: self.unreadable(content, &read),
            texts,
        }
    }

    /// Every call the patterns above could not read: a variable, a concatenation or an interpolated
    /// template literal. Reported so none is lost in silence.
    fn unreadable(&self, content: &str, read: &HashSet<usize>) -> Vec<Unreadable> {
        let mut unreadable = Vec::new();
        let mut position = 0;

        while let Some((start, after_call)) = self.next_call(content, position) {
            position = after_call.max(next_char(content, start));

            if read.contains(&start) {
                continue;
            }

            // A definition, function text(key, source), is not a call.
            if is_definition(content, start) {
                continue;
            }

            let slice = &content[start..];
            let mut end = slice.len().min(80);

            while !slice.is_char_boundary(end) {
                end -= 1;
            }

            let call = slice[..end]
                .split('\n')
                .find(|line| !line.is_empty())
                .unwrap_or_default();

            unreadable.push(Unreadable {
                line: content[..start].matches('\n').count() + 1,
                call: php_trim(call).to_owned(),
            });
        }

        unreadable
    }

    /// The next place at or after `from` where a call starts: its offset, and the offset after the
    /// name, the opening parenthesis and the whitespace that follows.
    fn next_call(&self, content: &str, from: usize) -> Option<(usize, usize)> {
        let mut index = from;

        while index < content.len() {
            if content.is_char_boundary(index)
                && let Some(after) = self.call_at(content, index)
            {
                return Some((index, after));
            }

            index += 1;
        }

        None
    }

    /// `BOUNDARY (?:name|name) \s* ( \s*` at an offset: the offset after it.
    fn call_at(&self, content: &str, index: usize) -> Option<usize> {
        if !boundary(content, index) {
            return None;
        }

        let rest = &content[index..];

        for name in &self.functions {
            let Some(after_name) = rest.strip_prefix(name.as_str()) else {
                continue;
            };

            let after_space = after_name.trim_start_matches(char::is_whitespace);

            let Some(after_paren) = after_space.strip_prefix('(') else {
                continue;
            };

            let after = after_paren.trim_start_matches(char::is_whitespace);

            return Some(content.len() - after.len());
        }

        None
    }
}

/// Where a call may start: not inside a longer name, not a method of another object (`post.text`),
/// but `this.$text` from an Alpine component is a call.
fn boundary(content: &str, index: usize) -> bool {
    let before = &content[..index];

    if let Some(object) = before.strip_suffix("this.") {
        // `\b` before `this`: it must not be the end of a longer word.
        return !object.chars().next_back().is_some_and(is_word);
    }

    !before
        .chars()
        .next_back()
        .is_some_and(|c| is_word(c) || c == '$' || c == '.')
}

fn is_word(character: char) -> bool {
    character.is_alphanumeric() || character == '_'
}

fn is_definition(content: &str, offset: usize) -> bool {
    let mut start = offset.saturating_sub(20);

    while !content.is_char_boundary(start) {
        start += 1;
    }

    let window = content[start..offset].trim_end_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']);

    window
        .strip_suffix("function")
        .is_some_and(|before| !before.chars().next_back().is_some_and(is_word))
}

fn next_char(content: &str, index: usize) -> usize {
    index + content[index..].chars().next().map_or(1, char::len_utf8)
}

fn php_trim(value: &str) -> &str {
    value.trim_matches(|c| matches!(c, ' ' | '\t' | '\n' | '\r' | '\0' | '\x0b'))
}

/// Only a template literal interpolates in JavaScript: `"a$b"` is a literal.
fn is_interpolated(quote: char, string: &str) -> bool {
    quote == '`' && string.contains("${")
}

struct Found<'a> {
    key_quote: char,
    key: &'a str,
    value_quote: char,
    value: &'a str,
    end: usize,
}

/// A one-line literal: single, double or back quotes. Returns the quote, the content and the offset
/// after the literal. `newline_escape` lets a backslash escape a line break, as in the two-argument
/// pattern, where `.` matches it.
fn key_literal(content: &str, at: usize, newline_escape: bool) -> Option<(char, &str, usize)> {
    let quote = content[at..].chars().next().filter(|c| matches!(c, '"' | '\'' | '`'))?;
    let start = at + 1;
    let mut index = start;

    loop {
        let character = content[index..].chars().next()?;

        if character == quote {
            return Some((quote, &content[start..index], index + 1));
        }

        if character == '\\' {
            let escaped = content[index + 1..].chars().next()?;

            if escaped == '\n' && !newline_escape {
                return None;
            }

            index += 1 + escaped.len_utf8();

            continue;
        }

        if character == '\r' || character == '\n' {
            return None;
        }

        index += character.len_utf8();
    }
}

/// A literal that may span lines, up to its closing quote.
fn value_literal(content: &str, at: usize) -> Option<(char, &str, usize)> {
    let quote = content[at..].chars().next().filter(|c| matches!(c, '"' | '\'' | '`'))?;
    let start = at + 1;
    let mut index = start;

    loop {
        let character = content[index..].chars().next()?;

        if character == quote {
            return Some((quote, &content[start..index], index + 1));
        }

        if character == '\\' {
            let escaped = content[index + 1..].chars().next()?;

            index += 1 + escaped.len_utf8();

            continue;
        }

        index += character.len_utf8();
    }
}

fn skip_whitespace(content: &str, at: usize) -> usize {
    content.len() - content[at..].trim_start_matches(char::is_whitespace).len()
}

fn two_arguments(content: &str, at: usize) -> Option<Found<'_>> {
    let (key_quote, key, after_key) = key_literal(content, at, true)?;
    let comma = skip_whitespace(content, after_key);

    if !content[comma..].starts_with(',') {
        return None;
    }

    let value_at = skip_whitespace(content, comma + 1);
    let (value_quote, value, end) = value_literal(content, value_at)?;
    let next = skip_whitespace(content, end);

    matches!(content[next..].chars().next(), Some(',' | ')')).then_some(Found {
        key_quote,
        key,
        value_quote,
        value,
        end,
    })
}

fn one_argument(content: &str, at: usize) -> Option<Found<'_>> {
    let (key_quote, key, after_key) = key_literal(content, at, false)?;
    let close = skip_whitespace(content, after_key);

    content[close..].starts_with(')').then_some(Found {
        key_quote,
        key,
        value_quote: key_quote,
        value: "",
        end: close + 1,
    })
}

/// Turns JavaScript escapes into the characters they stand for.
pub fn unescape(string: &str) -> String {
    let mut result = String::with_capacity(string.len());
    let mut rest = string;

    while let Some(position) = rest.find('\\') {
        result.push_str(&rest[..position]);

        let after = &rest[position + 1..];

        let Some(next) = after.chars().next() else {
            // A lone backslash at the end stays as it is.
            result.push('\\');

            rest = "";

            break;
        };

        match escape(after) {
            Some((text, used)) => {
                result.push_str(&text);

                rest = &after[used..];
            }
            None => {
                result.push(next);

                rest = &after[next.len_utf8()..];
            }
        }
    }

    result.push_str(rest);

    result
}

/// What an escape after the backslash stands for, and how many bytes it takes.
fn escape(after: &str) -> Option<(String, usize)> {
    let bytes = after.as_bytes();
    let hex = |from: usize, length: usize| -> Option<u32> {
        let digits = after.get(from..from + length)?;

        digits
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit())
            .then(|| u32::from_str_radix(digits, 16).ok())
            .flatten()
    };

    match bytes.first()? {
        b'u' => {
            // A surrogate pair: 😀.
            if let (Some(high), Some(true)) = (hex(1, 4), after.get(5..7).map(|pair| pair == "\\u"))
                && (0xD800..0xDC00).contains(&high)
                && let Some(low) = hex(7, 4)
                && (0xDC00..0xE000).contains(&low)
            {
                let code = ((high - 0xD800) << 10) + (low - 0xDC00) + 0x10000;

                return Some((char::from_u32(code).map(String::from).unwrap_or_default(), 11));
            }

            if bytes.get(1) == Some(&b'{') {
                let close = after.find('}')?;
                let digits = &after[2..close];

                if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_hexdigit()) {
                    let code = u32::from_str_radix(digits, 16).ok();

                    return Some((
                        code.and_then(char::from_u32).map(String::from).unwrap_or_default(),
                        close + 1,
                    ));
                }
            }

            hex(1, 4).map(|code| (char::from_u32(code).map(String::from).unwrap_or_default(), 5))
        }
        b'x' => hex(1, 2).map(|code| (char::from_u32(code).map(String::from).unwrap_or_default(), 3)),
        b'n' => Some(("\n".to_owned(), 1)),
        b'r' => Some(("\r".to_owned(), 1)),
        b't' => Some(("\t".to_owned(), 1)),
        b'b' => Some(("\x08".to_owned(), 1)),
        b'f' => Some(("\x0c".to_owned(), 1)),
        b'v' => Some(("\x0b".to_owned(), 1)),
        b'0' => Some(("\0".to_owned(), 1)),
        b'\r' if bytes.get(1) == Some(&b'\n') => Some((String::new(), 2)),
        b'\n' | b'\r' => Some((String::new(), 1)),
        _ => {
            let next = after.chars().next()?;

            if next == '\u{2028}' || next == '\u{2029}' {
                return Some((String::new(), next.len_utf8()));
            }

            None
        }
    }
}

/// The text a one-argument call gets: the last part of the key, words capitalised.
pub fn key_to_text(key: &str) -> String {
    crate::support::key_to_text(key)
}