@discord/intl-message-database 0.0.1-rc.0 → 0.0.1-rc.2

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 (46) hide show
  1. package/package.json +18 -10
  2. package/.cargo/config.toml +0 -12
  3. package/Cargo.toml +0 -38
  4. package/bench/keyless-json.js +0 -91
  5. package/bench/native.js +0 -114
  6. package/bench/util.js +0 -55
  7. package/build.rs +0 -5
  8. package/npm/darwin-arm64/README.md +0 -3
  9. package/npm/darwin-arm64/package.json +0 -18
  10. package/npm/darwin-x64/README.md +0 -3
  11. package/npm/darwin-x64/package.json +0 -18
  12. package/npm/linux-arm64-gnu/README.md +0 -3
  13. package/npm/linux-arm64-gnu/package.json +0 -21
  14. package/npm/linux-arm64-musl/README.md +0 -3
  15. package/npm/linux-arm64-musl/package.json +0 -21
  16. package/npm/linux-x64-gnu/README.md +0 -3
  17. package/npm/linux-x64-gnu/package.json +0 -21
  18. package/npm/linux-x64-musl/README.md +0 -3
  19. package/npm/linux-x64-musl/package.json +0 -21
  20. package/npm/win32-arm64-msvc/README.md +0 -3
  21. package/npm/win32-arm64-msvc/package.json +0 -18
  22. package/npm/win32-ia32-msvc/README.md +0 -3
  23. package/npm/win32-ia32-msvc/package.json +0 -18
  24. package/npm/win32-x64-msvc/README.md +0 -3
  25. package/npm/win32-x64-msvc/package.json +0 -18
  26. package/src/lib.rs +0 -14
  27. package/src/messages/database.rs +0 -343
  28. package/src/messages/error.rs +0 -43
  29. package/src/messages/message_definition.rs +0 -169
  30. package/src/messages/message_variables_visitor.rs +0 -299
  31. package/src/messages/meta.rs +0 -38
  32. package/src/messages/mod.rs +0 -27
  33. package/src/messages/source_file.rs +0 -75
  34. package/src/messages/symbols.rs +0 -164
  35. package/src/messages/translation.rs +0 -64
  36. package/src/messages/value.rs +0 -51
  37. package/src/napi.rs +0 -300
  38. package/src/services/mod.rs +0 -9
  39. package/src/services/precompile.rs +0 -91
  40. package/src/services/types.rs +0 -237
  41. package/src/services/validator.rs +0 -104
  42. package/src/sources/definitions_parser.rs +0 -347
  43. package/src/sources/mod.rs +0 -87
  44. package/src/sources/translations.rs +0 -75
  45. package/src/test.rs +0 -67
  46. package/src/threading.rs +0 -61
