@discord/intl-message-database 0.0.1-rc.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.
Files changed (50) hide show
  1. package/.cargo/config.toml +12 -0
  2. package/Cargo.toml +38 -0
  3. package/LICENSE +21 -0
  4. package/README.md +7 -0
  5. package/bench/keyless-json.js +91 -0
  6. package/bench/native.js +114 -0
  7. package/bench/util.js +55 -0
  8. package/build.rs +5 -0
  9. package/index.d.ts +52 -0
  10. package/index.js +86 -0
  11. package/npm/darwin-arm64/README.md +3 -0
  12. package/npm/darwin-arm64/package.json +18 -0
  13. package/npm/darwin-x64/README.md +3 -0
  14. package/npm/darwin-x64/package.json +18 -0
  15. package/npm/linux-arm64-gnu/README.md +3 -0
  16. package/npm/linux-arm64-gnu/package.json +21 -0
  17. package/npm/linux-arm64-musl/README.md +3 -0
  18. package/npm/linux-arm64-musl/package.json +21 -0
  19. package/npm/linux-x64-gnu/README.md +3 -0
  20. package/npm/linux-x64-gnu/package.json +21 -0
  21. package/npm/linux-x64-musl/README.md +3 -0
  22. package/npm/linux-x64-musl/package.json +21 -0
  23. package/npm/win32-arm64-msvc/README.md +3 -0
  24. package/npm/win32-arm64-msvc/package.json +18 -0
  25. package/npm/win32-ia32-msvc/README.md +3 -0
  26. package/npm/win32-ia32-msvc/package.json +18 -0
  27. package/npm/win32-x64-msvc/README.md +3 -0
  28. package/npm/win32-x64-msvc/package.json +18 -0
  29. package/package.json +44 -0
  30. package/src/lib.rs +14 -0
  31. package/src/messages/database.rs +343 -0
  32. package/src/messages/error.rs +43 -0
  33. package/src/messages/message_definition.rs +169 -0
  34. package/src/messages/message_variables_visitor.rs +299 -0
  35. package/src/messages/meta.rs +38 -0
  36. package/src/messages/mod.rs +27 -0
  37. package/src/messages/source_file.rs +75 -0
  38. package/src/messages/symbols.rs +164 -0
  39. package/src/messages/translation.rs +64 -0
  40. package/src/messages/value.rs +51 -0
  41. package/src/napi.rs +300 -0
  42. package/src/services/mod.rs +9 -0
  43. package/src/services/precompile.rs +91 -0
  44. package/src/services/types.rs +237 -0
  45. package/src/services/validator.rs +104 -0
  46. package/src/sources/definitions_parser.rs +347 -0
  47. package/src/sources/mod.rs +87 -0
  48. package/src/sources/translations.rs +75 -0
  49. package/src/test.rs +67 -0
  50. package/src/threading.rs +61 -0
