@coding-with-hassan/devkit 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -10,13 +10,13 @@ pnpm add -D @coding-with-hassan/devkit
10
10
 
11
11
  ## Configure
12
12
 
13
- Add a `hassan-devkit` block to your client repo's root `package.json` so the db commands know which container to talk to:
13
+ Add a `hassan-devkit` block to your client repo's root `package.json` so the db commands know which compose service to address:
14
14
 
15
15
  ```json
16
16
  {
17
17
  "hassan-devkit": {
18
18
  "db": {
19
- "container": "de-autozaak-db",
19
+ "service": "db",
20
20
  "user": "postgres",
21
21
  "name": "de_autozaak"
22
22
  }
@@ -24,6 +24,8 @@ Add a `hassan-devkit` block to your client repo's root `package.json` so the db
24
24
  }
25
25
  ```
26
26
 
27
+ `service` is the docker-compose service name, **not** a hardcoded container name. The CLI runs `docker compose exec <service>`, so the project name in your compose file handles disambiguation when multiple client stacks share a host.
28
+
27
29
  The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at the repo root (the convention the template repo ships with).
28
30
 
29
31
  ## Wire it into your scripts
@@ -48,7 +50,7 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
48
50
  - `hassan-devkit docker:up` — `docker compose up -d --build`
49
51
  - `hassan-devkit docker:down` — `docker compose down`
50
52
  - `hassan-devkit docker:logs` — tail logs
51
- - `hassan-devkit docker:restart <service>` — restart a single container by name
53
+ - `hassan-devkit docker:restart <service>` — `docker compose restart <service>`
52
54
 
53
55
  ### Database
54
56
 
@@ -58,6 +60,22 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
58
60
  - `hassan-devkit db:truncate <table>` — `TRUNCATE TABLE <table> CASCADE`
59
61
  - `hassan-devkit db:psql` — interactive psql shell
60
62
 
63
+ ### i18n
64
+
65
+ - `hassan-devkit i18n:check` — validates translation JSON: flags keys missing from any language file and enforces UPPERCASE_SNAKE_CASE key naming. Add `--detailed` (per-module key counts) or `--detailed --show-keys` to inspect. No-ops when the project has no i18n directory, and runs automatically in the shared pre-commit hook.
66
+
67
+ Configure via the `hassan-devkit.i18n` block in package.json (both fields optional):
68
+
69
+ ```json
70
+ {
71
+ "hassan-devkit": {
72
+ "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
73
+ }
74
+ }
75
+ ```
76
+
77
+ `dir` is resolved from the repo root — in a monorepo point it at the app (e.g. `spa/public/assets/i18n`). Defaults: `public/assets/i18n` and `["en", "nl"]`.
78
+
61
79
  ### Husky hooks
62
80
 
63
81
  - `hassan-devkit hooks:install` — installs husky if needed, then writes the shared `pre-commit` hook content into `.husky/pre-commit`. Re-run after bumping `@coding-with-hassan/devkit` to pick up changes to the hook.
@@ -66,4 +84,4 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
66
84
 
67
85
  ### Per-project extras
68
86
 