@@ -1,343 +0,0 @@
1
- use rustc_hash::{FxHashMap, FxHashSet};
2
-
3
- use crate::messages::symbols::KeySymbolMap;
4
- use crate::sources::Translations;
5
-
6
- use super::{
7
- FilePosition, global_get_symbol, global_intern_string, KeySymbol, LocaleId,
8
- Message, MessageMeta, MessagesError, MessagesResult, MessageValue, read_global_symbol_store, SourceFile,
9
- };
10
-
11
- #[derive(Debug)]
12
- pub struct MessagesDatabase {
13
- pub messages: KeySymbolMap<Message>,
14
- pub sources: KeySymbolMap<SourceFile>,
15
- pub hash_lookup: FxHashMap<String, KeySymbol>,
16
- pub known_locales: FxHashSet<KeySymbol>,
17
- }
18
-
19
- impl MessagesDatabase {
20
- pub fn new() -> Self {
21
- Self {
22
- messages: KeySymbolMap::default(),
23
- sources: KeySymbolMap::default(),
24
- hash_lookup: FxHashMap::default(),
25
- known_locales: FxHashSet::default(),
26
- }
27
- }
28
-
29
- /// Return the complete message definition under a given key.
30
- pub fn get_message(&self, key: &str) -> Option<&Message> {
31
- global_get_symbol(key)
32
- .ok()
33
- .and_then(|symbol| self.messages.get(&symbol))
34
- }
35
-
36
- /// Returns owned copies of all message names that are currently in the database.
37
- pub fn get_message_keys(&self) -> MessagesResult<Vec<String>> {
38
- let store = read_global_symbol_store()?;
39
-
40
- let mut result = vec![];
41
- for key in self.messages.keys() {
42
- match store.resolve(*key) {
43
- Some(value) => result.push(value.into()),
44
- _ => {}
45
- }
46
- }
47
- Ok(result)
48
- }
49
-
50
- /// Return the string value of a Symbol that has been interned.
51
- /// If the value is not known.
52
- pub fn get_symbol(&self, value: &str) -> MessagesResult<KeySymbol> {
53
- global_get_symbol(value)
54
- }
55
-
56
- pub fn get_source_file(&mut self, file_key: KeySymbol) -> Option<&SourceFile> {
57
- self.sources.get(&file_key)
58
- }
59
-
60
- pub fn create_source_file(
61
- &mut self,
62
- file_key: KeySymbol,
63
- file_name: &str,
64
- meta: MessageMeta,
65
- ) -> &SourceFile {
66
- self.sources.insert(
67
- file_key,
68
- SourceFile::Definition {
69
- file: file_name.into(),
70
- message_keys: FxHashSet::default(),
71
- meta,
72
- },
73
- );
74
- &self.sources[&file_key]
75
- }
76
-
77
- pub fn set_source_file_keys(
78
- &mut self,
79
- file_key: KeySymbol,
80
- keys: FxHashSet<KeySymbol>,
81
- ) -> MessagesResult<()> {
82
- self.sources
83
- .get_mut(&file_key)
84
- .map(|source| source.set_message_keys(keys))
85
- .ok_or(MessagesError::UnknownSourceFile(file_key))
86
- }
87
-
88
- /// Insert a new message definition into the database. If a Normal entry with the same key
89
- /// already exists and `replace_existing` is `false`, this method will return an Error that the
90
- /// message is already defined and cannot be replaced. However, if `replace_existing` is `true`
91
- /// and the existing definition comes from the same source file, _or_ if the existing entry is
92
- /// Undefined, this method will update and convert that entry to a Normal entry and return Ok.
93
- ///
94
- /// An Ok response from this method will _always_ return a `MessageDefinition::Normal` value.
95
- pub fn insert_definition(
96
- &mut self,
97
- name: &str,
98
- value: MessageValue,
99
- locale: KeySymbol,
100
- meta: MessageMeta,
101
- replace_existing: bool,
102
- ) -> MessagesResult<&Message> {
103
- let key = global_intern_string(name)?;
104
- match self.messages.get_mut(&key) {
105
- Some(existing) => {
106
- // Complete messages that already exist can not be re-added, since
107
- // that would mean two definitions exist. Instead, they can be
108
- // _updated_, for example when a definition file changes.
109
- if existing.is_defined() && !replace_existing {
110
- return Err(MessagesError::AlreadyDefined(key));
111
- }
112
-
113
- existing.set_definition(value, locale, meta);
114
- }
115
- _ => {
116
- // Otherwise this is an entirely new message that gets created.
117
- let message = Message::from_definition(key, name.into(), value, locale, meta);
118
- self.known_locales.insert(locale);
119
- self.hash_lookup.insert(message.hashed_key().clone(), key);
120
- self.messages.insert(key, message);
121
- }
122
- }
123
- Ok(&self.messages[&key])
124
- }
125
-
126
- /// If a message with the given `message_key` exists and has a source definition from the file
127
- /// with the given `file_key`, remove only the definition from the database. If there are
128
- /// existing translations for that message, they are preserved and the definition becomes
129
- /// Undefined. Otherwise, if there are no other translations, the message is removed entirely.
130
- pub fn remove_definition(&mut self, message_key: KeySymbol) -> Option<MessageValue> {
131
- self.messages
132
- .get_mut(&message_key)
133
- .and_then(|message| message.remove_definition().0)
134
- }
135
-
136
- /// Insert a new message definition into the database. If a Normal
137
- /// entry with the same key already exists, this method will return an
138
- /// Error. However, if the existing entry is Undefined, this method will
139
- /// convert that entry to a Normal entry and return Ok.
140
- ///
141
- /// An Ok response from this method will _always_ return a
142
- /// `MessageDefinition::Normal` value.
143
- fn insert_translation(
144
- &mut self,
145
- key: KeySymbol,
146
- locale: KeySymbol,
147
- value: MessageValue,
148
- replace_existing: bool,
149
- ) -> MessagesResult<&Message> {
150
- match self.messages.get_mut(&key) {
151
- // If the key has an existing message at all, it just gets a new
152
- // translation entry in the map. The type of the entry does not
153
- // change here.
154
- Some(message) => {
155
- if message.translations().contains_key(&locale) && !replace_existing {
156
- let store = read_global_symbol_store()?;
157
- let name = store
158
- .resolve(key)
159
- .ok_or_else(|| MessagesError::SymbolNotFound(key))?;
160
- return Err(MessagesError::TranslationAlreadySet(name.into(), locale));
161
- }
162
-
163
- self.known_locales.insert(locale);
164
- message.set_translation(locale, value);
165
- }
166
- // If it doesn't already exist, add a new Undefined message to hold
167
- // the translation until a definition is found.
168
- _ => {
169
- // Otherwise this is an entirely new message that gets created.
170
- let store = read_global_symbol_store()?;
171
- let name = store
172
- .resolve(key)
173
- .ok_or_else(|| MessagesError::SymbolNotFound(key))?;
174
- let message = Message::from_translation(key, name.into(), locale, value);
175
- self.known_locales.insert(locale);
176
- self.hash_lookup.insert(message.hashed_key().clone(), key);
177
- self.messages.insert(key, message);
178
- }
179
- }
180
-
181
- Ok(&self.messages[&key])
182
- }
183
-
184
- fn remove_translation(
185
- &mut self,
186
- message_key: KeySymbol,
187
- locale: KeySymbol,
188
- ) -> Option<MessageValue> {
189
- self.messages
190
- .get_mut(&message_key)
191
- .and_then(|message| message.remove_translation(locale))
192
- }
193
-
194
- /// Similar to [MessagesDatabase::process_translations_file], but where the
195
- /// caller has already done the work to read the file and parse it into a
196
- /// set of translations. Useful for multithreading on native platforms.
197
- pub fn insert_translations_from_file(
198
- &mut self,
199
- file_name: &str,
200
- locale: &LocaleId,
201
- translations: Translations,
202
- ) -> MessagesResult<&SourceFile> {
203
- let file_key = global_intern_string(file_name)?;
204
- let locale_symbol = global_intern_string(&locale)?;
205
-
206
- let mut inserted_translations = FxHashSet::default();
207
-
208
- for entry in translations.entries {
209
- let value = entry.value.with_file_position(FilePosition {
210
- file: file_key,
211
- offset: entry.start_offset as u32,
212
- });
213
- if let Ok(inserted) = self.insert_translation(entry.key, locale_symbol, value, false) {
214
- inserted_translations.insert(inserted.key_symbol());
215
- }
216
- }
217
-
218
- let source_file = SourceFile::Translation {
219
- file: file_name.into(),
220
- message_keys: inserted_translations,
221
- locale: locale.clone(),
222
- };
223
-
224
- self.sources.insert(file_key, source_file);
225
-
226
- Ok(&self.sources[&file_key])
227
- }
228
- }
229
-
230
- #[cfg(test)]
231
- mod tests {
232
- use std::fmt::Write;
233
-
234
- use intl_message_utils::RUNTIME_PACKAGE_NAME;
235
-
236
- use crate::messages::MessagesDatabase;
237
-
238
- fn new_database() -> MessagesDatabase {
239
- MessagesDatabase::new()
240
- }
241
-
242
- #[derive(Clone)]
243
- pub struct SourceMessagesBuilder {
244
- meta: Option<String>,
245
- messages: Vec<(String, String)>,
246
- }
247
-
248
- impl SourceMessagesBuilder {
249
- fn new() -> Self {
250
- Self {
251
- meta: None,
252
- messages: vec![],
253
- }
254
- }
255
-
256
- fn with_meta(mut self, meta: Option<String>) -> Self {
257
- self.meta = meta;
258
- self
259
- }
260
-
261
- fn with_message(mut self, key: &str, value: &str) -> Self {
262
- self.messages.push((key.into(), value.into()));
263
- self
264
- }
265
-
266
- fn remove_message(mut self, key: &str) -> Self {
267
- self.messages = Vec::from_iter(self.messages.into_iter().filter(|(k, _)| *k != key));
268
- self
269
- }
270
-
271
- fn count(&self) -> usize {
272
- self.messages.len()
273
- }
274
-
275
- fn to_definitions(&self) -> String {
276
- let mut buffer = String::new();
277
- buffer.push_str("import {defineMessages} from '");
278
- buffer.push_str(RUNTIME_PACKAGE_NAME);
279
- buffer.push_str("';\n");
280
-
281
- if let Some(meta) = &self.meta {
282
- write!(buffer, "export const meta = {};\n", meta).ok();
283
- }
284
- buffer.push_str("export default defineMessages({\n");
285
- for (key, value) in &self.messages {
286
- write!(buffer, "\"{}\": \"{}\",\n", key, value).ok();
287
- }
288
- buffer.push_str("});\n");
289
-
290
- buffer
291
- }
292
-
293
- fn to_translations(&self) -> String {
294
- let mut buffer = String::new();
295
- buffer.push_str("{\n");
296
- let mut is_first = true;
297
- for (key, value) in &self.messages {
298
- if is_first {
299
- is_first = false;
300
- buffer.push('\n');
301
- } else {
302
- buffer.push_str(",\n");
303
- }
304
- write!(buffer, "\"{}\":\"{}\"", key, value).ok();
305
- }
306
- buffer.push('}');
307
-
308
- buffer
309
- }
310
- }
311
-
312
- fn base_messages_file() -> SourceMessagesBuilder {
313
- SourceMessagesBuilder::new()
314
- .with_meta(Some("{secret: false}".into()))
315
- .with_message("CUSTOM_STATUS", "This is a custom status")
316
- .with_message("ANOTHER_STATUS", "This one is a _separate_ message")
317
- }
318
-
319
- // #[test]
320
- // fn test_definitions_removed_message() {
321
- // let mut database = new_database();
322
- //
323
- // let source_file_name = "SomeModule.messages.js";
324
- //
325
- // let original = base_messages_file();
326
- // let original_result =
327
- // database.process_definitions_file(source_file_name, &original.to_definitions());
328
- // assert_eq!(
329
- // original_result.unwrap().message_keys().len(),
330
- // original.count()
331
- // );
332
- //
333
- // let file_with_removed = original.clone().remove_message("CUSTOM_STATUS");
334
- // println!("{}", file_with_removed.to_definitions());
335
- // let updated_result = database
336
- // .process_definitions_file(source_file_name, &file_with_removed.to_definitions());
337
- // println!("{:#?}", updated_result);
338
- // assert_eq!(
339
- // updated_result.unwrap().message_keys().len(),
340
- // original.count() - 1,
341
- // );
342
- // }
343
- }
@@ -1,43 +0,0 @@
1
- use crate::messages::source_file::SourceFileKind;
2
- use thiserror::Error;
3
-
4
- use super::symbols::KeySymbol;
5
-
6
- #[derive(Debug, Error)]
7
- pub enum MessagesError {
8
- // Definition file errors
9
- #[error("Parsing error from SWC: {0:?}")]
10
- DefinitionParseError(swc_core::ecma::parser::error::Error),
11
- #[error("Message definition semantics were violated: {0}")]
12
- DefinitionRestrictionViolated(String),
13
- #[error("Definitions file did not contain any actual message definitions.")]
14
- NoDefinitionsFound,
15
- #[error("A meta object was defined in this file, but was not given an initializer")]
16
- NoMetaInitializer,
17
- #[error("Message definition for {0} did not contain a default message value")]
18
- NoMessageValue(String),
19
- #[error("{0} has already been defined in this source file and cannot be defined again")]
20
- AlreadyDefined(KeySymbol),
21
- #[error("{0} already has a translation in the locale {1} and cannot be set again")]
22
- TranslationAlreadySet(String, KeySymbol),
23
-
24
- // Translation file errors
25
- #[error(transparent)]
26
- TranslationDeserializationError(#[from] serde_json::Error),
27
-
28
- // Database errors
29
- #[error("Expected source file {file_name} to be a {expected} but found {found}")]
30
- MismatchedSourceFileKind {
31
- file_name: String,
32
- expected: SourceFileKind,
33
- found: SourceFileKind,
34
- },
35
- #[error("Global symbol store was poisoned and could not be read")]
36
- SymbolStorePoisonedError,
37
- #[error("Symbol {0:?} was not found in the symbol store")]
38
- SymbolNotFound(KeySymbol),
39
- #[error("Tried to look up symbol for the given value, but it has not yet been interned. The value was: {0}")]
40
- ValueNotInterned(String),
41
- #[error("Source file {0} is not a known source file in the database")]
42
- UnknownSourceFile(KeySymbol),
43
- }
@@ -1,169 +0,0 @@
1
- use super::{KeySymbol, MessageMeta, MessageValue, MessageVariables};
2
- use crate::messages::symbols::KeySymbolMap;
3
- use serde::Serialize;
4
- use intl_message_utils::hash_message_key;
5
-
6
- pub type MessageKey = String;
7
-
8
- /// A combination of a file name and a byte offset representing a location in
9
- /// a file.
10
- #[derive(Clone, Copy, Debug, PartialEq, Hash, Serialize)]
11
- pub struct FilePosition {
12
- /// File within which the offset applies.
13
- pub file: KeySymbol,
14
- /// Positional offset where the message value starts in the file.
15
- /// Used for presenting diagnostics at an accurate location and
16
- /// jumping to definitions.
17
- pub offset: u32,
18
- }
19
-
20
- /// Any message that is defined through `defineMessage` will be a `Normal`
21
- /// message definition.
22
- #[derive(Debug, PartialEq, Serialize)]
23
- pub struct Message {
24
- /// Flyweight handle used as the key for this message in various maps.
25
- #[serde(skip)]
26
- key_symbol: KeySymbol,
27
- /// Original, plain text name of the message given in its definition.
28
- key: MessageKey,
29
- /// Hashed version of the key, used everywhere for minification and obfuscation.
30
- hashed_key: String,
31
- /// Map of all translations for this message, including the default.
32
- translations: KeySymbolMap<MessageValue>,
33
- /// The source definition information for this message (locale and location).
34
- source_locale: Option<KeySymbol>,
35
- /// Meta information about how to handle and process this message.
36
- meta: MessageMeta,
37
- }
38
-
39
- impl Message {
40
- pub fn from_definition(
41
- key_symbol: KeySymbol,
42
- key: MessageKey,
43
- value: MessageValue,
44
- source_locale: KeySymbol,
45
- meta: MessageMeta,
46
- ) -> Self {
47
- let mut message = Self {
48
- key_symbol,
49
- hashed_key: hash_message_key(&key),
50
- key,
51
- translations: KeySymbolMap::default(),
52
- source_locale: Some(source_locale),
53
- meta,
54
- };
55
- message.translations.insert(source_locale, value);
56
- message
57
- }
58
-
59
- pub fn from_translation(
60
- key_symbol: KeySymbol,
61
- key: MessageKey,
62
- locale: KeySymbol,
63
- value: MessageValue,
64
- ) -> Self {
65
- let mut message = Self {
66
- key_symbol,
67
- hashed_key: hash_message_key(&key),
68
- key,
69
- translations: KeySymbolMap::default(),
70
- source_locale: None,
71
- meta: MessageMeta::default(),
72
- };
73
- message.translations.insert(locale, value);
74
- message
75
- }
76
-
77
- //#region Accessors
78
- pub fn is_defined(&self) -> bool {
79
- self.source_locale.is_some()
80
- }
81
-
82
- pub fn translations(&self) -> &KeySymbolMap<MessageValue> {
83
- &self.translations
84
- }
85
-
86
- pub fn key(&self) -> &String {
87
- &self.key
88
- }
89
-
90
- pub fn hashed_key(&self) -> &String {
91
- &self.hashed_key
92
- }
93
-
94
- pub fn key_symbol(&self) -> KeySymbol {
95
- self.key_symbol
96
- }
97
-
98
- pub fn source_locale(&self) -> &Option<KeySymbol> {
99
- &self.source_locale
100
- }
101
- //#endregion
102
-
103
- /// Create or update the definition for this message with the given information.
104
- pub fn set_definition(&mut self, source: MessageValue, locale: KeySymbol, meta: MessageMeta) {
105
- self.translations.insert(locale, source);
106
- self.source_locale = Some(locale);
107
- self.meta = meta;
108
- }
109
-
110
- /// Removes the source definition of this message, including both the translation and the
111
- /// source locale key, which are returned as a tuple from this method if they were present.
112
- pub fn remove_definition(&mut self) -> (Option<MessageValue>, Option<KeySymbol>) {
113
- let translation = match &self.source_locale {
114
- Some(locale) => self.translations.remove(locale),
115
- None => None,
116
- };
117
- (translation, self.source_locale.take())
118
- }
119
-
120
- pub fn set_translation(&mut self, locale: KeySymbol, value: MessageValue) {
121
- self.translations.insert(locale, value);
122
- }
123
-
124
- pub fn remove_translation(&mut self, locale: KeySymbol) -> Option<MessageValue> {
125
- self.translations.remove(&locale)
126
- }
127
-
128
- /// Return the translation entry for the default locale for this message.
129
- pub fn get_source_translation(&self) -> Option<&MessageValue> {
130
- self.source_locale
131
- .as_ref()
132
- .and_then(|locale| self.translations.get(locale))
133
- }
134
-
135
- /// Returns true if the definition of this message _does not_ contain any dynamic variables,
136
- /// meaning it can be treated as a static string and bypass any extra processing.
137
- pub fn is_static_definition(&self) -> bool {
138
- !self
139
- .main_variables()
140
- .as_ref()
141
- .is_some_and(|variables| variables.len() > 0)
142
- }
143
-
144
- /// Returns
145
- pub fn main_variables(&self) -> Option<&MessageVariables> {
146
- match self.get_source_translation() {
147
- Some(translation) => translation.variables.as_ref(),
148
- _ => None,
149
- }
150
- }
151
-
152
- /// Returns a merged set of all variables present in the message, across all translations.
153
- pub fn all_variables(&self) -> MessageVariables {
154
- let mut merged = self
155
- .main_variables()
156
- .map_or_else(|| MessageVariables::new(), Clone::clone);
157
-
158
- for (_, translation) in self.translations() {
159
- match &translation.variables {
160
- Some(variables) => {
161
- merged.merge(variables);
162
- }
163
- None => continue,
164
- }
165
- }
166
-
167
- merged
168
- }
169
- }