@vocab/phrase 0.0.0-package-files-20231142931 → 0.0.0-push-split-translation-files-20230508031119

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