Skip to content

Commit eb78cb4

Browse files
committed
style: run format
1 parent 590315a commit eb78cb4

File tree

5 files changed

+57
-60
lines changed

5 files changed

+57
-60
lines changed

cli/app.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1+
import fs from 'node:fs';
12
import { createServer } from 'node:http';
2-
import fs from 'node:fs'
33
import open from 'open';
4+
import pkg from '../package.json' with { type: 'json' };
45
import { mergeDB } from './helpers.js';
5-
import pkg from '../package.json' with { type: "json" };
66

77
const chunkRegex = /\$\{[0-9]\}/g;
8-
const chunks = (chunk, i) => (i ? ('${' + (i - 1) + '}') : '') + chunk;
8+
const chunks = (chunk, i) => (i ? '${' + (i - 1) + '}' : '') + chunk;
99

1010
const getRoute = (options, req, res) => {
1111
const routes = {
@@ -15,7 +15,7 @@ const getRoute = (options, req, res) => {
1515
const localizedSentence = options.db.indexed[key][options.locale].map(chunks).join('');
1616
const missingTranslation = defaultSentence === localizedSentence;
1717
return `
18-
<div class="group" ${(missingTranslation) ? 'data-missing-translation' : ''}>
18+
<div class="group" ${missingTranslation ? 'data-missing-translation' : ''}>
1919
<div>
2020
<b>en</b>
2121
<textarea disabled>${defaultSentence}</textarea>
@@ -28,7 +28,7 @@ const getRoute = (options, req, res) => {
2828
`;
2929
});
3030

31-
res.writeHead(200, {'Content-Type': 'text/html'});
31+
res.writeHead(200, { 'Content-Type': 'text/html' });
3232
res.end(`
3333
<!DOCTYPE html>
3434
<html lang="en" dir="ltr">
@@ -186,7 +186,7 @@ const getRoute = (options, req, res) => {
186186
'/update': (req, res) => {
187187
const body = [];
188188
const db = {};
189-
req.on('data', data => body.push(data));
189+
req.on('data', (data) => body.push(data));
190190
req.on('end', () => {
191191
const existingDB = options.db.fileSystem;
192192
const updatedDB = JSON.parse(body.join(''));
@@ -204,10 +204,10 @@ const getRoute = (options, req, res) => {
204204
res.end();
205205
process.exit(0);
206206
},
207-
'default': (req, res) => {
207+
default: (req, res) => {
208208
res.writeHead(404, 'Not Found');
209209
res.end();
210-
}
210+
},
211211
};
212212
return (routes[req.url] || routes['default'])(req, res);
213213
};

cli/cli.js

Lines changed: 33 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
#!/usr/bin/env node
22

3-
import fs from 'node:fs'
3+
import fs from 'node:fs';
44
import path from 'node:path';
5-
import meow from 'meow';
6-
import chalk from 'chalk';
75
import { parse } from '@babel/parser';
6+
import chalk from 'chalk';
7+
import meow from 'meow';
8+
import pkg from '../package.json' with { type: 'json' };
89
import { launchApp } from './app.js';
9-
import pkg from '../package.json' with { type: "json" };
1010

1111
const CLI_NAME = Object.keys(pkg.bin)[0];
1212
const CMDS = ['edit', 'check-missing-translations'];
13-
const getCommand = cmd => CMDS.includes(cmd) ? cmd : CMDS[0];
13+
const getCommand = (cmd) => (CMDS.includes(cmd) ? cmd : CMDS[0]);
1414

15-
const cli = meow(`
15+
const cli = meow(
16+
`
1617
Usage:
1718
$ ${CLI_NAME} <cmd> <entry> <locale> [db]
1819
@@ -30,37 +31,38 @@ const cli = meow(`
3031
3132
Example:
3233
$ ${CLI_NAME} edit ./index.js es
33-
`, {
34-
importMeta: import.meta,
35-
});
36-
34+
`,
35+
{
36+
importMeta: import.meta,
37+
},
38+
);
3739

3840
const args = [...cli.input];
39-
const flags = { ...cli.flags, root: cli.flags.root || process.env.PWD }
41+
const flags = { ...cli.flags, root: cli.flags.root || process.env.PWD };
4042

4143
const flag = {
42-
error: msg => chalk.red(`\n${msg}\nTry \`${CLI_NAME} --help\` for more informations.\n`)
44+
error: (msg) => chalk.red(`\n${msg}\nTry \`${CLI_NAME} --help\` for more informations.\n`),
4345
};
4446

4547
if (!CMDS.includes(args[0])) {
4648
args.unshift(CMDS[0]);
4749
}
4850

4951
const options = {
50-
cmd: args[0], // command with default fallback
51-
entry: args[1], // entry file
52-
locale: args[2], // locale to translate to
53-
db: args[3] || './i18n.db.json' // db file
52+
cmd: args[0], // command with default fallback
53+
entry: args[1], // entry file
54+
locale: args[2], // locale to translate to
55+
db: args[3] || './i18n.db.json', // db file
5456
};
5557

5658
if (!options.entry) {
5759
console.log(`${flag.error(`Missing <entry> argument.`)}`);
58-
process.exit(1);
60+
process.exit(1);
5961
}
6062

6163
if (options.cmd === CMDS[0] && !options.locale) {
6264
console.log(`${flag.error(`Missing <locale> argument.`)}`);
63-
process.exit(1);
65+
process.exit(1);
6466
}
6567

6668
const parserOptions = {
@@ -89,16 +91,16 @@ const parserOptions = {
8991
'objectRestSpread',
9092
'optionalCatchBinding',
9193
'optionalChaining',
92-
'throwExpressions'
93-
]
94+
'throwExpressions',
95+
],
9496
};
9597

9698
const NODE_PATH = process.env.NODE_PATH || '';
9799
const fileCache = [];
98100
const indexedFiles = [];
99101
const db = {
100102
fileSystem: JSON.parse(fs.readFileSync(options.db) || {}),
101-
indexed: {}
103+
indexed: {},
102104
};
103105

104106
traverseFiles(options.entry);
@@ -112,7 +114,7 @@ if (options.cmd === CMDS[0]) {
112114
if (options.cmd === CMDS[1]) {
113115
if (hasMissingTranslations(db)) {
114116
console.log(`Missing translations\n`);
115-
process.exit(1);
117+
process.exit(1);
116118
}
117119
}
118120

@@ -124,21 +126,19 @@ console.log(`
124126
Missing: ${Object.keys(db.indexed).length - Object.keys(db.fileSystem).length}
125127
`);
126128

127-
128-
129129
function traverseFiles(file) {
130130
const code = fs.readFileSync(file).toString();
131131
const ast = parse(code, parserOptions);
132132
const basePath = path.dirname(file);
133-
ast.program.body.forEach(node => traverseNode(node, basePath));
133+
ast.program.body.forEach((node) => traverseNode(node, basePath));
134134
}
135135

136136
function traverseNode(node, basePath) {
137137
switch (node.type) {
138138
case 'ImportDeclaration':
139139
let filePath = node.source.value;
140140
let dirPath = NODE_PATH;
141-
const isRelativePath = filePath.startsWith('.')
141+
const isRelativePath = filePath.startsWith('.');
142142
if (flags.rootAlias && filePath.startsWith(flags.rootAlias)) {
143143
filePath = filePath.replace(new RegExp(`^${flags.rootAlias}\/?`), '');
144144
dirPath = flags.root;
@@ -158,19 +158,21 @@ function traverseNode(node, basePath) {
158158
break;
159159
case 'TaggedTemplateExpression':
160160
if (node.tag.name === 'i18n') {
161-
const strings = node.quasi.quasis.map(quasi => quasi.value.raw);
161+
const strings = node.quasi.quasis.map((quasi) => quasi.value.raw);
162162
const key = strings.join('\x01');
163-
const translation = db.fileSystem[key] && db.fileSystem[key][options.locale || 'default'] || strings.slice();
163+
const translation =
164+
(db.fileSystem[key] && db.fileSystem[key][options.locale || 'default']) ||
165+
strings.slice();
164166
// Skip empty strings & already existing keys
165167
if (!db.indexed[key] && translation.join('') !== '') {
166168
(db.indexed[key] = {})[options.locale || 'default'] = translation;
167169
}
168170
}
169171
break;
170172
default:
171-
for (let key in node) {
173+
for (const key in node) {
172174
if (typeof node[key] === 'object') {
173-
traverseNode((node[key] || {}), basePath);
175+
traverseNode(node[key] || {}, basePath);
174176
}
175177
}
176178
}
@@ -181,5 +183,5 @@ function hasMissingTranslations(db) {
181183
// TODO: check for missing language translations
182184
const totalIndexedDBKeys = Object.keys(db.indexed).length;
183185
const totalFileSystemDBKeys = Object.keys(db.fileSystem).length;
184-
return (totalIndexedDBKeys !== totalFileSystemDBKeys);
186+
return totalIndexedDBKeys !== totalFileSystemDBKeys;
185187
}

cli/helpers.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
export const mergeDB = (existingDB, updatedDB) => {
22
// We merge the existing translations with the new updated database.
33
return Object.keys(updatedDB).reduce((obj, key) => {
4-
obj[key] = { ...existingDB[key], ...updatedDB[key]}
4+
obj[key] = { ...existingDB[key], ...updatedDB[key] };
55
return obj;
66
}, {});
77
};

index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
export default function i18n(strings, ...values) {
22
const key = strings.join('\x01');
33
const translation = (i18n.db[key] && i18n.db[key][i18n.locale]) || strings;
4-
return translation.map((string, idx) => [string, values[idx]])
4+
return translation
5+
.map((string, idx) => [string, values[idx]])
56
.reduce((acc, val) => acc.concat(val), [])
67
.join('');
7-
};
8+
}
89

910
// Defaults
1011
i18n.locale = 'en';

test/index.spec.js

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,39 @@
11
import { deepEqual, equal } from 'node:assert';
22
import { it } from 'node:test';
3-
import i18n from '../index.js';
43
import { mergeDB } from '../cli/helpers.js';
5-
import db from './i18n.db.json' with { type: "json" };
4+
import i18n from '../index.js';
5+
import db from './i18n.db.json' with { type: 'json' };
66

77
// Define db
88
i18n.db = db;
99

1010
// Dummy data
11-
const data = [
12-
'World',
13-
'🍦',
14-
'✌️'
15-
];
16-
11+
const data = ['World', '🍦', '✌️'];
1712

1813
it('locale change', () => {
1914
i18n.locale = 'es';
20-
equal(i18n`Hello ${data[0]}!`, `Hola ${data[0]}!`);
15+
equal(i18n`Hello ${data[0]}!`, `Hola ${data[0]}!`);
2116

2217
i18n.locale = 'de';
23-
equal(i18n`Hello ${data[0]}!`, `Hallo ${data[0]}!`);
18+
equal(i18n`Hello ${data[0]}!`, `Hallo ${data[0]}!`);
2419
});
2520

2621
it('nested tags', () => {
2722
const template = `Hello test ${data[0]}... ${i18n`${data[1]} - ${data[2]}... Such wow!`}`;
28-
equal(i18n`${template}`, template);
23+
equal(i18n`${template}`, template);
2924
});
3025

3126
it('CLI mergeDB', () => {
3227
const data = {
3328
de: 'Hallo'.split(' '),
34-
es: 'Hola'.split(' ')
29+
es: 'Hola'.split(' '),
3530
};
36-
const existingDB = {'token': { 'de': data.de }};
37-
const updatedDB = {'token': { 'es': data.es }};
38-
const mergedDB = {'token': { de: data.de, es: data.es }};
39-
deepEqual(mergeDB(existingDB, updatedDB), mergedDB);
40-
deepEqual(mergeDB({}, updatedDB), updatedDB);
31+
const existingDB = { token: { de: data.de } };
32+
const updatedDB = { token: { es: data.es } };
33+
const mergedDB = { token: { de: data.de, es: data.es } };
34+
deepEqual(mergeDB(existingDB, updatedDB), mergedDB);
35+
deepEqual(mergeDB({}, updatedDB), updatedDB);
4136
});
4237

43-
4438
// test.todo('traverseFile relative + absolute (NODE_PATH) imports')
4539
// test.todo('traverseNode')

0 commit comments

Comments
 (0)