@vocab/phrase 2.1.1 → 2.1.2-fix-messageformat-import-20250923014407

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.
@@ -1,2 +0,0 @@
1
- export { pull } from "./pull-translations.js";
2
- export { push } from "./push-translations.js";
@@ -1,8 +0,0 @@
1
- import { type UserConfig } from '@vocab/core';
2
- interface PullOptions {
3
- branch?: string;
4
- deleteUnusedKeys?: boolean;
5
- errorOnNoGlobalKeyTranslation?: boolean;
6
- }
7
- export declare function pull({ branch, errorOnNoGlobalKeyTranslation }: PullOptions, config: UserConfig): Promise<void>;
8
- export {};
@@ -1,12 +0,0 @@
1
- import { type UserConfig } from '@vocab/core';
2
- interface PushOptions {
3
- branch: string;
4
- deleteUnusedKeys?: boolean;
5
- ignore?: string[];
6
- }
7
- /**
8
- * Uploads translations to the Phrase API for each language.
9
- * A unique namespace is appended to each key using the file path the key came from.
10
- */
11
- export declare function push({ branch, deleteUnusedKeys, ignore }: PushOptions, config: UserConfig): Promise<void>;
12
- export {};
@@ -1,2 +0,0 @@
1
- export * from "./declarations/src/index.js";
2
- //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidm9jYWItcGhyYXNlLmNqcy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi9kZWNsYXJhdGlvbnMvc3JjL2luZGV4LmQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEifQ==
@@ -1,358 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var fs = require('fs');
6
- var path = require('path');
7
- var core = require('@vocab/core');
8
- var pc = require('picocolors');
9
- var debug = require('debug');
10
- var sync = require('csv-stringify/sync');
11
-
12
- function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
13
-
14
- var path__default = /*#__PURE__*/_interopDefault(path);
15
- var pc__default = /*#__PURE__*/_interopDefault(pc);
16
- var debug__default = /*#__PURE__*/_interopDefault(debug);
17
-
18
- const mkdir = fs.promises.mkdir;
19
- const writeFile = fs.promises.writeFile;
20
-
21
- const trace = debug__default["default"](`vocab:phrase`);
22
- const log = (...params) => {
23
- // eslint-disable-next-line no-console
24
- console.log(pc__default["default"].yellow('Vocab'), ...params);
25
- };
26
-
27
- function translationsToCsv(translations, devLanguage) {
28
- const languages = Object.keys(translations);
29
- const altLanguages = languages.filter(language => language !== devLanguage);
30
- const devLanguageTranslations = translations[devLanguage];
31
- const csvFilesByLanguage = Object.fromEntries(languages.map(language => [language, []]));
32
- Object.entries(devLanguageTranslations).map(([key, {
33
- message,
34
- description,
35
- tags
36
- }]) => {
37
- const sharedData = [key, description, tags === null || tags === void 0 ? void 0 : tags.join(',')];
38
- const devLanguageRow = [...sharedData, message];
39
- csvFilesByLanguage[devLanguage].push(devLanguageRow);
40
- altLanguages.map(language => {
41
- var _translations$languag;
42
- const altTranslationMessage = (_translations$languag = translations[language]) === null || _translations$languag === void 0 || (_translations$languag = _translations$languag[key]) === null || _translations$languag === void 0 ? void 0 : _translations$languag.message;
43
- if (altTranslationMessage) {
44
- csvFilesByLanguage[language].push([...sharedData, altTranslationMessage]);
45
- }
46
- });
47
- });
48
- const csvFileStrings = Object.fromEntries(Object.entries(csvFilesByLanguage)
49
- // Ensure CSV files are only created if the language has at least 1 translation
50
- .filter(([_, csvFile]) => csvFile.length > 0).map(([language, csvFile]) => {
51
- const csvFileString = sync.stringify(csvFile, {
52
- delimiter: ',',
53
- header: false
54
- });
55
- return [language, csvFileString];
56
- }));
57
-
58
- // Column indices start at 1
59
- const keyIndex = 1;
60
- const commentIndex = keyIndex + 1;
61
- const tagColumn = commentIndex + 1;
62
- const messageIndex = tagColumn + 1;
63
- return {
64
- csvFileStrings,
65
- keyIndex,
66
- messageIndex,
67
- commentIndex,
68
- tagColumn
69
- };
70
- }
71
-
72
- /* eslint-disable no-console */
73
- function _callPhrase(path, options = {}) {
74
- const phraseApiToken = process.env.PHRASE_API_TOKEN;
75
- if (!phraseApiToken) {
76
- throw new Error('Missing PHRASE_API_TOKEN');
77
- }
78
- return fetch(path, {
79
- ...options,
80
- headers: {
81
- Authorization: `token ${phraseApiToken}`,
82
- // Provide identification via User Agent as requested in https://developers.phrase.com/api/#overview--identification-via-user-agent
83
- 'User-Agent': 'Vocab Client (https://github.com/seek-oss/vocab)',
84
- ...options.headers
85
- }
86
- }).then(async response => {
87
- console.log(`${path}: ${response.status} - ${response.statusText}`);
88
- const secondsUntilLimitReset = Math.ceil(Number.parseFloat(response.headers.get('X-Rate-Limit-Reset') || '0') - Date.now() / 1000);
89
- console.log(`Rate Limit: ${response.headers.get('X-Rate-Limit-Remaining')} of ${response.headers.get('X-Rate-Limit-Limit')} remaining. (${secondsUntilLimitReset} seconds remaining)`);
90
- trace('\nLink:', response.headers.get('Link'), '\n');
91
- // Print All Headers:
92
- // console.log(Array.from(r.headers.entries()));
93
-
94
- try {
95
- var _response$headers$get;
96
- const result = await response.json();
97
- trace(`Internal Result (Length: ${result.length})\n`);
98
- 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')) {
99
- var _response$headers$get2, _response$headers$get3;
100
- 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 : [];
101
- if (!nextPageUrl) {
102
- throw new Error("Can't parse next page URL");
103
- }
104
- console.log('Results received with next page: ', nextPageUrl);
105
- const nextPageResult = await _callPhrase(nextPageUrl, options);
106
- return [...result, ...nextPageResult];
107
- }
108
- return result;
109
- } catch (e) {
110
- console.error('Unable to parse response as JSON', e);
111
- return response.text();
112
- }
113
- });
114
- }
115
- async function callPhrase(relativePath, options = {}) {
116
- const projectId = process.env.PHRASE_PROJECT_ID;
117
- if (!projectId) {
118
- throw new Error('Missing PHRASE_PROJECT_ID');
119
- }
120
- return _callPhrase(`https://api.phrase.com/v2/projects/${projectId}/${relativePath}`, options).then(result => {
121
- if (Array.isArray(result)) {
122
- console.log('Result length:', result.length);
123
- }
124
- return result;
125
- }).catch(error => {
126
- console.error(`Error calling phrase for ${relativePath}:`, error);
127
- throw Error;
128
- });
129
- }
130
- async function pullAllTranslations(branch) {
131
- const phraseResult = await callPhrase(`translations?branch=${branch}&per_page=100`);
132
- const translations = {};
133
- for (const r of phraseResult) {
134
- if (!translations[r.locale.name]) {
135
- translations[r.locale.name] = {};
136
- }
137
- translations[r.locale.name][r.key.name] = {
138
- message: r.content
139
- };
140
- }
141
- return translations;
142
- }
143
- async function pushTranslations(translationsByLanguage, {
144
- devLanguage,
145
- branch
146
- }) {
147
- const {
148
- csvFileStrings,
149
- keyIndex,
150
- commentIndex,
151
- tagColumn,
152
- messageIndex
153
- } = translationsToCsv(translationsByLanguage, devLanguage);
154
- let devLanguageUploadId = '';
155
- for (const [language, csvFileString] of Object.entries(csvFileStrings)) {
156
- const formData = new FormData();
157
- formData.append('file', new Blob([csvFileString], {
158
- type: 'text/csv'
159
- }), `${language}.translations.csv`);
160
- formData.append('file_format', 'csv');
161
- formData.append('branch', branch);
162
- formData.append('update_translations', 'true');
163
- formData.append('update_descriptions', 'true');
164
- formData.append(`locale_mapping[${language}]`, messageIndex.toString());
165
- formData.append('format_options[key_index]', keyIndex.toString());
166
- formData.append('format_options[comment_index]', commentIndex.toString());
167
- formData.append('format_options[tag_column]', tagColumn.toString());
168
- formData.append('format_options[enable_pluralization]', 'false');
169
- log(`Uploading translations for language ${language}`);
170
- const result = await callPhrase(`uploads`, {
171
- method: 'POST',
172
- body: formData
173
- });
174
- trace('Upload result:\n', result);
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
- if (language === devLanguage) {
184
- devLanguageUploadId = result.id;
185
- }
186
- }
187
- return {
188
- devLanguageUploadId
189
- };
190
- }
191
- async function deleteUnusedKeys(uploadId, branch) {
192
- const query = `unmentioned_in_upload:${uploadId}`;
193
- const {
194
- records_affected
195
- } = await callPhrase('keys', {
196
- method: 'DELETE',
197
- headers: {
198
- 'Content-Type': 'application/json'
199
- },
200
- body: JSON.stringify({
201
- branch,
202
- q: query
203
- })
204
- });
205
- log('Successfully deleted', records_affected, 'unused keys from branch', branch);
206
- }
207
- async function ensureBranch(branch) {
208
- await callPhrase(`branches`, {
209
- method: 'POST',
210
- headers: {
211
- 'Content-Type': 'application/json'
212
- },
213
- body: JSON.stringify({
214
- name: branch
215
- })
216
- });
217
- log('Created branch:', branch);
218
- }
219
-
220
- async function pull({
221
- branch = 'local-development',
222
- errorOnNoGlobalKeyTranslation
223
- }, config) {
224
- trace(`Pulling translations from branch ${branch}`);
225
- await ensureBranch(branch);
226
- const alternativeLanguages = core.getAltLanguages(config);
227
- const allPhraseTranslations = await pullAllTranslations(branch);
228
- trace(`Pulling translations from Phrase for languages ${config.devLanguage} and ${alternativeLanguages.join(', ')}`);
229
- const phraseLanguages = Object.keys(allPhraseTranslations);
230
- trace(`Found Phrase translations for languages ${phraseLanguages.join(', ')}`);
231
- if (!phraseLanguages.includes(config.devLanguage)) {
232
- 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.`);
233
- }
234
- const allVocabTranslations = await core.loadAllTranslations({
235
- fallbacks: 'none',
236
- includeNodeModules: false,
237
- withTags: true
238
- }, config);
239
- for (const loadedTranslation of allVocabTranslations) {
240
- const devTranslations = loadedTranslation.languages[config.devLanguage];
241
- if (!devTranslations) {
242
- throw new Error('No dev language translations loaded');
243
- }
244
- const defaultValues = {
245
- ...devTranslations
246
- };
247
- const localKeys = Object.keys(defaultValues);
248
- for (const key of localKeys) {
249
- var _defaultValues$key$gl;
250
- defaultValues[key] = {
251
- ...defaultValues[key],
252
- ...allPhraseTranslations[config.devLanguage][(_defaultValues$key$gl = defaultValues[key].globalKey) !== null && _defaultValues$key$gl !== void 0 ? _defaultValues$key$gl : core.getUniqueKey(key, loadedTranslation.namespace)]
253
- };
254
- }
255
-
256
- // Only write a `_meta` field if necessary
257
- if (Object.keys(loadedTranslation.metadata).length > 0) {
258
- defaultValues._meta = loadedTranslation.metadata;
259
- }
260
- await writeFile(loadedTranslation.filePath, `${JSON.stringify(defaultValues, null, 2)}\n`);
261
- for (const alternativeLanguage of alternativeLanguages) {
262
- if (alternativeLanguage in allPhraseTranslations) {
263
- const altTranslations = {
264
- ...loadedTranslation.languages[alternativeLanguage]
265
- };
266
- const phraseAltTranslations = allPhraseTranslations[alternativeLanguage];
267
- for (const key of localKeys) {
268
- var _defaultValues$key$gl2, _phraseAltTranslation;
269
- const phraseKey = (_defaultValues$key$gl2 = defaultValues[key].globalKey) !== null && _defaultValues$key$gl2 !== void 0 ? _defaultValues$key$gl2 : core.getUniqueKey(key, loadedTranslation.namespace);
270
- const phraseTranslationMessage = (_phraseAltTranslation = phraseAltTranslations[phraseKey]) === null || _phraseAltTranslation === void 0 ? void 0 : _phraseAltTranslation.message;
271
- if (!phraseTranslationMessage) {
272
- trace(`Missing translation. No translation for key ${key} in phrase as ${phraseKey} in language ${alternativeLanguage}.`);
273
- if (errorOnNoGlobalKeyTranslation && defaultValues[key].globalKey) {
274
- throw new Error(`Missing translation for global key ${key} in language ${alternativeLanguage}`);
275
- }
276
- continue;
277
- }
278
- altTranslations[key] = {
279
- ...altTranslations[key],
280
- message: phraseTranslationMessage
281
- };
282
- }
283
- const altTranslationFilePath = core.getAltLanguageFilePath(loadedTranslation.filePath, alternativeLanguage);
284
- await mkdir(path__default["default"].dirname(altTranslationFilePath), {
285
- recursive: true
286
- });
287
- await writeFile(altTranslationFilePath, `${JSON.stringify(altTranslations, null, 2)}\n`);
288
- }
289
- }
290
- }
291
- }
292
-
293
- /**
294
- * Uploads translations to the Phrase API for each language.
295
- * A unique namespace is appended to each key using the file path the key came from.
296
- */
297
- async function push({
298
- branch,
299
- deleteUnusedKeys: deleteUnusedKeys$1,
300
- ignore
301
- }, config) {
302
- if (ignore) {
303
- trace(`ignoring files on paths: ${ignore.join(', ')}`);
304
- }
305
- const allLanguageTranslations = await core.loadAllTranslations({
306
- fallbacks: 'none',
307
- includeNodeModules: false,
308
- withTags: true
309
- }, {
310
- ...config,
311
- ignore: [...(config.ignore || []), ...(ignore || [])]
312
- });
313
- trace(`Pushing translations to branch ${branch}`);
314
- const allLanguages = config.languages.map(v => v.name);
315
- await ensureBranch(branch);
316
- trace(`Pushing translations to phrase for languages ${allLanguages.join(', ')}`);
317
- const phraseTranslations = {};
318
- for (const loadedTranslation of allLanguageTranslations) {
319
- for (const language of allLanguages) {
320
- const localTranslations = loadedTranslation.languages[language];
321
- if (!localTranslations) {
322
- continue;
323
- }
324
- if (!phraseTranslations[language]) {
325
- phraseTranslations[language] = {};
326
- }
327
- const {
328
- metadata: {
329
- tags: sharedTags = []
330
- }
331
- } = loadedTranslation;
332
- for (const localKey of Object.keys(localTranslations)) {
333
- const {
334
- tags = [],
335
- ...localTranslation
336
- } = localTranslations[localKey];
337
- if (language === config.devLanguage) {
338
- localTranslation.tags = [...tags, ...sharedTags];
339
- }
340
- const globalKey = loadedTranslation.languages[config.devLanguage][localKey].globalKey;
341
- const phraseKey = globalKey !== null && globalKey !== void 0 ? globalKey : core.getUniqueKey(localKey, loadedTranslation.namespace);
342
- phraseTranslations[language][phraseKey] = localTranslation;
343
- }
344
- }
345
- }
346
- const {
347
- devLanguageUploadId
348
- } = await pushTranslations(phraseTranslations, {
349
- devLanguage: config.devLanguage,
350
- branch
351
- });
352
- if (deleteUnusedKeys$1) {
353
- await deleteUnusedKeys(devLanguageUploadId, branch);
354
- }
355
- }
356
-
357
- exports.pull = pull;
358
- exports.push = push;
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- if (process.env.NODE_ENV === "production") {
4
- module.exports = require("./vocab-phrase.cjs.prod.js");
5
- } else {
6
- module.exports = require("./vocab-phrase.cjs.dev.js");
7
- }