@20baht/cli 0.0.0-stage → 0.1.1

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.
Files changed (140) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +214 -2
  3. package/dist/application/create.js +72 -0
  4. package/dist/application/generate.js +239 -0
  5. package/dist/application/ports.js +1 -0
  6. package/dist/args.js +49 -0
  7. package/dist/cli.js +207 -0
  8. package/dist/domain/blueprint.js +6 -0
  9. package/dist/domain/create-plan.js +59 -0
  10. package/dist/domain/deploy-plan.js +82 -0
  11. package/dist/domain/form-dsl.js +120 -0
  12. package/dist/domain/generate-plan.js +60 -0
  13. package/dist/domain/naming.js +18 -0
  14. package/dist/domain/remote-plan.js +153 -0
  15. package/dist/domain/template-path.js +19 -0
  16. package/dist/infrastructure/fs-reader.js +19 -0
  17. package/dist/infrastructure/fs-writer.js +27 -0
  18. package/dist/infrastructure/shell-runner.js +32 -0
  19. package/dist/infrastructure/spawn-plan.js +35 -0
  20. package/dist/infrastructure/template-renderer.js +16 -0
  21. package/dist/infrastructure/template-source.js +28 -0
  22. package/package.json +53 -4
  23. package/templates/angular/README.md.hbs +46 -0
  24. package/templates/angular/_dependency-cruiser.mjs +51 -0
  25. package/templates/angular/apps/server/package.json +30 -0
  26. package/templates/angular/apps/server/src/app.ts +14 -0
  27. package/templates/angular/apps/server/src/index.ts +8 -0
  28. package/templates/angular/apps/server/test/app.test.ts +12 -0
  29. package/templates/angular/apps/server/tsconfig.json +7 -0
  30. package/templates/angular/apps/server/tsconfig.types.json +12 -0
  31. package/templates/angular/apps/shell/_editorconfig +17 -0
  32. package/templates/angular/apps/shell/angular.json +115 -0
  33. package/templates/angular/apps/shell/federation.config.mjs +44 -0
  34. package/templates/angular/apps/shell/package.json +43 -0
  35. package/templates/angular/apps/shell/public/federation.manifest.json +1 -0
  36. package/templates/angular/apps/shell/src/app/app.config.ts +20 -0
  37. package/templates/angular/apps/shell/src/app/app.css +4 -0
  38. package/templates/angular/apps/shell/src/app/app.html.hbs +16 -0
  39. package/templates/angular/apps/shell/src/app/app.routes.ts.hbs +39 -0
  40. package/templates/angular/apps/shell/src/app/app.ts +57 -0
  41. package/templates/angular/apps/shell/src/app/core/federation/load-remote.ts +31 -0
  42. package/templates/angular/apps/shell/src/app/core/federation/manifest.spec.ts +46 -0
  43. package/templates/angular/apps/shell/src/app/core/federation/manifest.ts +37 -0
  44. package/templates/angular/apps/shell/src/app/core/federation/remote-loader.ts +20 -0
  45. package/templates/angular/apps/shell/src/app/core/federation/timeout.ts +17 -0
  46. package/templates/angular/apps/shell/src/app/modules/home/home.component.ts.hbs +46 -0
  47. package/templates/angular/apps/shell/src/app/modules/unavailable/unavailable.component.ts +39 -0
  48. package/templates/angular/apps/shell/src/bootstrap.ts +25 -0
  49. package/templates/angular/apps/shell/src/environments/environment.development.ts +10 -0
  50. package/templates/angular/apps/shell/src/environments/environment.ts +10 -0
  51. package/templates/angular/apps/shell/src/index.html.hbs +12 -0
  52. package/templates/angular/apps/shell/src/main.ts +43 -0
  53. package/templates/angular/apps/shell/src/styles.css +19 -0
  54. package/templates/angular/apps/shell/tsconfig.app.json +10 -0
  55. package/templates/angular/apps/shell/tsconfig.federation.json +4 -0
  56. package/templates/angular/apps/shell/tsconfig.json.hbs +39 -0
  57. package/templates/angular/apps/shell/tsconfig.spec.json +9 -0
  58. package/templates/angular/bahtui.json +6 -0
  59. package/templates/angular/eslint.config.ts.hbs +28 -0
  60. package/templates/angular/knip.ts +30 -0
  61. package/templates/angular/package.json.hbs +52 -0
  62. package/templates/angular/packages/kit/package.json.hbs +27 -0
  63. package/templates/angular/packages/kit/src/api.ts +21 -0
  64. package/templates/angular/packages/kit/src/errors.ts +28 -0
  65. package/templates/angular/packages/kit/src/index.ts +2 -0
  66. package/templates/angular/packages/kit/test/errors.test.ts +28 -0
  67. package/templates/angular/packages/kit/tsconfig.json +9 -0
  68. package/templates/create/README.md.hbs +32 -0
  69. package/templates/create/_github/workflows/ci.yml +56 -0
  70. package/templates/create/_gitignore +6 -0
  71. package/templates/create/_husky/pre-commit +3 -0
  72. package/templates/create/_prettierignore +3 -0
  73. package/templates/create/_prettierrc.json +4 -0
  74. package/templates/create/apps/api/package.json.hbs +21 -0
  75. package/templates/create/apps/api/src/index.test.ts.hbs +10 -0
  76. package/templates/create/apps/api/src/index.ts.hbs +14 -0
  77. package/templates/create/apps/api/tsconfig.json +7 -0
  78. package/templates/create/apps/web/index.html.hbs +20 -0
  79. package/templates/create/apps/web/package.json.hbs +24 -0
  80. package/templates/create/apps/web/src/App.tsx.hbs +31 -0
  81. package/templates/create/apps/web/src/app.css +27 -0
  82. package/templates/create/apps/web/src/health.test.ts.hbs +28 -0
  83. package/templates/create/apps/web/src/health.ts.hbs +14 -0
  84. package/templates/create/apps/web/src/main.tsx.hbs +20 -0
  85. package/templates/create/apps/web/src/vite-env.d.ts.hbs +1 -0
  86. package/templates/create/apps/web/tsconfig.json +8 -0
  87. package/templates/create/apps/web/vite.config.ts.hbs +6 -0
  88. package/templates/create/bahtui.json.hbs +7 -0
  89. package/templates/create/eslint.config.js +30 -0
  90. package/templates/create/knip.json +9 -0
  91. package/templates/create/libs/shared/eden/index.ts.hbs +9 -0
  92. package/templates/create/libs/shared/eden/package.json.hbs +15 -0
  93. package/templates/create/libs/shared/eden/tsconfig.json +4 -0
  94. package/templates/create/package.json.hbs +47 -0
  95. package/templates/create/tsconfig.base.json +17 -0
  96. package/templates/deploy/deploy/__project__.service.hbs +23 -0
  97. package/templates/deploy/deploy/env.example.hbs +4 -0
  98. package/templates/deploy/deploy/install.sh.hbs +58 -0
  99. package/templates/deploy/deploy/nginx.conf.hbs +67 -0
  100. package/templates/deploy/scripts/deploy.ts.hbs +33 -0
  101. package/templates/deploy/scripts/preview.ts.hbs +57 -0
  102. package/templates/deploy/scripts/release.ts.hbs +48 -0
  103. package/templates/new/CLAUDE.md +3 -0
  104. package/templates/new/README.md.hbs +38 -0
  105. package/templates/new/_dependency-cruiser.mjs +9 -0
  106. package/templates/new/_github/actions/setup/action.yml +15 -0
  107. package/templates/new/_github/workflows/ci.yml +122 -0
  108. package/templates/new/_gitignore +12 -0
  109. package/templates/new/_gitleaks.toml +6 -0
  110. package/templates/new/_husky/commit-msg +1 -0
  111. package/templates/new/_husky/pre-commit +8 -0
  112. package/templates/new/_husky/pre-push +1 -0
  113. package/templates/new/_jscpd.json +20 -0
  114. package/templates/new/_mcp.json +9 -0
  115. package/templates/new/_prettierignore +5 -0
  116. package/templates/new/apps/_gitkeep +0 -0
  117. package/templates/new/commitlint.config.js +1 -0
  118. package/templates/new/eslint.config.ts.hbs +7 -0
  119. package/templates/new/knip.ts +7 -0
  120. package/templates/new/lint-staged.config.js +1 -0
  121. package/templates/new/package.json.hbs +51 -0
  122. package/templates/new/packages/_gitkeep +0 -0
  123. package/templates/new/renovate.json +23 -0
  124. package/templates/new/scripts/dev.ts +54 -0
  125. package/templates/new/scripts/each.ts +29 -0
  126. package/templates/new/scripts/workspaces.ts +24 -0
  127. package/templates/new/tsconfig.base.json +3 -0
  128. package/templates/new/tsconfig.json +7 -0
  129. package/templates/remote/_editorconfig +17 -0
  130. package/templates/remote/angular.json.hbs +95 -0
  131. package/templates/remote/federation.config.mjs.hbs +48 -0
  132. package/templates/remote/package.json.hbs +38 -0
  133. package/templates/remote/src/app/__name__.routes.ts.hbs +12 -0
  134. package/templates/remote/src/app/modules/__name__/__name__.component.ts.hbs +37 -0
  135. package/templates/remote/src/app/services/__name__.service.ts.hbs +14 -0
  136. package/templates/remote/src/index.html.hbs +11 -0
  137. package/templates/remote/src/main.ts.hbs +3 -0
  138. package/templates/remote/tsconfig.app.json +10 -0
  139. package/templates/remote/tsconfig.federation.json +4 -0
  140. package/templates/remote/tsconfig.json.hbs +36 -0
