@vocab/phrase 1.1.0 → 1.2.1

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.
@@ -9,6 +9,7 @@ var FormData = require('form-data');
9
9
  var fetch = require('node-fetch');
10
10
  var chalk = require('chalk');
11
11
  var debug = require('debug');
12
+ var sync = require('csv-stringify/sync');
12
13
 
13
14
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
14
15
 
@@ -21,20 +22,56 @@ var debug__default = /*#__PURE__*/_interopDefault(debug);
21
22
  const mkdir = fs.promises.mkdir;
22
23
  const writeFile = fs.promises.writeFile;
23
24
 
24
- const trace = debug__default['default'](`vocab:phrase`);
25
+ const trace = debug__default["default"](`vocab:phrase`);
25
26
  const log = (...params) => {
26
27
  // eslint-disable-next-line no-console
27
- console.log(chalk__default['default'].yellow('Vocab'), ...params);
28
+ console.log(chalk__default["default"].yellow('Vocab'), ...params);
28
29
  };
29
30
 
31
+ function translationsToCsv(translations, devLanguage) {
32
+ const languages = Object.keys(translations);
33
+ const altLanguages = languages.filter(language => language !== devLanguage);
34
+ // Ensure languages are ordered for locale mapping
35
+ const orderedLanguages = [devLanguage, ...altLanguages];
36
+ const devLanguageTranslations = translations[devLanguage];
37
+ const csv = Object.entries(devLanguageTranslations).map(([key, {
38
+ message,
39
+ description,
40
+ tags
41
+ }]) => {
42
+ const altTranslationMessages = altLanguages.map(language => {
43
+ var _translations$languag, _translations$languag2;
44
+ return (_translations$languag = translations[language]) === null || _translations$languag === void 0 ? void 0 : (_translations$languag2 = _translations$languag[key]) === null || _translations$languag2 === void 0 ? void 0 : _translations$languag2.message;
45
+ });
46
+ return [message, ...altTranslationMessages, key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
47
+ });
48
+ const csvString = sync.stringify(csv, {
49
+ delimiter: ',',
50
+ header: false
51
+ });
52
+
53
+ // Column indices start at 1
54
+ const localeMapping = Object.fromEntries(orderedLanguages.map((language, index) => [language, index + 1]));
55
+ const keyIndex = orderedLanguages.length + 1;
56
+ const commentIndex = keyIndex + 1;
57
+ const tagColumn = commentIndex + 1;
58
+ return {
59
+ csvString,
60
+ localeMapping,
61
+ keyIndex,
62
+ commentIndex,
63
+ tagColumn
64
+ };
65
+ }
66
+
67
+ /* eslint-disable no-console */
30
68
  function _callPhrase(path, options = {}) {
31
69
  const phraseApiToken = process.env.PHRASE_API_TOKEN;
32
-
33
70
  if (!phraseApiToken) {
34
71
  throw new Error('Missing PHRASE_API_TOKEN');
35
72
  }
36
-
37
- return fetch__default['default'](path, { ...options,
73
+ return fetch__default["default"](path, {
74
+ ...options,
38
75
  headers: {
39
76
  Authorization: `token ${phraseApiToken}`,
40
77
  // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
@@ -43,30 +80,26 @@ function _callPhrase(path, options = {}) {
43
80
  }
44
81
  }).then(async response => {
45
82
  console.log(`${path}: ${response.status} - ${response.statusText}`);
46
- console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${response.headers.get('X-Rate-Limit-Reset')} seconds remaining})`);
47
- trace('\nLink:', response.headers.get('Link'), '\n'); // Print All Headers:
83
+ const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
84
+ console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
85
+ trace('\nLink:', response.headers.get('Link'), '\n');
86
+ // Print All Headers:
48
87
  // console.log(Array.from(r.headers.entries()));
49
88
 
50
89
  try {
51
90
  var _response$headers$get;
52
-
53
91
  const result = await response.json();
54
92
  trace(`Internal Result (Length: ${result.length})\n`);
55
-
56
93
  if ((!options.method || options.method === 'GET') && (_response$headers$get = response.headers.get('Link')) !== null && _response$headers$get !== void 0 && _response$headers$get.includes('rel=next')) {
57
94
  var _response$headers$get2, _response$headers$get3;
58
-
59
95
  const [, nextPageUrl] = (_response$headers$get2 = (_response$headers$get3 = response.headers.get('Link')) === null || _response$headers$get3 === void 0 ? void 0 : _response$headers$get3.match(/<([^>]*)>; rel=next/)) !== null && _response$headers$get2 !== void 0 ? _response$headers$get2 : [];
60
-
61
96
  if (!nextPageUrl) {
62
97
  throw new Error("Can't parse next page URL");
63
98
  }
64
-
65
99
  console.log('Results received with next page: ', nextPageUrl);
66
100
  const nextPageResult = await _callPhrase(nextPageUrl, options);
67
101
  return [...result, ...nextPageResult];
68
102
  }
69
-
70
103
  return result;
71
104
  } catch (e) {
72
105
  console.error('Unable to parse response as JSON', e);
@@ -74,19 +107,15 @@ function _callPhrase(path, options = {}) {
74
107
  }
75
108
  });
76
109
  }
77
-
78
110
  async function callPhrase(relativePath, options = {}) {
79
111
  const projectId = process.env.PHRASE_PROJECT_ID;
80
-
81
112
  if (!projectId) {
82
113
  throw new Error('Missing PHRASE_PROJECT_ID');
83
114
  }
84
-
85
115
  return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
86
116
  if (Array.isArray(result)) {
87
117
  console.log('Result length:', result.length);
88
118
  }
89
-
90
119
  return result;
91
120
  }).catch(error => {
92
121
  console.error(`Error calling phrase for ${relativePath}:`, error);
@@ -96,44 +125,62 @@ async function callPhrase(relativePath, options = {}) {
96
125
  async function pullAllTranslations(branch) {
97
126
  const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
98
127
  const translations = {};
99
-
100
128
  for (const r of phraseResult) {
101
129
  if (!translations[r.locale.code]) {
102
130
  translations[r.locale.code] = {};
103
131
  }
104
-
105
132
  translations[r.locale.code][r.key.name] = {
106
133
  message: r.content
107
134
  };
108
135
  }
109
-
110
136
  return translations;
111
137
  }
112
- async function pushTranslationsByLocale(contents, locale, branch) {
113
- const formData = new FormData__default['default']();
114
- const fileContents = Buffer.from(JSON.stringify(contents));
138
+ async function pushTranslations(translationsByLanguage, {
139
+ devLanguage,
140
+ branch
141
+ }) {
142
+ const formData = new FormData__default["default"]();
143
+ const {
144
+ csvString,
145
+ localeMapping,
146
+ keyIndex,
147
+ commentIndex,
148
+ tagColumn
149
+ } = translationsToCsv(translationsByLanguage, devLanguage);
150
+ const fileContents = Buffer.from(csvString);
115
151
  formData.append('file', fileContents, {
116
- contentType: 'application/json',
117
- filename: `${locale}.json`
152
+ contentType: 'text/csv',
153
+ filename: 'translations.csv'
118
154
  });
119
- formData.append('file_format', 'json');
120
- formData.append('locale_id', locale);
155
+ formData.append('file_format', 'csv');
121
156
  formData.append('branch', branch);
122
157
  formData.append('update_translations', 'true');
123
- log('Starting to upload:', locale, '\n');
124
- const {
125
- id
126
- } = await callPhrase(`uploads`, {
158
+ for (const [locale, index] of Object.entries(localeMapping)) {
159
+ formData.append(`locale_mapping[${locale}]`, index);
160
+ }
161
+ formData.append('format_options[key_index]', keyIndex);
162
+ formData.append('format_options[comment_index]', commentIndex);
163
+ formData.append('format_options[tag_column]', tagColumn);
164
+ formData.append('format_options[enable_pluralization]', 'false');
165
+ log('Uploading translations');
166
+ const result = await callPhrase(`uploads`, {
127
167
  method: 'POST',
128
168
  body: formData
129
169
  });
130
- log('Upload ID:', id, '\n');
131
- log('Successfully Uploaded:', locale, '\n');
170
+ trace('Upload result:\n', result);
171
+ if (result && 'id' in result) {
172
+ log('Upload ID:', result.id, '\n');
173
+ log('Successfully Uploaded\n');
174
+ } else {
175
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
176
+ log('Response:', result);
177
+ throw new Error('Error uploading');
178
+ }
132
179
  return {
133
- uploadId: id
180
+ uploadId: result.id
134
181
  };
135
182
  }
136
- async function deleteUnusedKeys(uploadId, locale, branch) {
183
+ async function deleteUnusedKeys(uploadId, branch) {
137
184
  const query = `unmentioned_in_upload:${uploadId}`;
138
185
  const {
139
186
  records_affected
@@ -144,7 +191,6 @@ async function deleteUnusedKeys(uploadId, locale, branch) {
144
191
  },
145
192
  body: JSON.stringify({
146
193
  branch,
147
- locale_id: locale,
148
194
  q: query
149
195
  })
150
196
  });
@@ -173,59 +219,56 @@ async function pull({
173
219
  trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
174
220
  const phraseLanguages = Object.keys(allPhraseTranslations);
175
221
  trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
176
-
177
222
  if (!phraseLanguages.includes(config.devLanguage)) {
178
223
  throw new Error(`Phrase did not return any translations for the configured development language "${config.devLanguage}".\nPlease ensure this language is present in your Phrase project's configuration.`);
179
224
  }
180
-
181
225
  const allVocabTranslations = await core.loadAllTranslations({
182
226
  fallbacks: 'none',
183
- includeNodeModules: false
227
+ includeNodeModules: false,
228
+ withTags: true
184
229
  }, config);
185
-
186
230
  for (const loadedTranslation of allVocabTranslations) {
187
231
  const devTranslations = loadedTranslation.languages[config.devLanguage];
188
-
189
232
  if (!devTranslations) {
190
233
  throw new Error('No dev language translations loaded');
191
234
  }
192
-
193
- const defaultValues = { ...devTranslations
235
+ const defaultValues = {
236
+ ...devTranslations
194
237
  };
195
238
  const localKeys = Object.keys(defaultValues);
196
-
197
239
  for (const key of localKeys) {
198
- defaultValues[key] = { ...defaultValues[key],
240
+ defaultValues[key] = {
241
+ ...defaultValues[key],
199
242
  ...allPhraseTranslations[config.devLanguage][core.getUniqueKey(key, loadedTranslation.namespace)]
200
243
  };
201
244
  }
202
245
 
246
+ // Only write a `_meta` field if necessary
247
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
248
+ defaultValues._meta = loadedTranslation.metadata;
249
+ }
203
250
  await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
204
-
205
251
  for (const alternativeLanguage of alternativeLanguages) {
206
252
  if (alternativeLanguage in allPhraseTranslations) {
207
- const altTranslations = { ...loadedTranslation.languages[alternativeLanguage]
253
+ const altTranslations = {
254
+ ...loadedTranslation.languages[alternativeLanguage]
208
255
  };
209
256
  const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
210
-
211
257
  for (const key of localKeys) {
212
258
  var _phraseAltTranslation;
213
-
214
259
  const phraseKey = core.getUniqueKey(key, loadedTranslation.namespace);
215
260
  const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
216
-
217
261
  if (!phraseTranslationMessage) {
218
262
  trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
219
263
  continue;
220
264
  }
221
-
222
- altTranslations[key] = { ...altTranslations[key],
265
+ altTranslations[key] = {
266
+ ...altTranslations[key],
223
267
  message: phraseTranslationMessage
224
268
  };
225
269
  }
226
-
227
270
  const altTranslationFilePath = core.getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
228
- await mkdir(path__default['default'].dirname(altTranslationFilePath), {
271
+ await mkdir(path__default["default"].dirname(altTranslationFilePath), {
229
272
  recursive: true
230
273
  });
231
274
  await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
@@ -235,7 +278,8 @@ async function pull({
235
278
  }
236
279
 
237
280
  /**
238
- * Uploading to the Phrase API for each language. Adding a unique namespace to each key using file path they key came from
281
+ * Uploads translations to the Phrase API for each language.
282
+ * A unique namespace is appended to each key using the file path the key came from.
239
283
  */
240
284
  async function push({
241
285
  branch,
@@ -243,43 +287,49 @@ async function push({
243
287
  }, config) {
244
288
  const allLanguageTranslations = await core.loadAllTranslations({
245
289
  fallbacks: 'none',
246
- includeNodeModules: false
290
+ includeNodeModules: false,
291
+ withTags: true
247
292
  }, config);
248
293
  trace(`Pushing translations to branch ${branch}`);
249
294
  const allLanguages = config.languages.map(v => v.name);
250
295
  await ensureBranch(branch);
251
296
  trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
252
297
  const phraseTranslations = {};
253
-
254
298
  for (const loadedTranslation of allLanguageTranslations) {
255
299
  for (const language of allLanguages) {
256
300
  const localTranslations = loadedTranslation.languages[language];
257
-
258
301
  if (!localTranslations) {
259
302
  continue;
260
303
  }
261
-
262
304
  if (!phraseTranslations[language]) {
263
305
  phraseTranslations[language] = {};
264
306
  }
265
-
307
+ const {
308
+ metadata: {
309
+ tags: sharedTags = []
310
+ }
311
+ } = loadedTranslation;
266
312
  for (const localKey of Object.keys(localTranslations)) {
267
313
  const phraseKey = core.getUniqueKey(localKey, loadedTranslation.namespace);
268
- phraseTranslations[language][phraseKey] = localTranslations[localKey];
314
+ const {
315
+ tags = [],
316
+ ...localTranslation
317
+ } = localTranslations[localKey];
318
+ if (language === config.devLanguage) {
319
+ localTranslation.tags = [...tags, ...sharedTags];
320
+ }
321
+ phraseTranslations[language][phraseKey] = localTranslation;
269
322
  }
270
323
  }
271
324
  }
272
-
273
- for (const language of allLanguages) {
274
- if (phraseTranslations[language]) {
275
- const {
276
- uploadId
277
- } = await pushTranslationsByLocale(phraseTranslations[language], language, branch);
278
-
279
- if (deleteUnusedKeys$1) {
280
- await deleteUnusedKeys(uploadId, language, branch);
281
- }
282
- }
325
+ const {
326
+ uploadId
327
+ } = await pushTranslations(phraseTranslations, {
328
+ devLanguage: config.devLanguage,
329
+ branch
330
+ });
331
+ if (deleteUnusedKeys$1) {
332
+ await deleteUnusedKeys(uploadId, branch);
283
333
  }
284
334
  }
285
335