@@ -0,0 +1,104 @@
1
+ use codespan_reporting::diagnostic::{Diagnostic, Label};
2
+
3
+ use crate::messages::{KeySymbol, Message};
4
+
5
+ /// Validate the content of a message across all of its translations, returning
6
+ /// a full set of diagnostics with information about each one.
7
+ ///
8
+ /// Only normal messages can be validated, since validation implies some source
9
+ /// of truth (a definition) to check against. Undefined messages can still have
10
+ /// diagnostics presented from general errors, like invalid syntax or
11
+ /// unsupported syntax.
12
+ pub fn validate_message(message: &Message) -> Vec<Diagnostic<KeySymbol>> {
13
+ let Some(source) = message.get_source_translation() else {
14
+ return vec![];
15
+ };
16
+
17
+ // SAFETY: If the message has a source translation, it must have a source locale.
18
+ let source_locale = message.source_locale().unwrap();
19
+
20
+ // If the source message couldn't be parsed, then it can't be used as a comparison.
21
+ // TODO: Re-add when parsing diagnostics are added.
22
+ // if let Err(err) = &source.value.parsed {
23
+ // let diagnostic = Diagnostic::error().with_message("Source message could not be parsed");
24
+ // return vec![diagnostic
25
+ // .with_labels(vec![Label::primary(source.file(), source.full_span())])
26
+ // .with_notes(vec![err.to_string()])];
27
+ // }
28
+
29
+ let mut diagnostics = vec![];
30
+
31
+ let source_variables = &source.variables;
32
+ let source_has_variables = source_variables
33
+ .as_ref()
34
+ .is_some_and(|variables| variables.count() > 0);
35
+
36
+ for (locale, translation) in message.translations() {
37
+ if *locale == source_locale {
38
+ continue;
39
+ }
40
+
41
+ // TODO: Re-add when parsing diagnostics are added.
42
+ // if let Err(err) = &translation.value.parsed {
43
+ // diagnostics.push(
44
+ // Diagnostic::error()
45
+ // .with_message("Translation could not be parsed")
46
+ // .with_labels(vec![Label::primary(
47
+ // translation.file(),
48
+ // translation.full_span(),
49
+ // )])
50
+ // .with_notes(vec![err.to_string()]),
51
+ // );
52
+ // continue;
53
+ // }
54
+
55
+ let _translation_variables = match &translation.variables {
56
+ // If the translation contains variables but the source does not,
57
+ // it's likely unintended (the only time this should reasonably
58
+ // happen is when translations are out-of-date, which should be
59
+ // fixed automatically once the translations are imported again).
60
+ Some(translation_variables)
61
+ if !source_has_variables && translation_variables.count() > 0 =>
62
+ {
63
+ // Moved out because the rustfmt doesn't understand this otherwise.
64
+ let message = String::from("This is okay, but likely unintentional. Check that the source message is defined as expected.");
65
+ diagnostics.push(
66
+ Diagnostic::warning()
67
+ .with_message(
68
+ "Translation includes variables, but the source message does not",
69
+ )
70
+ .with_labels(vec![Label::primary(
71
+ translation.file_position.unwrap().file,
72
+ translation.file_position.unwrap().offset as usize
73
+ ..translation.file_position.unwrap().offset as usize,
74
+ )])
75
+ .with_notes(vec![message]),
76
+ );
77
+ continue;
78
+ }
79
+
80
+ Some(translated_variables) => translated_variables,
81
+ // If the translation has no variables, but the source does, this
82
+ // also likely not intentional, but still won't break things.
83
+ _ => {
84
+ if source_has_variables {
85
+ diagnostics.push(
86
+ Diagnostic::warning()
87
+ .with_message(
88
+ "Source message includes variables, but this translation has none.",
89
+ )
90
+ .with_labels(vec![Label::primary(
91
+ translation.file_position.unwrap().file,
92
+ translation.file_position.unwrap().offset as usize
93
+ ..translation.file_position.unwrap().offset as usize,
94
+ )]),
95
+ );
96
+ }
97
+
98
+ continue;
99
+ }
100
+ };
101
+ }
102
+
103
+ diagnostics
104
+ }
@@ -0,0 +1,347 @@
1
+ use std::borrow::Borrow;
2
+
3
+ use swc_common::{FileName, SourceMap, Spanned};
4
+ use swc_common::sync::Lrc;
5
+ use swc_core::ecma::ast::{
6
+ ExportDecl, ExportDefaultExpr, Expr, Id, ImportDecl, ImportSpecifier, Lit, Module, ObjectLit,
7
+ };
8
+ use swc_core::ecma::parser::{lexer::Lexer, Parser, PResult, StringInput, Syntax};
9
+ use swc_core::ecma::visit::{noop_visit_type, Visit, VisitWith};
10
+
11
+ use intl_message_utils::RUNTIME_PACKAGE_NAME;
12
+
13
+ use crate::messages::{MessageKey, MessageMeta, MessagesError, MessagesResult};
14
+
15
+ pub fn parse_message_definitions_file(file_name: &str, source: &str) -> PResult<Module> {
16
+ let cm: Lrc<SourceMap> = Default::default();
17
+
18
+ let fm = cm.new_source_file(FileName::Custom(file_name.into()), source.into());
19
+ let lexer = Lexer::new(
20
+ Syntax::Es(Default::default()),
21
+ Default::default(),
22
+ StringInput::from(&*fm),
23
+ None,
24
+ );
25
+
26
+ let mut parser = Parser::new_from(lexer);
27
+ parser.parse_module()
28
+ }
29
+
30
+ pub fn extract_message_definitions(module: Module) -> MessageDefinitionsExtractor {
31
+ let mut extractor = MessageDefinitionsExtractor::new();
32
+ module.visit_with(&mut extractor);
33
+ extractor
34
+ }
35
+
36
+ /// A temporary representation of a message directly from a definition file.
37
+ /// This includes all of the resolved meta and other information of a
38
+ /// [NormalMessage], but does _not_ do any parsing or processing of the data
39
+ /// beyond that, since that would create intertwined lifetime dependencies.
40
+ pub struct ExtractedMessage {
41
+ pub name: MessageKey,
42
+ pub offset: u32,
43
+ pub value: String,
44
+ pub meta: MessageMeta,
45
+ }
46
+
47
+ /// A Visitor to extract message definitions from a source AST.
48
+ pub struct MessageDefinitionsExtractor {
49
+ pub message_definitions: Vec<ExtractedMessage>,
50
+ pub failed_definitions: Vec<MessagesError>,
51
+ pub root_meta: Option<MessageMeta>,
52
+ define_messages_id: Option<Id>,
53
+ }
54
+
55
+ impl MessageDefinitionsExtractor {
56
+ fn new() -> Self {
57
+ MessageDefinitionsExtractor {
58
+ define_messages_id: None,
59
+ message_definitions: vec![],
60
+ failed_definitions: vec![],
61
+ root_meta: None,
62
+ }
63
+ }
64
+
65
+ /// Parses the given `object` into a set of MessageDefinitions, storing
66
+ /// that result in `self.message_definitions`.
67
+ fn parse_definitions_object(&mut self, object: &ObjectLit) {
68
+ for property in object.props.iter() {
69
+ let Some(keyvalue) = property.as_prop().and_then(|prop| prop.as_key_value()) else {
70
+ continue;
71
+ };
72
+ let name = if let Some(name) = keyvalue.key.as_ident() {
73
+ &name.sym
74
+ } else if let Some(name) = keyvalue.key.as_str() {
75
+ &name.value
76
+ } else {
77
+ continue;
78
+ };
79
+
80
+ let parse_result = if let Some(object) = keyvalue.value.as_object() {
81
+ self.parse_complete_definition(&name, &object)
82
+ } else if let Some(lit @ Lit::Str(string)) = keyvalue.value.as_lit() {
83
+ self.parse_oneline_definition(&name, &string.value, lit.span_lo().0)
84
+ } else if let Some(template) = keyvalue.value.as_tpl() {
85
+ // With JS, you can write static strings as template strings to
86
+ // avoid needing to escape different quotes, like:
87
+ // SOME_STRING: `"this" is valid, isn't it?`
88
+ // We want to support that syntax, but we can't allow templates
89
+ // that have embedded expressions or multiple elements.
90
+ let string_value = template.quasis.get(0).map(|expr| &expr.raw);
91
+ let is_static = template.quasis.len() == 1 && template.exprs.len() == 0;
92
+
93
+ match string_value {
94
+ Some(string) if is_static => self.parse_oneline_definition(&name, &string, template.span_lo().0),
95
+ _ => Err(MessagesError::DefinitionRestrictionViolated("Encountered non-static template string. Interpolations are currently invalid".into()))
96
+ }
97
+ } else {
98
+ Err(MessagesError::DefinitionRestrictionViolated(
99
+ "Encountered an unknown message definition structure".into(),
100
+ ))
101
+ };
102
+
103
+ match parse_result {
104
+ Ok(definition) => self.message_definitions.push(definition),
105
+ Err(error) => self.failed_definitions.push(error),
106
+ }
107
+ }
108
+ }
109
+
110
+ /// Parse a single message definition into a structured object, resolving
111
+ /// all meta information needed for it.
112
+ fn parse_complete_definition(
113
+ &self,
114
+ key: &str,
115
+ object: &ObjectLit,
116
+ ) -> MessagesResult<ExtractedMessage> {
117
+ let mut default_value: Option<String> = None;
118
+ let mut local_meta = self.clone_meta();
119
+
120
+ for property in object.props.iter() {
121
+ let Some(keyvalue) = property.as_prop().and_then(|prop| prop.as_key_value()) else {
122
+ continue;
123
+ };
124
+ let Some(name) = keyvalue.key.as_ident() else {
125
+ continue;
126
+ };
127
+
128
+ match name.sym.as_str() {
129
+ "message" => {
130
+ self.parse_string_value(keyvalue.value.borrow())
131
+ .map(|value| default_value = Some(value));
132
+ }
133
+ name => self.parse_meta_property(name, keyvalue.value.borrow(), &mut local_meta),
134
+ }
135
+ }
136
+
137
+ // If no `message` was provided in the object definition, it's invalid
138
+ // and can't be used.
139
+ let Some(default_value) = default_value else {
140
+ return Err(MessagesError::NoMessageValue(key.into()));
141
+ };
142
+
143
+ Ok(ExtractedMessage {
144
+ name: key.into(),
145
+ value: default_value,
146
+ offset: object.span.lo.0,
147
+ meta: local_meta,
148
+ })
149
+ }
150
+
151
+ /// Parse a message definition using the shorthand `name: "value"`
152
+ fn parse_oneline_definition(
153
+ &self,
154
+ key: &str,
155
+ value: &str,
156
+ offset: u32,
157
+ ) -> MessagesResult<ExtractedMessage> {
158
+ Ok(ExtractedMessage {
159
+ name: key.into(),
160
+ value: value.to_string(),
161
+ offset,
162
+ meta: self.clone_meta(),
163
+ })
164
+ }
165
+
166
+ /// Return a clone of the root meta, or a new object with the default
167
+ /// values if none existed.
168
+ fn clone_meta(&self) -> MessageMeta {
169
+ self.root_meta
170
+ .as_ref()
171
+ .map_or_else(Default::default, Clone::clone)
172
+ }
173
+
174
+ // Parses the given `object` as a meta definition, then stores the result
175
+ // in `self.root_meta`.
176
+ fn parse_root_meta_initializer(&mut self, object: &ObjectLit) {
177
+ let mut result = MessageMeta::default();
178
+
179
+ for property in object.props.iter() {
180
+ let Some(keyvalue) = property.as_prop().and_then(|prop| prop.as_key_value()) else {
181
+ continue;
182
+ };
183
+ let Some(name) = keyvalue.key.as_ident() else {
184
+ continue;
185
+ };
186
+
187
+ self.parse_meta_property(&name.sym, keyvalue.value.borrow(), &mut result);
188
+ }
189
+
190
+ self.root_meta = Some(result);
191
+ }
192
+
193
+ /// Interpret a given name/value pair to see if it represents a MessageMeta
194
+ /// property. If it does, apply the value to the corresponding field in
195
+ /// `target`. Otherwise, nothing is done.
196
+ fn parse_meta_property(&self, name: &str, value: &Expr, target: &mut MessageMeta) {
197
+ // NOTE: This effectively relies on TypeScript's checker to provide
198
+ // hints when the value types would be incorrect (e.g., `secret` is
199
+ // given a number value instead of a boolean).
200
+ match name {
201
+ "secret" => self
202
+ .parse_boolean_value(value)
203
+ .map(|value| target.secret = value),
204
+ "bundleSecrets" => self
205
+ .parse_boolean_value(value)
206
+ .map(|value| target.bundle_secrets = value),
207
+ "translate" => self
208
+ .parse_boolean_value(value)
209
+ .map(|value| target.translate = value),
210
+ "translationsPath" => self
211
+ .parse_string_value(value)
212
+ .map(|value| target.translations_path = value),
213
+ _ => None,
214
+ };
215
+ }
216
+
217
+ /// If the given expression is a boolean literal, it is interpreted into an
218
+ /// actual boolean value. Any other expression will return None.
219
+ fn parse_boolean_value(&self, expr: &Expr) -> Option<bool> {
220
+ match expr.as_lit() {
221
+ Some(Lit::Bool(bool)) => Some(bool.value),
222
+ _ => None,
223
+ }
224
+ }
225
+
226
+ /// If the given expression is a string literal, the value of that literal
227
+ /// is returned. Any other expression will return None.
228
+ fn parse_string_value(&self, expr: &Expr) -> Option<String> {
229
+ match expr.as_lit() {
230
+ Some(Lit::Str(string)) => Some(string.value.to_owned().to_string()),
231
+ _ => None,
232
+ }
233
+ }
234
+ }
235
+
236
+ impl Visit for MessageDefinitionsExtractor {
237
+ noop_visit_type!();
238
+
239
+ // Captures `meta` declarations.
240
+ fn visit_export_decl(&mut self, export: &ExportDecl) {
241
+ let Some(decl) = export.decl.as_var() else {
242
+ return;
243
+ };
244
+
245
+ for decl in decl.decls.iter() {
246
+ let is_meta_declaration = decl
247
+ .name
248
+ .as_ident()
249
+ .is_some_and(|id| id.id.sym.as_str() == "meta");
250
+ if !is_meta_declaration {
251
+ continue;
252
+ }
253
+
254
+ if let Some(initializer) = decl.init.as_ref().and_then(|init| init.as_object()) {
255
+ self.parse_root_meta_initializer(initializer);
256
+ } else {
257
+ // We've found the meta and determined it didn't have an
258
+ // initializer, so we don't need to continue iterating.
259
+ // TODO: Use this error.
260
+ drop(MessagesError::NoMetaInitializer);
261
+ break;
262
+ }
263
+ }
264
+ }
265
+
266
+ // Captures `defineMessages` calls as the default export.
267
+ fn visit_export_default_expr(&mut self, default_export: &ExportDefaultExpr) {
268
+ let Some(call_expr) = default_export.expr.as_call() else {
269
+ return;
270
+ };
271
+
272
+ // This is almost definitely set before reaching here. If not, it's an
273
+ // error anyway.
274
+ let Some(define_messages_id) = &self.define_messages_id else {
275
+ return;
276
+ };
277
+
278
+ // Ensure this is the default-exported `defineMessages()` call that we
279
+ // want to parse.
280
+ if !call_expr
281
+ .callee
282
+ .as_expr()
283
+ .and_then(|callee| callee.as_ident())
284
+ .is_some_and(|ident| ident.to_id() == *define_messages_id)
285
+ {
286
+ return;
287
+ }
288
+
289
+ // If it has an object expression as the first argument
290
+ if let Some(definition_object) = call_expr.args.get(0).and_then(|arg| arg.expr.as_object())
291
+ {
292
+ self.parse_definitions_object(definition_object);
293
+ }
294
+ }
295
+
296
+ fn visit_import_decl(&mut self, import_decl: &ImportDecl) {
297
+ let import_source_path = &import_decl.src.value;
298
+ if import_source_path != RUNTIME_PACKAGE_NAME {
299
+ return;
300
+ }
301
+
302
+ for spec in import_decl.specifiers.iter() {
303
+ match spec {
304
+ ImportSpecifier::Named(specifier) => {
305
+ self.define_messages_id = Some(specifier.local.to_id());
306
+ }
307
+ _ => continue,
308
+ }
309
+ }
310
+ }
311
+ }
312
+
313
+ #[cfg(test)]
314
+ mod tests {
315
+ use intl_message_utils::RUNTIME_PACKAGE_NAME;
316
+
317
+ use crate::messages::global_intern_string;
318
+
319
+ use super::parse_message_definitions_file;
320
+
321
+ #[test]
322
+ fn test_parsing() {
323
+ let module = parse_message_definitions_file("testing.js", "const t = hello".into());
324
+ println!("{:#?}", module);
325
+ }
326
+
327
+ #[test]
328
+ fn test_template_string() {
329
+ let module = parse_message_definitions_file(
330
+ "testing.js",
331
+ &format!(
332
+ r#"
333
+ import {{defineMessages}} from '{RUNTIME_PACKAGE_NAME}';
334
+
335
+ export default defineMessages({{
336
+ TEMPLATED: `this is a template`,
337
+ INVALID: `this is an ${{invalidTemplate}}`,
338
+ 'string-key': 'this has a stringy key',
339
+ }});
340
+ "#
341
+ ),
342
+ )
343
+ .expect("failed to parse source code");
344
+
345
+ let file_symbol = global_intern_string("testing.js").expect("couldn't intern symbol");
346
+ }
347
+ }
@@ -0,0 +1,87 @@
1
+ use rustc_hash::FxHashSet;
2
+ use swc_core::ecma::ast::Module;
3
+
4
+ pub use definitions_parser::{extract_message_definitions, parse_message_definitions_file};
5
+ pub use translations::{extract_message_translations, Translations};
6
+
7
+ use crate::messages::{
8
+ FilePosition, global_intern_string, KeySymbol, MessageMeta, MessagesDatabase, MessagesError,
9
+ MessagesResult, MessageValue,
10
+ };
11
+
12
+ mod definitions_parser;
13
+ mod translations;
14
+
15
+ // TODO: Allow this to be configurable, or determined by the source file itself.
16
+ static TEMP_DEFAULT_LOCALE: &str = "en-US";
17
+
18
+ pub fn parse_definitions_file(file_name: &str, content: &str) -> MessagesResult<Module> {
19
+ parse_message_definitions_file(file_name, content).map_err(MessagesError::DefinitionParseError)
20
+ }
21
+
22
+ pub fn process_definitions_file(
23
+ db: &mut MessagesDatabase,
24
+ file_name: &str,
25
+ content: &str,
26
+ ) -> MessagesResult<KeySymbol> {
27
+ let file_key = global_intern_string(file_name)?;
28
+ let default_locale = global_intern_string(TEMP_DEFAULT_LOCALE)?;
29
+ let extracted = parse_definitions_file(file_name, content).map(extract_message_definitions)?;
30
+ let file_meta = extracted.root_meta.unwrap_or(MessageMeta::default());
31
+
32
+ let definitions = extracted.message_definitions;
33
+
34
+ // Check if this file has already been processed into the database before. If it has, this
35
+ // becomes an Update operation, which allows definitions to be overridden. Otherwise, it is
36
+ if let Some(existing_source_file) = db.get_source_file(file_key) {
37
+ // Keys that used to exist in the file but are not found on this iteration are _removed_,
38
+ // meaning they will have their entry in the database taken out, and won't be considered
39
+ // part of the source file anymore.
40
+ // To do that, this takes the existing list of keys and removes each found entry from it,
41
+ // then uses those keys to delete values from the database.
42
+ let mut to_remove = existing_source_file.message_keys().clone();
43
+ for definition in definitions.into_iter() {
44
+ let value =
45
+ MessageValue::from_raw(&definition.value).with_file_position(FilePosition {
46
+ file: file_key,
47
+ offset: definition.offset,
48
+ });
49
+ let message = db.insert_definition(
50
+ &definition.name,
51
+ value,
52
+ default_locale,
53
+ definition.meta,
54
+ true,
55
+ )?;
56
+ to_remove.remove(&message.key_symbol());
57
+ }
58
+
59
+ for key in to_remove {
60
+ db.remove_definition(key);
61
+ }
62
+ } else {
63
+ db.create_source_file(file_key, file_name, file_meta);
64
+ // An insert operation doesn't need to track any existing behavior, so it can just insert
65
+ // incrementally. The interior will track adding the keys to the set.
66
+ // TODO: fix this
67
+ let mut inserted_keys = FxHashSet::default();
68
+ for definition in definitions.into_iter() {
69
+ let value =
70
+ MessageValue::from_raw(&definition.value).with_file_position(FilePosition {
71
+ file: file_key,
72
+ offset: definition.offset,
73
+ });
74
+ let message = db.insert_definition(
75
+ &definition.name,
76
+ value,
77
+ default_locale,
78
+ definition.meta,
79
+ true,
80
+ )?;
81
+ inserted_keys.insert(message.key_symbol());
82
+ }
83
+ db.set_source_file_keys(file_key, inserted_keys)?;
84
+ }
85
+
86
+ Ok(file_key)
87
+ }
@@ -0,0 +1,75 @@
1
+ use serde::de::{Deserialize, Deserializer, Error, MapAccess, Visitor};
2
+ use std::borrow::Cow;
3
+
4
+ use crate::messages::{
5
+ global_intern_string, KeySymbol, MessageValue, MessagesError, MessagesResult,
6
+ };
7
+
8
+ /// A temporary type representing a string key and its parsed value from a
9
+ /// translation file. This structure can directly deserialize a translation
10
+ /// file into a list of entries, avoiding a temporary HashMap allocation.
11
+ pub struct TranslationEntry {
12
+ pub key: KeySymbol,
13
+ pub value: MessageValue,
14
+ pub start_offset: usize,
15
+ }
16
+
17
+ /// Custom deserialization visitor that converts a map like {"key": "value"}
18
+ /// into a vector of entries [TranslationEntry(key, value)]. This is much more
19
+ /// efficient than reading the file as plain JSON into a Map, then iterating
20
+ /// the map to create another map of parsed message values, then returning that
21
+ /// and iterating _again_ to insert into the database.
22
+ struct TranslationEntryVisitor;
23
+
24
+ impl<'de> Visitor<'de> for TranslationEntryVisitor {
25
+ type Value = Translations;
26
+
27
+ fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
28
+ formatter.write_str(r#"Translation entry ("key": "value")"#)
29
+ }
30
+
31
+ fn visit_map<V>(self, mut map: V) -> Result<Translations, V::Error>
32
+ where
33
+ V: MapAccess<'de>,
34
+ {
35
+ let mut entries: Vec<TranslationEntry> = vec![];
36
+ loop {
37
+ let entry: Option<(&str, Cow<str>)> = map.next_entry()?;
38
+ if entry.is_none() {
39
+ break;
40
+ }
41
+ let (key, value) = entry.unwrap();
42
+
43
+ let key = global_intern_string(key)
44
+ .map_err(|_| Error::custom("Failed to read the global symbol store"))?;
45
+ entries.push(TranslationEntry {
46
+ key,
47
+ value: MessageValue::from_raw(&value),
48
+ start_offset: 0,
49
+ })
50
+ }
51
+
52
+ Ok(Translations { entries })
53
+ }
54
+ }
55
+
56
+ /// A newtype wrapping a Vec of translations so that we can validly create the
57
+ /// custom Deserialize implementation below.
58
+ pub struct Translations {
59
+ pub entries: Vec<TranslationEntry>,
60
+ }
61
+
62
+ impl<'de> Deserialize<'de> for Translations {
63
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
64
+ where
65
+ D: Deserializer<'de>,
66
+ {
67
+ deserializer.deserialize_map(TranslationEntryVisitor)
68
+ }
69
+ }
70
+
71
+ /// Parse the given content string as JSON, interpreting each entry in the
72
+ /// object as a new Translation definition.
73
+ pub fn extract_message_translations(content: &str) -> MessagesResult<Translations> {
74
+ serde_json::from_str(content).map_err(MessagesError::TranslationDeserializationError)
75
+ }
package/src/test.rs ADDED
@@ -0,0 +1,67 @@
1
+ use std::fs::read_to_string;
2
+
3
+ use crate::messages::{global_get_symbol, MessagesDatabase};
4
+ use crate::services;
5
+ use crate::services::IntlService;
6
+ use crate::services::precompile::CompiledMessageFormat;
7
+
8
+ #[test]
9
+ pub fn test() {
10
+ let translations = read_to_string("./data/input/fr.jsona").unwrap();
11
+ let mut database = MessagesDatabase::new();
12
+
13
+ let locales = vec![
14
+ ("bg.json", "bg"),
15
+ ("cs.json", "cs"),
16
+ // ("da.json", "da"),
17
+ // ("de.json", "de"),
18
+ // ("el.json", "el"),
19
+ // ("en-GB.json", "en-GB"),
20
+ // ("es-419.json", "es-419"),
21
+ // ("es-ES.json", "es-ES"),
22
+ // ("fi.json", "fi"),
23
+ ("fr.json", "fr"),
24
+ // ("hi.json", "hi"),
25
+ // ("hr.json", "hr"),
26
+ // ("hu.json", "hu"),
27
+ // ("id.json", "id"),
28
+ // ("it.json", "it"),
29
+ // ("ja.json", "ja"),
30
+ // ("ko.json", "ko"),
31
+ // ("lt.json", "lt"),
32
+ // ("nl.json", "nl"),
33
+ // ("no.json", "no"),
34
+ // ("pl.json", "pl"),
35
+ // ("pt-BR.json", "pt-BR"),
36
+ // ("ro.json", "ro"),
37
+ // ("ru.json", "ru"),
38
+ // ("sv-SE.json", "sv-SE"),
39
+ // ("th.json", "th"),
40
+ // ("tr.json", "tr"),
41
+ // ("uk.json", "uk"),
42
+ // ("vi.json", "vi"),
43
+ // ("zh-CN.json", "zh-CN"),
44
+ // ("zh-TW.json", "zh-TW"),
45
+ ];
46
+
47
+ // for (file, locale) in locales {
48
+ // database
49
+ // .process_translations_file(file, &locale.into(), &translations)
50
+ // .expect("failed to process file");
51
+ // }
52
+
53
+ let locale_key = global_get_symbol("fr").unwrap();
54
+
55
+ let mut buffer = Vec::new();
56
+ for _ in 0..10 {
57
+ buffer.clear();
58
+ services::precompile::IntlMessagePreCompiler::new(
59
+ &database,
60
+ &mut buffer,
61
+ locale_key,
62
+ CompiledMessageFormat::Json,
63
+ )
64
+ .run()
65
+ .ok();
66
+ }
67
+ }