@vocab/phrase 1.1.0 → 1.2.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.
@@ -5,6 +5,7 @@ import FormData from 'form-data';
5
5
  import fetch from 'node-fetch';
6
6
  import chalk from 'chalk';
7
7
  import debug from 'debug';
8
+ import { stringify } from 'csv-stringify/sync';
8
9
 
9
10
  const mkdir = promises.mkdir;
10
11
  const writeFile = promises.writeFile;
@@ -15,6 +16,44 @@ const log = (...params) => {
15
16
  console.log(chalk.yellow('Vocab'), ...params);
16
17
  };
17
18
 
19
+ function translationsToCsv(translations, devLanguage) {
20
+ const languages = Object.keys(translations);
21
+ const altLanguages = languages.filter(language => language !== devLanguage); // Ensure languages are ordered for locale mapping
22
+
23
+ const orderedLanguages = [devLanguage, ...altLanguages];
24
+ const devLanguageTranslations = translations[devLanguage];
25
+ const csv = Object.entries(devLanguageTranslations).map(([key, {
26
+ message,
27
+ description,
28
+ tags
29
+ }]) => {
30
+ const altTranslationMessages = altLanguages.map(language => {
31
+ var _translations$languag, _translations$languag2;
32
+
33
+ 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;
34
+ });
35
+ return [message, ...altTranslationMessages, key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
36
+ });
37
+ const csvString = stringify(csv, {
38
+ delimiter: ',',
39
+ header: false
40
+ }); // Column indices start at 1
41
+
42
+ const localeMapping = Object.fromEntries(orderedLanguages.map((language, index) => [language, index + 1]));
43
+ const keyIndex = orderedLanguages.length + 1;
44
+ const commentIndex = keyIndex + 1;
45
+ const tagColumn = commentIndex + 1;
46
+ return {
47
+ csvString,
48
+ localeMapping,
49
+ keyIndex,
50
+ commentIndex,
51
+ tagColumn
52
+ };
53
+ }
54
+
55
+ /* eslint-disable no-console */
56
+
18
57
  function _callPhrase(path, options = {}) {
19
58
  const phraseApiToken = process.env.PHRASE_API_TOKEN;
20
59
 
@@ -97,31 +136,56 @@ async function pullAllTranslations(branch) {
97
136
 
98
137
  return translations;
99
138
  }
100
- async function pushTranslationsByLocale(contents, locale, branch) {
139
+ async function pushTranslations(translationsByLanguage, {
140
+ devLanguage,
141
+ branch
142
+ }) {
101
143
  const formData = new FormData();
102
- const fileContents = Buffer.from(JSON.stringify(contents));
144
+ const {
145
+ csvString,
146
+ localeMapping,
147
+ keyIndex,
148
+ commentIndex,
149
+ tagColumn
150
+ } = translationsToCsv(translationsByLanguage, devLanguage);
151
+ const fileContents = Buffer.from(csvString);
103
152
  formData.append('file', fileContents, {
104
- contentType: 'application/json',
105
- filename: `${locale}.json`
153
+ contentType: 'text/csv',
154
+ filename: 'translations.csv'
106
155
  });
107
- formData.append('file_format', 'json');
108
- formData.append('locale_id', locale);
156
+ formData.append('file_format', 'csv');
109
157
  formData.append('branch', branch);
110
158
  formData.append('update_translations', 'true');
111
- log('Starting to upload:', locale, '\n');
112
- const {
113
- id
114
- } = await callPhrase(`uploads`, {
159
+
160
+ for (const [locale, index] of Object.entries(localeMapping)) {
161
+ formData.append(`locale_mapping[${locale}]`, index);
162
+ }
163
+
164
+ formData.append('format_options[key_index]', keyIndex);
165
+ formData.append('format_options[comment_index]', commentIndex);
166
+ formData.append('format_options[tag_column]', tagColumn);
167
+ formData.append('format_options[enable_pluralization]', 'false');
168
+ log('Uploading translations');
169
+ const result = await callPhrase(`uploads`, {
115
170
  method: 'POST',
116
171
  body: formData
117
172
  });
118
- log('Upload ID:', id, '\n');
119
- log('Successfully Uploaded:', locale, '\n');
173
+ trace('Upload result:\n', result);
174
+
175
+ if (result && 'id' in result) {
176
+ log('Upload ID:', result.id, '\n');
177
+ log('Successfully Uploaded\n');
178
+ } else {
179
+ log(`Error uploading: ${result === null || result === void 0 ? void 0 : result.message}\n`);
180
+ log('Response:', result);
181
+ throw new Error('Error uploading');
182
+ }
183
+
120
184
  return {
121
- uploadId: id
185
+ uploadId: result.id
122
186
  };
123
187
  }
124
- async function deleteUnusedKeys(uploadId, locale, branch) {
188
+ async function deleteUnusedKeys(uploadId, branch) {
125
189
  const query = `unmentioned_in_upload:${uploadId}`;
126
190
  const {
127
191
  records_affected
@@ -132,7 +196,6 @@ async function deleteUnusedKeys(uploadId, locale, branch) {
132
196
  },
133
197
  body: JSON.stringify({
134
198
  branch,
135
- locale_id: locale,
136
199
  q: query
137
200
  })
138
201
  });
@@ -168,7 +231,8 @@ async function pull({
168
231
 
169
232
  const allVocabTranslations = await loadAllTranslations({
170
233
  fallbacks: 'none',
171
- includeNodeModules: false
234
+ includeNodeModules: false,
235
+ withTags: true
172
236
  }, config);
173
237
 
174
238
  for (const loadedTranslation of allVocabTranslations) {
@@ -186,6 +250,11 @@ async function pull({
186
250
  defaultValues[key] = { ...defaultValues[key],
187
251
  ...allPhraseTranslations[config.devLanguage][getUniqueKey(key, loadedTranslation.namespace)]
188
252
  };
253
+ } // Only write a `_meta` field if necessary
254
+
255
+
256
+ if (Object.keys(loadedTranslation.metadata).length > 0) {
257
+ defaultValues._meta = loadedTranslation.metadata;
189
258
  }
190
259
 
191
260
  await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
@@ -223,7 +292,8 @@ async function pull({
223
292
  }
224
293
 
225
294
  /**
226
- * Uploading to the Phrase API for each language. Adding a unique namespace to each key using file path they key came from
295
+ * Uploads translations to the Phrase API for each language.
296
+ * A unique namespace is appended to each key using the file path the key came from.
227
297
  */
228
298
  async function push({
229
299
  branch,
@@ -231,7 +301,8 @@ async function push({
231
301
  }, config) {
232
302
  const allLanguageTranslations = await loadAllTranslations({
233
303
  fallbacks: 'none',
234
- includeNodeModules: false
304
+ includeNodeModules: false,
305
+ withTags: true
235
306
  }, config);
236
307
  trace(`Pushing translations to branch ${branch}`);
237
308
  const allLanguages = config.languages.map(v => v.name);
@@ -251,23 +322,37 @@ async function push({
251
322
  phraseTranslations[language] = {};
252
323
  }
253
324
 
325
+ const {
326
+ metadata: {
327
+ tags: sharedTags = []
328
+ }
329
+ } = loadedTranslation;
330
+
254
331
  for (const localKey of Object.keys(localTranslations)) {
255
332
  const phraseKey = getUniqueKey(localKey, loadedTranslation.namespace);
256
- phraseTranslations[language][phraseKey] = localTranslations[localKey];
333
+ const {
334
+ tags = [],
335
+ ...localTranslation
336
+ } = localTranslations[localKey];
337
+
338
+ if (language === config.devLanguage) {
339
+ localTranslation.tags = [...tags, ...sharedTags];
340
+ }
341
+
342
+ phraseTranslations[language][phraseKey] = localTranslation;
257
343
  }
258
344
  }
259
345
  }
260
346
 
261
- for (const language of allLanguages) {
262
- if (phraseTranslations[language]) {
263
- const {
264
- uploadId
265
- } = await pushTranslationsByLocale(phraseTranslations[language], language, branch);
347
+ const {
348
+ uploadId
349
+ } = await pushTranslations(phraseTranslations, {
350
+ devLanguage: config.devLanguage,
351
+ branch
352
+ });
266
353
 
267
- if (deleteUnusedKeys$1) {
268
- await deleteUnusedKeys(uploadId, language, branch);
269
- }
270
- }
354
+ if (deleteUnusedKeys$1) {
355
+ await deleteUnusedKeys(uploadId, branch);
271
356
  }
272
357
  }
273
358
 
package/package.json CHANGED
@@ -1,19 +1,23 @@
1
1
  {
2
2
  "name": "@vocab/phrase",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "main": "dist/vocab-phrase.cjs.js",
5
5
  "module": "dist/vocab-phrase.esm.js",
6
6
  "author": "SEEK",
7
7
  "license": "MIT",
8
8
  "dependencies": {
9
- "@vocab/core": "^1.0.0",
10
- "@vocab/types": "^1.0.0",
9
+ "@vocab/core": "^1.2.0",
10
+ "@vocab/types": "^1.1.2",
11
11
  "chalk": "^4.1.0",
12
+ "csv-stringify": "^6.2.3",
12
13
  "debug": "^4.3.1",
13
14
  "form-data": "^3.0.0",
14
15
  "node-fetch": "^2.6.1"
15
16
  },
16
17
  "devDependencies": {
17
18
  "@types/node-fetch": "^2.5.7"
18
- }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ]
19
23
  }
package/CHANGELOG.md DELETED
@@ -1,145 +0,0 @@
1
- # @vocab/phrase
2
-
3
- ## 1.1.0
4
-
5
- ### Minor Changes
6
-
7
- - [`66ed22c`](https://github.com/seek-oss/vocab/commit/66ed22cac6f89018d5fd69fd6f6408e090e1a382) [#93](https://github.com/seek-oss/vocab/pull/93) Thanks [@askoufis](https://github.com/askoufis)! - Add an optional `deleteUnusedKeys` flag to the `push` function. If set to `true`, unused keys will be deleted from Phrase after translations are pushed.
8
-
9
- **EXAMPLE USAGE**:
10
-
11
- ```js
12
- import { push } from '@vocab/phrase';
13
-
14
- const vocabConfig = {
15
- devLanguage: 'en',
16
- language: ['en', 'fr'],
17
- };
18
-
19
- await push({ branch: 'myBranch', deleteUnusedKeys: true }, vocabConfig);
20
- ```
21
-
22
- ### Patch Changes
23
-
24
- - [`159d559`](https://github.com/seek-oss/vocab/commit/159d559c87c66c3e91c707fb45a1f67ebec07b4d) [#91](https://github.com/seek-oss/vocab/pull/91) Thanks [@askoufis](https://github.com/askoufis)! - Improve error message when Phrase doesn't return any translations for the dev language
25
-
26
- ## 1.0.1
27
-
28
- ### Patch Changes
29
-
30
- - [`20eec77`](https://github.com/seek-oss/vocab/commit/20eec770705d05048ad8b32575cb92720b887f5b) [#76](https://github.com/seek-oss/vocab/pull/76) Thanks [@askoufis](https://github.com/askoufis)! - `vocab pull` no longer errors when phrase returns no translations for a configured language
31
-
32
- ## 1.0.0
33
-
34
- ### Major Changes
35
-
36
- - [`3031054`](https://github.com/seek-oss/vocab/commit/303105440851db6126f0606e1607745b27dd981c) [#51](https://github.com/seek-oss/vocab/pull/51) Thanks [@jahredhope](https://github.com/jahredhope)! - Release v1.0.0
37
-
38
- Release Vocab as v1.0.0 to signify a stable API and support future [semver versioning](https://semver.org/) releases.
39
-
40
- Vocab has seen a lot of iteration and changes since it was first published on 20 November 2020. We are now confident with the API and believe Vocab is ready for common use.
41
-
42
- ### Patch Changes
43
-
44
- - Updated dependencies [[`0074382`](https://github.com/seek-oss/vocab/commit/007438273ef70f5d5ded45777933651ad8df36f6), [`3031054`](https://github.com/seek-oss/vocab/commit/303105440851db6126f0606e1607745b27dd981c)]:
45
- - @vocab/core@1.0.0
46
- - @vocab/types@1.0.0
47
-
48
- ## 0.0.11
49
-
50
- ### Patch Changes
51
-
52
- - Updated dependencies [[`5b1fdc0`](https://github.com/seek-oss/vocab/commit/5b1fdc019522b12e7ef94b2fec57b54a9310d41c)]:
53
- - @vocab/core@0.0.11
54
- - @vocab/types@0.0.9
55
-
56
- ## 0.0.10
57
-
58
- ### Patch Changes
59
-
60
- - Updated dependencies [[`7c96a14`](https://github.com/seek-oss/vocab/commit/7c96a142f602132d38c1df1a47a1f4657dc5c94c)]:
61
- - @vocab/core@0.0.10
62
-
63
- ## 0.0.9
64
-
65
- ### Patch Changes
66
-
67
- - Updated dependencies [[`3034bd3`](https://github.com/seek-oss/vocab/commit/3034bd3de610a9d1f3bfbd8caefa27064dee2710), [`c110745`](https://github.com/seek-oss/vocab/commit/c110745b79df1a8ade6b1d8a49e798b04a7b95e1)]:
68
- - @vocab/core@0.0.9
69
-
70
- ## 0.0.8
71
-
72
- ### Patch Changes
73
-
74
- - Updated dependencies [[`f2fca67`](https://github.com/seek-oss/vocab/commit/f2fca679c66ae65405a0aa24f0a0e472026aad0d)]:
75
- - @vocab/core@0.0.8
76
- - @vocab/types@0.0.8
77
-
78
- ## 0.0.7
79
-
80
- ### Patch Changes
81
-
82
- - [`283bcad`](https://github.com/seek-oss/vocab/commit/283bcada06e622ab14ed891743ed3f55cf09e245) [#33](https://github.com/seek-oss/vocab/pull/33) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Move all vocab files to single directory with configurable suffix
83
-
84
- - Updated dependencies [[`283bcad`](https://github.com/seek-oss/vocab/commit/283bcada06e622ab14ed891743ed3f55cf09e245), [`ad0d240`](https://github.com/seek-oss/vocab/commit/ad0d2404545ded8e11621eae8f29467ff3352366), [`f3992ef`](https://github.com/seek-oss/vocab/commit/f3992efbf08939ebf853fac650a49cc46dc51dfb), [`f3992ef`](https://github.com/seek-oss/vocab/commit/f3992efbf08939ebf853fac650a49cc46dc51dfb)]:
85
- - @vocab/core@0.0.7
86
- - @vocab/types@0.0.7
87
-
88
- ## 0.0.6
89
-
90
- ### Patch Changes
91
-
92
- - [`80a46c0`](https://github.com/seek-oss/vocab/commit/80a46c01a55408675f5822c3618519f80136c3ab) [#27](https://github.com/seek-oss/vocab/pull/27) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Add `ignore` config for ignoring files/folders from cli scripts
93
-
94
- * [`80a46c0`](https://github.com/seek-oss/vocab/commit/80a46c01a55408675f5822c3618519f80136c3ab) [#27](https://github.com/seek-oss/vocab/pull/27) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Ignore node_modules from push, pull and compile scripts
95
-
96
- * Updated dependencies [[`80a46c0`](https://github.com/seek-oss/vocab/commit/80a46c01a55408675f5822c3618519f80136c3ab), [`80a46c0`](https://github.com/seek-oss/vocab/commit/80a46c01a55408675f5822c3618519f80136c3ab)]:
97
- - @vocab/core@0.0.6
98
- - @vocab/types@0.0.6
99
-
100
- ## 0.0.5
101
-
102
- ### Patch Changes
103
-
104
- - Updated dependencies [[`371ed16`](https://github.com/seek-oss/vocab/commit/371ed16a232a04dab13afa7e2b352dfb6724eea4), [`c222d68`](https://github.com/seek-oss/vocab/commit/c222d68a3c0c24723a338eccb959798881f6a118)]:
105
- - @vocab/core@0.0.5
106
-
107
- ## 0.0.4
108
-
109
- ### Patch Changes
110
-
111
- - [`5f5c581`](https://github.com/seek-oss/vocab/commit/5f5c581a65bff28729ee19e1ec0bdea488a9d6c2) [#19](https://github.com/seek-oss/vocab/pull/19) Thanks [@jahredhope](https://github.com/jahredhope)! - Compile useable TypeScript importable files with `vocab compile`.
112
-
113
- The new `vocab compile` step replaces `vocab generate-types` in creating a fully functional **translations.ts** file.
114
-
115
- This allows vocab to be used **without the Webpack Plugin**, however use of the plugin is still heavily advised to ensure optimal loading of translation content on the web.
116
-
117
- Support for unit testing is now better than ever! The newly created **translations.ts** means your unit test code will see the same code as available while rendering.
118
-
119
- See the [documentation](https://github.com/seek-oss/vocab) for further usage details.
120
-
121
- * [`02f943c`](https://github.com/seek-oss/vocab/commit/02f943ca892913b41f9e4720a72400777cf14b3d) [#17](https://github.com/seek-oss/vocab/pull/17) Thanks [@jahredhope](https://github.com/jahredhope)! - Add additional debug traces
122
-
123
- * Updated dependencies [[`5f5c581`](https://github.com/seek-oss/vocab/commit/5f5c581a65bff28729ee19e1ec0bdea488a9d6c2), [`02f943c`](https://github.com/seek-oss/vocab/commit/02f943ca892913b41f9e4720a72400777cf14b3d)]:
124
- - @vocab/core@0.0.4
125
- - @vocab/types@0.0.5
126
-
127
- ## 0.0.3
128
-
129
- ### Patch Changes
130
-
131
- - [`08de30d`](https://github.com/seek-oss/vocab/commit/08de30d338c2a5ebdcf14da7c736dddf22e7ca9e) [#14](https://github.com/seek-oss/vocab/pull/14) Thanks [@mattcompiles](https://github.com/mattcompiles)! - Add ability to override files namespace with \$namespace
132
-
133
- * [`26b52f4`](https://github.com/seek-oss/vocab/commit/26b52f4878ded440841e08c858bdc9e685500c2a) [#16](https://github.com/seek-oss/vocab/pull/16) Thanks [@jahredhope](https://github.com/jahredhope)! - Enable debugging with DEBUG environment variable
134
-
135
- * Updated dependencies [[`08de30d`](https://github.com/seek-oss/vocab/commit/08de30d338c2a5ebdcf14da7c736dddf22e7ca9e), [`ed6cf40`](https://github.com/seek-oss/vocab/commit/ed6cf408973f2e9c4d07a71fcb52f40294ebaf65), [`26b52f4`](https://github.com/seek-oss/vocab/commit/26b52f4878ded440841e08c858bdc9e685500c2a), [`b5a5a05`](https://github.com/seek-oss/vocab/commit/b5a5a05a5bb87b48e6e9160af75f555728143ea2)]:
136
- - @vocab/core@0.0.3
137
- - @vocab/types@0.0.4
138
-
139
- ## 0.0.2
140
-
141
- ### Patch Changes
142
-
143
- - Updated dependencies [[`4710f34`](https://github.com/seek-oss/vocab/commit/4710f341f2827643e3eff69ef7e26d44ec6e8a2b), [`4710f34`](https://github.com/seek-oss/vocab/commit/4710f341f2827643e3eff69ef7e26d44ec6e8a2b)]:
144
- - @vocab/types@0.0.3
145
- - @vocab/core@0.0.2
package/src/file.ts DELETED
@@ -1,4 +0,0 @@
1
- import { promises as fs } from 'fs';
2
-
3
- export const mkdir = fs.mkdir;
4
- export const writeFile = fs.writeFile;
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export { pull } from './pull-translations';
2
- export { push } from './push-translations';
package/src/logger.ts DELETED
@@ -1,9 +0,0 @@
1
- import chalk from 'chalk';
2
- import debug from 'debug';
3
-
4
- export const trace = debug(`vocab:phrase`);
5
-
6
- export const log = (...params: unknown[]) => {
7
- // eslint-disable-next-line no-console
8
- console.log(chalk.yellow('Vocab'), ...params);
9
- };
package/src/phrase-api.ts DELETED
@@ -1,181 +0,0 @@
1
- import FormData from 'form-data';
2
- import { TranslationsByKey } from './../../types/src/index';
3
- /* eslint-disable no-console */
4
- import type { TranslationsByLanguage } from '@vocab/types';
5
- import fetch from 'node-fetch';
6
- import { log, trace } from './logger';
7
-
8
- function _callPhrase(path: string, options: Parameters<typeof fetch>[1] = {}) {
9
- const phraseApiToken = process.env.PHRASE_API_TOKEN;
10
-
11
- if (!phraseApiToken) {
12
- throw new Error('Missing PHRASE_API_TOKEN');
13
- }
14
-
15
- return fetch(path, {
16
- ...options,
17
- headers: {
18
- Authorization: `token ${phraseApiToken}`,
19
- // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
20
- 'User-Agent': 'SEEK Demo Candidate App (jhope@seek.com.au)',
21
- ...options.headers,
22
- },
23
- }).then(async (response) => {
24
- console.log(`${path}: ${response.status} - ${response.statusText}`);
25
- console.log(
26
- `Rate Limit: ${response.headers.get(
27
- 'X-Rate-Limit-Remaining',
28
- )} of ${response.headers.get(
29
- 'X-Rate-Limit-Limit',
30
- )} remaining. (${response.headers.get(
31
- 'X-Rate-Limit-Reset',
32
- )} seconds remaining})`,
33
- );
34
- trace('\nLink:', response.headers.get('Link'), '\n');
35
- // Print All Headers:
36
- // console.log(Array.from(r.headers.entries()));
37
-
38
- try {
39
- const result = await response.json();
40
-
41
- trace(`Internal Result (Length: ${result.length})\n`);
42
-
43
- if (
44
- (!options.method || options.method === 'GET') &&
45
- response.headers.get('Link')?.includes('rel=next')
46
- ) {
47
- const [, nextPageUrl] =
48
- response.headers.get('Link')?.match(/<([^>]*)>; rel=next/) ?? [];
49
-
50
- if (!nextPageUrl) {
51
- throw new Error("Can't parse next page URL");
52
- }
53
-
54
- console.log('Results received with next page: ', nextPageUrl);
55
-
56
- const nextPageResult = (await _callPhrase(nextPageUrl, options)) as any;
57
-
58
- return [...result, ...nextPageResult];
59
- }
60
-
61
- return result;
62
- } catch (e) {
63
- console.error('Unable to parse response as JSON', e);
64
- return response.text();
65
- }
66
- });
67
- }
68
-
69
- export async function callPhrase<T = any>(
70
- relativePath: string,
71
- options: Parameters<typeof fetch>[1] = {},
72
- ): Promise<T> {
73
- const projectId = process.env.PHRASE_PROJECT_ID;
74
-
75
- if (!projectId) {
76
- throw new Error('Missing PHRASE_PROJECT_ID');
77
- }
78
- return _callPhrase(
79
- `https://api.phrase.com/v2/projects/${projectId}/${relativePath}`,
80
- options,
81
- )
82
- .then((result) => {
83
- if (Array.isArray(result)) {
84
- console.log('Result length:', result.length);
85
- }
86
- return result;
87
- })
88
- .catch((error) => {
89
- console.error(`Error calling phrase for ${relativePath}:`, error);
90
- throw Error;
91
- });
92
- }
93
-
94
- export async function pullAllTranslations(
95
- branch: string,
96
- ): Promise<TranslationsByLanguage> {
97
- const phraseResult = await callPhrase<
98
- Array<{
99
- key: { name: string };
100
- locale: { code: string };
101
- content: string;
102
- }>
103
- >(`translations?branch=${branch}&per_page=100`);
104
-
105
- const translations: TranslationsByLanguage = {};
106
-
107
- for (const r of phraseResult) {
108
- if (!translations[r.locale.code]) {
109
- translations[r.locale.code] = {};
110
- }
111
- translations[r.locale.code][r.key.name] = { message: r.content };
112
- }
113
-
114
- return translations;
115
- }
116
-
117
- export async function pushTranslationsByLocale(
118
- contents: TranslationsByKey,
119
- locale: string,
120
- branch: string,
121
- ) {
122
- const formData = new FormData();
123
- const fileContents = Buffer.from(JSON.stringify(contents));
124
- formData.append('file', fileContents, {
125
- contentType: 'application/json',
126
- filename: `${locale}.json`,
127
- });
128
-
129
- formData.append('file_format', 'json');
130
- formData.append('locale_id', locale);
131
- formData.append('branch', branch);
132
- formData.append('update_translations', 'true');
133
-
134
- log('Starting to upload:', locale, '\n');
135
-
136
- const { id } = await callPhrase<{ id: string }>(`uploads`, {
137
- method: 'POST',
138
- body: formData,
139
- });
140
- log('Upload ID:', id, '\n');
141
- log('Successfully Uploaded:', locale, '\n');
142
-
143
- return { uploadId: id };
144
- }
145
-
146
- export async function deleteUnusedKeys(
147
- uploadId: string,
148
- locale: string,
149
- branch: string,
150
- ) {
151
- const query = `unmentioned_in_upload:${uploadId}`;
152
- const { records_affected } = await callPhrase<{ records_affected: number }>(
153
- 'keys',
154
- {
155
- method: 'DELETE',
156
- headers: {
157
- 'Content-Type': 'application/json',
158
- },
159
- body: JSON.stringify({ branch, locale_id: locale, q: query }),
160
- },
161
- );
162
-
163
- log(
164
- 'Successfully deleted',
165
- records_affected,
166
- 'unused keys from branch',
167
- branch,
168
- );
169
- }
170
-
171
- export async function ensureBranch(branch: string) {
172
- await callPhrase(`branches`, {
173
- method: 'POST',
174
- headers: {
175
- 'Content-Type': 'application/json',
176
- },
177
- body: JSON.stringify({ name: branch }),
178
- });
179
-
180
- log('Created branch:', branch);
181
- }