@shipi18n/cli 1.1.3 → 1.1.4

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/README.md CHANGED
@@ -26,6 +26,7 @@ Command-line tool for translating locale files with [Shipi18n](https://shipi18n.
26
26
  - ✅ **Placeholder preservation** - Keep `{name}`, `{{value}}`, `%s`, etc. intact
27
27
  - ✅ **Key-based pricing** - 100 free translation keys (unlimited characters!)
28
28
  - ✅ **Language limits enforced** - FREE: 3 languages, STARTER: 10, PRO: unlimited
29
+ - ✅ **ZIP output** - Bundle translations into a single downloadable ZIP file
29
30
  - ✅ **Config file support** - Save settings in `~/.shipi18n/config.yml`
30
31
  - ✅ **Translation Memory** - Manage keys with `shipi18n keys` commands
31
32
  - ✅ **Beautiful output** - Colored, formatted terminal output
@@ -104,6 +105,11 @@ shipi18n translate <input> [options]
104
105
  - `preserve` - Keep HTML tags and translate text between them
105
106
  - `--no-fallback` - Disable fallback to source for missing translations
106
107
  - `--no-regional-fallback` - Disable regional fallback (e.g., pt-BR → pt)
108
+ - `-i, --incremental` - Only translate new/missing keys (skip existing translations)
109
+ - `--skip-keys <keys>` - Keys to skip from translation (comma-separated exact paths)
110
+ - `--skip-paths <patterns>` - Path patterns to skip (comma-separated, supports wildcards like `nav.*`)
111
+ - `--context-file <path>` - JSON file with context annotations for disambiguation
112
+ - `--zip [filename]` - Output translations as a single ZIP file (default: `translations.zip`)
107
113
 
108
114
  **Examples:**
109
115
 
@@ -125,6 +131,23 @@ shipi18n translate en.json --target es,pt-BR,zh-TW
125
131
 
126
132
  # Disable fallback (strict mode - fail if translation missing)
127
133
  shipi18n translate en.json --target es --no-fallback
134
+
135
+ # Skip specific keys from translation (e.g., US state names, brand names)
136
+ shipi18n translate en.json --target es --skip-keys "states.CA,states.NY,company.name"
137
+
138
+ # Skip keys using glob patterns (e.g., all states, all config secrets)
139
+ shipi18n translate en.json --target es --skip-paths "states.*,config.*.secret"
140
+
141
+ # Combined - skip exact keys and patterns
142
+ shipi18n translate en.json --target es,fr \
143
+ --skip-keys "brandName" \
144
+ --skip-paths "states.*,internal.*"
145
+
146
+ # Output as ZIP file (default name: translations.zip)
147
+ shipi18n translate en.json --target es,fr,de --zip
148
+
149
+ # Output as ZIP with custom filename
150
+ shipi18n translate en.json --target es,fr,de --zip my-translations.zip
128
151
  ```
129
152
 
130
153
  ### Fallback Behavior
@@ -163,6 +186,109 @@ shipi18n translate en.json --target es --no-fallback
163
186
  shipi18n translate en.json --target pt-BR --no-regional-fallback
164
187
  ```
165
188
 
189
+ ### Skipping Keys
190
+
191
+ Exclude specific keys or patterns from translation - useful for brand names, US state codes, or config values that should stay in English:
192
+
193
+ ```bash
194
+ # Skip exact key paths
195
+ shipi18n translate en.json --target es --skip-keys "company.name,legal.terms"
196
+
197
+ # Skip using glob patterns
198
+ shipi18n translate en.json --target es --skip-paths "states.*,config.*.internal"
199
+ ```
200
+
201
+ **Pattern Matching:**
202
+ | Pattern | Matches |
203
+ |---------|---------|
204
+ | `states.CA` | Exact path only |
205
+ | `states.*` | `states.CA`, `states.NY`, etc. (single level) |
206
+ | `config.*.secret` | `config.api.secret`, `config.db.secret` |
207
+ | `**.internal` | Any path ending with `.internal` |
208
+
209
+ **Example output with skipped keys:**
210
+ ```
211
+ ✓ Translated 45 keys to 2 languages!
212
+ ℹ Skipped 5 key(s) from translation:
213
+ • states.CA
214
+ • states.NY
215
+ • states.TX
216
+ • company.name
217
+ • config.api.secret
218
+
219
+ ✨ Successfully translated 2 files!
220
+ ```
221
+
222
+ ### Context Annotations
223
+
224
+ Improve translation quality for ambiguous words by providing context hints:
225
+
226
+ ```bash
227
+ # Create a context file
228
+ echo '{"close": "button - dismiss window", "address": "form field - location"}' > context.json
229
+
230
+ # Translate with context
231
+ shipi18n translate en.json --target es --context-file context.json
232
+ ```
233
+
234
+ **Example context.json:**
235
+ ```json
236
+ {
237
+ "close": "button label - dismiss/shut a dialog",
238
+ "address": "form field - physical location/street address",
239
+ "post": "verb - publish content"
240
+ }
241
+ ```
242
+
243
+ **Result:** "close" → "Cerrar" (not "Cerca"), "address" → "Dirección" (not "Dirigirse")
244
+
245
+ ### Legal Content Warning
246
+
247
+ The CLI automatically warns when translating keys that may contain legal content:
248
+
249
+ ```
250
+ ⚠️ Legal content detected - review these keys:
251
+ • terms_of_service
252
+ • privacy_policy
253
+ • disclaimer
254
+ Machine-translated legal text may not be legally binding.
255
+ ```
256
+
257
+ **Detected patterns:** terms, privacy, disclaimer, legal, tos, eula, copyright, license, gdpr, cookie_policy, compliance, data_protection, refund, warranty
258
+
259
+ ### ZIP Output
260
+
261
+ Bundle all translations into a single ZIP file for easy distribution:
262
+
263
+ ```bash
264
+ # Default filename (translations.zip)
265
+ shipi18n translate en.json --target es,fr,de,ja --zip
266
+
267
+ # Custom filename
268
+ shipi18n translate en.json --target es,fr,de,ja --zip locales-v2.zip
269
+
270
+ # With custom output directory
271
+ shipi18n translate en.json --target es,fr --zip --output ./dist/i18n
272
+ ```
273
+
274
+ **Output:**
275
+ ```
276
+ ✔ Translated 50 keys to 4 languages!
277
+ ✓ Saved: ./locales/translations.zip (4 files)
278
+
279
+ ✨ Successfully translated 4 files!
280
+ Output: ./locales
281
+ ```
282
+
283
+ **ZIP structure:**
284
+ ```
285
+ translations.zip
286
+ ├── es.json
287
+ ├── fr.json
288
+ ├── de.json
289
+ └── ja.json
290
+ ```
291
+
166
292
  ### Keys Management
167
293
 
168
294
  Manage your translation keys in Translation Memory:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shipi18n/cli",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Command-line tool for translating locale files with Shipi18n",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -42,12 +42,13 @@
42
42
  "author": "Shipi18n",
43
43
  "license": "MIT",
44
44
  "dependencies": {
45
- "commander": "^11.1.0",
45
+ "archiver": "^7.0.1",
46
46
  "chalk": "^5.3.0",
47
+ "commander": "^11.1.0",
47
48
  "dotenv": "^16.3.1",
48
- "yaml": "^2.3.4",
49
+ "inquirer": "^9.2.12",
49
50
  "ora": "^7.0.1",
50
- "inquirer": "^9.2.12"
51
+ "yaml": "^2.3.4"
51
52
  },
52
53
  "devDependencies": {
53
54
  "jest": "^29.7.0"
@@ -1,6 +1,7 @@
1
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
1
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, createWriteStream } from 'fs';
2
2
  import { join, parse, dirname } from 'path';
3
3
  import chalk from 'chalk';
4
+ import archiver from 'archiver';
4
5
  import { Shipi18nAPI } from '../lib/api.js';
5
6
  import { getConfig } from '../lib/config.js';
6
7
  import { logger, formatError } from '../utils/logger.js';
@@ -19,6 +20,10 @@ export function translateCommand(program) {
19
20
  .option('--no-fallback', 'Disable fallback to source language for missing translations')
20
21
  .option('--no-regional-fallback', 'Disable regional fallback (e.g., pt-BR -> pt)')
21
22
  .option('-i, --incremental', 'Only translate new/missing keys (skip existing translations)')
23
+ .option('--skip-keys <keys>', 'Keys to skip from translation (comma-separated exact paths)')
24
+ .option('--skip-paths <patterns>', 'Paths to skip using wildcards (comma-separated, e.g., "states.*,config.*.secret")')
25
+ .option('--context-file <path>', 'JSON file with context annotations for disambiguation (e.g., {"close": "button - dismiss"})')
26
+ .option('--zip [filename]', 'Output translations as ZIP file (default: translations.zip)')
22
27
  .action(async (input, options) => {
23
28
  const spinner = logger.spinner('Translating...');
24
29
 
@@ -59,6 +64,38 @@ export function translateCommand(program) {
59
64
  const outputDir = options.output;
60
65
  const inputFileName = parse(input).name;
61
66
 
67
+ // Parse skip options
68
+ const skipKeys = options.skipKeys
69
+ ? options.skipKeys.split(',').map(k => k.trim())
70
+ : [];
71
+ const skipPaths = options.skipPaths
72
+ ? options.skipPaths.split(',').map(p => p.trim())
73
+ : [];
74
+
75
+ if (skipKeys.length > 0 || skipPaths.length > 0) {
76
+ logger.info(`Skipping ${skipKeys.length + skipPaths.length} key/pattern(s) from translation`);
77
+ }
78
+
79
+ // Parse context annotations file
80
+ let contextAnnotations = {};
81
+ if (options.contextFile) {
82
+ if (!existsSync(options.contextFile)) {
83
+ spinner.fail();
84
+ logger.error(`Context file not found: ${options.contextFile}`);
85
+ process.exit(1);
86
+ }
87
+ try {
88
+ const contextContent = readFileSync(options.contextFile, 'utf8');
89
+ contextAnnotations = JSON.parse(contextContent);
90
+ const contextCount = Object.keys(contextAnnotations).length;
91
+ logger.info(`Loaded ${contextCount} context annotation(s) from ${options.contextFile}`);
92
+ } catch (error) {
93
+ spinner.fail();
94
+ logger.error(`Invalid JSON in context file: ${error.message}`);
95
+ process.exit(1);
96
+ }
97
+ }
98
+
62
99
  // Incremental mode: load existing translations and find missing keys
63
100
  let jsonToTranslate = json;
64
101
  const existingTranslations = {};
@@ -137,6 +174,9 @@ export function translateCommand(program) {
137
174
  fallbackToSource: options.fallback !== false,
138
175
  regionalFallback: options.regionalFallback !== false,
139
176
  },
177
+ skipKeys,
178
+ skipPaths,
179
+ contextAnnotations,
140
180
  });
141
181
 
142
182
  const keyCount = Object.keys(flattenObject(jsonToTranslate)).length;
@@ -148,19 +188,50 @@ export function translateCommand(program) {
148
188
  }
149
189
 
150
190
  let savedCount = 0;
191
+
192
+ // Prepare translations for output (filter metadata, apply merging)
193
+ const outputTranslations = {};
151
194
  for (const [langCode, content] of Object.entries(translations)) {
152
- if (langCode === 'warnings' || langCode === 'fallbackInfo' || langCode === 'namespaceInfo') continue;
195
+ if (langCode === 'warnings' || langCode === 'fallbackInfo' || langCode === 'namespaceInfo' || langCode === 'skipped' || langCode === 'contextEnhanced') continue;
153
196
 
154
- // In incremental mode, merge with existing translations
155
197
  let finalContent = content;
156
198
  if (options.incremental && existingTranslations[langCode]) {
157
199
  finalContent = deepMerge(existingTranslations[langCode], content);
158
200
  }
201
+ outputTranslations[langCode] = finalContent;
202
+ }
203
+
204
+ if (options.zip) {
205
+ // ZIP output mode
206
+ const zipFileName = typeof options.zip === 'string' ? options.zip : 'translations.zip';
207
+ const zipPath = join(outputDir, zipFileName);
208
+
209
+ await new Promise((resolve, reject) => {
210
+ const output = createWriteStream(zipPath);
211
+ const archive = archiver('zip', { zlib: { level: 9 } });
212
+
213
+ output.on('close', resolve);
214
+ archive.on('error', reject);
215
+
216
+ archive.pipe(output);
217
+
218
+ for (const [langCode, content] of Object.entries(outputTranslations)) {
219
+ archive.append(JSON.stringify(content, null, 2), { name: `${langCode}.json` });
220
+ savedCount++;
221
+ }
222
+
223
+ archive.finalize();
224
+ });
159
225
 
160
- const outputFile = join(outputDir, `${langCode}.json`);
161
- writeFileSync(outputFile, JSON.stringify(finalContent, null, 2), 'utf8');
162
- logger.success(`Saved: ${chalk.cyan(outputFile)}${options.incremental ? chalk.gray(' (merged)') : ''}`);
163
- savedCount++;
226
+ logger.success(`Saved: ${chalk.cyan(zipPath)} (${savedCount} file${savedCount !== 1 ? 's' : ''})`);
227
+ } else {
228
+ // Individual files mode
229
+ for (const [langCode, content] of Object.entries(outputTranslations)) {
230
+ const outputFile = join(outputDir, `${langCode}.json`);
231
+ writeFileSync(outputFile, JSON.stringify(content, null, 2), 'utf8');
232
+ logger.success(`Saved: ${chalk.cyan(outputFile)}${options.incremental ? chalk.gray(' (merged)') : ''}`);
233
+ savedCount++;
234
+ }
164
235
  }
165
236
 
166
237
  // Show fallback info if any fallbacks were used
@@ -196,11 +267,52 @@ export function translateCommand(program) {
196
267
  }
197
268
  }
198
269
 
199
- // Show warnings if any
200
- if (translations.warnings && translations.warnings.length > 0) {
270
+ // Show skipped keys info if any
271
+ if (translations.skipped && translations.skipped.count > 0) {
272
+ logger.log('');
273
+ logger.info(`Skipped ${translations.skipped.count} key${translations.skipped.count > 1 ? 's' : ''} from translation:`);
274
+ const keysToShow = translations.skipped.keys.slice(0, 10);
275
+ keysToShow.forEach(key => {
276
+ logger.log(` ${chalk.gray('•')} ${key}`);
277
+ });
278
+ if (translations.skipped.keys.length > 10) {
279
+ logger.log(` ${chalk.gray(`... and ${translations.skipped.keys.length - 10} more`)}`);
280
+ }
281
+ }
282
+
283
+ // Show context-enhanced keys info if any
284
+ if (translations.contextEnhanced && translations.contextEnhanced.count > 0) {
285
+ logger.log('');
286
+ logger.info(`${chalk.cyan('🎯')} ${translations.contextEnhanced.count} key${translations.contextEnhanced.count > 1 ? 's' : ''} translated with context annotations:`);
287
+ const keysToShow = translations.contextEnhanced.keys.slice(0, 10);
288
+ keysToShow.forEach(key => {
289
+ logger.log(` ${chalk.cyan('•')} ${key}`);
290
+ });
291
+ if (translations.contextEnhanced.keys.length > 10) {
292
+ logger.log(` ${chalk.gray(`... and ${translations.contextEnhanced.keys.length - 10} more`)}`);
293
+ }
294
+ }
295
+
296
+ // Show legal content warning with key details
297
+ const legalWarning = translations.warnings?.find(w => w.type === 'legal_content');
298
+ if (legalWarning?.details?.keys?.length > 0) {
299
+ logger.log('');
300
+ logger.warn(`${chalk.yellow('⚠️')} Legal content detected - review these keys:`);
301
+ legalWarning.details.keys.forEach(key => {
302
+ logger.log(` ${chalk.yellow('•')} ${key}`);
303
+ });
304
+ if (legalWarning.details.count > 10) {
305
+ logger.log(` ${chalk.gray(`... and ${legalWarning.details.count - 10} more`)}`);
306
+ }
307
+ logger.log(` ${chalk.gray('Machine-translated legal text may not be legally binding.')}`);
308
+ }
309
+
310
+ // Show other warnings if any (exclude legal_content since we showed it above)
311
+ const otherWarnings = translations.warnings?.filter(w => w.type !== 'legal_content') || [];
312
+ if (otherWarnings.length > 0) {
201
313
  logger.log('');
202
314
  logger.warn('Warnings:');
203
- translations.warnings.forEach(warning => {
315
+ otherWarnings.forEach(warning => {
204
316
  logger.log(` ${chalk.yellow('•')} ${warning.message}`);
205
317
  });
206
318
  }
package/src/lib/api.js CHANGED
@@ -24,6 +24,9 @@ export class Shipi18nAPI {
24
24
  * @param {boolean} options.fallback.fallbackToSource - Use source content when translation missing (default: true)
25
25
  * @param {boolean} options.fallback.regionalFallback - Enable pt-BR -> pt fallback (default: true)
26
26
  * @param {string} options.fallback.fallbackLanguage - Custom fallback language
27
+ * @param {string[]} options.skipKeys - Exact key paths to skip from translation
28
+ * @param {string[]} options.skipPaths - Glob patterns to skip (e.g., "nav.*", "config.*.secret")
29
+ * @param {Object} options.contextAnnotations - Per-key context hints for disambiguation
27
30
  */
28
31
  async translateJSON({
29
32
  json,
@@ -31,7 +34,10 @@ export class Shipi18nAPI {
31
34
  targetLanguages,
32
35
  preservePlaceholders = true,
33
36
  htmlHandling = 'none',
34
- fallback = {}
37
+ fallback = {},
38
+ skipKeys = [],
39
+ skipPaths = [],
40
+ contextAnnotations = {},
35
41
  }) {
36
42
  if (!this.apiKey) {
37
43
  throw new Error('API key is required. Set SHIPI18N_API_KEY or run: shipi18n config set apiKey YOUR_KEY');
@@ -62,6 +68,9 @@ export class Shipi18nAPI {
62
68
  targetLanguages: JSON.stringify(processedTargets),
63
69
  preservePlaceholders: String(preservePlaceholders),
64
70
  htmlHandling,
71
+ skipKeys,
72
+ skipPaths,
73
+ contextAnnotations,
65
74
  }),
66
75
  });
67
76
 
@@ -78,7 +87,7 @@ export class Shipi18nAPI {
78
87
  // Parse JSON strings back to objects
79
88
  const parsed = {};
80
89
  for (const [lang, jsonStr] of Object.entries(result)) {
81
- if (lang === 'warnings' || lang === 'namespaceInfo') {
90
+ if (lang === 'warnings' || lang === 'namespaceInfo' || lang === 'skipped' || lang === 'contextEnhanced') {
82
91
  parsed[lang] = jsonStr;
83
92
  continue;
84
93
  }