@coding-with-hassan/devkit 0.2.0 → 0.4.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
@@ -28,6 +28,16 @@ Add a `hassan-devkit` block to your client repo's root `package.json` so the db
28
28
 
29
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).
30
30
 
31
+ Optionally add a `docker.preUp` hook — a shell command `docker:up` runs from the repo root right before `docker compose up`. Use it to refresh values your compose file reads from `.env` (image tags derived from the lockfile, compose profiles, ports) so they can never go stale between ups; a non-zero exit aborts the up:
32
+
33
+ ```json
34
+ {
35
+ "hassan-devkit": {
36
+ "docker": { "preUp": "scripts/worktree.sh env" }
37
+ }
38
+ }
39
+ ```
40
+
31
41
  ## Wire it into your scripts
32
42
 
33
43
  ```json
@@ -47,7 +57,7 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
47
57
 
48
58
  ### Docker
49
59
 
50
- - `hassan-devkit docker:up` — `docker compose up -d --build`
60
+ - `hassan-devkit docker:up` — runs the `docker.preUp` hook when configured, then `docker compose up -d --build`
51
61
  - `hassan-devkit docker:down` — `docker compose down`
52
62
  - `hassan-devkit docker:logs` — tail logs
53
63
  - `hassan-devkit docker:restart <service>` — `docker compose restart <service>`
@@ -60,6 +70,22 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
60
70
  - `hassan-devkit db:truncate <table>` — `TRUNCATE TABLE <table> CASCADE`
61
71
  - `hassan-devkit db:psql` — interactive psql shell
62
72
 
73
+ ### i18n
74
+
75
+ - `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.
76
+
77
+ Configure via the `hassan-devkit.i18n` block in package.json (both fields optional):
78
+
79
+ ```json
80
+ {
81
+ "hassan-devkit": {
82
+ "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
83
+ }
84
+ }
85
+ ```
86
+
87
+ `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"]`.
88
+
63
89
  ### Husky hooks
64
90
 
65
91
  - `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.
@@ -68,4 +94,4 @@ The docker commands assume `docker/docker-compose.dev.yml` and a `.env` file at
68
94
 
69
95
  ### Per-project extras
70
96
 
71
- 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.
97
+ 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.2.0",
3
+ "version": "0.4.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,4 +1,5 @@
1
1
  import { runCommand, exitOnFailure } from '../util/run.js';
2
+ import { readDockerConfig } from '../util/config.js';
2
3
 
3
4
  const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
4
5
  const ENV_FILE = '.env';
@@ -7,10 +8,20 @@ function compose(args) {
7
8
  return runCommand('docker', ['compose', '--env-file', ENV_FILE, '-f', COMPOSE_FILE, ...args]);
8
9
  }
9
10
 
11
+ async function up() {
12
+ const { preUp } = readDockerConfig();
13
+ if (preUp) {
14
+ console.log(`hassan-devkit: docker.preUp → ${preUp}`);
15
+ // Through the shell so the hook can be any command line, not just a binary.
16
+ await runCommand(preUp, [], { shell: true });
17
+ }
18
+ await compose(['up', '-d', '--build']);
19
+ }
20
+
10
21
  export function registerDocker(cli) {
11
22
  cli
12
- .command('docker:up', 'Build and start the dev docker compose stack')
13
- .action(() => exitOnFailure(compose(['up', '-d', '--build'])));
23
+ .command('docker:up', 'Run the docker.preUp hook (if configured), then build and start the dev docker compose stack')
24
+ .action(() => exitOnFailure(up()));
14
25
 
15
26
  cli
16
27
  .command('docker:down', 'Stop the dev docker compose stack')
@@ -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());
@@ -34,3 +34,32 @@ export function requireDbConfig() {
34
34
  }
35
35
  return cfg;
36
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
+ }
52
+
53
+ /**
54
+ * Read the optional `docker` config block. `preUp` is a shell command that
55
+ * `docker:up` runs from the consumer's cwd BEFORE composing the stack, so a
56
+ * project can refresh whatever its compose file reads from `.env` (image
57
+ * tags, profiles, ports) on every up. A non-zero exit aborts the up.
58
+ *
59
+ * "hassan-devkit": { "docker": { "preUp": "scripts/worktree.sh env" } }
60
+ */
61
+ export function readDockerConfig() {
62
+ const cfg = readDevkitConfig().docker ?? {};
63
+ const preUp = typeof cfg.preUp === 'string' ? cfg.preUp.trim() : '';
64
+ return { preUp: preUp || null };
65
+ }