use std::collections::HashSet;
use indexmap::IndexMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unreadable {
pub line: usize,
pub call: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Extracted {
pub texts: IndexMap<String, String>,
pub unreadable: Vec<Unreadable>,
}
#[derive(Debug, Clone)]
pub struct ScriptTexts {
functions: Vec<String>,
}
impl ScriptTexts {
pub fn new(functions: impl IntoIterator<Item = impl Into<String>>) -> Self {
Self {
functions: functions.into_iter().map(Into::into).collect(),
}
}
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(),
}],
},
}
}
pub fn extract(&self, content: &str) -> Extracted {
let mut texts = IndexMap::new();
let mut read: HashSet<usize> = HashSet::new();
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,
}
}
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;
}
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
}
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
}
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
}
}
fn boundary(content: &str, index: usize) -> bool {
let before = &content[..index];
if let Some(object) = before.strip_suffix("this.") {
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'))
}
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,
}
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();
}
}
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,
})
}
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 {
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
}
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' => {
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
}
}
}
pub fn key_to_text(key: &str) -> String {
crate::support::key_to_text(key)
}