package/dist/cli.js ADDED
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ import { resolve } from 'node:path';
3
+ import { readFileSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { runCreate, CreateError } from './application/create.js';
6
+ import { runGenerate, runGenerateDeploy, runGenerateRemote, runInit, GenerateError, } from './application/generate.js';
7
+ import { DiskTemplateSource } from './infrastructure/template-source.js';
8
+ import { TemplateRenderer } from './infrastructure/template-renderer.js';
9
+ import { DiskFileWriter } from './infrastructure/fs-writer.js';
10
+ import { DiskFileReader } from './infrastructure/fs-reader.js';
11
+ import { ShellRunner } from './infrastructure/shell-runner.js';
12
+ import { KNOWN_FLAGS, parseArgs } from './args.js';
13
+ const HELP = `bahtui — bun-workspace DDD scaffolding (React or Angular + Elysia + Eden)
14
+
15
+ Usage:
16
+ bahtui new <name> [options] bare bun workspace in ./<name> — toolchain only
17
+ (eslint, prettier, knip, husky, commitlint, gitleaks, jscpd, depcruise, CI), no apps
18
+ bahtui create <name> [options] full monorepo in ./<name> (React + Elysia + Eden)
19
+ bahtui create <name> --angular Angular Native Federation host + one remote + Elysia
20
+ server + shared web kit, on the new toolchain
21
+ bahtui init [options] write bahtui.json into an existing repo
22
+ bahtui g model <domain> libs/domain/<d>/model package
23
+ bahtui g form <domain>/<name> --fields "key:type:mod,…"
24
+ engine-validated FormDefinition JSON
25
+ bahtui g remote <name> Angular workspace: apps/<name>-web remote, added to the
26
+ host manifests, eslint, knip and dependency-cruiser
27
+ bahtui g deploy [nginx] Angular workspace: deploy/ (nginx, systemd, install.sh)
28
+ and release / deploy / preview scripts
29
+ Field DSL:
30
+ title:text:required,priority:dropdown:options=low|medium|high,qty:number:min=1
31
+
32
+ Options:
33
+ --fields <dsl> g form: the field list (required)
34
+ --angular create: the Angular Native Federation scaffold instead of React
35
+ --frontend <react|none> init: default react
36
+ --backend <elysia|none> init: default elysia
37
+ --dry-run print what would be generated, write nothing
38
+ --no-install new/create: skip "bun install" (also skips the initial commit)
39
+ --no-git new/create: skip git init + initial commit
40
+ --skip-install / --skip-git Angular-style aliases of the two above
41
+ --force overwrite existing files/dirs
42
+ -h, --help this help
43
+ -v, --version print version
44
+ `;
45
+ function version() {
46
+ const pkg = fileURLToPath(new URL('../package.json', import.meta.url));
47
+ return JSON.parse(readFileSync(pkg, 'utf8')).version;
48
+ }
49
+ const log = {
50
+ info: (m) => {
51
+ console.log(m);
52
+ },
53
+ step: (m) => {
54
+ console.log(`• ${m}`);
55
+ },
56
+ error: (m) => {
57
+ console.error(`✖ ${m}`);
58
+ },
59
+ };
60
+ /** Handles unknown flags, --version and --help; null = carry on. */
61
+ function preflight({ flags }) {
62
+ const unknownFlags = [...flags].filter((f) => !KNOWN_FLAGS.has(f));
63
+ if (unknownFlags.length > 0) {
64
+ log.error(`Unknown flag${unknownFlags.length > 1 ? 's' : ''}: ${unknownFlags.join(', ')}`);
65
+ return 1;
66
+ }
67
+ if (flags.has('-v') || flags.has('--version')) {
68
+ try {
69
+ log.info(version());
70
+ return 0;
71
+ }
72
+ catch (err) {
73
+ log.error(`cannot read package version: ${String(err)}`);
74
+ return 1;
75
+ }
76
+ }
77
+ if (flags.has('-h') || flags.has('--help')) {
78
+ log.info(HELP);
79
+ return 0;
80
+ }
81
+ return null;
82
+ }
83
+ function presetFor(a, command) {
84
+ if (command === 'new')
85
+ return 'workspace';
86
+ return a.flags.has('--angular') ? 'angular' : 'full';
87
+ }
88
+ function commandCreate(a, command) {
89
+ if (!a.name) {
90
+ log.error(`${command} needs a project name: bahtui ${command} <name>`);
91
+ return 1;
92
+ }
93
+ runCreate({
94
+ name: a.name,
95
+ preset: presetFor(a, command),
96
+ targetDir: resolve(process.cwd(), a.name),
97
+ install: !a.flags.has('--no-install') && !a.flags.has('--skip-install'),
98
+ git: !a.flags.has('--no-git') && !a.flags.has('--skip-git'),
99
+ dryRun: a.flags.has('--dry-run'),
100
+ force: a.flags.has('--force'),
101
+ }, {
102
+ templates: new DiskTemplateSource(),
103
+ renderer: new TemplateRenderer(),
104
+ writer: new DiskFileWriter(),
105
+ runner: new ShellRunner(),
106
+ log,
107
+ });
108
+ return 0;
109
+ }
110
+ /** A flag that picks one stack or `none`; anything else is a typo, not a request for the default. */
111
+ function stackFlag(flag, value, stack) {
112
+ if (value === undefined || value === stack)
113
+ return stack;
114
+ if (value === 'none')
115
+ return null;
116
+ throw new GenerateError(`${flag} takes ${stack} or none, not ${JSON.stringify(value)}.`);
117
+ }
118
+ function commandInit(a, generateDeps) {
119
+ runInit({
120
+ root: process.cwd(),
121
+ frontend: stackFlag('--frontend', a.frontend, 'react'),
122
+ backend: stackFlag('--backend', a.backend, 'elysia'),
123
+ dryRun: a.flags.has('--dry-run'),
124
+ force: a.flags.has('--force'),
125
+ }, generateDeps);
126
+ return 0;
127
+ }
128
+ function commandGenerate(a, generateDeps) {
129
+ const { name, sub } = a;
130
+ if (name === 'remote')
131
+ return commandRemote(a, generateDeps);
132
+ if (name === 'deploy')
133
+ return commandDeploy(a, generateDeps);
134
+ if (name !== 'model' && name !== 'form') {
135
+ log.error('Unknown generator — bahtui g model <domain> | g form <domain>/<name> | g remote <name> | g deploy.');
136
+ return 1;
137
+ }
138
+ if (!sub) {
139
+ log.error(`g ${name} needs a target: bahtui g ${name} <${name === 'model' ? 'domain' : 'domain/name'}>`);
140
+ return 1;
141
+ }
142
+ runGenerate({
143
+ root: process.cwd(),
144
+ kind: name,
145
+ target: sub,
146
+ fields: a.fields,
147
+ dryRun: a.flags.has('--dry-run'),
148
+ force: a.flags.has('--force'),
149
+ }, generateDeps);
150
+ return 0;
151
+ }
152
+ function commandRemote(a, generateDeps) {
153
+ if (!a.sub) {
154
+ log.error('g remote needs a name: bahtui g remote <name>');
155
+ return 1;
156
+ }
157
+ runGenerateRemote({
158
+ root: process.cwd(),
159
+ name: a.sub,
160
+ dryRun: a.flags.has('--dry-run'),
161
+ force: a.flags.has('--force'),
162
+ }, { ...generateDeps, templates: new DiskTemplateSource(), renderer: new TemplateRenderer() });
163
+ return 0;
164
+ }
165
+ function commandDeploy(a, generateDeps) {
166
+ if (a.sub !== undefined && a.sub !== 'nginx') {
167
+ log.error(`g deploy knows one target, nginx (got "${a.sub}").`);
168
+ return 1;
169
+ }
170
+ runGenerateDeploy({ root: process.cwd(), dryRun: a.flags.has('--dry-run'), force: a.flags.has('--force') }, { ...generateDeps, templates: new DiskTemplateSource(), renderer: new TemplateRenderer() });
171
+ return 0;
172
+ }
173
+ function dispatch(a, command) {
174
+ const generateDeps = {
175
+ reader: new DiskFileReader(),
176
+ writer: new DiskFileWriter(),
177
+ log,
178
+ };
179
+ if (command === 'create' || command === 'new')
180
+ return commandCreate(a, command);
181
+ if (command === 'init')
182
+ return commandInit(a, generateDeps);
183
+ if (command === 'g')
184
+ return commandGenerate(a, generateDeps);
185
+ log.error(`Unknown command "${command}".`);
186
+ log.error(HELP);
187
+ return 1;
188
+ }
189
+ function main(rawArgv) {
190
+ const parsed = parseArgs(rawArgv);
191
+ const early = preflight(parsed);
192
+ if (early !== null)
193
+ return early;
194
+ if (parsed.command === undefined) {
195
+ log.error('No command given — see usage below.');
196
+ log.error(HELP);
197
+ return 1;
198
+ }
199
+ try {
200
+ return dispatch(parsed, parsed.command);
201
+ }
202
+ catch (err) {
203
+ log.error(err instanceof CreateError || err instanceof GenerateError ? err.message : String(err));
204
+ return 1;
205
+ }
206
+ }
207
+ process.exit(main(process.argv.slice(2)));
@@ -0,0 +1,6 @@
1
+ /**
2
+ * A Blueprint is WHAT will be generated, as plain data — no fs, no side
3
+ * effects. Adapters (fs-writer, shell-runner) make it real; --dry-run just
4
+ * prints it. This split is the testing seam for every generator.
5
+ */
6
+ export {};
@@ -0,0 +1,59 @@
1
+ import { isTemplate, outputPath } from './template-path.js';
2
+ /** Template sets per preset; a later set's file replaces an earlier one at the same path. */
3
+ export const PRESET_TEMPLATE_SETS = {
4
+ full: ['create'],
5
+ workspace: ['new'],
6
+ angular: ['new', 'angular'],
7
+ };
8
+ /** The Angular preset's host app folder. */
9
+ export const ANGULAR_HOST = 'apps/shell';
10
+ /**
11
+ * Lays template sets over each other by output path (`x.hbs` and `x` are the same file). A
12
+ * `_gitkeep` placeholder is dropped from any folder a later set puts files in.
13
+ */
14
+ export function overlayTemplates(sets) {
15
+ const byPath = new Map();
16
+ for (const set of sets)
17
+ for (const t of set)
18
+ byPath.set(t.relPath.replace(/\.hbs$/, ''), t);
19
+ const all = [...byPath.values()];
20
+ const dirOf = (p) => p.slice(0, p.lastIndexOf('/') + 1);
21
+ return all.filter((t) => !t.relPath.endsWith('_gitkeep') ||
22
+ !all.some((o) => o !== t && o.relPath.startsWith(dirOf(t.relPath))));
23
+ }
24
+ /**
25
+ * Template naming conventions (the whole contract between templates/ and here):
26
+ * - `*.hbs` → rendered with the data below, suffix stripped.
27
+ * anything else → copied verbatim (so files with `${{ }}` like ci.yml
28
+ * never meet the renderer).
29
+ * - leading `_` on a basename → `.` (npm pack silently drops/renames real
30
+ * .gitignore files inside packages, so templates ship `_gitignore`).
31
+ */
32
+ export function planCreate(options, templates, render) {
33
+ const data = { name: options.name };
34
+ const files = templates
35
+ .map((t) => {
36
+ const contents = isTemplate(t.relPath) ? render(t.raw, data) : t.raw;
37
+ return { path: outputPath(t.relPath), contents };
38
+ })
39
+ .sort((a, b) => (a.path < b.path ? -1 : 1)); // codepoint order — stable across locales
40
+ const postCommands = [];
41
+ if (options.git) {
42
+ postCommands.push({ cmd: 'git', args: ['init', '-b', 'main'], label: 'git init' });
43
+ }
44
+ if (options.install) {
45
+ // after git init so husky's prepare hook finds .git
46
+ postCommands.push({ cmd: 'bun', args: ['install'], label: 'bun install' });
47
+ }
48
+ if (options.git && options.install) {
49
+ // the first commit runs the freshly installed pre-commit hook — the
50
+ // generated repo proves its own toolchain before the user touches it
51
+ postCommands.push({ cmd: 'git', args: ['add', '-A'], label: 'git add' });
52
+ postCommands.push({
53
+ cmd: 'git',
54
+ args: ['commit', '-m', 'chore: scaffold with @20baht/cli'],
55
+ label: 'git commit (pre-commit hook runs here)',
56
+ });
57
+ }
58
+ return { root: options.targetDir, files, postCommands };
59
+ }
@@ -0,0 +1,82 @@
1
+ /** The server template listens on `PORT`, 3001 unless set. */
2
+ export const DEFAULT_API_PORT = 3001;
3
+ export class DeployPlanError extends Error {
4
+ }
5
+ const SCRIPTS = {
6
+ release: 'bun run scripts/release.ts',
7
+ deploy: 'bun run scripts/deploy.ts',
8
+ preview: 'bun run scripts/preview.ts',
9
+ };
10
+ const RELEASE_DIR = '.release';
11
+ const ESLINT_IGNORE = [
12
+ '// What `bun run release` builds: bundled output, not source.',
13
+ "{ ignores: ['.release/**'] },",
14
+ ];
15
+ function withLine(text, line) {
16
+ if (text.split('\n').some((l) => l.trim() === line))
17
+ return text;
18
+ return `${text.endsWith('\n') || text === '' ? text : `${text}\n`}${line}\n`;
19
+ }
20
+ function withScripts(text) {
21
+ let pkg;
22
+ try {
23
+ pkg = JSON.parse(text);
24
+ }
25
+ catch {
26
+ throw new DeployPlanError('package.json is not valid JSON.');
27
+ }
28
+ if (typeof pkg !== 'object' || pkg === null || Array.isArray(pkg)) {
29
+ throw new DeployPlanError('package.json must hold a JSON object.');
30
+ }
31
+ const record = pkg;
32
+ const scripts = (record.scripts ?? {});
33
+ const taken = Object.keys(SCRIPTS).filter((name) => name in scripts);
34
+ if (taken.length > 0) {
35
+ throw new DeployPlanError(`package.json already has ${taken.map((t) => `"${t}"`).join(', ')} — remove them or use --force.`);
36
+ }
37
+ return JSON.stringify({ ...record, scripts: { ...scripts, ...SCRIPTS } }, null, 2) + '\n';
38
+ }
39
+ function withEslintIgnore(text) {
40
+ if (text.includes("'.release/**'"))
41
+ return text;
42
+ const lines = text.split('\n');
43
+ const at = lines.findIndex((l) => l.includes('defineConfig(['));
44
+ if (at === -1) {
45
+ throw new DeployPlanError(`eslint.config.ts has no "defineConfig([" to add the release folder to. Add this by hand:\n${ESLINT_IGNORE.join('\n')}`);
46
+ }
47
+ lines.splice(at + 1, 0, ...ESLINT_IGNORE.map((l) => ` ${l}`));
48
+ return lines.join('\n');
49
+ }
50
+ /**
51
+ * The deploy files rendered from `templates/deploy` (`__project__` in a path is the project
52
+ * name), plus the edits: package.json scripts, `.release` in `.gitignore` / `.prettierignore`, and
53
+ * an eslint ignore for it. `force` replaces existing release/deploy/preview scripts.
54
+ */
55
+ export function planDeploy(target, current, templates, render, force = false) {
56
+ const files = templates.map((t) => {
57
+ const isTemplate = t.relPath.endsWith('.hbs');
58
+ const rel = isTemplate ? t.relPath.slice(0, -'.hbs'.length) : t.relPath;
59
+ return {
60
+ path: rel.replaceAll('__project__', target.project),
61
+ contents: isTemplate ? render(t.raw, { ...target }) : t.raw,
62
+ };
63
+ });
64
+ const packageJson = force ? withoutScripts(current.packageJson) : current.packageJson;
65
+ return [
66
+ ...files,
67
+ { path: 'package.json', contents: withScripts(packageJson) },
68
+ { path: '.gitignore', contents: withLine(current.gitignore, RELEASE_DIR) },
69
+ { path: '.prettierignore', contents: withLine(current.prettierignore, RELEASE_DIR) },
70
+ { path: 'eslint.config.ts', contents: withEslintIgnore(current.eslint) },
71
+ ];
72
+ }
73
+ function withoutScripts(text) {
74
+ try {
75
+ const pkg = JSON.parse(text);
76
+ const scripts = Object.entries(pkg.scripts ?? {}).filter(([name]) => !(name in SCRIPTS));
77
+ return JSON.stringify({ ...pkg, scripts: Object.fromEntries(scripts) });
78
+ }
79
+ catch {
80
+ return text;
81
+ }
82
+ }
@@ -0,0 +1,120 @@
1
+ import { parseSchema } from '@20baht/validator';
2
+ /**
3
+ * Compact field DSL for `bahtui g form` (spec 04-adjacent, PRD P3):
4
+ *
5
+ * --fields "title:text:required,priority:dropdown:options=low|medium|high,qty:number"
6
+ *
7
+ * field = key ':' type (':' modifier)*
8
+ * mods = 'required' | 'options=a|b|c' | 'min=N' | 'max=N' | 'step=N' | 'ref=LOOKUP' | 'flag=NAME'
9
+ *
10
+ * The result is engine-validated (parseSchema) BEFORE any file is written —
11
+ * an invalid spec exits 1 with zero files (the P1 guarantee, kept).
12
+ */
13
+ const FIELD_TYPES = new Set([
14
+ 'text',
15
+ 'textarea',
16
+ 'markdown',
17
+ 'number',
18
+ 'currency',
19
+ 'email',
20
+ 'password',
21
+ 'dropdown',
22
+ 'multiselect',
23
+ 'checkbox',
24
+ 'radio',
25
+ 'toggle',
26
+ 'date',
27
+ 'file',
28
+ 'rating',
29
+ 'range',
30
+ 'reference',
31
+ 'tags',
32
+ ]);
33
+ const KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
34
+ const titleCase = (key) => key
35
+ .split('_')
36
+ .map((w) => (w ? w[0].toUpperCase() + w.slice(1) : w))
37
+ .join(' ');
38
+ /** `min=`/`max=` must be a real, non-empty number — never silently coerced to NaN/0. */
39
+ function parseNumberMod(name, raw, part) {
40
+ const n = Number(raw);
41
+ if (raw.trim() === '' || !Number.isFinite(n)) {
42
+ throw new FormDslError(`Bad ${name} value ${JSON.stringify(raw)} in "${part}" — expected a number.`);
43
+ }
44
+ return n;
45
+ }
46
+ function parseOptionsMod(mod, part) {
47
+ const opts = mod
48
+ .slice('options='.length)
49
+ .split('|')
50
+ .map((o) => o.trim())
51
+ .filter(Boolean);
52
+ if (opts.length === 0) {
53
+ throw new FormDslError(`options modifier needs at least one value in "${part}".`);
54
+ }
55
+ if (new Set(opts).size !== opts.length) {
56
+ throw new FormDslError(`Duplicate option keys in "${part}".`);
57
+ }
58
+ return opts.map((o) => ({ key: o, label: titleCase(o) }));
59
+ }
60
+ function applyModifier(field, mod, part) {
61
+ if (mod === 'required')
62
+ field.required = true;
63
+ else if (mod.startsWith('options='))
64
+ field.options = parseOptionsMod(mod, part);
65
+ else if (mod.startsWith('min='))
66
+ field.min = parseNumberMod('min', mod.slice(4), part);
67
+ else if (mod.startsWith('max='))
68
+ field.max = parseNumberMod('max', mod.slice(4), part);
69
+ else if (mod.startsWith('step='))
70
+ field.step = parseNumberMod('step', mod.slice(5), part);
71
+ else if (mod.startsWith('ref='))
72
+ field.reference = mod.slice(4);
73
+ else if (mod.startsWith('flag='))
74
+ field.flag = mod.slice(5);
75
+ else
76
+ throw new FormDslError(`Unknown modifier ${JSON.stringify(mod)} in "${part}".`);
77
+ }
78
+ function parseFieldPart(part, order) {
79
+ const [key, type, ...mods] = part.split(':').map((s) => s.trim());
80
+ if (!key || !KEY_PATTERN.test(key)) {
81
+ throw new FormDslError(`Bad field key ${JSON.stringify(key ?? '')} in "${part}".`);
82
+ }
83
+ if (!type || !FIELD_TYPES.has(type)) {
84
+ throw new FormDslError(`Unknown field type ${JSON.stringify(type ?? '')} in "${part}" — one of: ${[...FIELD_TYPES].join(', ')}.`);
85
+ }
86
+ const field = { order, type, key, label: titleCase(key) };
87
+ for (const mod of mods)
88
+ applyModifier(field, mod, part);
89
+ return field;
90
+ }
91
+ export function parseFieldsDsl(dsl) {
92
+ const parts = dsl
93
+ .split(',')
94
+ .map((p) => p.trim())
95
+ .filter(Boolean);
96
+ if (parts.length === 0)
97
+ throw new FormDslError('No fields given — pass --fields "key:type,…".');
98
+ const fields = parts.map((part, i) => parseFieldPart(part, i + 1));
99
+ const keys = fields.map((f) => f.key);
100
+ if (new Set(keys).size !== keys.length) {
101
+ throw new FormDslError('Field keys must be unique.');
102
+ }
103
+ return fields;
104
+ }
105
+ /** DSL -> FormDefinition, engine-validated. Throws FormDslError on any problem. */
106
+ export function buildFormDefinition(domain, name, dsl) {
107
+ const form = {
108
+ form_id: `${domain}-${name}`,
109
+ form_name: titleCase(name.replace(/-/g, '_')).replace(/ /g, '_'),
110
+ fields: parseFieldsDsl(dsl),
111
+ };
112
+ try {
113
+ return parseSchema(JSON.stringify(form));
114
+ }
115
+ catch (err) {
116
+ throw new FormDslError(`Engine rejected the form spec: ${err instanceof Error ? err.message : String(err)}`);
117
+ }
118
+ }
119
+ export class FormDslError extends Error {
120
+ }
@@ -0,0 +1,60 @@
1
+ export const DEFAULT_CONFIG = {
2
+ apps: { web: 'apps/web', api: 'apps/api' },
3
+ libsDir: 'libs',
4
+ frontend: 'react',
5
+ backend: 'elysia',
6
+ edenClient: 'libs/shared/eden',
7
+ };
8
+ const DOMAIN_PATTERN = /^[a-z][a-z0-9-]*$/;
9
+ export function validateDomainName(domain) {
10
+ return DOMAIN_PATTERN.test(domain)
11
+ ? []
12
+ : [`"${domain}" is not a valid domain name — lowercase letters, digits, dashes.`];
13
+ }
14
+ /** `bahtui init` — write bahtui.json into an existing repo (root = cwd). */
15
+ export function planInit(root, config) {
16
+ return {
17
+ root,
18
+ files: [{ path: 'bahtui.json', contents: JSON.stringify(config, null, 2) + '\n' }],
19
+ postCommands: [],
20
+ };
21
+ }
22
+ export function modelDir(config, domain) {
23
+ return `${config.libsDir}/domain/${domain}/model`;
24
+ }
25
+ /** `bahtui g model <domain>` — the framework-free domain model lib (PRD). */
26
+ export function planModel(root, config, domain) {
27
+ const dir = modelDir(config, domain);
28
+ const pkg = {
29
+ name: `domain-${domain}-model`,
30
+ version: '0.0.0',
31
+ private: true,
32
+ type: 'module',
33
+ exports: { '.': './src/index.ts' },
34
+ };
35
+ return {
36
+ root,
37
+ files: [
38
+ { path: `${dir}/package.json`, contents: JSON.stringify(pkg, null, 2) + '\n' },
39
+ {
40
+ path: `${dir}/src/index.ts`,
41
+ contents: `// ${domain} domain model — entities and form JSON live here.\n// NO react, NO elysia in this package (dependency rule: everything points AT model).\nexport {};\n`,
42
+ },
43
+ ],
44
+ postCommands: [],
45
+ };
46
+ }
47
+ /** `bahtui g form <domain>/<name>` — engine-validated FormDefinition JSON. */
48
+ export function planForm(root, config, domain, name, form) {
49
+ const dir = modelDir(config, domain);
50
+ return {
51
+ root,
52
+ files: [
53
+ {
54
+ path: `${dir}/src/${name}.form.json`,
55
+ contents: JSON.stringify(form, null, 2) + '\n',
56
+ },
57
+ ],
58
+ postCommands: [],
59
+ };
60
+ }
@@ -0,0 +1,18 @@
1
+ /** Project-name rules: must be usable as npm scope, directory, and package name. */
2
+ const NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
3
+ const RESERVED = new Set(['node_modules', 'apps', 'libs', 'src', 'dist', 'test', 'bun']);
4
+ export function validateProjectName(name) {
5
+ const errors = [];
6
+ if (name.length === 0)
7
+ errors.push('Project name is required.');
8
+ else if (name.length > 64)
9
+ errors.push('Project name must be 64 characters or fewer.');
10
+ if (name.length > 0 && !NAME_PATTERN.test(name)) {
11
+ errors.push(`"${name}" is not a valid project name — use lowercase letters, digits and dashes, starting with a letter (it becomes the @${name}/* package scope).`);
12
+ }
13
+ if (RESERVED.has(name))
14
+ errors.push(`"${name}" is a reserved name.`);
15
+ if (name.endsWith('-'))
16
+ errors.push('Project name must not end with a dash.');
17
+ return errors;
18
+ }