69
- If a project needs to run something extra before the standard lint-staged step (e.g., the de-autozaak SPA's translation consistency check), drop a `scripts/pre-commit-extra.sh` in the repo root. It runs first, must `exit 0` to continue.
87
+ If a project needs to run something extra before the standard `i18n:check` + lint-staged steps, drop a `scripts/pre-commit-extra.sh` in the repo root. It runs first, must `exit 0` to continue. (Translation consistency is now built in via `i18n:check` — see above — so it no longer belongs here.)
@@ -6,5 +6,8 @@ if [ -f "scripts/pre-commit-extra.sh" ]; then
6
6
  sh scripts/pre-commit-extra.sh || exit 1
7
7
  fi
8
8
 
9
+ # Validate translation keys (no-op if the project has no i18n directory)
10
+ pnpm exec hassan-devkit i18n:check || exit 1
11
+
9
12
  # Project-aware lint/format on staged files
10
13
  pnpm exec lint-staged
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coding-with-hassan/devkit",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI for the developer workflow shared across Hassan's client projects: docker compose orchestration, db helpers, and husky hook installation.",
5
5
  "license": "MIT",
6
6
  "author": "Hassan Khousheish",
@@ -1,28 +1,25 @@
1
1
  import { runCommand, exitOnFailure } from '../util/run.js';
2
2
  import { requireDbConfig } from '../util/config.js';
3
3
 
4
+ const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
5
+ const ENV_FILE = '.env';
6
+
7
+ function composeExec(args, extraOpts = {}) {
8
+ return runCommand(
9
+ 'docker',
10
+ ['compose', '--env-file', ENV_FILE, '-f', COMPOSE_FILE, 'exec', ...args],
11
+ extraOpts,
12
+ );
13
+ }
14
+
4
15
  function psqlExec(sql) {
5
16
  const db = requireDbConfig();
6
- return runCommand('docker', [
7
- 'exec',
8
- db.container,
9
- 'psql',
10
- '-U',
11
- db.user,
12
- '-d',
13
- db.name,
14
- '-c',
15
- sql,
16
- ]);
17
+ return composeExec([db.service, 'psql', '-U', db.user, '-d', db.name, '-c', sql]);
17
18
  }
18
19
 
19
20
  function psqlShell() {
20
21
  const db = requireDbConfig();
21
- return runCommand(
22
- 'docker',
23
- ['exec', '-it', db.container, 'psql', '-U', db.user, '-d', db.name],
24
- { stdio: 'inherit' },
25
- );
22
+ return composeExec([db.service, 'psql', '-U', db.user, '-d', db.name], { stdio: 'inherit' });
26
23
  }
27
24
 
28
25
  export function registerDb(cli) {
@@ -21,6 +21,6 @@ export function registerDocker(cli) {
21
21
  .action(() => exitOnFailure(compose(['logs', '-f'])));
22
22
 
23
23
  cli
24
- .command('docker:restart <service>', 'Restart a single container')
25
- .action((service) => exitOnFailure(runCommand('docker', ['restart', service])));
24
+ .command('docker:restart <service>', 'Restart a single service in the dev stack')
25
+ .action((service) => exitOnFailure(compose(['restart', service])));
26
26
  }
@@ -0,0 +1,184 @@
1
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { readI18nConfig } from '../util/config.js';
4
+
5
+ const colors = {
6
+ red: (t) => `\x1b[31m${t}\x1b[0m`,
7
+ green: (t) => `\x1b[32m${t}\x1b[0m`,
8
+ yellow: (t) => `\x1b[33m${t}\x1b[0m`,
9
+ cyan: (t) => `\x1b[36m${t}\x1b[0m`,
10
+ gray: (t) => `\x1b[90m${t}\x1b[0m`,
11
+ };
12
+
13
+ // Each dot-separated segment of a key must be UPPERCASE_SNAKE_CASE.
14
+ const SEGMENT_RE = /^[A-Z0-9_]+$/;
15
+ const isValidKey = (key) => key.split('.').every((segment) => SEGMENT_RE.test(segment));
16
+
17
+ // Recursively collect every nested key in dot notation.
18
+ function extractKeys(obj, prefix = '') {
19
+ const keys = new Set();
20
+ for (const [key, value] of Object.entries(obj)) {
21
+ const fullKey = prefix ? `${prefix}.${key}` : key;
22
+ keys.add(fullKey);
23
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
24
+ for (const nested of extractKeys(value, fullKey)) keys.add(nested);
25
+ }
26
+ }
27
+ return keys;
28
+ }
29
+
30
+ function readJson(filePath) {
31
+ try {
32
+ return JSON.parse(readFileSync(filePath, 'utf8'));
33
+ } catch (error) {
34
+ console.error(colors.red(`Error reading ${filePath}: ${error.message}`));
35
+ return null;
36
+ }
37
+ }
38
+
39
+ function listModules(i18nDir) {
40
+ return readdirSync(i18nDir, { withFileTypes: true })
41
+ .filter((dirent) => dirent.isDirectory())
42
+ .map((dirent) => dirent.name)
43
+ .sort();
44
+ }
45
+
46
+ function checkModule(i18nDir, module, languages) {
47
+ const modulePath = join(i18nDir, module);
48
+ const result = {
49
+ module,
50
+ errors: [],
51
+ warnings: [],
52
+ languageKeys: new Map(),
53
+ allKeys: new Set(),
54
+ validLanguages: [],
55
+ };
56
+
57
+ const existingFiles = new Map();
58
+ for (const lang of languages) {
59
+ const filePath = join(modulePath, `${lang}.json`);
60
+ if (existsSync(filePath)) {
61
+ existingFiles.set(lang, filePath);
62
+ result.validLanguages.push(lang);
63
+ } else {
64
+ result.warnings.push(`Missing language file: ${lang}.json`);
65
+ }
66
+ }
67
+
68
+ if (existingFiles.size === 0) {
69
+ result.errors.push({ type: 'general', message: `No translation files found in ${module}` });
70
+ return result;
71
+ }
72
+
73
+ for (const [lang, filePath] of existingFiles) {
74
+ const json = readJson(filePath);
75
+ if (json) {
76
+ const keys = extractKeys(json);
77
+ result.languageKeys.set(lang, keys);
78
+ for (const key of keys) result.allKeys.add(key);
79
+ } else {
80
+ result.errors.push({ type: 'general', message: `Failed to parse ${lang}.json in ${module}` });
81
+ }
82
+ }
83
+
84
+ // Missing keys: present in one language but absent in another.
85
+ for (const [lang, langKeys] of result.languageKeys) {
86
+ const missingKeys = [...result.allKeys].filter((key) => !langKeys.has(key));
87
+ if (missingKeys.length > 0) {
88
+ result.errors.push({ type: 'missing', language: lang, keys: missingKeys.sort() });
89
+ }
90
+ }
91
+
92
+ // Naming: every key must be UPPERCASE_SNAKE_CASE.
93
+ const invalidKeys = [...result.allKeys].filter((key) => !isValidKey(key));
94
+ if (invalidKeys.length > 0) {
95
+ result.errors.push({ type: 'naming', keys: invalidKeys.sort() });
96
+ }
97
+
98
+ return result;
99
+ }
100
+
101
+ function displayResults(allResults) {
102
+ let totalErrors = 0;
103
+ let totalWarnings = 0;
104
+
105
+ console.log(colors.cyan('\n🔍 Translation Check Results\n'));
106
+
107
+ for (const result of allResults) {
108
+ if (result.errors.length === 0 && result.warnings.length === 0) {
109
+ console.log(colors.green(`✅ ${result.module} — OK`));
110
+ continue;
111
+ }
112
+
113
+ console.log(colors.yellow(`📁 ${result.module}`));
114
+ for (const error of result.errors) {
115
+ totalErrors++;
116
+ if (error.type === 'general') {
117
+ console.log(colors.red(` ❌ ${error.message}`));
118
+ } else if (error.type === 'missing') {
119
+ console.log(colors.red(` ❌ ${error.language}.json missing ${error.keys.length} key(s):`));
120
+ for (const key of error.keys) console.log(colors.red(` - ${key}`));
121
+ } else if (error.type === 'naming') {
122
+ console.log(
123
+ colors.red(` ❌ ${error.keys.length} key(s) are not UPPERCASE_SNAKE_CASE:`),
124
+ );
125
+ for (const key of error.keys) console.log(colors.red(` - ${key}`));
126
+ }
127
+ }
128
+ for (const warning of result.warnings) {
129
+ totalWarnings++;
130
+ console.log(colors.yellow(` ⚠️ ${warning}`));
131
+ }
132
+ console.log('');
133
+ }
134
+
135
+ console.log(colors.cyan('📊 Summary:'));
136
+ console.log(` Modules checked: ${allResults.length}`);
137
+ console.log(` Total errors: ${colors.red(totalErrors)}`);
138
+ console.log(` Total warnings: ${colors.yellow(totalWarnings)}`);
139
+
140
+ if (totalErrors > 0) {
141
+ console.log(colors.red('\n❌ Translation check failed.'));
142
+ process.exit(1);
143
+ }
144
+ console.log(colors.green('\n✅ All translations are consistent and correctly cased!'));
145
+ }
146
+
147
+ function detailedReport(allResults, showKeys) {
148
+ console.log(colors.cyan('\n📋 Detailed Report\n'));
149
+ for (const result of allResults) {
150
+ console.log(colors.yellow(`Module: ${result.module}`));
151
+ console.log(` Languages: ${result.validLanguages.join(', ')}`);
152
+ console.log(` Total keys: ${result.allKeys.size}`);
153
+ if (showKeys) {
154
+ for (const key of [...result.allKeys].sort()) console.log(` - ${key}`);
155
+ }
156
+ console.log('');
157
+ }
158
+ }
159
+
160
+ export function registerI18n(cli) {
161
+ cli
162
+ .command(
163
+ 'i18n:check',
164
+ 'Validate translation JSON: matching keys across languages and UPPERCASE_SNAKE_CASE naming',
165
+ )
166
+ .option('--detailed', 'Show per-module key counts')
167
+ .option('--show-keys', 'List every key per module (use with --detailed)')
168
+ .action((options) => {
169
+ const { dir, languages } = readI18nConfig();
170
+ const i18nDir = resolve(process.cwd(), dir);
171
+
172
+ // No-op for projects without translations (keeps the shared hook happy).
173
+ if (!existsSync(i18nDir)) {
174
+ console.log(colors.gray(`No i18n directory at ${dir} — skipping translation check.`));
175
+ return;
176
+ }
177
+
178
+ const modules = listModules(i18nDir);
179
+ const allResults = modules.map((module) => checkModule(i18nDir, module, languages));
180
+
181
+ if (options.detailed) detailedReport(allResults, options.showKeys);
182
+ displayResults(allResults);
183
+ });
184
+ }
package/src/index.js CHANGED
@@ -2,6 +2,7 @@ import { cac } from 'cac';
2
2
  import { registerDocker } from './commands/docker.js';
3
3
  import { registerDb } from './commands/db.js';
4
4
  import { registerHooks } from './commands/hooks.js';
5
+ import { registerI18n } from './commands/i18n.js';
5
6
 
6
7
  export function run(argv) {
7
8
  const cli = cac('hassan-devkit');
@@ -9,6 +10,7 @@ export function run(argv) {
9
10
  registerDocker(cli);
10
11
  registerDb(cli);
11
12
  registerHooks(cli);
13
+ registerI18n(cli);
12
14
 
13
15
  cli.help();
14
16
  cli.version(readVersion());
@@ -6,9 +6,13 @@ import { resolve } from 'node:path';
6
6
  *
7
7
  * {
8
8
  * "hassan-devkit": {
9
- * "db": { "container": "...", "user": "postgres", "name": "..." }
9
+ * "db": { "service": "db", "user": "postgres", "name": "..." }
10
10
  * }
11
11
  * }
12
+ *
13
+ * `service` is the docker-compose service name (e.g. `db`), not a hardcoded
14
+ * container name. The CLI uses `docker compose exec <service>` so the project
15
+ * name in compose handles disambiguation across clients.
12
16
  */
13
17
  export function readDevkitConfig() {
14
18
  const pkgPath = resolve(process.cwd(), 'package.json');
@@ -22,10 +26,26 @@ export function readDevkitConfig() {
22
26
 
23
27
  export function requireDbConfig() {
24
28
  const cfg = readDevkitConfig().db;
25
- if (!cfg?.container || !cfg?.user || !cfg?.name) {
29
+ if (!cfg?.service || !cfg?.user || !cfg?.name) {
26
30
  throw new Error(
27
- 'Missing db config. Add a "hassan-devkit": { "db": { "container": "...", "user": "...", "name": "..." } } block to package.json.',
31
+ 'Missing db config. Add a "hassan-devkit": { "db": { "service": "...", "user": "...", "name": "..." } } block to package.json. ' +
32
+ '("service" is the compose service name, e.g. "db".)',
28
33
  );
29
34
  }
30
35
  return cfg;
31
36
  }
37
+
38
+ /**
39
+ * Read the optional `i18n` config block, applying defaults. `dir` is resolved
40
+ * relative to the consumer's cwd; in a monorepo point it at the app, e.g.
41
+ * "spa/public/assets/i18n".
42
+ *
43
+ * "hassan-devkit": { "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] } }
44
+ */
45
+ export function readI18nConfig() {
46
+ const cfg = readDevkitConfig().i18n ?? {};
47
+ return {
48
+ dir: cfg.dir ?? 'public/assets/i18n',
49
+ languages: cfg.languages ?? ['en', 'nl'],
50
+ };
51
+ }