@vocab/phrase 0.0.0-phrase-pull-dev-language-202281412540 → 0.0.0-push-split-translation-files-20230508035947

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ ### MIT License
2
+
3
+ Copyright (c) 2020 SEEK
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ import type { TranslationsByLanguage } from '@vocab/core';
2
+ export declare function translationsToCsv(translations: TranslationsByLanguage, devLanguage: string): {
3
+ csvFileStrings: {
4
+ [k: string]: string;
5
+ };
6
+ keyIndex: number;
7
+ commentIndex: number;
8
+ tagColumn: number;
9
+ messageIndex: number;
10
+ };
@@ -1,4 +1,4 @@
1
- /// <reference types="node" />
2
- import { promises as fs } from 'fs';
3
- export declare const mkdir: typeof fs.mkdir;
4
- export declare const writeFile: typeof fs.writeFile;
1
+ /// <reference types="node" />
2
+ import { promises as fs } from 'fs';
3
+ export declare const mkdir: typeof fs.mkdir;
4
+ export declare const writeFile: typeof fs.writeFile;
@@ -1,2 +1,2 @@
1
- export { pull } from './pull-translations';
2
- export { push } from './push-translations';
1
+ export { pull } from './pull-translations';
2
+ export { push } from './push-translations';
@@ -1,3 +1,3 @@
1
- import debug from 'debug';
2
- export declare const trace: debug.Debugger;
3
- export declare const log: (...params: unknown[]) => void;
1
+ import debug from 'debug';
2
+ export declare const trace: debug.Debugger;
3
+ export declare const log: (...params: unknown[]) => void;
@@ -1,7 +1,12 @@
1
- import { TranslationsByKey } from './../../types/src/index';
2
- import type { TranslationsByLanguage } from '@vocab/types';
3
- import fetch from 'node-fetch';
4
- export declare function callPhrase(relativePath: string, options?: Parameters<typeof fetch>[1]): Promise<any>;
5
- export declare function pullAllTranslations(branch: string): Promise<TranslationsByLanguage>;
6
- export declare function pushTranslationsByLocale(contents: TranslationsByKey, locale: string, branch: string): Promise<void>;
7
- export declare function ensureBranch(branch: string): Promise<void>;
1
+ import type { TranslationsByLanguage } from '@vocab/core';
2
+ import fetch from 'node-fetch';
3
+ export declare function callPhrase<T = any>(relativePath: string, options?: Parameters<typeof fetch>[1]): Promise<T>;
4
+ export declare function pullAllTranslations(branch: string): Promise<TranslationsByLanguage>;
5
+ export declare function pushTranslations(translationsByLanguage: TranslationsByLanguage, { devLanguage, branch }: {
6
+ devLanguage: string;
7
+ branch: string;
8
+ }): Promise<{
9
+ uploadIds: string[];
10
+ }>;
11
+ export declare function deleteUnusedKeys(uploadId: string, branch: string): Promise<void>;
12
+ export declare function ensureBranch(branch: string): Promise<void>;
@@ -1,6 +1,7 @@
1
- import type { UserConfig } from '@vocab/types';
2
- interface PullOptions {
3
- branch?: string;
4
- }
5
- export declare function pull({ branch }: PullOptions, config: UserConfig): Promise<void>;
6
- export {};
1
+ import type { UserConfig } from '@vocab/core';
2
+ interface PullOptions {
3
+ branch?: string;
4
+ deleteUnusedKeys?: boolean;
5
+ }
6
+ export declare function pull({ branch }: PullOptions, config: UserConfig): Promise<void>;
7
+ export {};
@@ -1,9 +1,11 @@
1
- import { UserConfig } from '@vocab/types';
2
- interface PushOptions {
3
- branch: string;
4
- }
5
- /**
6
- * Uploading to the Phrase API for each language. Adding a unique namespace to each key using file path they key came from
7
- */
8
- export declare function push({ branch }: PushOptions, config: UserConfig): Promise<void>;
9
- export {};
1
+ import type { UserConfig } from '@vocab/core';
2
+ interface PushOptions {
3
+ branch: string;
4
+ deleteUnusedKeys?: boolean;
5
+ }
6
+ /**
7
+ * Uploads translations to the Phrase API for each language.
8
+ * A unique namespace is appended to each key using the file path the key came from.
9
+ */
10
+ export declare function push({ branch, deleteUnusedKeys }: PushOptions, config: UserConfig): Promise<void>;
11
+ export {};
@@ -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,68 @@ 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
+ // Might not need this anymore?
36
+ // const orderedLanguages = [devLanguage, ...altLanguages];
37
+
38
+ const devLanguageTranslations = translations[devLanguage];
39
+ const csvFilesByLanguage = Object.fromEntries(languages.map(language => [language, []]));
40
+ Object.entries(devLanguageTranslations).map(([key, {
41
+ message,
42
+ description,
43
+ tags
44
+ }]) => {
45
+ const sharedData = [key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
46
+ const devLanguageRow = [...sharedData, message];
47
+ csvFilesByLanguage[devLanguage].push(devLanguageRow);
48
+ altLanguages.map(language => {
49
+ var _translations$languag, _translations$languag2;
50
+ const altTranslationMessage = (_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;
51
+ if (altTranslationMessage) {
52
+ csvFilesByLanguage[language].push([...sharedData, altTranslationMessage]);
53
+ }
54
+ });
55
+ });
56
+ const csvFilesWithKeys = Object.fromEntries(Object.entries(csvFilesByLanguage).filter(([_, csvFile]) => csvFile.length > 0));
57
+ const csvFileStrings = Object.fromEntries(Object.entries(csvFilesWithKeys).map(([language, csvFile]) => {
58
+ const csvFileString = sync.stringify(csvFile, {
59
+ delimiter: ',',
60
+ header: false
61
+ });
62
+ return [language, csvFileString];
63
+ }));
64
+
65
+ // Column indices start at 1
66
+ const keyIndex = 1;
67
+ const commentIndex = keyIndex + 1;
68
+ const tagColumn = commentIndex + 1;
69
+ const messageIndex = tagColumn + 1;
70
+ return {
71
+ csvFileStrings,
72
+ keyIndex,
73
+ commentIndex,
74
+ tagColumn,
75
+ messageIndex
76
+ };
77
+ }
78
+
79
+ /* eslint-disable no-console */
30
80
  function _callPhrase(path, options = {}) {
31
81
  const phraseApiToken = process.env.PHRASE_API_TOKEN;
32
-
33
82
  if (!phraseApiToken) {
34
83
  throw new Error('Missing PHRASE_API_TOKEN');
35
84
  }
36
-
37
- return fetch__default['default'](path, { ...options,
85
+ return fetch__default["default"](path, {
86
+ ...options,
38
87
  headers: {
39
88
  Authorization: `token ${phraseApiToken}`,
40
89
  // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
@@ -43,30 +92,26 @@ function _callPhrase(path, options = {}) {
43
92
  }
44
93
  }).then(async response => {
45
94
  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
- console.log('\nLink:', response.headers.get('Link'), '\n'); // Print All Headers:
95
+ const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
96
+ console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
97
+ trace('\nLink:', response.headers.get('Link'), '\n');
98
+ // Print All Headers:
48
99
  // console.log(Array.from(r.headers.entries()));
49
100
 
50
101
  try {
51
102
  var _response$headers$get;
52
-
53
103
  const result = await response.json();
54
- console.log(`Internal Result (Length: ${result.length})\n`);
55
-
104
+ trace(`Internal Result (Length: ${result.length})\n`);
56
105
  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
106
  var _response$headers$get2, _response$headers$get3;
58
-
59
107
  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
108
  if (!nextPageUrl) {
62
- throw new Error('Cant parse next page URL');
109
+ throw new Error("Can't parse next page URL");
63
110
  }
64
-
65
- console.log('Results recieved with next page: ', nextPageUrl);
111
+ console.log('Results received with next page: ', nextPageUrl);
66
112
  const nextPageResult = await _callPhrase(nextPageUrl, options);
67
113
  return [...result, ...nextPageResult];
68
114
  }
69
-
70
115
  return result;
71
116
  } catch (e) {
72
117
  console.error('Unable to parse response as JSON', e);
@@ -74,19 +119,15 @@ function _callPhrase(path, options = {}) {
74
119
  }
75
120
  });
76
121
  }
77
-
78
122
  async function callPhrase(relativePath, options = {}) {
79
123
  const projectId = process.env.PHRASE_PROJECT_ID;
80
-
81
124
  if (!projectId) {
82
125
  throw new Error('Missing PHRASE_PROJECT_ID');
83
126
  }
84
-
85
127
  return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
86
128
  if (Array.isArray(result)) {
87
129
  console.log('Result length:', result.length);
88
130
  }
89
-
90
131
  return result;
91
132
  }).catch(error => {
92
133
  console.error(`Error calling phrase for ${relativePath}:`, error);
@@ -96,36 +137,79 @@ async function callPhrase(relativePath, options = {}) {
96
137
  async function pullAllTranslations(branch) {
97
138
  const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
98
139
  const translations = {};
99
-
100
140
  for (const r of phraseResult) {
101
141
  if (!translations[r.locale.code]) {
102
142
  translations[r.locale.code] = {};
103
143
  }
104
-
105
144
  translations[r.locale.code][r.key.name] = {
106
145
  message: r.content
107
146
  };
108
147
  }
109
-
110
148
  return translations;
111
149
  }
112
- async function pushTranslationsByLocale(contents, locale, branch) {
113
- const formData = new FormData__default['default']();
114
- const fileContents = Buffer.from(JSON.stringify(contents));
115
- formData.append('file', fileContents, {
116
- contentType: 'application/json',
117
- filename: `${locale}.json`
118
- });
119
- formData.append('file_format', 'json');
120
- formData.append('locale_id', locale);
121
- formData.append('branch', branch);
122
- formData.append('update_translations', 'true');
123
- trace('Starting to upload:', locale);
124
- await callPhrase(`uploads`, {
125
- method: 'POST',
126
- body: formData
150
+ async function pushTranslations(translationsByLanguage, {
151
+ devLanguage,
152
+ branch
153
+ }) {
154
+ const {
155
+ csvFileStrings,
156
+ keyIndex,
157
+ commentIndex,
158
+ tagColumn,
159
+ messageIndex
160
+ } = translationsToCsv(translationsByLanguage, devLanguage);
161
+ const uploadIds = [];
162
+ for (const [language, csvFileString] of Object.entries(csvFileStrings)) {
163
+ const formData = new FormData__default["default"]();
164
+ const fileContents = Buffer.from(csvFileString);
165
+ formData.append('file', fileContents, {
166
+ contentType: 'text/csv',
167
+ filename: 'translations.csv'
168
+ });
169
+ formData.append('file_format', 'csv');
170
+ formData.append('branch', branch);
171
+ formData.append('update_translations', 'true');
172
+ formData.append('update_descriptions', 'true');
173
+ formData.append(`locale_mapping[${language}]`, messageIndex);
174
+ formData.append('format_options[key_index]', keyIndex);
175
+ formData.append('format_options[comment_index]', commentIndex);
176
+ formData.append('format_options[tag_column]', tagColumn);
177
+ formData.append('format_options[enable_pluralization]', 'false');
178
+ log(`Uploading translations for language ${language}`);
179
+ const result = await callPhrase(`uploads`, {
180
+ method: 'POST',
181
+ body: formData
182
+ });
183
+ trace('Upload result:\n', result);
184
+ if (result && 'id' in result) {
185
+ log('Upload ID:', result.id, '\n');
186
+ log('Successfully Uploaded\n');
187
+ } else {
188
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
189
+ log('Response:', result);
190
+ throw new Error('Error uploading');
191
+ }
192
+ uploadIds.push(result.id);
193
+ }
194
+ return {
195
+ uploadIds
196
+ };
197
+ }
198
+ async function deleteUnusedKeys(uploadId, branch) {
199
+ const query = `unmentioned_in_upload:${uploadId}`;
200
+ const {
201
+ records_affected
202
+ } = await callPhrase('keys', {
203
+ method: 'DELETE',
204
+ headers: {
205
+ 'Content-Type': 'application/json'
206
+ },
207
+ body: JSON.stringify({
208
+ branch,
209
+ q: query
210
+ })
127
211
  });
128
- log('Successfully Uploaded:', locale, '\n');
212
+ log('Successfully deleted', records_affected, 'unused keys from branch', branch);
129
213
  }
130
214
  async function ensureBranch(branch) {
131
215
  await callPhrase(`branches`, {
@@ -137,7 +221,7 @@ async function ensureBranch(branch) {
137
221
  name: branch
138
222
  })
139
223
  });
140
- trace('Created branch:', branch);
224
+ log('Created branch:', branch);
141
225
  }
142
226
 
143
227
  async function pull({
@@ -149,64 +233,57 @@ async function pull({
149
233
  const allPhraseTranslations = await pullAllTranslations(branch);
150
234
  trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
151
235
  const phraseLanguages = Object.keys(allPhraseTranslations);
152
- const phraseLanguagesWithTranslations = phraseLanguages.filter(language => {
153
- const phraseTranslationsForLanguage = allPhraseTranslations[language];
154
- return Object.keys(phraseTranslationsForLanguage).length > 0;
155
- });
156
- trace(`Found Phrase translations for languages ${phraseLanguagesWithTranslations.join(', ')}`);
157
-
158
- if (!phraseLanguagesWithTranslations.includes(config.devLanguage)) {
159
- throw new Error(`Phrase did not return any translations for dev language "${config.devLanguage}".\nEnsure you have configured your Phrase project for your dev language, and have pushed your translations.`);
236
+ trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
237
+ if (!phraseLanguages.includes(config.devLanguage)) {
238
+ 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.`);
160
239
  }
161
-
162
240
  const allVocabTranslations = await core.loadAllTranslations({
163
241
  fallbacks: 'none',
164
- includeNodeModules: false
242
+ includeNodeModules: false,
243
+ withTags: true
165
244
  }, config);
166
-
167
245
  for (const loadedTranslation of allVocabTranslations) {
168
246
  const devTranslations = loadedTranslation.languages[config.devLanguage];
169
-
170
247
  if (!devTranslations) {
171
248
  throw new Error('No dev language translations loaded');
172
249
  }
173
-
174
- const defaultValues = { ...devTranslations
250
+ const defaultValues = {
251
+ ...devTranslations
175
252
  };
176
253
  const localKeys = Object.keys(defaultValues);
177
-
178
254
  for (const key of localKeys) {
179
- defaultValues[key] = { ...defaultValues[key],
255
+ defaultValues[key] = {
256
+ ...defaultValues[key],
180
257
  ...allPhraseTranslations[config.devLanguage][core.getUniqueKey(key, loadedTranslation.namespace)]
181
258
  };
182
259
  }
183
260
 
261
+ // Only write a `_meta` field if necessary
262
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
263
+ defaultValues._meta = loadedTranslation.metadata;
264
+ }
184
265
  await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
185
-
186
266
  for (const alternativeLanguage of alternativeLanguages) {
187
267
  if (alternativeLanguage in allPhraseTranslations) {
188
- const altTranslations = { ...loadedTranslation.languages[alternativeLanguage]
268
+ const altTranslations = {
269
+ ...loadedTranslation.languages[alternativeLanguage]
189
270
  };
190
271
  const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
191
-
192
272
  for (const key of localKeys) {
193
273
  var _phraseAltTranslation;
194
-
195
274
  const phraseKey = core.getUniqueKey(key, loadedTranslation.namespace);
196
275
  const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
197
-
198
276
  if (!phraseTranslationMessage) {
199
277
  trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
200
278
  continue;
201
279
  }
202
-
203
- altTranslations[key] = { ...altTranslations[key],
280
+ altTranslations[key] = {
281
+ ...altTranslations[key],
204
282
  message: phraseTranslationMessage
205
283
  };
206
284
  }
207
-
208
285
  const altTranslationFilePath = core.getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
209
- await mkdir(path__default['default'].dirname(altTranslationFilePath), {
286
+ await mkdir(path__default["default"].dirname(altTranslationFilePath), {
210
287
  recursive: true
211
288
  });
212
289
  await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
@@ -216,43 +293,59 @@ async function pull({
216
293
  }
217
294
 
218
295
  /**
219
- * Uploading to the Phrase API for each language. Adding a unique namespace to each key using file path they key came from
296
+ * Uploads translations to the Phrase API for each language.
297
+ * A unique namespace is appended to each key using the file path the key came from.
220
298
  */
221
299
  async function push({
222
- branch
300
+ branch,
301
+ deleteUnusedKeys: deleteUnusedKeys$1
223
302
  }, config) {
224
303
  const allLanguageTranslations = await core.loadAllTranslations({
225
304
  fallbacks: 'none',
226
- includeNodeModules: false
305
+ includeNodeModules: false,
306
+ withTags: true
227
307
  }, config);
228
308
  trace(`Pushing translations to branch ${branch}`);
229
309
  const allLanguages = config.languages.map(v => v.name);
230
310
  await ensureBranch(branch);
231
311
  trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
232
312
  const phraseTranslations = {};
233
-
234
313
  for (const loadedTranslation of allLanguageTranslations) {
235
314
  for (const language of allLanguages) {
236
315
  const localTranslations = loadedTranslation.languages[language];
237
-
238
316
  if (!localTranslations) {
239
317
  continue;
240
318
  }
241
-
242
319
  if (!phraseTranslations[language]) {
243
320
  phraseTranslations[language] = {};
244
321
  }
245
-
322
+ const {
323
+ metadata: {
324
+ tags: sharedTags = []
325
+ }
326
+ } = loadedTranslation;
246
327
  for (const localKey of Object.keys(localTranslations)) {
247
328
  const phraseKey = core.getUniqueKey(localKey, loadedTranslation.namespace);
248
- phraseTranslations[language][phraseKey] = localTranslations[localKey];
329
+ const {
330
+ tags = [],
331
+ ...localTranslation
332
+ } = localTranslations[localKey];
333
+ if (language === config.devLanguage) {
334
+ localTranslation.tags = [...tags, ...sharedTags];
335
+ }
336
+ phraseTranslations[language][phraseKey] = localTranslation;
249
337
  }
250
338
  }
251
339
  }
252
-
253
- for (const language of allLanguages) {
254
- if (phraseTranslations[language]) {
255
- await pushTranslationsByLocale(phraseTranslations[language], language, branch);
340
+ const {
341
+ uploadIds
342
+ } = await pushTranslations(phraseTranslations, {
343
+ devLanguage: config.devLanguage,
344
+ branch
345
+ });
346
+ if (deleteUnusedKeys$1) {
347
+ for (const uploadId of uploadIds) {
348
+ await deleteUnusedKeys(uploadId, branch);
256
349
  }
257
350
  }
258
351
  }