@forinda/kickjs-cli 5.0.2 → 5.2.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/dist/builtins-BW3g09hP.mjs +8538 -0
- package/dist/builtins-C_VfEGdg.mjs +4182 -0
- package/dist/builtins-C_VfEGdg.mjs.map +1 -0
- package/dist/cli.mjs +21 -9299
- package/dist/config-DDrgs-I3.mjs +171 -0
- package/dist/config-DDrgs-I3.mjs.map +1 -0
- package/dist/config-DsQe2yzy.mjs +169 -0
- package/dist/generator-extension-DRNQpoZP.mjs +4380 -0
- package/dist/generator-extension-DRNQpoZP.mjs.map +1 -0
- package/dist/index.d.mts +513 -138
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +5 -4159
- package/dist/plugin-6_YlK-JG.mjs +71 -0
- package/dist/plugin-6_YlK-JG.mjs.map +1 -0
- package/dist/plugin-CQ0yYXyr.mjs +80 -0
- package/dist/rolldown-runtime-CYBbkZNy.mjs +24 -0
- package/dist/run-plugins-B1R0HG0g.mjs +12 -0
- package/dist/typegen-CYCsmCRF.mjs +1351 -0
- package/dist/{typegen-D8MJ2hPX.mjs → typegen-DugZmi-0.mjs} +127 -224
- package/dist/typegen-DugZmi-0.mjs.map +1 -0
- package/dist/types-CGB8BiQh.mjs +25 -0
- package/dist/types-CGB8BiQh.mjs.map +1 -0
- package/package.json +9 -3
- package/dist/index.mjs.map +0 -1
- package/dist/typegen-D8MJ2hPX.mjs.map +0 -1
|
@@ -0,0 +1,4380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forinda/kickjs-cli v5.2.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Felix Orinda
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
13
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
15
|
+
import * as clack from "@clack/prompts";
|
|
16
|
+
import pc from "picocolors";
|
|
17
|
+
import pkg from "pluralize";
|
|
18
|
+
import { execSync } from "node:child_process";
|
|
19
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
20
|
+
//#region src/utils/fs.ts
|
|
21
|
+
let _dryRun = false;
|
|
22
|
+
/** Enable/disable dry run mode globally for all writeFileSafe calls */
|
|
23
|
+
function setDryRun(enabled) {
|
|
24
|
+
_dryRun = enabled;
|
|
25
|
+
}
|
|
26
|
+
/** Extensions oxfmt can format. Anything else is written verbatim. */
|
|
27
|
+
const FORMATTABLE = new Set([
|
|
28
|
+
".ts",
|
|
29
|
+
".tsx",
|
|
30
|
+
".js",
|
|
31
|
+
".jsx",
|
|
32
|
+
".mjs",
|
|
33
|
+
".cjs",
|
|
34
|
+
".json",
|
|
35
|
+
".md"
|
|
36
|
+
]);
|
|
37
|
+
/**
|
|
38
|
+
* Write a file, creating parent directories if needed.
|
|
39
|
+
*
|
|
40
|
+
* After write, runs oxfmt against the file when:
|
|
41
|
+
* - format-on-write is enabled (default)
|
|
42
|
+
* - the extension is in {@link FORMATTABLE}
|
|
43
|
+
* - oxfmt resolves from the user's project (or our own cwd)
|
|
44
|
+
*
|
|
45
|
+
* Failures (missing oxfmt, unparseable source, formatter crash) are
|
|
46
|
+
* swallowed silently — formatting is a polish step, not a correctness
|
|
47
|
+
* gate. The pre-commit hook still catches anything we couldn't format.
|
|
48
|
+
*
|
|
49
|
+
* Skips writing entirely in dry run mode.
|
|
50
|
+
*/
|
|
51
|
+
async function writeFileSafe(filePath, content) {
|
|
52
|
+
if (_dryRun) return;
|
|
53
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
54
|
+
await writeFile(filePath, content, "utf-8");
|
|
55
|
+
if (FORMATTABLE.has(extname(filePath))) await formatFile(filePath, content).catch(() => {});
|
|
56
|
+
}
|
|
57
|
+
let _oxfmt = void 0;
|
|
58
|
+
/** Resolve oxfmt from the user's project; cache the result (or null) for the process. */
|
|
59
|
+
async function resolveOxfmt(cwd) {
|
|
60
|
+
if (_oxfmt !== void 0) return _oxfmt;
|
|
61
|
+
try {
|
|
62
|
+
_oxfmt = await import(createRequire(join(cwd, "package.json")).resolve("oxfmt"));
|
|
63
|
+
} catch {
|
|
64
|
+
_oxfmt = null;
|
|
65
|
+
}
|
|
66
|
+
return _oxfmt;
|
|
67
|
+
}
|
|
68
|
+
async function formatFile(filePath, content) {
|
|
69
|
+
const oxfmt = await resolveOxfmt(process.cwd());
|
|
70
|
+
if (!oxfmt) return;
|
|
71
|
+
const options = await loadOxfmtConfig(filePath);
|
|
72
|
+
if (options === null) return;
|
|
73
|
+
const result = await oxfmt.format(filePath, content, options);
|
|
74
|
+
if (result.code === content) return;
|
|
75
|
+
await writeFile(filePath, result.code, "utf-8");
|
|
76
|
+
}
|
|
77
|
+
const _oxfmtConfigCache = /* @__PURE__ */ new Map();
|
|
78
|
+
/**
|
|
79
|
+
* Walk up from `filePath`'s directory looking for `.oxfmtrc.json`.
|
|
80
|
+
* Returns `null` when no config is found anywhere on the path —
|
|
81
|
+
* generators then leave the raw template alone (which already
|
|
82
|
+
* follows project conventions). Cached per starting directory so
|
|
83
|
+
* the walk is one-shot per generator run.
|
|
84
|
+
*/
|
|
85
|
+
async function loadOxfmtConfig(filePath) {
|
|
86
|
+
let dir = dirname(filePath);
|
|
87
|
+
const startDir = dir;
|
|
88
|
+
if (_oxfmtConfigCache.has(startDir)) return _oxfmtConfigCache.get(startDir);
|
|
89
|
+
while (true) {
|
|
90
|
+
const configPath = join(dir, ".oxfmtrc.json");
|
|
91
|
+
if (existsSync(configPath)) try {
|
|
92
|
+
const raw = await readFile(configPath, "utf-8");
|
|
93
|
+
const parsed = JSON.parse(raw);
|
|
94
|
+
delete parsed["$schema"];
|
|
95
|
+
delete parsed.ignorePatterns;
|
|
96
|
+
_oxfmtConfigCache.set(startDir, parsed);
|
|
97
|
+
return parsed;
|
|
98
|
+
} catch {
|
|
99
|
+
_oxfmtConfigCache.set(startDir, null);
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
const parent = dirname(dir);
|
|
103
|
+
if (parent === dir) {
|
|
104
|
+
_oxfmtConfigCache.set(startDir, null);
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
dir = parent;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Check if a file exists */
|
|
111
|
+
async function fileExists(filePath) {
|
|
112
|
+
try {
|
|
113
|
+
await access(filePath);
|
|
114
|
+
return true;
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/utils/colors.ts
|
|
121
|
+
const METHOD_COLOR_MAP = {
|
|
122
|
+
GET: pc.green,
|
|
123
|
+
POST: pc.cyan,
|
|
124
|
+
PUT: pc.yellow,
|
|
125
|
+
PATCH: pc.magenta,
|
|
126
|
+
DELETE: pc.red
|
|
127
|
+
};
|
|
128
|
+
/** Color an HTTP method string for terminal display */
|
|
129
|
+
function httpMethodColor(method) {
|
|
130
|
+
return (METHOD_COLOR_MAP[method] ?? pc.dim)(method.padEnd(7));
|
|
131
|
+
}
|
|
132
|
+
/** Color a severity tag for terminal display (padded to 10 chars) */
|
|
133
|
+
function severityColor(severity) {
|
|
134
|
+
const tag = `[${severity}]`.padEnd(10);
|
|
135
|
+
switch (severity) {
|
|
136
|
+
case "CRITICAL": return pc.red(tag);
|
|
137
|
+
case "WARNING": return pc.yellow(tag);
|
|
138
|
+
case "INFO": return pc.blue(pc.dim(tag));
|
|
139
|
+
default: return tag;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
pc.green("✓"), pc.red("✖"), pc.yellow("⚠"), pc.blue("ℹ");
|
|
143
|
+
/** Show branded intro banner */
|
|
144
|
+
function intro(title) {
|
|
145
|
+
clack.intro(pc.bgCyan(pc.black(` ${title} `)));
|
|
146
|
+
}
|
|
147
|
+
/** Show closing message */
|
|
148
|
+
function outro(message) {
|
|
149
|
+
clack.outro(message);
|
|
150
|
+
}
|
|
151
|
+
/** Handle cancellation — print message and exit */
|
|
152
|
+
function handleCancel(value) {
|
|
153
|
+
if (clack.isCancel(value)) {
|
|
154
|
+
clack.cancel("Operation cancelled.");
|
|
155
|
+
process.exit(0);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/** Text input prompt */
|
|
159
|
+
async function text(opts) {
|
|
160
|
+
const value = await clack.text(opts);
|
|
161
|
+
handleCancel(value);
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
/** Single select prompt */
|
|
165
|
+
async function select(opts) {
|
|
166
|
+
const value = await clack.select(opts);
|
|
167
|
+
handleCancel(value);
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
/** Multi-select prompt with checkboxes */
|
|
171
|
+
async function multiSelect(opts) {
|
|
172
|
+
const value = await clack.multiselect(opts);
|
|
173
|
+
handleCancel(value);
|
|
174
|
+
return value;
|
|
175
|
+
}
|
|
176
|
+
/** Yes/no confirmation prompt */
|
|
177
|
+
async function confirm(opts) {
|
|
178
|
+
const value = await clack.confirm(opts);
|
|
179
|
+
handleCancel(value);
|
|
180
|
+
return value;
|
|
181
|
+
}
|
|
182
|
+
/** Create a spinner for progress indication */
|
|
183
|
+
function spinner() {
|
|
184
|
+
return clack.spinner();
|
|
185
|
+
}
|
|
186
|
+
/** Log utilities for styled messages inside clack flow */
|
|
187
|
+
const log = clack.log;
|
|
188
|
+
//#endregion
|
|
189
|
+
//#region src/utils/naming.ts
|
|
190
|
+
/** Convert a name to PascalCase */
|
|
191
|
+
function toPascalCase(name) {
|
|
192
|
+
return name.replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : "").replace(/^(.)/, (c) => c.toUpperCase());
|
|
193
|
+
}
|
|
194
|
+
/** Convert a name to camelCase */
|
|
195
|
+
function toCamelCase(name) {
|
|
196
|
+
const pascal = toPascalCase(name);
|
|
197
|
+
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
|
|
198
|
+
}
|
|
199
|
+
/** Convert a name to kebab-case */
|
|
200
|
+
function toKebabCase(name) {
|
|
201
|
+
return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Pluralize a kebab-case name for directory/file names.
|
|
205
|
+
* Uses the `pluralize` npm package for correct English pluralization
|
|
206
|
+
* including irregulars (person → people, status → statuses, child → children).
|
|
207
|
+
*/
|
|
208
|
+
function pluralize(name) {
|
|
209
|
+
return pkg.plural(name);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Pluralize a PascalCase name for class identifiers.
|
|
213
|
+
* Used for `List${pluralPascal}UseCase` to avoid `ListUserssUseCase`.
|
|
214
|
+
*/
|
|
215
|
+
function pluralizePascal(name) {
|
|
216
|
+
return pkg.plural(name);
|
|
217
|
+
}
|
|
218
|
+
//#endregion
|
|
219
|
+
//#region src/generators/templates/module-index.ts
|
|
220
|
+
const repoLabelMap = {
|
|
221
|
+
inmemory: "in-memory",
|
|
222
|
+
drizzle: "Drizzle",
|
|
223
|
+
prisma: "Prisma"
|
|
224
|
+
};
|
|
225
|
+
function toPascalRepoType(repo) {
|
|
226
|
+
return repo.charAt(0).toUpperCase() + repo.slice(1).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
227
|
+
}
|
|
228
|
+
function toKebabRepoType(repo) {
|
|
229
|
+
return repo.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
|
|
230
|
+
}
|
|
231
|
+
function repoLabel(repo) {
|
|
232
|
+
return repoLabelMap[repo] ?? toPascalRepoType(repo);
|
|
233
|
+
}
|
|
234
|
+
function repoMaps(pascal, kebab, repo) {
|
|
235
|
+
const repoClassMap = {
|
|
236
|
+
inmemory: `InMemory${pascal}Repository`,
|
|
237
|
+
drizzle: `Drizzle${pascal}Repository`,
|
|
238
|
+
prisma: `Prisma${pascal}Repository`
|
|
239
|
+
};
|
|
240
|
+
const repoFileMap = {
|
|
241
|
+
inmemory: `in-memory-${kebab}`,
|
|
242
|
+
drizzle: `drizzle-${kebab}`,
|
|
243
|
+
prisma: `prisma-${kebab}`
|
|
244
|
+
};
|
|
245
|
+
return {
|
|
246
|
+
repoClass: repoClassMap[repo] ?? `${toPascalRepoType(repo)}${pascal}Repository`,
|
|
247
|
+
repoFile: repoFileMap[repo] ?? `${toKebabRepoType(repo)}-${kebab}`
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/** DDD module index — nested folders, use-cases, domain services */
|
|
251
|
+
function generateModuleIndex(ctx) {
|
|
252
|
+
const { pascal, kebab, plural = "", repo } = ctx;
|
|
253
|
+
const { repoClass, repoFile } = repoMaps(pascal, kebab, repo);
|
|
254
|
+
return `/**
|
|
255
|
+
* ${pascal} Module
|
|
256
|
+
*
|
|
257
|
+
* Self-contained feature module following Domain-Driven Design (DDD).
|
|
258
|
+
* Registers dependencies in the DI container and declares HTTP routes.
|
|
259
|
+
*
|
|
260
|
+
* Structure:
|
|
261
|
+
* presentation/ — HTTP controllers (entry points)
|
|
262
|
+
* application/ — Use cases (orchestration) and DTOs (validation)
|
|
263
|
+
* domain/ — Entities, value objects, repository interfaces, domain services
|
|
264
|
+
* infrastructure/ — Repository implementations (currently ${repoLabel(repo)})
|
|
265
|
+
*/
|
|
266
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
267
|
+
import { buildRoutes } from '@forinda/kickjs'
|
|
268
|
+
import { ${pascal.toUpperCase()}_REPOSITORY } from './domain/repositories/${kebab}.repository'
|
|
269
|
+
import { ${repoClass} } from './infrastructure/repositories/${repoFile}.repository'
|
|
270
|
+
import { ${pascal}Controller } from './presentation/${kebab}.controller'
|
|
271
|
+
|
|
272
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
273
|
+
import.meta.glob(
|
|
274
|
+
['./domain/services/**/*.ts', './application/use-cases/**/*.ts', '!./**/*.test.ts'],
|
|
275
|
+
{ eager: true },
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
export class ${pascal}Module implements AppModule {
|
|
279
|
+
/**
|
|
280
|
+
* Register module dependencies in the DI container.
|
|
281
|
+
* Bind repository interface tokens to their implementations here.
|
|
282
|
+
* Currently wired to ${repoLabel(repo)}. To swap implementations, change the factory target.
|
|
283
|
+
*/
|
|
284
|
+
register(container: Container): void {
|
|
285
|
+
container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
|
|
286
|
+
container.resolve(${repoClass}),
|
|
287
|
+
)
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Declare HTTP routes for this module.
|
|
292
|
+
* The path is prefixed with the global apiPrefix and version (e.g. /api/v1/${plural}).
|
|
293
|
+
* Passing 'controller' enables automatic OpenAPI spec generation via SwaggerAdapter.
|
|
294
|
+
*/
|
|
295
|
+
routes(): ModuleRoutes {
|
|
296
|
+
return {
|
|
297
|
+
path: '/${plural}',
|
|
298
|
+
router: buildRoutes(${pascal}Controller),
|
|
299
|
+
controller: ${pascal}Controller,
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
`;
|
|
304
|
+
}
|
|
305
|
+
/** REST module index — flat folder, service + controller, no use-cases */
|
|
306
|
+
function generateRestModuleIndex(ctx) {
|
|
307
|
+
const { pascal, kebab, plural = "", repo } = ctx;
|
|
308
|
+
const { repoClass, repoFile } = repoMaps(pascal, kebab, repo);
|
|
309
|
+
return `/**
|
|
310
|
+
* ${pascal} Module
|
|
311
|
+
*
|
|
312
|
+
* REST module with a flat folder structure.
|
|
313
|
+
* Controller delegates to service, service wraps the repository.
|
|
314
|
+
*
|
|
315
|
+
* Structure:
|
|
316
|
+
* ${kebab}.controller.ts — HTTP routes (CRUD)
|
|
317
|
+
* ${kebab}.service.ts — Business logic
|
|
318
|
+
* ${kebab}.repository.ts — Repository interface
|
|
319
|
+
* ${repoFile}.repository.ts — Repository implementation
|
|
320
|
+
* dtos/ — Request/response schemas
|
|
321
|
+
*/
|
|
322
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
323
|
+
import { buildRoutes } from '@forinda/kickjs'
|
|
324
|
+
import { ${pascal.toUpperCase()}_REPOSITORY } from './${kebab}.repository'
|
|
325
|
+
import { ${repoClass} } from './${repoFile}.repository'
|
|
326
|
+
import { ${pascal}Controller } from './${kebab}.controller'
|
|
327
|
+
|
|
328
|
+
// Eagerly load decorated classes so @Service()/@Repository() decorators register in the DI container
|
|
329
|
+
import.meta.glob(['./**/*.service.ts', './**/*.repository.ts', '!./**/*.test.ts'], { eager: true })
|
|
330
|
+
|
|
331
|
+
export class ${pascal}Module implements AppModule {
|
|
332
|
+
register(container: Container): void {
|
|
333
|
+
container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
|
|
334
|
+
container.resolve(${repoClass}),
|
|
335
|
+
)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
routes(): ModuleRoutes {
|
|
339
|
+
return {
|
|
340
|
+
path: '/${plural}',
|
|
341
|
+
router: buildRoutes(${pascal}Controller),
|
|
342
|
+
controller: ${pascal}Controller,
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
`;
|
|
347
|
+
}
|
|
348
|
+
/** Minimal module index — just controller, no service/repo */
|
|
349
|
+
function generateMinimalModuleIndex(ctx) {
|
|
350
|
+
const { pascal, kebab, plural = "" } = ctx;
|
|
351
|
+
return `import { type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
352
|
+
import { buildRoutes } from '@forinda/kickjs'
|
|
353
|
+
import { ${pascal}Controller } from './${kebab}.controller'
|
|
354
|
+
|
|
355
|
+
export class ${pascal}Module implements AppModule {
|
|
356
|
+
routes(): ModuleRoutes {
|
|
357
|
+
return {
|
|
358
|
+
path: '/${plural}',
|
|
359
|
+
router: buildRoutes(${pascal}Controller),
|
|
360
|
+
controller: ${pascal}Controller,
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
`;
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/generators/templates/controller.ts
|
|
368
|
+
/** DDD controller — injects use-cases, nested import paths */
|
|
369
|
+
function generateController$1(ctx) {
|
|
370
|
+
const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
|
|
371
|
+
return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
372
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
373
|
+
import { Create${pascal}UseCase } from '../application/use-cases/create-${kebab}.use-case'
|
|
374
|
+
import { Get${pascal}UseCase } from '../application/use-cases/get-${kebab}.use-case'
|
|
375
|
+
import { List${pluralPascal}UseCase } from '../application/use-cases/list-${plural}.use-case'
|
|
376
|
+
import { Update${pascal}UseCase } from '../application/use-cases/update-${kebab}.use-case'
|
|
377
|
+
import { Delete${pascal}UseCase } from '../application/use-cases/delete-${kebab}.use-case'
|
|
378
|
+
import { create${pascal}Schema } from '../application/dtos/create-${kebab}.dto'
|
|
379
|
+
import { update${pascal}Schema } from '../application/dtos/update-${kebab}.dto'
|
|
380
|
+
import { ${pascal.toUpperCase()}_QUERY_CONFIG } from '../constants'
|
|
381
|
+
|
|
382
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
|
|
383
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
384
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
385
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
386
|
+
|
|
387
|
+
@Controller()
|
|
388
|
+
export class ${pascal}Controller {
|
|
389
|
+
@Autowired() private readonly create${pascal}UseCase!: Create${pascal}UseCase
|
|
390
|
+
@Autowired() private readonly get${pascal}UseCase!: Get${pascal}UseCase
|
|
391
|
+
@Autowired() private readonly list${pluralPascal}UseCase!: List${pluralPascal}UseCase
|
|
392
|
+
@Autowired() private readonly update${pascal}UseCase!: Update${pascal}UseCase
|
|
393
|
+
@Autowired() private readonly delete${pascal}UseCase!: Delete${pascal}UseCase
|
|
394
|
+
|
|
395
|
+
@Get('/')
|
|
396
|
+
@ApiTags('${pascal}')
|
|
397
|
+
@ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
|
|
398
|
+
async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
|
|
399
|
+
return ctx.paginate(
|
|
400
|
+
(parsed) => this.list${pluralPascal}UseCase.execute(parsed),
|
|
401
|
+
${pascal.toUpperCase()}_QUERY_CONFIG,
|
|
402
|
+
)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
@Get('/:id')
|
|
406
|
+
@ApiTags('${pascal}')
|
|
407
|
+
async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
|
|
408
|
+
const result = await this.get${pascal}UseCase.execute(ctx.params.id)
|
|
409
|
+
if (!result) return ctx.notFound('${pascal} not found')
|
|
410
|
+
ctx.json(result)
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
@Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
|
|
414
|
+
@ApiTags('${pascal}')
|
|
415
|
+
async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
|
|
416
|
+
const result = await this.create${pascal}UseCase.execute(ctx.body)
|
|
417
|
+
ctx.created(result)
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
@Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
|
|
421
|
+
@ApiTags('${pascal}')
|
|
422
|
+
async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
|
|
423
|
+
const result = await this.update${pascal}UseCase.execute(ctx.params.id, ctx.body)
|
|
424
|
+
ctx.json(result)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
@Delete('/:id')
|
|
428
|
+
@ApiTags('${pascal}')
|
|
429
|
+
async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
|
|
430
|
+
await this.delete${pascal}UseCase.execute(ctx.params.id)
|
|
431
|
+
ctx.noContent()
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
`;
|
|
435
|
+
}
|
|
436
|
+
/** REST controller — injects service directly, flat import paths */
|
|
437
|
+
function generateRestController(ctx) {
|
|
438
|
+
const { pascal, kebab } = ctx;
|
|
439
|
+
const camel = pascal.charAt(0).toLowerCase() + pascal.slice(1);
|
|
440
|
+
return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
441
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
442
|
+
import { ${pascal}Service } from './${kebab}.service'
|
|
443
|
+
import { create${pascal}Schema } from './dtos/create-${kebab}.dto'
|
|
444
|
+
import { update${pascal}Schema } from './dtos/update-${kebab}.dto'
|
|
445
|
+
import { ${pascal.toUpperCase()}_QUERY_CONFIG } from './${kebab}.constants'
|
|
446
|
+
|
|
447
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
|
|
448
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
449
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
450
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
451
|
+
|
|
452
|
+
@Controller()
|
|
453
|
+
export class ${pascal}Controller {
|
|
454
|
+
@Autowired() private readonly ${camel}Service!: ${pascal}Service
|
|
455
|
+
|
|
456
|
+
@Get('/')
|
|
457
|
+
@ApiTags('${pascal}')
|
|
458
|
+
@ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
|
|
459
|
+
async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
|
|
460
|
+
return ctx.paginate(
|
|
461
|
+
(parsed) => this.${camel}Service.findPaginated(parsed),
|
|
462
|
+
${pascal.toUpperCase()}_QUERY_CONFIG,
|
|
463
|
+
)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
@Get('/:id')
|
|
467
|
+
@ApiTags('${pascal}')
|
|
468
|
+
async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
|
|
469
|
+
const result = await this.${camel}Service.findById(ctx.params.id)
|
|
470
|
+
if (!result) return ctx.notFound('${pascal} not found')
|
|
471
|
+
ctx.json(result)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
@Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
|
|
475
|
+
@ApiTags('${pascal}')
|
|
476
|
+
async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
|
|
477
|
+
const result = await this.${camel}Service.create(ctx.body)
|
|
478
|
+
ctx.created(result)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
@Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
|
|
482
|
+
@ApiTags('${pascal}')
|
|
483
|
+
async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
|
|
484
|
+
const result = await this.${camel}Service.update(ctx.params.id, ctx.body)
|
|
485
|
+
ctx.json(result)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
@Delete('/:id')
|
|
489
|
+
@ApiTags('${pascal}')
|
|
490
|
+
async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
|
|
491
|
+
await this.${camel}Service.delete(ctx.params.id)
|
|
492
|
+
ctx.noContent()
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
`;
|
|
496
|
+
}
|
|
497
|
+
//#endregion
|
|
498
|
+
//#region src/generators/templates/constants.ts
|
|
499
|
+
function generateConstants(ctx) {
|
|
500
|
+
const { pascal } = ctx;
|
|
501
|
+
return `import type { QueryParamsConfig } from '@forinda/kickjs'
|
|
502
|
+
|
|
503
|
+
export const ${pascal.toUpperCase()}_QUERY_CONFIG: QueryParamsConfig = {
|
|
504
|
+
filterable: ['name'],
|
|
505
|
+
sortable: ['name', 'createdAt'],
|
|
506
|
+
searchable: ['name'],
|
|
507
|
+
}
|
|
508
|
+
`;
|
|
509
|
+
}
|
|
510
|
+
//#endregion
|
|
511
|
+
//#region src/generators/templates/dtos.ts
|
|
512
|
+
function generateCreateDTO(ctx) {
|
|
513
|
+
const { pascal } = ctx;
|
|
514
|
+
return `import { z } from 'zod'
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Create ${pascal} DTO — Zod schema for validating POST request bodies.
|
|
518
|
+
* This schema is passed to @Post('/', { body: create${pascal}Schema }) for automatic validation.
|
|
519
|
+
* It also generates OpenAPI request body docs when SwaggerAdapter is used.
|
|
520
|
+
*
|
|
521
|
+
* Add more fields as needed. Supported Zod types:
|
|
522
|
+
* z.string(), z.number(), z.boolean(), z.enum([...]),
|
|
523
|
+
* z.array(), z.object(), .optional(), .default(), .transform()
|
|
524
|
+
*/
|
|
525
|
+
export const create${pascal}Schema = z.object({
|
|
526
|
+
name: z.string().min(1, 'Name is required').max(200),
|
|
527
|
+
})
|
|
528
|
+
|
|
529
|
+
export type Create${pascal}DTO = z.infer<typeof create${pascal}Schema>
|
|
530
|
+
`;
|
|
531
|
+
}
|
|
532
|
+
function generateUpdateDTO(ctx) {
|
|
533
|
+
const { pascal } = ctx;
|
|
534
|
+
return `import { z } from 'zod'
|
|
535
|
+
|
|
536
|
+
export const update${pascal}Schema = z.object({
|
|
537
|
+
name: z.string().min(1).max(200).optional(),
|
|
538
|
+
})
|
|
539
|
+
|
|
540
|
+
export type Update${pascal}DTO = z.infer<typeof update${pascal}Schema>
|
|
541
|
+
`;
|
|
542
|
+
}
|
|
543
|
+
function generateResponseDTO(ctx) {
|
|
544
|
+
const { pascal } = ctx;
|
|
545
|
+
return `export interface ${pascal}ResponseDTO {
|
|
546
|
+
id: string
|
|
547
|
+
name: string
|
|
548
|
+
createdAt: string
|
|
549
|
+
updatedAt: string
|
|
550
|
+
}
|
|
551
|
+
`;
|
|
552
|
+
}
|
|
553
|
+
//#endregion
|
|
554
|
+
//#region src/generators/templates/use-cases.ts
|
|
555
|
+
function generateUseCases(ctx) {
|
|
556
|
+
const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
|
|
557
|
+
return [
|
|
558
|
+
{
|
|
559
|
+
file: `create-${kebab}.use-case.ts`,
|
|
560
|
+
content: `/**
|
|
561
|
+
* Create ${pascal} Use Case
|
|
562
|
+
*
|
|
563
|
+
* Application layer — orchestrates a single business operation.
|
|
564
|
+
* Use cases are thin: validate input (via DTO), call domain/repo, return response.
|
|
565
|
+
* Keep business rules in the domain service, not here.
|
|
566
|
+
*/
|
|
567
|
+
import { Service, Inject } from '@forinda/kickjs'
|
|
568
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
|
|
569
|
+
import type { Create${pascal}DTO } from '../dtos/create-${kebab}.dto'
|
|
570
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
571
|
+
|
|
572
|
+
@Service()
|
|
573
|
+
export class Create${pascal}UseCase {
|
|
574
|
+
constructor(
|
|
575
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
576
|
+
) {}
|
|
577
|
+
|
|
578
|
+
async execute(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
579
|
+
return this.repo.create(dto)
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
`
|
|
583
|
+
},
|
|
584
|
+
{
|
|
585
|
+
file: `get-${kebab}.use-case.ts`,
|
|
586
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
587
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
|
|
588
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
589
|
+
|
|
590
|
+
@Service()
|
|
591
|
+
export class Get${pascal}UseCase {
|
|
592
|
+
constructor(
|
|
593
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
594
|
+
) {}
|
|
595
|
+
|
|
596
|
+
async execute(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
597
|
+
return this.repo.findById(id)
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
`
|
|
601
|
+
},
|
|
602
|
+
{
|
|
603
|
+
file: `list-${plural}.use-case.ts`,
|
|
604
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
605
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
|
|
606
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
607
|
+
|
|
608
|
+
@Service()
|
|
609
|
+
export class List${pluralPascal}UseCase {
|
|
610
|
+
constructor(
|
|
611
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
612
|
+
) {}
|
|
613
|
+
|
|
614
|
+
async execute(parsed: ParsedQuery) {
|
|
615
|
+
return this.repo.findPaginated(parsed)
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
`
|
|
619
|
+
},
|
|
620
|
+
{
|
|
621
|
+
file: `update-${kebab}.use-case.ts`,
|
|
622
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
623
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
|
|
624
|
+
import type { Update${pascal}DTO } from '../dtos/update-${kebab}.dto'
|
|
625
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
626
|
+
|
|
627
|
+
@Service()
|
|
628
|
+
export class Update${pascal}UseCase {
|
|
629
|
+
constructor(
|
|
630
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
631
|
+
) {}
|
|
632
|
+
|
|
633
|
+
async execute(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
634
|
+
return this.repo.update(id, dto)
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
`
|
|
638
|
+
},
|
|
639
|
+
{
|
|
640
|
+
file: `delete-${kebab}.use-case.ts`,
|
|
641
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
642
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../../domain/repositories/${kebab}.repository'
|
|
643
|
+
|
|
644
|
+
@Service()
|
|
645
|
+
export class Delete${pascal}UseCase {
|
|
646
|
+
constructor(
|
|
647
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
648
|
+
) {}
|
|
649
|
+
|
|
650
|
+
async execute(id: string): Promise<void> {
|
|
651
|
+
await this.repo.delete(id)
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
`
|
|
655
|
+
}
|
|
656
|
+
];
|
|
657
|
+
}
|
|
658
|
+
//#endregion
|
|
659
|
+
//#region src/generators/templates/repository.ts
|
|
660
|
+
function generateRepositoryInterface(ctx) {
|
|
661
|
+
const { pascal, kebab, dtoPrefix = "../../application/dtos", tokenScope = "app" } = ctx;
|
|
662
|
+
return `/**
|
|
663
|
+
* ${pascal} Repository Interface
|
|
664
|
+
*
|
|
665
|
+
* Defines the contract for data access.
|
|
666
|
+
* The interface declares what operations are available;
|
|
667
|
+
* implementations (in-memory, Drizzle, Prisma) fulfill the contract.
|
|
668
|
+
*
|
|
669
|
+
* To swap implementations, change the factory in the module's register() method.
|
|
670
|
+
*/
|
|
671
|
+
import { createToken } from '@forinda/kickjs'
|
|
672
|
+
import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
|
|
673
|
+
import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
|
|
674
|
+
import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
|
|
675
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
676
|
+
|
|
677
|
+
export interface I${pascal}Repository {
|
|
678
|
+
findById(id: string): Promise<${pascal}ResponseDTO | null>
|
|
679
|
+
findAll(): Promise<${pascal}ResponseDTO[]>
|
|
680
|
+
findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }>
|
|
681
|
+
create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO>
|
|
682
|
+
update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO>
|
|
683
|
+
delete(id: string): Promise<void>
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Collision-safe DI token bound to \`I${pascal}Repository\`.
|
|
688
|
+
* \`container.resolve(${pascal.toUpperCase()}_REPOSITORY)\` and
|
|
689
|
+
* \`@Inject(${pascal.toUpperCase()}_REPOSITORY)\` both return the typed
|
|
690
|
+
* interface — no manual generic, no \`any\` cast.
|
|
691
|
+
*
|
|
692
|
+
* The \`'${tokenScope}/'\` prefix matches the project scope so
|
|
693
|
+
* \`kick-lint\`'s \`token-reserved-prefix\` rule never fires —
|
|
694
|
+
* adopters must NOT use the reserved \`'kick/'\` namespace.
|
|
695
|
+
*/
|
|
696
|
+
export const ${pascal.toUpperCase()}_REPOSITORY = createToken<I${pascal}Repository>('${tokenScope}/${kebab}/repository')
|
|
697
|
+
`;
|
|
698
|
+
}
|
|
699
|
+
function generateInMemoryRepository(ctx) {
|
|
700
|
+
const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
|
|
701
|
+
return `/**
|
|
702
|
+
* In-Memory ${pascal} Repository
|
|
703
|
+
*
|
|
704
|
+
* Implements the repository interface using a Map.
|
|
705
|
+
* Useful for prototyping and testing. Replace with a database implementation
|
|
706
|
+
* (Drizzle, Prisma, etc.) for production use.
|
|
707
|
+
*
|
|
708
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
709
|
+
*/
|
|
710
|
+
import { randomUUID } from 'node:crypto'
|
|
711
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
712
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
713
|
+
import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
|
|
714
|
+
import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
|
|
715
|
+
import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
|
|
716
|
+
import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
|
|
717
|
+
|
|
718
|
+
@Repository()
|
|
719
|
+
export class InMemory${pascal}Repository implements I${pascal}Repository {
|
|
720
|
+
private store = new Map<string, ${pascal}ResponseDTO>()
|
|
721
|
+
|
|
722
|
+
async findById(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
723
|
+
return this.store.get(id) ?? null
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
async findAll(): Promise<${pascal}ResponseDTO[]> {
|
|
727
|
+
return Array.from(this.store.values())
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
|
|
731
|
+
const all = Array.from(this.store.values())
|
|
732
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
733
|
+
return { data, total: all.length }
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
737
|
+
const now = new Date().toISOString()
|
|
738
|
+
const entity: ${pascal}ResponseDTO = {
|
|
739
|
+
id: randomUUID(),
|
|
740
|
+
name: dto.name,
|
|
741
|
+
createdAt: now,
|
|
742
|
+
updatedAt: now,
|
|
743
|
+
}
|
|
744
|
+
this.store.set(entity.id, entity)
|
|
745
|
+
return entity
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
749
|
+
const existing = this.store.get(id)
|
|
750
|
+
if (!existing) throw HttpException.notFound('${pascal} not found')
|
|
751
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
752
|
+
this.store.set(id, updated)
|
|
753
|
+
return updated
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async delete(id: string): Promise<void> {
|
|
757
|
+
if (!this.store.has(id)) throw HttpException.notFound('${pascal} not found')
|
|
758
|
+
this.store.delete(id)
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
`;
|
|
762
|
+
}
|
|
763
|
+
function generateCustomRepository(ctx) {
|
|
764
|
+
const { pascal, kebab, repoType = "", repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
|
|
765
|
+
const repoTypePascal = repoType.charAt(0).toUpperCase() + repoType.slice(1).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
766
|
+
return `/**
|
|
767
|
+
* ${repoTypePascal} ${pascal} Repository
|
|
768
|
+
*
|
|
769
|
+
* Stub implementation for a custom '${repoType}' repository.
|
|
770
|
+
* Implements the repository interface using an in-memory Map as a placeholder.
|
|
771
|
+
*
|
|
772
|
+
* TODO: Replace the in-memory Map with your ${repoType} data-access logic.
|
|
773
|
+
* See I${pascal}Repository for the interface contract.
|
|
774
|
+
*
|
|
775
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
776
|
+
*/
|
|
777
|
+
import { randomUUID } from 'node:crypto'
|
|
778
|
+
import { Repository, HttpException } from '@forinda/kickjs'
|
|
779
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
780
|
+
import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
|
|
781
|
+
import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
|
|
782
|
+
import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
|
|
783
|
+
import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
|
|
784
|
+
|
|
785
|
+
@Repository()
|
|
786
|
+
export class ${repoTypePascal}${pascal}Repository implements I${pascal}Repository {
|
|
787
|
+
// TODO: Replace with your ${repoType} client/connection
|
|
788
|
+
private store = new Map<string, ${pascal}ResponseDTO>()
|
|
789
|
+
|
|
790
|
+
async findById(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
791
|
+
// TODO: Implement with ${repoType}
|
|
792
|
+
return this.store.get(id) ?? null
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
async findAll(): Promise<${pascal}ResponseDTO[]> {
|
|
796
|
+
// TODO: Implement with ${repoType}
|
|
797
|
+
return Array.from(this.store.values())
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
|
|
801
|
+
// TODO: Implement with ${repoType}
|
|
802
|
+
const all = Array.from(this.store.values())
|
|
803
|
+
const data = all.slice(parsed.pagination.offset, parsed.pagination.offset + parsed.pagination.limit)
|
|
804
|
+
return { data, total: all.length }
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
808
|
+
// TODO: Implement with ${repoType}
|
|
809
|
+
const now = new Date().toISOString()
|
|
810
|
+
const entity: ${pascal}ResponseDTO = {
|
|
811
|
+
id: randomUUID(),
|
|
812
|
+
name: dto.name,
|
|
813
|
+
createdAt: now,
|
|
814
|
+
updatedAt: now,
|
|
815
|
+
}
|
|
816
|
+
this.store.set(entity.id, entity)
|
|
817
|
+
return entity
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
821
|
+
// TODO: Implement with ${repoType}
|
|
822
|
+
const existing = this.store.get(id)
|
|
823
|
+
if (!existing) throw HttpException.notFound('${pascal} not found')
|
|
824
|
+
const updated = { ...existing, ...dto, updatedAt: new Date().toISOString() }
|
|
825
|
+
this.store.set(id, updated)
|
|
826
|
+
return updated
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
async delete(id: string): Promise<void> {
|
|
830
|
+
// TODO: Implement with ${repoType}
|
|
831
|
+
if (!this.store.has(id)) throw HttpException.notFound('${pascal} not found')
|
|
832
|
+
this.store.delete(id)
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
`;
|
|
836
|
+
}
|
|
837
|
+
//#endregion
|
|
838
|
+
//#region src/generators/templates/domain.ts
|
|
839
|
+
function generateDomainService(ctx) {
|
|
840
|
+
const { pascal, kebab } = ctx;
|
|
841
|
+
return `/**
|
|
842
|
+
* ${pascal} Domain Service
|
|
843
|
+
*
|
|
844
|
+
* Domain layer — contains business rules that don't belong to a single entity.
|
|
845
|
+
* Use this for cross-entity logic, validation rules, and domain invariants.
|
|
846
|
+
* Keep it free of HTTP/framework concerns.
|
|
847
|
+
*/
|
|
848
|
+
import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
849
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../repositories/${kebab}.repository'
|
|
850
|
+
|
|
851
|
+
@Service()
|
|
852
|
+
export class ${pascal}DomainService {
|
|
853
|
+
constructor(
|
|
854
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
855
|
+
) {}
|
|
856
|
+
|
|
857
|
+
async ensureExists(id: string): Promise<void> {
|
|
858
|
+
const entity = await this.repo.findById(id)
|
|
859
|
+
if (!entity) {
|
|
860
|
+
throw HttpException.notFound('${pascal} not found')
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
`;
|
|
865
|
+
}
|
|
866
|
+
function generateEntity(ctx) {
|
|
867
|
+
const { pascal, kebab } = ctx;
|
|
868
|
+
return `/**
|
|
869
|
+
* ${pascal} Entity
|
|
870
|
+
*
|
|
871
|
+
* Domain layer — the core business object.
|
|
872
|
+
* Uses a private constructor with static factory methods (create, reconstitute)
|
|
873
|
+
* to enforce invariants. Properties are accessed via getters to maintain encapsulation.
|
|
874
|
+
*
|
|
875
|
+
* Patterns used:
|
|
876
|
+
* - Private constructor: prevents direct instantiation
|
|
877
|
+
* - create(): factory for new entities (generates ID, sets timestamps)
|
|
878
|
+
* - reconstitute(): factory for rebuilding from persistence (no side effects)
|
|
879
|
+
* - changeName(): mutation method that enforces business rules
|
|
880
|
+
*/
|
|
881
|
+
import { ${pascal}Id } from '../value-objects/${kebab}-id.vo'
|
|
882
|
+
|
|
883
|
+
interface ${pascal}Props {
|
|
884
|
+
id: ${pascal}Id
|
|
885
|
+
name: string
|
|
886
|
+
createdAt: Date
|
|
887
|
+
updatedAt: Date
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
export class ${pascal} {
|
|
891
|
+
private constructor(private props: ${pascal}Props) {}
|
|
892
|
+
|
|
893
|
+
static create(params: { name: string }): ${pascal} {
|
|
894
|
+
const now = new Date()
|
|
895
|
+
return new ${pascal}({
|
|
896
|
+
id: ${pascal}Id.create(),
|
|
897
|
+
name: params.name,
|
|
898
|
+
createdAt: now,
|
|
899
|
+
updatedAt: now,
|
|
900
|
+
})
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
static reconstitute(props: ${pascal}Props): ${pascal} {
|
|
904
|
+
return new ${pascal}(props)
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
get id(): ${pascal}Id {
|
|
908
|
+
return this.props.id
|
|
909
|
+
}
|
|
910
|
+
get name(): string {
|
|
911
|
+
return this.props.name
|
|
912
|
+
}
|
|
913
|
+
get createdAt(): Date {
|
|
914
|
+
return this.props.createdAt
|
|
915
|
+
}
|
|
916
|
+
get updatedAt(): Date {
|
|
917
|
+
return this.props.updatedAt
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
changeName(name: string): void {
|
|
921
|
+
if (!name || name.trim().length === 0) {
|
|
922
|
+
throw new Error('Name cannot be empty')
|
|
923
|
+
}
|
|
924
|
+
this.props.name = name.trim()
|
|
925
|
+
this.props.updatedAt = new Date()
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
toJSON() {
|
|
929
|
+
return {
|
|
930
|
+
id: this.props.id.toString(),
|
|
931
|
+
name: this.props.name,
|
|
932
|
+
createdAt: this.props.createdAt.toISOString(),
|
|
933
|
+
updatedAt: this.props.updatedAt.toISOString(),
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
`;
|
|
938
|
+
}
|
|
939
|
+
function generateValueObject(ctx) {
|
|
940
|
+
const { pascal } = ctx;
|
|
941
|
+
return `/**
|
|
942
|
+
* ${pascal} ID Value Object
|
|
943
|
+
*
|
|
944
|
+
* Domain layer — wraps a primitive ID with type safety and validation.
|
|
945
|
+
* Value objects are immutable and compared by value, not reference.
|
|
946
|
+
*
|
|
947
|
+
* ${pascal}Id.create() — generate a new UUID
|
|
948
|
+
* ${pascal}Id.from(id) — wrap an existing ID string (validates non-empty)
|
|
949
|
+
* id.equals(other) — compare two IDs by value
|
|
950
|
+
*/
|
|
951
|
+
import { randomUUID } from 'node:crypto'
|
|
952
|
+
|
|
953
|
+
export class ${pascal}Id {
|
|
954
|
+
private constructor(private readonly value: string) {}
|
|
955
|
+
|
|
956
|
+
static create(): ${pascal}Id {
|
|
957
|
+
return new ${pascal}Id(randomUUID())
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
static from(id: string): ${pascal}Id {
|
|
961
|
+
if (!id || id.trim().length === 0) {
|
|
962
|
+
throw new Error('${pascal}Id cannot be empty')
|
|
963
|
+
}
|
|
964
|
+
return new ${pascal}Id(id)
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
toString(): string {
|
|
968
|
+
return this.value
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
equals(other: ${pascal}Id): boolean {
|
|
972
|
+
return this.value === other.value
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
`;
|
|
976
|
+
}
|
|
977
|
+
//#endregion
|
|
978
|
+
//#region src/generators/templates/tests.ts
|
|
979
|
+
function generateControllerTest(ctx) {
|
|
980
|
+
const { pascal, kebab, plural = "" } = ctx;
|
|
981
|
+
return `import { describe, it, expect, beforeEach } from 'vitest'
|
|
982
|
+
import { Container } from '@forinda/kickjs'
|
|
983
|
+
|
|
984
|
+
describe('${pascal}Controller', () => {
|
|
985
|
+
beforeEach(() => {
|
|
986
|
+
Container.reset()
|
|
987
|
+
})
|
|
988
|
+
|
|
989
|
+
it('should be defined', () => {
|
|
990
|
+
expect(true).toBe(true)
|
|
991
|
+
})
|
|
992
|
+
|
|
993
|
+
describe('POST /${plural}', () => {
|
|
994
|
+
it('should create a new ${kebab}', async () => {
|
|
995
|
+
// TODO: Set up test module, call create endpoint, assert 201
|
|
996
|
+
expect(true).toBe(true)
|
|
997
|
+
})
|
|
998
|
+
})
|
|
999
|
+
|
|
1000
|
+
describe('GET /${plural}', () => {
|
|
1001
|
+
it('should return paginated ${plural}', async () => {
|
|
1002
|
+
// TODO: Set up test module, call list endpoint, assert { data, meta }
|
|
1003
|
+
expect(true).toBe(true)
|
|
1004
|
+
})
|
|
1005
|
+
})
|
|
1006
|
+
|
|
1007
|
+
describe('GET /${plural}/:id', () => {
|
|
1008
|
+
it('should return a ${kebab} by id', async () => {
|
|
1009
|
+
// TODO: Create a ${kebab}, then fetch by id, assert match
|
|
1010
|
+
expect(true).toBe(true)
|
|
1011
|
+
})
|
|
1012
|
+
|
|
1013
|
+
it('should return 404 for non-existent ${kebab}', async () => {
|
|
1014
|
+
// TODO: Fetch non-existent id, assert 404
|
|
1015
|
+
expect(true).toBe(true)
|
|
1016
|
+
})
|
|
1017
|
+
})
|
|
1018
|
+
|
|
1019
|
+
describe('PUT /${plural}/:id', () => {
|
|
1020
|
+
it('should update an existing ${kebab}', async () => {
|
|
1021
|
+
// TODO: Create, update, assert changes
|
|
1022
|
+
expect(true).toBe(true)
|
|
1023
|
+
})
|
|
1024
|
+
})
|
|
1025
|
+
|
|
1026
|
+
describe('DELETE /${plural}/:id', () => {
|
|
1027
|
+
it('should delete a ${kebab}', async () => {
|
|
1028
|
+
// TODO: Create, delete, assert gone
|
|
1029
|
+
expect(true).toBe(true)
|
|
1030
|
+
})
|
|
1031
|
+
})
|
|
1032
|
+
})
|
|
1033
|
+
`;
|
|
1034
|
+
}
|
|
1035
|
+
function generateRepositoryTest(ctx) {
|
|
1036
|
+
const { pascal, kebab, plural = "", repoPrefix = `../infrastructure/repositories/in-memory-${kebab}.repository` } = ctx;
|
|
1037
|
+
return `import { describe, it, expect, beforeEach } from 'vitest'
|
|
1038
|
+
import { InMemory${pascal}Repository } from '${repoPrefix}'
|
|
1039
|
+
|
|
1040
|
+
describe('InMemory${pascal}Repository', () => {
|
|
1041
|
+
let repo: InMemory${pascal}Repository
|
|
1042
|
+
|
|
1043
|
+
beforeEach(() => {
|
|
1044
|
+
repo = new InMemory${pascal}Repository()
|
|
1045
|
+
})
|
|
1046
|
+
|
|
1047
|
+
it('should create and retrieve a ${kebab}', async () => {
|
|
1048
|
+
const created = await repo.create({ name: 'Test ${pascal}' })
|
|
1049
|
+
expect(created).toBeDefined()
|
|
1050
|
+
expect(created.name).toBe('Test ${pascal}')
|
|
1051
|
+
expect(created.id).toBeDefined()
|
|
1052
|
+
|
|
1053
|
+
const found = await repo.findById(created.id)
|
|
1054
|
+
expect(found).toEqual(created)
|
|
1055
|
+
})
|
|
1056
|
+
|
|
1057
|
+
it('should return null for non-existent id', async () => {
|
|
1058
|
+
const found = await repo.findById('non-existent')
|
|
1059
|
+
expect(found).toBeNull()
|
|
1060
|
+
})
|
|
1061
|
+
|
|
1062
|
+
it('should list all ${plural}', async () => {
|
|
1063
|
+
await repo.create({ name: '${pascal} 1' })
|
|
1064
|
+
await repo.create({ name: '${pascal} 2' })
|
|
1065
|
+
|
|
1066
|
+
const all = await repo.findAll()
|
|
1067
|
+
expect(all).toHaveLength(2)
|
|
1068
|
+
})
|
|
1069
|
+
|
|
1070
|
+
it('should return paginated results', async () => {
|
|
1071
|
+
await repo.create({ name: '${pascal} 1' })
|
|
1072
|
+
await repo.create({ name: '${pascal} 2' })
|
|
1073
|
+
await repo.create({ name: '${pascal} 3' })
|
|
1074
|
+
|
|
1075
|
+
const result = await repo.findPaginated({
|
|
1076
|
+
filters: [],
|
|
1077
|
+
sort: [],
|
|
1078
|
+
search: '',
|
|
1079
|
+
pagination: { page: 1, limit: 2, offset: 0 },
|
|
1080
|
+
})
|
|
1081
|
+
|
|
1082
|
+
expect(result.data).toHaveLength(2)
|
|
1083
|
+
expect(result.total).toBe(3)
|
|
1084
|
+
})
|
|
1085
|
+
|
|
1086
|
+
it('should update a ${kebab}', async () => {
|
|
1087
|
+
const created = await repo.create({ name: 'Original' })
|
|
1088
|
+
const updated = await repo.update(created.id, { name: 'Updated' })
|
|
1089
|
+
expect(updated.name).toBe('Updated')
|
|
1090
|
+
})
|
|
1091
|
+
|
|
1092
|
+
it('should delete a ${kebab}', async () => {
|
|
1093
|
+
const created = await repo.create({ name: 'To Delete' })
|
|
1094
|
+
await repo.delete(created.id)
|
|
1095
|
+
const found = await repo.findById(created.id)
|
|
1096
|
+
expect(found).toBeNull()
|
|
1097
|
+
})
|
|
1098
|
+
})
|
|
1099
|
+
`;
|
|
1100
|
+
}
|
|
1101
|
+
//#endregion
|
|
1102
|
+
//#region src/generators/templates/rest-service.ts
|
|
1103
|
+
/** REST service — wraps repository with CRUD methods, replaces use-cases for flat pattern */
|
|
1104
|
+
function generateRestService(ctx) {
|
|
1105
|
+
const { pascal, kebab } = ctx;
|
|
1106
|
+
return `import { Service, Inject, HttpException } from '@forinda/kickjs'
|
|
1107
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1108
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from './${kebab}.repository'
|
|
1109
|
+
import type { ${pascal}ResponseDTO } from './dtos/${kebab}-response.dto'
|
|
1110
|
+
import type { Create${pascal}DTO } from './dtos/create-${kebab}.dto'
|
|
1111
|
+
import type { Update${pascal}DTO } from './dtos/update-${kebab}.dto'
|
|
1112
|
+
|
|
1113
|
+
@Service()
|
|
1114
|
+
export class ${pascal}Service {
|
|
1115
|
+
constructor(
|
|
1116
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1117
|
+
) {}
|
|
1118
|
+
|
|
1119
|
+
async findById(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
1120
|
+
return this.repo.findById(id)
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
async findAll(): Promise<${pascal}ResponseDTO[]> {
|
|
1124
|
+
return this.repo.findAll()
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
async findPaginated(parsed: ParsedQuery) {
|
|
1128
|
+
return this.repo.findPaginated(parsed)
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1132
|
+
return this.repo.create(dto)
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1136
|
+
return this.repo.update(id, dto)
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
async delete(id: string): Promise<void> {
|
|
1140
|
+
await this.repo.delete(id)
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
`;
|
|
1144
|
+
}
|
|
1145
|
+
/** REST constants — query config for flat pattern */
|
|
1146
|
+
function generateRestConstants(ctx) {
|
|
1147
|
+
const { pascal } = ctx;
|
|
1148
|
+
return `import type { QueryFieldConfig } from '@forinda/kickjs'
|
|
1149
|
+
|
|
1150
|
+
export const ${pascal.toUpperCase()}_QUERY_CONFIG: QueryFieldConfig = {
|
|
1151
|
+
filterable: ['name'],
|
|
1152
|
+
sortable: ['name', 'createdAt'],
|
|
1153
|
+
searchable: ['name'],
|
|
1154
|
+
}
|
|
1155
|
+
`;
|
|
1156
|
+
}
|
|
1157
|
+
//#endregion
|
|
1158
|
+
//#region src/generators/templates/cqrs.ts
|
|
1159
|
+
/** CQRS module index — commands, queries, events, WebSocket + queue integration */
|
|
1160
|
+
function generateCqrsModuleIndex(ctx) {
|
|
1161
|
+
const { pascal, kebab, plural = "", repo } = ctx;
|
|
1162
|
+
const repoClassMap = {
|
|
1163
|
+
inmemory: `InMemory${pascal}Repository`,
|
|
1164
|
+
drizzle: `Drizzle${pascal}Repository`,
|
|
1165
|
+
prisma: `Prisma${pascal}Repository`
|
|
1166
|
+
};
|
|
1167
|
+
const repoFileMap = {
|
|
1168
|
+
inmemory: `in-memory-${kebab}`,
|
|
1169
|
+
drizzle: `drizzle-${kebab}`,
|
|
1170
|
+
prisma: `prisma-${kebab}`
|
|
1171
|
+
};
|
|
1172
|
+
const repoClass = repoClassMap[repo] ?? repoClassMap.inmemory;
|
|
1173
|
+
const repoFile = repoFileMap[repo] ?? repoFileMap.inmemory;
|
|
1174
|
+
return `/**
|
|
1175
|
+
* ${pascal} Module — CQRS Pattern
|
|
1176
|
+
*
|
|
1177
|
+
* Separates read (queries) and write (commands) operations.
|
|
1178
|
+
* Events are emitted after state changes and can be handled via
|
|
1179
|
+
* WebSocket broadcasts, queue jobs, or ETL pipelines.
|
|
1180
|
+
*
|
|
1181
|
+
* Structure:
|
|
1182
|
+
* commands/ — Write operations (create, update, delete)
|
|
1183
|
+
* queries/ — Read operations (get, list)
|
|
1184
|
+
* events/ — Domain events + handlers (WS broadcast, queue dispatch)
|
|
1185
|
+
* dtos/ — Request/response schemas
|
|
1186
|
+
*/
|
|
1187
|
+
import { Container, type AppModule, type ModuleRoutes } from '@forinda/kickjs'
|
|
1188
|
+
import { buildRoutes } from '@forinda/kickjs'
|
|
1189
|
+
import { ${pascal.toUpperCase()}_REPOSITORY } from './${kebab}.repository'
|
|
1190
|
+
import { ${repoClass} } from './${repoFile}.repository'
|
|
1191
|
+
import { ${pascal}Controller } from './${kebab}.controller'
|
|
1192
|
+
|
|
1193
|
+
// Eagerly load decorated classes
|
|
1194
|
+
import.meta.glob(
|
|
1195
|
+
[
|
|
1196
|
+
'./commands/**/*.ts',
|
|
1197
|
+
'./queries/**/*.ts',
|
|
1198
|
+
'./events/**/*.ts',
|
|
1199
|
+
'!./**/*.test.ts',
|
|
1200
|
+
],
|
|
1201
|
+
{ eager: true },
|
|
1202
|
+
)
|
|
1203
|
+
|
|
1204
|
+
export class ${pascal}Module implements AppModule {
|
|
1205
|
+
register(container: Container): void {
|
|
1206
|
+
container.registerFactory(${pascal.toUpperCase()}_REPOSITORY, () =>
|
|
1207
|
+
container.resolve(${repoClass}),
|
|
1208
|
+
)
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
routes(): ModuleRoutes {
|
|
1212
|
+
return {
|
|
1213
|
+
path: '/${plural}',
|
|
1214
|
+
router: buildRoutes(${pascal}Controller),
|
|
1215
|
+
controller: ${pascal}Controller,
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
`;
|
|
1220
|
+
}
|
|
1221
|
+
/** CQRS controller — dispatches to command/query handlers */
|
|
1222
|
+
function generateCqrsController(ctx) {
|
|
1223
|
+
const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
|
|
1224
|
+
return `import { Controller, Get, Post, Put, Delete, Autowired, ApiQueryParams, type Ctx } from '@forinda/kickjs'
|
|
1225
|
+
import { ApiTags } from '@forinda/kickjs-swagger'
|
|
1226
|
+
import { Create${pascal}Command } from './commands/create-${kebab}.command'
|
|
1227
|
+
import { Update${pascal}Command } from './commands/update-${kebab}.command'
|
|
1228
|
+
import { Delete${pascal}Command } from './commands/delete-${kebab}.command'
|
|
1229
|
+
import { Get${pascal}Query } from './queries/get-${kebab}.query'
|
|
1230
|
+
import { List${pluralPascal}Query } from './queries/list-${plural}.query'
|
|
1231
|
+
import { create${pascal}Schema } from './dtos/create-${kebab}.dto'
|
|
1232
|
+
import { update${pascal}Schema } from './dtos/update-${kebab}.dto'
|
|
1233
|
+
import { ${pascal.toUpperCase()}_QUERY_CONFIG } from './${kebab}.constants'
|
|
1234
|
+
|
|
1235
|
+
// Each handler annotates its \`ctx\` with \`Ctx<KickRoutes.${pascal}Controller['<method>']>\`
|
|
1236
|
+
// so \`ctx.params\`, \`ctx.body\`, and \`ctx.query\` are typed end-to-end.
|
|
1237
|
+
// The \`KickRoutes\` namespace is generated by \`kick typegen\` (auto-run on
|
|
1238
|
+
// \`kick dev\`) — see https://forinda.github.io/kick-js/guide/typegen.
|
|
1239
|
+
|
|
1240
|
+
@Controller()
|
|
1241
|
+
export class ${pascal}Controller {
|
|
1242
|
+
@Autowired() private readonly create${pascal}Command!: Create${pascal}Command
|
|
1243
|
+
@Autowired() private readonly update${pascal}Command!: Update${pascal}Command
|
|
1244
|
+
@Autowired() private readonly delete${pascal}Command!: Delete${pascal}Command
|
|
1245
|
+
@Autowired() private readonly get${pascal}Query!: Get${pascal}Query
|
|
1246
|
+
@Autowired() private readonly list${pluralPascal}Query!: List${pluralPascal}Query
|
|
1247
|
+
|
|
1248
|
+
@Get('/')
|
|
1249
|
+
@ApiTags('${pascal}')
|
|
1250
|
+
@ApiQueryParams(${pascal.toUpperCase()}_QUERY_CONFIG)
|
|
1251
|
+
async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
|
|
1252
|
+
return ctx.paginate(
|
|
1253
|
+
(parsed) => this.list${pluralPascal}Query.execute(parsed),
|
|
1254
|
+
${pascal.toUpperCase()}_QUERY_CONFIG,
|
|
1255
|
+
)
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
@Get('/:id')
|
|
1259
|
+
@ApiTags('${pascal}')
|
|
1260
|
+
async getById(ctx: Ctx<KickRoutes.${pascal}Controller['getById']>) {
|
|
1261
|
+
const result = await this.get${pascal}Query.execute(ctx.params.id)
|
|
1262
|
+
if (!result) return ctx.notFound('${pascal} not found')
|
|
1263
|
+
ctx.json(result)
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
@Post('/', { body: create${pascal}Schema, name: 'Create${pascal}' })
|
|
1267
|
+
@ApiTags('${pascal}')
|
|
1268
|
+
async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
|
|
1269
|
+
const result = await this.create${pascal}Command.execute(ctx.body)
|
|
1270
|
+
ctx.created(result)
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
@Put('/:id', { body: update${pascal}Schema, name: 'Update${pascal}' })
|
|
1274
|
+
@ApiTags('${pascal}')
|
|
1275
|
+
async update(ctx: Ctx<KickRoutes.${pascal}Controller['update']>) {
|
|
1276
|
+
const result = await this.update${pascal}Command.execute(ctx.params.id, ctx.body)
|
|
1277
|
+
ctx.json(result)
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
@Delete('/:id')
|
|
1281
|
+
@ApiTags('${pascal}')
|
|
1282
|
+
async remove(ctx: Ctx<KickRoutes.${pascal}Controller['remove']>) {
|
|
1283
|
+
await this.delete${pascal}Command.execute(ctx.params.id)
|
|
1284
|
+
ctx.noContent()
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
`;
|
|
1288
|
+
}
|
|
1289
|
+
/** CQRS commands — write operations that emit events */
|
|
1290
|
+
function generateCqrsCommands(ctx) {
|
|
1291
|
+
const { pascal, kebab } = ctx;
|
|
1292
|
+
return [
|
|
1293
|
+
{
|
|
1294
|
+
file: `create-${kebab}.command.ts`,
|
|
1295
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
1296
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
|
|
1297
|
+
import type { Create${pascal}DTO } from '../dtos/create-${kebab}.dto'
|
|
1298
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
1299
|
+
import { ${pascal}Events } from '../events/${kebab}.events'
|
|
1300
|
+
|
|
1301
|
+
@Service()
|
|
1302
|
+
export class Create${pascal}Command {
|
|
1303
|
+
constructor(
|
|
1304
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1305
|
+
@Inject(${pascal}Events) private readonly events: ${pascal}Events,
|
|
1306
|
+
) {}
|
|
1307
|
+
|
|
1308
|
+
async execute(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1309
|
+
const result = await this.repo.create(dto)
|
|
1310
|
+
this.events.emit('${kebab}.created', result)
|
|
1311
|
+
return result
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
`
|
|
1315
|
+
},
|
|
1316
|
+
{
|
|
1317
|
+
file: `update-${kebab}.command.ts`,
|
|
1318
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
1319
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
|
|
1320
|
+
import type { Update${pascal}DTO } from '../dtos/update-${kebab}.dto'
|
|
1321
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
1322
|
+
import { ${pascal}Events } from '../events/${kebab}.events'
|
|
1323
|
+
|
|
1324
|
+
@Service()
|
|
1325
|
+
export class Update${pascal}Command {
|
|
1326
|
+
constructor(
|
|
1327
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1328
|
+
@Inject(${pascal}Events) private readonly events: ${pascal}Events,
|
|
1329
|
+
) {}
|
|
1330
|
+
|
|
1331
|
+
async execute(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1332
|
+
const result = await this.repo.update(id, dto)
|
|
1333
|
+
this.events.emit('${kebab}.updated', result)
|
|
1334
|
+
return result
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
`
|
|
1338
|
+
},
|
|
1339
|
+
{
|
|
1340
|
+
file: `delete-${kebab}.command.ts`,
|
|
1341
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
1342
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
|
|
1343
|
+
import { ${pascal}Events } from '../events/${kebab}.events'
|
|
1344
|
+
|
|
1345
|
+
@Service()
|
|
1346
|
+
export class Delete${pascal}Command {
|
|
1347
|
+
constructor(
|
|
1348
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1349
|
+
@Inject(${pascal}Events) private readonly events: ${pascal}Events,
|
|
1350
|
+
) {}
|
|
1351
|
+
|
|
1352
|
+
async execute(id: string): Promise<void> {
|
|
1353
|
+
await this.repo.delete(id)
|
|
1354
|
+
this.events.emit('${kebab}.deleted', { id })
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
`
|
|
1358
|
+
}
|
|
1359
|
+
];
|
|
1360
|
+
}
|
|
1361
|
+
/** CQRS queries — read operations */
|
|
1362
|
+
function generateCqrsQueries(ctx) {
|
|
1363
|
+
const { pascal, kebab, plural = "", pluralPascal = "" } = ctx;
|
|
1364
|
+
return [{
|
|
1365
|
+
file: `get-${kebab}.query.ts`,
|
|
1366
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
1367
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
|
|
1368
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
1369
|
+
|
|
1370
|
+
@Service()
|
|
1371
|
+
export class Get${pascal}Query {
|
|
1372
|
+
constructor(
|
|
1373
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1374
|
+
) {}
|
|
1375
|
+
|
|
1376
|
+
async execute(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
1377
|
+
return this.repo.findById(id)
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
`
|
|
1381
|
+
}, {
|
|
1382
|
+
file: `list-${plural}.query.ts`,
|
|
1383
|
+
content: `import { Service, Inject } from '@forinda/kickjs'
|
|
1384
|
+
import { ${pascal.toUpperCase()}_REPOSITORY, type I${pascal}Repository } from '../${kebab}.repository'
|
|
1385
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1386
|
+
|
|
1387
|
+
@Service()
|
|
1388
|
+
export class List${pluralPascal}Query {
|
|
1389
|
+
constructor(
|
|
1390
|
+
@Inject(${pascal.toUpperCase()}_REPOSITORY) private readonly repo: I${pascal}Repository,
|
|
1391
|
+
) {}
|
|
1392
|
+
|
|
1393
|
+
async execute(parsed: ParsedQuery) {
|
|
1394
|
+
return this.repo.findPaginated(parsed)
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
`
|
|
1398
|
+
}];
|
|
1399
|
+
}
|
|
1400
|
+
/** CQRS events — domain event emitter + handler with WS/queue integration */
|
|
1401
|
+
function generateCqrsEvents(ctx) {
|
|
1402
|
+
const { pascal, kebab } = ctx;
|
|
1403
|
+
return [{
|
|
1404
|
+
file: `${kebab}.events.ts`,
|
|
1405
|
+
content: `import { Service } from '@forinda/kickjs'
|
|
1406
|
+
import { EventEmitter } from 'node:events'
|
|
1407
|
+
import type { ${pascal}ResponseDTO } from '../dtos/${kebab}-response.dto'
|
|
1408
|
+
|
|
1409
|
+
/**
|
|
1410
|
+
* ${pascal} domain event types.
|
|
1411
|
+
*
|
|
1412
|
+
* These events are emitted by commands after state changes.
|
|
1413
|
+
* Subscribe to them in event handlers for side effects:
|
|
1414
|
+
* - WebSocket broadcasts (real-time UI updates)
|
|
1415
|
+
* - Queue jobs (async processing, ETL pipelines)
|
|
1416
|
+
* - Audit logging
|
|
1417
|
+
* - Cache invalidation
|
|
1418
|
+
*/
|
|
1419
|
+
export interface ${pascal}EventMap {
|
|
1420
|
+
'${kebab}.created': ${pascal}ResponseDTO
|
|
1421
|
+
'${kebab}.updated': ${pascal}ResponseDTO
|
|
1422
|
+
'${kebab}.deleted': { id: string }
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
@Service()
|
|
1426
|
+
export class ${pascal}Events {
|
|
1427
|
+
private emitter = new EventEmitter()
|
|
1428
|
+
|
|
1429
|
+
emit<K extends keyof ${pascal}EventMap>(event: K, data: ${pascal}EventMap[K]): void {
|
|
1430
|
+
this.emitter.emit(event, data)
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
on<K extends keyof ${pascal}EventMap>(event: K, handler: (data: ${pascal}EventMap[K]) => void): void {
|
|
1434
|
+
this.emitter.on(event, handler)
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
off<K extends keyof ${pascal}EventMap>(event: K, handler: (data: ${pascal}EventMap[K]) => void): void {
|
|
1438
|
+
this.emitter.off(event, handler)
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
`
|
|
1442
|
+
}, {
|
|
1443
|
+
file: `on-${kebab}-change.handler.ts`,
|
|
1444
|
+
content: `import { Service, Autowired } from '@forinda/kickjs'
|
|
1445
|
+
import { ${pascal}Events } from './${kebab}.events'
|
|
1446
|
+
|
|
1447
|
+
/**
|
|
1448
|
+
* ${pascal} Change Event Handler
|
|
1449
|
+
*
|
|
1450
|
+
* Reacts to domain events emitted by commands.
|
|
1451
|
+
* Wire up side effects here:
|
|
1452
|
+
*
|
|
1453
|
+
* 1. WebSocket broadcast — notify connected clients in real-time
|
|
1454
|
+
* import { WsGateway } from '@forinda/kickjs-ws'
|
|
1455
|
+
* this.ws.broadcast('${kebab}-channel', { event, data })
|
|
1456
|
+
*
|
|
1457
|
+
* 2. Queue dispatch — offload heavy processing to background workers
|
|
1458
|
+
* import { QueueService } from '@forinda/kickjs-queue'
|
|
1459
|
+
* this.queue.add('${kebab}-etl', { action: event, payload: data })
|
|
1460
|
+
*
|
|
1461
|
+
* 3. ETL pipeline — transform and load data to external systems
|
|
1462
|
+
* await this.etlPipeline.process(data)
|
|
1463
|
+
*/
|
|
1464
|
+
@Service()
|
|
1465
|
+
export class On${pascal}ChangeHandler {
|
|
1466
|
+
@Autowired() private events!: ${pascal}Events
|
|
1467
|
+
|
|
1468
|
+
// Uncomment to inject WebSocket and Queue services:
|
|
1469
|
+
// @Autowired() private ws!: WsGateway
|
|
1470
|
+
// @Autowired() private queue!: QueueService
|
|
1471
|
+
|
|
1472
|
+
onInit(): void {
|
|
1473
|
+
this.events.on('${kebab}.created', (data) => {
|
|
1474
|
+
console.log('[${pascal}] Created:', data.id)
|
|
1475
|
+
// TODO: Broadcast via WebSocket
|
|
1476
|
+
// this.ws.broadcast('${kebab}-channel', { event: '${kebab}.created', data })
|
|
1477
|
+
// TODO: Dispatch to queue for async processing / ETL
|
|
1478
|
+
// this.queue.add('${kebab}-etl', { action: 'create', payload: data })
|
|
1479
|
+
})
|
|
1480
|
+
|
|
1481
|
+
this.events.on('${kebab}.updated', (data) => {
|
|
1482
|
+
console.log('[${pascal}] Updated:', data.id)
|
|
1483
|
+
// TODO: Broadcast via WebSocket
|
|
1484
|
+
// this.ws.broadcast('${kebab}-channel', { event: '${kebab}.updated', data })
|
|
1485
|
+
})
|
|
1486
|
+
|
|
1487
|
+
this.events.on('${kebab}.deleted', (data) => {
|
|
1488
|
+
console.log('[${pascal}] Deleted:', data.id)
|
|
1489
|
+
// TODO: Broadcast via WebSocket
|
|
1490
|
+
// this.ws.broadcast('${kebab}-channel', { event: '${kebab}.deleted', data })
|
|
1491
|
+
})
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
`
|
|
1495
|
+
}];
|
|
1496
|
+
}
|
|
1497
|
+
//#endregion
|
|
1498
|
+
//#region src/generators/templates/drizzle/index.ts
|
|
1499
|
+
function generateDrizzleRepository(ctx) {
|
|
1500
|
+
const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
|
|
1501
|
+
return `/**
|
|
1502
|
+
* Drizzle ${pascal} Repository
|
|
1503
|
+
*
|
|
1504
|
+
* Implements the repository interface using Drizzle ORM.
|
|
1505
|
+
* Uses buildFromColumns() with Column objects for type-safe query building.
|
|
1506
|
+
*
|
|
1507
|
+
* TODO: Update the schema import to match your Drizzle schema file.
|
|
1508
|
+
* TODO: Replace DRIZZLE_DB injection token with your actual database token.
|
|
1509
|
+
*
|
|
1510
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
1511
|
+
*/
|
|
1512
|
+
import { eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc, count, sql } from 'drizzle-orm'
|
|
1513
|
+
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
1514
|
+
import { DRIZZLE_DB, DrizzleQueryAdapter } from '@forinda/kickjs-drizzle'
|
|
1515
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1516
|
+
import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
|
|
1517
|
+
import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
|
|
1518
|
+
import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
|
|
1519
|
+
import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
|
|
1520
|
+
import { ${pascal.toUpperCase()}_QUERY_CONFIG } from '../../constants'
|
|
1521
|
+
|
|
1522
|
+
// TODO: Import your Drizzle schema table — e.g.:
|
|
1523
|
+
// import { ${kebab}s } from '@/db/schema'
|
|
1524
|
+
|
|
1525
|
+
const queryAdapter = new DrizzleQueryAdapter({
|
|
1526
|
+
eq, ne, gt, gte, lt, lte, ilike, inArray, between, and, or, asc, desc,
|
|
1527
|
+
})
|
|
1528
|
+
|
|
1529
|
+
@Repository()
|
|
1530
|
+
export class Drizzle${pascal}Repository implements I${pascal}Repository {
|
|
1531
|
+
constructor(@Inject(DRIZZLE_DB) private db: any) {}
|
|
1532
|
+
|
|
1533
|
+
async findById(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
1534
|
+
// TODO: Implement with Drizzle
|
|
1535
|
+
// const row = this.db.select().from(${kebab}s).where(eq(${kebab}s.id, id)).get()
|
|
1536
|
+
// return row ?? null
|
|
1537
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented — update schema imports and queries')
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
async findAll(): Promise<${pascal}ResponseDTO[]> {
|
|
1541
|
+
// TODO: Implement with Drizzle
|
|
1542
|
+
// return this.db.select().from(${kebab}s).all()
|
|
1543
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented')
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
|
|
1547
|
+
// TODO: Use buildFromColumns() with your query config for type-safe filtering
|
|
1548
|
+
// const query = queryAdapter.buildFromColumns(parsed, ${pascal.toUpperCase()}_QUERY_CONFIG)
|
|
1549
|
+
//
|
|
1550
|
+
// const data = this.db
|
|
1551
|
+
// .select().from(${kebab}s).$dynamic()
|
|
1552
|
+
// .where(query.where).orderBy(...query.orderBy)
|
|
1553
|
+
// .limit(query.limit).offset(query.offset).all()
|
|
1554
|
+
//
|
|
1555
|
+
// const totalResult = this.db
|
|
1556
|
+
// .select({ count: count() }).from(${kebab}s)
|
|
1557
|
+
// .$dynamic().where(query.where).get()
|
|
1558
|
+
//
|
|
1559
|
+
// return { data, total: totalResult?.count ?? 0 }
|
|
1560
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented')
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1564
|
+
// TODO: Implement with Drizzle
|
|
1565
|
+
// return this.db.insert(${kebab}s).values(dto).returning().get()
|
|
1566
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented')
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1570
|
+
// TODO: Implement with Drizzle
|
|
1571
|
+
// const row = this.db.update(${kebab}s).set(dto).where(eq(${kebab}s.id, id)).returning().get()
|
|
1572
|
+
// if (!row) throw HttpException.notFound('${pascal} not found')
|
|
1573
|
+
// return row
|
|
1574
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented')
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
async delete(id: string): Promise<void> {
|
|
1578
|
+
// TODO: Implement with Drizzle
|
|
1579
|
+
// this.db.delete(${kebab}s).where(eq(${kebab}s.id, id)).run()
|
|
1580
|
+
throw new Error('Drizzle ${pascal} repository not yet implemented')
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
`;
|
|
1584
|
+
}
|
|
1585
|
+
function generateDrizzleConstants(ctx) {
|
|
1586
|
+
const { pascal, kebab } = ctx;
|
|
1587
|
+
return `import type { DrizzleQueryParamsConfig } from '@forinda/kickjs-drizzle'
|
|
1588
|
+
// TODO: Import your schema table and reference actual columns for type safety
|
|
1589
|
+
// import { ${kebab}s } from '@/db/schema'
|
|
1590
|
+
|
|
1591
|
+
export const ${pascal.toUpperCase()}_QUERY_CONFIG: DrizzleQueryParamsConfig = {
|
|
1592
|
+
columns: {
|
|
1593
|
+
// Replace with actual Drizzle Column references for type-safe filtering:
|
|
1594
|
+
// name: ${kebab}s.name,
|
|
1595
|
+
// status: ${kebab}s.status,
|
|
1596
|
+
},
|
|
1597
|
+
sortable: {
|
|
1598
|
+
// name: ${kebab}s.name,
|
|
1599
|
+
// createdAt: ${kebab}s.createdAt,
|
|
1600
|
+
},
|
|
1601
|
+
searchColumns: [
|
|
1602
|
+
// ${kebab}s.name,
|
|
1603
|
+
],
|
|
1604
|
+
}
|
|
1605
|
+
`;
|
|
1606
|
+
}
|
|
1607
|
+
//#endregion
|
|
1608
|
+
//#region src/generators/templates/prisma/index.ts
|
|
1609
|
+
function generatePrismaRepository(ctx) {
|
|
1610
|
+
const { pascal, kebab, repoPrefix = "../../domain/repositories", dtoPrefix = "../../application/dtos" } = ctx;
|
|
1611
|
+
const camel = kebab.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
1612
|
+
return `/**
|
|
1613
|
+
* Prisma ${pascal} Repository
|
|
1614
|
+
*
|
|
1615
|
+
* Implements the repository interface using Prisma Client.
|
|
1616
|
+
* Requires a PrismaClient instance injected via the DI container.
|
|
1617
|
+
*
|
|
1618
|
+
* Ensure your Prisma schema has a '${pascal}' model defined.
|
|
1619
|
+
*
|
|
1620
|
+
* For full Prisma field-level type safety, replace PrismaModelDelegate with your PrismaClient:
|
|
1621
|
+
* @Inject(PRISMA_CLIENT) private prisma!: PrismaClient
|
|
1622
|
+
*
|
|
1623
|
+
* @Repository() registers this class in the DI container as a singleton.
|
|
1624
|
+
*/
|
|
1625
|
+
import { Repository, HttpException, Inject } from '@forinda/kickjs'
|
|
1626
|
+
import { PRISMA_CLIENT, type PrismaModelDelegate } from '@forinda/kickjs-prisma'
|
|
1627
|
+
import type { ParsedQuery } from '@forinda/kickjs'
|
|
1628
|
+
import type { I${pascal}Repository } from '${repoPrefix}/${kebab}.repository'
|
|
1629
|
+
import type { ${pascal}ResponseDTO } from '${dtoPrefix}/${kebab}-response.dto'
|
|
1630
|
+
import type { Create${pascal}DTO } from '${dtoPrefix}/create-${kebab}.dto'
|
|
1631
|
+
import type { Update${pascal}DTO } from '${dtoPrefix}/update-${kebab}.dto'
|
|
1632
|
+
|
|
1633
|
+
@Repository()
|
|
1634
|
+
export class Prisma${pascal}Repository implements I${pascal}Repository {
|
|
1635
|
+
@Inject(PRISMA_CLIENT) private prisma!: { ${camel}: PrismaModelDelegate }
|
|
1636
|
+
|
|
1637
|
+
async findById(id: string): Promise<${pascal}ResponseDTO | null> {
|
|
1638
|
+
return this.prisma.${camel}.findUnique({ where: { id } }) as Promise<${pascal}ResponseDTO | null>
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
async findAll(): Promise<${pascal}ResponseDTO[]> {
|
|
1642
|
+
return this.prisma.${camel}.findMany() as Promise<${pascal}ResponseDTO[]>
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
async findPaginated(parsed: ParsedQuery): Promise<{ data: ${pascal}ResponseDTO[]; total: number }> {
|
|
1646
|
+
const [data, total] = await Promise.all([
|
|
1647
|
+
this.prisma.${camel}.findMany({
|
|
1648
|
+
skip: parsed.pagination.offset,
|
|
1649
|
+
take: parsed.pagination.limit,
|
|
1650
|
+
}) as Promise<${pascal}ResponseDTO[]>,
|
|
1651
|
+
this.prisma.${camel}.count(),
|
|
1652
|
+
])
|
|
1653
|
+
return { data, total }
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
async create(dto: Create${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1657
|
+
return this.prisma.${camel}.create({ data: dto as Record<string, unknown> }) as Promise<${pascal}ResponseDTO>
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
async update(id: string, dto: Update${pascal}DTO): Promise<${pascal}ResponseDTO> {
|
|
1661
|
+
const existing = await this.prisma.${camel}.findUnique({ where: { id } })
|
|
1662
|
+
if (!existing) throw HttpException.notFound('${pascal} not found')
|
|
1663
|
+
return this.prisma.${camel}.update({ where: { id }, data: dto as Record<string, unknown> }) as Promise<${pascal}ResponseDTO>
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
async delete(id: string): Promise<void> {
|
|
1667
|
+
await this.prisma.${camel}.deleteMany({ where: { id } })
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
`;
|
|
1671
|
+
}
|
|
1672
|
+
//#endregion
|
|
1673
|
+
//#region src/generators/templates/project-app.ts
|
|
1674
|
+
/**
|
|
1675
|
+
* Generate src/index.ts entry file with template-specific bootstrap.
|
|
1676
|
+
*
|
|
1677
|
+
* All templates export the app for the Vite plugin (dev mode).
|
|
1678
|
+
* In production, bootstrap() auto-starts the HTTP server when
|
|
1679
|
+
* `globalThis.__kickjs_httpServer` is not set.
|
|
1680
|
+
*/
|
|
1681
|
+
function generateEntryFile(name, template, version, packages = []) {
|
|
1682
|
+
switch (template) {
|
|
1683
|
+
case "cqrs": {
|
|
1684
|
+
const cqrsImports = [];
|
|
1685
|
+
const cqrsAdapters = [];
|
|
1686
|
+
if (packages.includes("devtools")) {
|
|
1687
|
+
cqrsImports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
|
|
1688
|
+
cqrsAdapters.push(` DevToolsAdapter(),`);
|
|
1689
|
+
}
|
|
1690
|
+
if (packages.includes("swagger")) {
|
|
1691
|
+
cqrsImports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
|
|
1692
|
+
cqrsAdapters.push(` SwaggerAdapter({\n info: { title: '${name}', version: '${version}' },\n }),`);
|
|
1693
|
+
}
|
|
1694
|
+
return `import 'reflect-metadata'
|
|
1695
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
1696
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
1697
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1698
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
1699
|
+
import './config'
|
|
1700
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1701
|
+
// import { WsAdapter } from '@forinda/kickjs-ws'
|
|
1702
|
+
// import { QueueAdapter, BullMQProvider } from '@forinda/kickjs-queue'
|
|
1703
|
+
${cqrsImports.length ? cqrsImports.join("\n") + "\n" : ""}import { modules } from './modules'
|
|
1704
|
+
|
|
1705
|
+
// Export the app for the Vite plugin (dev mode)
|
|
1706
|
+
export const app = await bootstrap({
|
|
1707
|
+
modules,${cqrsImports.length ? `\n adapters: [\n${cqrsAdapters.join("\n")}\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],` : `\n adapters: [\n // Uncomment for WebSocket support:\n // WsAdapter(),\n // Uncomment when Redis is available:\n // QueueAdapter({\n // provider: new BullMQProvider({ host: 'localhost', port: 6379 }),\n // }),\n ],`}
|
|
1708
|
+
})
|
|
1709
|
+
`;
|
|
1710
|
+
}
|
|
1711
|
+
case "minimal": {
|
|
1712
|
+
const imports = [];
|
|
1713
|
+
const adapters = [];
|
|
1714
|
+
if (packages.includes("swagger")) {
|
|
1715
|
+
imports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
|
|
1716
|
+
adapters.push(` SwaggerAdapter({ info: { title: '${name}', version: '${version}' } }),`);
|
|
1717
|
+
}
|
|
1718
|
+
if (packages.includes("devtools")) {
|
|
1719
|
+
imports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
|
|
1720
|
+
adapters.push(` DevToolsAdapter(),`);
|
|
1721
|
+
}
|
|
1722
|
+
return `import 'reflect-metadata'
|
|
1723
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
1724
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
1725
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1726
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
1727
|
+
import './config'
|
|
1728
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
1729
|
+
${imports.length ? imports.join("\n") + "\n" : ""}import { modules } from './modules'
|
|
1730
|
+
|
|
1731
|
+
// Export the app for the Vite plugin (dev mode)
|
|
1732
|
+
export const app = await bootstrap({ modules${adapters.length ? `,\n adapters: [\n${adapters.join("\n")}\n ]` : ""} })
|
|
1733
|
+
`;
|
|
1734
|
+
}
|
|
1735
|
+
default: {
|
|
1736
|
+
const restImports = [];
|
|
1737
|
+
const restAdapters = [];
|
|
1738
|
+
if (packages.includes("devtools")) {
|
|
1739
|
+
restImports.push(`import { DevToolsAdapter } from '@forinda/kickjs-devtools'`);
|
|
1740
|
+
restAdapters.push(` DevToolsAdapter(),`);
|
|
1741
|
+
}
|
|
1742
|
+
if (packages.includes("swagger")) {
|
|
1743
|
+
restImports.push(`import { SwaggerAdapter } from '@forinda/kickjs-swagger'`);
|
|
1744
|
+
restAdapters.push(` SwaggerAdapter({\n info: { title: '${name}', version: '${version}' },\n }),`);
|
|
1745
|
+
}
|
|
1746
|
+
return `import 'reflect-metadata'
|
|
1747
|
+
// Side-effect import — registers the extended env schema with kickjs
|
|
1748
|
+
// **before** any controller / service / @Value gets resolved. Without
|
|
1749
|
+
// this line ConfigService.get('YOUR_KEY') returns undefined because the
|
|
1750
|
+
// cached schema would still be the base shape. See guide/configuration.
|
|
1751
|
+
import './config'
|
|
1752
|
+
import express from 'express'
|
|
1753
|
+
import {
|
|
1754
|
+
bootstrap,
|
|
1755
|
+
requestId,
|
|
1756
|
+
requestLogger,
|
|
1757
|
+
helmet,
|
|
1758
|
+
cors,
|
|
1759
|
+
} from '@forinda/kickjs'
|
|
1760
|
+
${restImports.length ? restImports.join("\n") + "\n" : ""}import { modules } from './modules'
|
|
1761
|
+
|
|
1762
|
+
// Export the app for the Vite plugin (dev mode)
|
|
1763
|
+
export const app = await bootstrap({
|
|
1764
|
+
modules,${restAdapters.length ? `\n adapters: [\n${restAdapters.join("\n")}\n ],` : ""}
|
|
1765
|
+
middleware: [
|
|
1766
|
+
helmet(),
|
|
1767
|
+
cors({ origin: '*' }),
|
|
1768
|
+
requestId(),
|
|
1769
|
+
requestLogger(),
|
|
1770
|
+
express.json(),
|
|
1771
|
+
],
|
|
1772
|
+
})
|
|
1773
|
+
`;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
/** Generate src/modules/index.ts module registry */
|
|
1778
|
+
function generateModulesIndex() {
|
|
1779
|
+
return `import type { AppModuleClass } from '@forinda/kickjs'
|
|
1780
|
+
import { HelloModule } from './hello/hello.module'
|
|
1781
|
+
|
|
1782
|
+
// Remove HelloModule and run: kick g module <name>
|
|
1783
|
+
export const modules: AppModuleClass[] = [HelloModule]
|
|
1784
|
+
`;
|
|
1785
|
+
}
|
|
1786
|
+
/**
|
|
1787
|
+
* Generate `src/config/index.ts` — the project's typed env schema.
|
|
1788
|
+
*
|
|
1789
|
+
* Default-exports a `defineEnv(...)` schema so `kick typegen` can
|
|
1790
|
+
* infer it into the global `KickEnv` registry, and *also* calls
|
|
1791
|
+
* `loadEnv(envSchema)` as a module-load side effect so `ConfigService`
|
|
1792
|
+
* and `@Value()` see the extended shape from the very first DI
|
|
1793
|
+
* resolution. The companion `src/index.ts` template adds
|
|
1794
|
+
* `import './config'` immediately after `reflect-metadata` so the
|
|
1795
|
+
* registration runs before `bootstrap()` constructs anything.
|
|
1796
|
+
*
|
|
1797
|
+
* After typegen runs:
|
|
1798
|
+
*
|
|
1799
|
+
* @Value('DATABASE_URL') private url!: Env<'DATABASE_URL'>
|
|
1800
|
+
* process.env.DATABASE_URL // typed as string
|
|
1801
|
+
*
|
|
1802
|
+
* Both autocomplete and type-check at compile time.
|
|
1803
|
+
*/
|
|
1804
|
+
function generateEnvFile() {
|
|
1805
|
+
return `import { defineEnv, loadEnv } from '@forinda/kickjs/config'
|
|
1806
|
+
import { z } from 'zod'
|
|
1807
|
+
|
|
1808
|
+
/**
|
|
1809
|
+
* Project environment schema.
|
|
1810
|
+
*
|
|
1811
|
+
* Extend the base schema with your application's variables. The
|
|
1812
|
+
* default export is the contract \`kick typegen\` reads to populate
|
|
1813
|
+
* the global \`KickEnv\` registry — that's what makes \`@Value('FOO')\`
|
|
1814
|
+
* autocomplete and \`process.env.FOO\` typed.
|
|
1815
|
+
*
|
|
1816
|
+
* @example
|
|
1817
|
+
* DATABASE_URL: z.string().url(),
|
|
1818
|
+
* JWT_SECRET: z.string().min(32),
|
|
1819
|
+
* REDIS_URL: z.string().url().optional(),
|
|
1820
|
+
*/
|
|
1821
|
+
const envSchema = defineEnv((base) =>
|
|
1822
|
+
base.extend({
|
|
1823
|
+
// DATABASE_URL: z.string().url(),
|
|
1824
|
+
}),
|
|
1825
|
+
)
|
|
1826
|
+
|
|
1827
|
+
/**
|
|
1828
|
+
* IMPORTANT — side effect: register the schema with kickjs's env cache
|
|
1829
|
+
* **at module-load time**. \`ConfigService\` and \`@Value()\` both consume
|
|
1830
|
+
* this cache, and they will fall back to the base schema (or undefined)
|
|
1831
|
+
* if no extended schema has been registered before they're resolved.
|
|
1832
|
+
*
|
|
1833
|
+
* As long as \`src/index.ts\` imports this file (\`import './env'\`) at the
|
|
1834
|
+
* top — before \`bootstrap()\` runs — every controller and service in the
|
|
1835
|
+
* app sees the typed extended values.
|
|
1836
|
+
*/
|
|
1837
|
+
export const env = loadEnv(envSchema)
|
|
1838
|
+
|
|
1839
|
+
export default envSchema
|
|
1840
|
+
`;
|
|
1841
|
+
}
|
|
1842
|
+
/** Generate src/modules/hello/hello.service.ts */
|
|
1843
|
+
function generateHelloService() {
|
|
1844
|
+
return `import { Service } from '@forinda/kickjs'
|
|
1845
|
+
|
|
1846
|
+
@Service()
|
|
1847
|
+
export class HelloService {
|
|
1848
|
+
greet(name: string) {
|
|
1849
|
+
return { message: \`Hello \${name} from KickJS!\`, timestamp: new Date().toISOString() }
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
healthCheck() {
|
|
1853
|
+
return { status: 'ok', uptime: process.uptime() }
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
`;
|
|
1857
|
+
}
|
|
1858
|
+
/** Generate src/modules/hello/hello.controller.ts */
|
|
1859
|
+
function generateHelloController() {
|
|
1860
|
+
return `import { Controller, Get, Autowired, type Ctx } from '@forinda/kickjs'
|
|
1861
|
+
import { HelloService } from './hello.service'
|
|
1862
|
+
|
|
1863
|
+
// \`Ctx<KickRoutes.HelloController['<method>']>\` is generated by
|
|
1864
|
+
// \`kick typegen\` (auto-run on \`kick dev\`). The first run after a fresh
|
|
1865
|
+
// scaffold creates \`.kickjs/types/routes.ts\` so this file typechecks.
|
|
1866
|
+
// See https://forinda.github.io/kick-js/guide/typegen.
|
|
1867
|
+
|
|
1868
|
+
@Controller()
|
|
1869
|
+
export class HelloController {
|
|
1870
|
+
@Autowired() private readonly helloService!: HelloService
|
|
1871
|
+
|
|
1872
|
+
@Get('/')
|
|
1873
|
+
index(ctx: Ctx<KickRoutes.HelloController['index']>) {
|
|
1874
|
+
ctx.json(this.helloService.greet('World'))
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
@Get('/health')
|
|
1878
|
+
health(ctx: Ctx<KickRoutes.HelloController['health']>) {
|
|
1879
|
+
ctx.json(this.helloService.healthCheck())
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
`;
|
|
1883
|
+
}
|
|
1884
|
+
/** Generate src/modules/hello/hello.module.ts */
|
|
1885
|
+
function generateHelloModule() {
|
|
1886
|
+
return `import { type AppModule, type ModuleRoutes, buildRoutes } from '@forinda/kickjs'
|
|
1887
|
+
import { HelloController } from './hello.controller'
|
|
1888
|
+
|
|
1889
|
+
export class HelloModule implements AppModule {
|
|
1890
|
+
// \`register(container)\` is optional — only implement it when you need
|
|
1891
|
+
// to bind a token to a concrete implementation, e.g.
|
|
1892
|
+
// register(container) {
|
|
1893
|
+
// container.registerFactory(USER_REPOSITORY, () => container.resolve(InMemoryUserRepository))
|
|
1894
|
+
// }
|
|
1895
|
+
// The HelloService uses @Service() so the decorator handles registration.
|
|
1896
|
+
|
|
1897
|
+
routes(): ModuleRoutes {
|
|
1898
|
+
return {
|
|
1899
|
+
path: '/hello',
|
|
1900
|
+
router: buildRoutes(HelloController),
|
|
1901
|
+
controller: HelloController,
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
`;
|
|
1906
|
+
}
|
|
1907
|
+
/** Generate kick.config.ts CLI configuration */
|
|
1908
|
+
function generateKickConfig(template, defaultRepo = "inmemory", packageManager = "pnpm") {
|
|
1909
|
+
return `import { defineConfig } from '@forinda/kickjs-cli'
|
|
1910
|
+
|
|
1911
|
+
export default defineConfig({
|
|
1912
|
+
pattern: '${template}',
|
|
1913
|
+
// Pinned so \`kick add\` and other dep-installing commands always use the
|
|
1914
|
+
// project's intended package manager, regardless of which lockfile exists.
|
|
1915
|
+
packageManager: '${packageManager}',
|
|
1916
|
+
modules: {
|
|
1917
|
+
dir: 'src/modules',
|
|
1918
|
+
repo: ${[
|
|
1919
|
+
"drizzle",
|
|
1920
|
+
"inmemory",
|
|
1921
|
+
"prisma"
|
|
1922
|
+
].includes(defaultRepo) ? `'${defaultRepo}'` : `{ name: '${defaultRepo}' }`},
|
|
1923
|
+
pluralize: true,
|
|
1924
|
+
},
|
|
1925
|
+
|
|
1926
|
+
// \`kick typegen\` populates \`.kickjs/types/\` so \`Ctx<KickRoutes.X['method']>\`
|
|
1927
|
+
// resolves to fully-typed params/body/query. Auto-runs on \`kick dev\`.
|
|
1928
|
+
// Set \`schemaValidator: false\` to skip schema-driven body typing entirely.
|
|
1929
|
+
typegen: {
|
|
1930
|
+
schemaValidator: 'zod',
|
|
1931
|
+
},
|
|
1932
|
+
|
|
1933
|
+
commands: [
|
|
1934
|
+
{
|
|
1935
|
+
name: 'test',
|
|
1936
|
+
description: 'Run tests with Vitest',
|
|
1937
|
+
steps: 'npx vitest run',
|
|
1938
|
+
},
|
|
1939
|
+
{
|
|
1940
|
+
name: 'format',
|
|
1941
|
+
description: 'Format code with Prettier',
|
|
1942
|
+
steps: 'npx prettier --write src/',
|
|
1943
|
+
},
|
|
1944
|
+
{
|
|
1945
|
+
name: 'format:check',
|
|
1946
|
+
description: 'Check formatting without writing',
|
|
1947
|
+
steps: 'npx prettier --check src/',
|
|
1948
|
+
},
|
|
1949
|
+
{
|
|
1950
|
+
name: 'ci:check',
|
|
1951
|
+
description: 'Run typecheck + format check',
|
|
1952
|
+
steps: ['npx tsc --noEmit', 'npx prettier --check src/'],
|
|
1953
|
+
aliases: ['verify'],
|
|
1954
|
+
},
|
|
1955
|
+
],
|
|
1956
|
+
})
|
|
1957
|
+
`;
|
|
1958
|
+
}
|
|
1959
|
+
//#endregion
|
|
1960
|
+
//#region src/generators/patterns/minimal.ts
|
|
1961
|
+
async function generateMinimalFiles(ctx) {
|
|
1962
|
+
const { pascal, kebab, plural, write } = ctx;
|
|
1963
|
+
await write(`${kebab}.module.ts`, generateMinimalModuleIndex({
|
|
1964
|
+
pascal,
|
|
1965
|
+
kebab,
|
|
1966
|
+
plural
|
|
1967
|
+
}));
|
|
1968
|
+
await write(`${kebab}.controller.ts`, `import { Controller, Get, type Ctx } from '@forinda/kickjs'
|
|
1969
|
+
|
|
1970
|
+
// \`Ctx<KickRoutes.${pascal}Controller['<method>']>\` is generated by
|
|
1971
|
+
// \`kick typegen\` (auto-run on \`kick dev\`).
|
|
1972
|
+
|
|
1973
|
+
@Controller()
|
|
1974
|
+
export class ${pascal}Controller {
|
|
1975
|
+
@Get('/')
|
|
1976
|
+
async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
|
|
1977
|
+
ctx.json({ message: '${pascal} list' })
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
`);
|
|
1981
|
+
}
|
|
1982
|
+
//#endregion
|
|
1983
|
+
//#region src/generators/patterns/rest.ts
|
|
1984
|
+
async function generateRestFiles(ctx) {
|
|
1985
|
+
const { pascal, kebab, plural, pluralPascal, repo, noTests, prismaClientPath, tokenScope, write } = ctx;
|
|
1986
|
+
await write(`${kebab}.module.ts`, generateRestModuleIndex({
|
|
1987
|
+
pascal,
|
|
1988
|
+
kebab,
|
|
1989
|
+
plural,
|
|
1990
|
+
repo
|
|
1991
|
+
}));
|
|
1992
|
+
await write(`${kebab}.constants.ts`, generateRestConstants({
|
|
1993
|
+
pascal,
|
|
1994
|
+
kebab
|
|
1995
|
+
}));
|
|
1996
|
+
await write(`${kebab}.controller.ts`, generateRestController({
|
|
1997
|
+
pascal,
|
|
1998
|
+
kebab,
|
|
1999
|
+
plural,
|
|
2000
|
+
pluralPascal
|
|
2001
|
+
}));
|
|
2002
|
+
await write(`${kebab}.service.ts`, generateRestService({
|
|
2003
|
+
pascal,
|
|
2004
|
+
kebab
|
|
2005
|
+
}));
|
|
2006
|
+
await write(`dtos/create-${kebab}.dto.ts`, generateCreateDTO({
|
|
2007
|
+
pascal,
|
|
2008
|
+
kebab
|
|
2009
|
+
}));
|
|
2010
|
+
await write(`dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
|
|
2011
|
+
pascal,
|
|
2012
|
+
kebab
|
|
2013
|
+
}));
|
|
2014
|
+
await write(`dtos/${kebab}-response.dto.ts`, generateResponseDTO({
|
|
2015
|
+
pascal,
|
|
2016
|
+
kebab
|
|
2017
|
+
}));
|
|
2018
|
+
await write(`${kebab}.repository.ts`, generateRepositoryInterface({
|
|
2019
|
+
pascal,
|
|
2020
|
+
kebab,
|
|
2021
|
+
dtoPrefix: "./dtos",
|
|
2022
|
+
tokenScope
|
|
2023
|
+
}));
|
|
2024
|
+
const builtinRepoFileMap = {
|
|
2025
|
+
inmemory: `in-memory-${kebab}`,
|
|
2026
|
+
drizzle: `drizzle-${kebab}`,
|
|
2027
|
+
prisma: `prisma-${kebab}`
|
|
2028
|
+
};
|
|
2029
|
+
const builtinRepoGeneratorMap = {
|
|
2030
|
+
inmemory: () => generateInMemoryRepository({
|
|
2031
|
+
pascal,
|
|
2032
|
+
kebab,
|
|
2033
|
+
repoPrefix: ".",
|
|
2034
|
+
dtoPrefix: "./dtos"
|
|
2035
|
+
}),
|
|
2036
|
+
drizzle: () => generateDrizzleRepository({
|
|
2037
|
+
pascal,
|
|
2038
|
+
kebab,
|
|
2039
|
+
repoPrefix: ".",
|
|
2040
|
+
dtoPrefix: "./dtos"
|
|
2041
|
+
}),
|
|
2042
|
+
prisma: () => generatePrismaRepository({
|
|
2043
|
+
pascal,
|
|
2044
|
+
kebab,
|
|
2045
|
+
repoPrefix: ".",
|
|
2046
|
+
dtoPrefix: "./dtos",
|
|
2047
|
+
prismaClientPath
|
|
2048
|
+
})
|
|
2049
|
+
};
|
|
2050
|
+
const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
|
|
2051
|
+
const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
|
|
2052
|
+
pascal,
|
|
2053
|
+
kebab,
|
|
2054
|
+
repoType: repo,
|
|
2055
|
+
repoPrefix: ".",
|
|
2056
|
+
dtoPrefix: "./dtos"
|
|
2057
|
+
}));
|
|
2058
|
+
await write(`${repoFile}.repository.ts`, repoGenerator());
|
|
2059
|
+
if (!noTests) {
|
|
2060
|
+
if (repo !== "inmemory") await write(`in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
|
|
2061
|
+
pascal,
|
|
2062
|
+
kebab,
|
|
2063
|
+
repoPrefix: ".",
|
|
2064
|
+
dtoPrefix: "./dtos"
|
|
2065
|
+
}));
|
|
2066
|
+
await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
|
|
2067
|
+
pascal,
|
|
2068
|
+
kebab,
|
|
2069
|
+
plural
|
|
2070
|
+
}));
|
|
2071
|
+
await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
|
|
2072
|
+
pascal,
|
|
2073
|
+
kebab,
|
|
2074
|
+
plural,
|
|
2075
|
+
repoPrefix: `../${builtinRepoFileMap.inmemory ?? `in-memory-${kebab}`}.repository`
|
|
2076
|
+
}));
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
//#endregion
|
|
2080
|
+
//#region src/generators/patterns/cqrs.ts
|
|
2081
|
+
async function generateCqrsFiles(ctx) {
|
|
2082
|
+
const { pascal, kebab, plural, pluralPascal, repo, noTests, prismaClientPath, tokenScope, write } = ctx;
|
|
2083
|
+
await write(`${kebab}.module.ts`, generateCqrsModuleIndex({
|
|
2084
|
+
pascal,
|
|
2085
|
+
kebab,
|
|
2086
|
+
plural,
|
|
2087
|
+
repo
|
|
2088
|
+
}));
|
|
2089
|
+
await write(`${kebab}.constants.ts`, generateRestConstants({
|
|
2090
|
+
pascal,
|
|
2091
|
+
kebab
|
|
2092
|
+
}));
|
|
2093
|
+
await write(`${kebab}.controller.ts`, generateCqrsController({
|
|
2094
|
+
pascal,
|
|
2095
|
+
kebab,
|
|
2096
|
+
plural,
|
|
2097
|
+
pluralPascal
|
|
2098
|
+
}));
|
|
2099
|
+
await write(`dtos/create-${kebab}.dto.ts`, generateCreateDTO({
|
|
2100
|
+
pascal,
|
|
2101
|
+
kebab
|
|
2102
|
+
}));
|
|
2103
|
+
await write(`dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
|
|
2104
|
+
pascal,
|
|
2105
|
+
kebab
|
|
2106
|
+
}));
|
|
2107
|
+
await write(`dtos/${kebab}-response.dto.ts`, generateResponseDTO({
|
|
2108
|
+
pascal,
|
|
2109
|
+
kebab
|
|
2110
|
+
}));
|
|
2111
|
+
const commands = generateCqrsCommands({
|
|
2112
|
+
pascal,
|
|
2113
|
+
kebab
|
|
2114
|
+
});
|
|
2115
|
+
for (const cmd of commands) await write(`commands/${cmd.file}`, cmd.content);
|
|
2116
|
+
const queries = generateCqrsQueries({
|
|
2117
|
+
pascal,
|
|
2118
|
+
kebab,
|
|
2119
|
+
plural,
|
|
2120
|
+
pluralPascal
|
|
2121
|
+
});
|
|
2122
|
+
for (const q of queries) await write(`queries/${q.file}`, q.content);
|
|
2123
|
+
const events = generateCqrsEvents({
|
|
2124
|
+
pascal,
|
|
2125
|
+
kebab
|
|
2126
|
+
});
|
|
2127
|
+
for (const e of events) await write(`events/${e.file}`, e.content);
|
|
2128
|
+
await write(`${kebab}.repository.ts`, generateRepositoryInterface({
|
|
2129
|
+
pascal,
|
|
2130
|
+
kebab,
|
|
2131
|
+
dtoPrefix: "./dtos",
|
|
2132
|
+
tokenScope
|
|
2133
|
+
}));
|
|
2134
|
+
const builtinRepoFileMap = {
|
|
2135
|
+
inmemory: `in-memory-${kebab}`,
|
|
2136
|
+
drizzle: `drizzle-${kebab}`,
|
|
2137
|
+
prisma: `prisma-${kebab}`
|
|
2138
|
+
};
|
|
2139
|
+
const builtinRepoGeneratorMap = {
|
|
2140
|
+
inmemory: () => generateInMemoryRepository({
|
|
2141
|
+
pascal,
|
|
2142
|
+
kebab,
|
|
2143
|
+
repoPrefix: ".",
|
|
2144
|
+
dtoPrefix: "./dtos"
|
|
2145
|
+
}),
|
|
2146
|
+
drizzle: () => generateDrizzleRepository({
|
|
2147
|
+
pascal,
|
|
2148
|
+
kebab,
|
|
2149
|
+
repoPrefix: ".",
|
|
2150
|
+
dtoPrefix: "./dtos"
|
|
2151
|
+
}),
|
|
2152
|
+
prisma: () => generatePrismaRepository({
|
|
2153
|
+
pascal,
|
|
2154
|
+
kebab,
|
|
2155
|
+
repoPrefix: ".",
|
|
2156
|
+
dtoPrefix: "./dtos",
|
|
2157
|
+
prismaClientPath
|
|
2158
|
+
})
|
|
2159
|
+
};
|
|
2160
|
+
const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
|
|
2161
|
+
const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
|
|
2162
|
+
pascal,
|
|
2163
|
+
kebab,
|
|
2164
|
+
repoType: repo,
|
|
2165
|
+
repoPrefix: ".",
|
|
2166
|
+
dtoPrefix: "./dtos"
|
|
2167
|
+
}));
|
|
2168
|
+
await write(`${repoFile}.repository.ts`, repoGenerator());
|
|
2169
|
+
if (!noTests) {
|
|
2170
|
+
if (repo !== "inmemory") await write(`in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
|
|
2171
|
+
pascal,
|
|
2172
|
+
kebab,
|
|
2173
|
+
repoPrefix: ".",
|
|
2174
|
+
dtoPrefix: "./dtos"
|
|
2175
|
+
}));
|
|
2176
|
+
await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
|
|
2177
|
+
pascal,
|
|
2178
|
+
kebab,
|
|
2179
|
+
plural
|
|
2180
|
+
}));
|
|
2181
|
+
await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
|
|
2182
|
+
pascal,
|
|
2183
|
+
kebab,
|
|
2184
|
+
plural,
|
|
2185
|
+
repoPrefix: `../${builtinRepoFileMap.inmemory ?? `in-memory-${kebab}`}.repository`
|
|
2186
|
+
}));
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
//#endregion
|
|
2190
|
+
//#region src/generators/patterns/ddd.ts
|
|
2191
|
+
async function generateDddFiles(ctx) {
|
|
2192
|
+
const { pascal, kebab, plural, pluralPascal, repo, noEntity, noTests, prismaClientPath, tokenScope, write } = ctx;
|
|
2193
|
+
await write(`${kebab}.module.ts`, generateModuleIndex({
|
|
2194
|
+
pascal,
|
|
2195
|
+
kebab,
|
|
2196
|
+
plural,
|
|
2197
|
+
repo
|
|
2198
|
+
}));
|
|
2199
|
+
await write("constants.ts", repo === "drizzle" ? generateDrizzleConstants({
|
|
2200
|
+
pascal,
|
|
2201
|
+
kebab
|
|
2202
|
+
}) : generateConstants({
|
|
2203
|
+
pascal,
|
|
2204
|
+
kebab
|
|
2205
|
+
}));
|
|
2206
|
+
await write(`presentation/${kebab}.controller.ts`, generateController$1({
|
|
2207
|
+
pascal,
|
|
2208
|
+
kebab,
|
|
2209
|
+
plural,
|
|
2210
|
+
pluralPascal
|
|
2211
|
+
}));
|
|
2212
|
+
await write(`application/dtos/create-${kebab}.dto.ts`, generateCreateDTO({
|
|
2213
|
+
pascal,
|
|
2214
|
+
kebab
|
|
2215
|
+
}));
|
|
2216
|
+
await write(`application/dtos/update-${kebab}.dto.ts`, generateUpdateDTO({
|
|
2217
|
+
pascal,
|
|
2218
|
+
kebab
|
|
2219
|
+
}));
|
|
2220
|
+
await write(`application/dtos/${kebab}-response.dto.ts`, generateResponseDTO({
|
|
2221
|
+
pascal,
|
|
2222
|
+
kebab
|
|
2223
|
+
}));
|
|
2224
|
+
const useCases = generateUseCases({
|
|
2225
|
+
pascal,
|
|
2226
|
+
kebab,
|
|
2227
|
+
plural,
|
|
2228
|
+
pluralPascal
|
|
2229
|
+
});
|
|
2230
|
+
for (const uc of useCases) await write(`application/use-cases/${uc.file}`, uc.content);
|
|
2231
|
+
await write(`domain/repositories/${kebab}.repository.ts`, generateRepositoryInterface({
|
|
2232
|
+
pascal,
|
|
2233
|
+
kebab,
|
|
2234
|
+
tokenScope
|
|
2235
|
+
}));
|
|
2236
|
+
await write(`domain/services/${kebab}-domain.service.ts`, generateDomainService({
|
|
2237
|
+
pascal,
|
|
2238
|
+
kebab
|
|
2239
|
+
}));
|
|
2240
|
+
const builtinRepoFileMap = {
|
|
2241
|
+
inmemory: `in-memory-${kebab}`,
|
|
2242
|
+
drizzle: `drizzle-${kebab}`,
|
|
2243
|
+
prisma: `prisma-${kebab}`
|
|
2244
|
+
};
|
|
2245
|
+
const builtinRepoGeneratorMap = {
|
|
2246
|
+
inmemory: () => generateInMemoryRepository({
|
|
2247
|
+
pascal,
|
|
2248
|
+
kebab
|
|
2249
|
+
}),
|
|
2250
|
+
drizzle: () => generateDrizzleRepository({
|
|
2251
|
+
pascal,
|
|
2252
|
+
kebab
|
|
2253
|
+
}),
|
|
2254
|
+
prisma: () => generatePrismaRepository({
|
|
2255
|
+
pascal,
|
|
2256
|
+
kebab,
|
|
2257
|
+
prismaClientPath
|
|
2258
|
+
})
|
|
2259
|
+
};
|
|
2260
|
+
const repoFile = builtinRepoFileMap[repo] ?? `${toKebabCase(repo)}-${kebab}`;
|
|
2261
|
+
const repoGenerator = builtinRepoGeneratorMap[repo] ?? (() => generateCustomRepository({
|
|
2262
|
+
pascal,
|
|
2263
|
+
kebab,
|
|
2264
|
+
repoType: repo
|
|
2265
|
+
}));
|
|
2266
|
+
await write(`infrastructure/repositories/${repoFile}.repository.ts`, repoGenerator());
|
|
2267
|
+
if (!noEntity) {
|
|
2268
|
+
await write(`domain/entities/${kebab}.entity.ts`, generateEntity({
|
|
2269
|
+
pascal,
|
|
2270
|
+
kebab
|
|
2271
|
+
}));
|
|
2272
|
+
await write(`domain/value-objects/${kebab}-id.vo.ts`, generateValueObject({
|
|
2273
|
+
pascal,
|
|
2274
|
+
kebab
|
|
2275
|
+
}));
|
|
2276
|
+
}
|
|
2277
|
+
if (!noTests) {
|
|
2278
|
+
if (repo !== "inmemory") await write(`infrastructure/repositories/in-memory-${kebab}.repository.ts`, generateInMemoryRepository({
|
|
2279
|
+
pascal,
|
|
2280
|
+
kebab
|
|
2281
|
+
}));
|
|
2282
|
+
await write(`__tests__/${kebab}.controller.test.ts`, generateControllerTest({
|
|
2283
|
+
pascal,
|
|
2284
|
+
kebab,
|
|
2285
|
+
plural
|
|
2286
|
+
}));
|
|
2287
|
+
await write(`__tests__/${kebab}.repository.test.ts`, generateRepositoryTest({
|
|
2288
|
+
pascal,
|
|
2289
|
+
kebab,
|
|
2290
|
+
plural
|
|
2291
|
+
}));
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
//#endregion
|
|
2295
|
+
//#region src/generators/module.ts
|
|
2296
|
+
/** Resolve a RepoTypeConfig (from kick.config.ts) into a flat repo type string */
|
|
2297
|
+
function resolveRepoType(config) {
|
|
2298
|
+
if (!config) return "inmemory";
|
|
2299
|
+
if (typeof config === "string") return config;
|
|
2300
|
+
return config.name;
|
|
2301
|
+
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Generate a module — structure depends on the project pattern.
|
|
2304
|
+
*
|
|
2305
|
+
* Patterns:
|
|
2306
|
+
* rest — flat folder: controller + service + DTOs + repo
|
|
2307
|
+
* ddd — nested DDD: presentation/ application/ domain/ infrastructure/
|
|
2308
|
+
* cqrs — commands, queries, events with WS/queue integration
|
|
2309
|
+
* minimal — just controller + module index
|
|
2310
|
+
*/
|
|
2311
|
+
async function generateModule(options) {
|
|
2312
|
+
const { name, modulesDir, noEntity, noTests, repo = "inmemory", force, dryRun } = options;
|
|
2313
|
+
const shouldPluralize = options.pluralize !== false;
|
|
2314
|
+
let pattern = options.pattern ?? "ddd";
|
|
2315
|
+
if (options.minimal) pattern = "minimal";
|
|
2316
|
+
const kebab = toKebabCase(name);
|
|
2317
|
+
const pascal = toPascalCase(name);
|
|
2318
|
+
const plural = shouldPluralize ? pluralize(kebab) : kebab;
|
|
2319
|
+
const pluralPascal = shouldPluralize ? pluralizePascal(pascal) : pascal;
|
|
2320
|
+
const moduleDir = join(modulesDir, plural);
|
|
2321
|
+
const files = [];
|
|
2322
|
+
let overwriteAll = force ?? false;
|
|
2323
|
+
const write = async (relativePath, content) => {
|
|
2324
|
+
const fullPath = join(moduleDir, relativePath);
|
|
2325
|
+
if (dryRun) {
|
|
2326
|
+
files.push(fullPath);
|
|
2327
|
+
return;
|
|
2328
|
+
}
|
|
2329
|
+
if (!overwriteAll && await fileExists(fullPath)) {
|
|
2330
|
+
if (!await confirm({
|
|
2331
|
+
message: `File exists: ${pc.dim(relativePath)}. Overwrite?`,
|
|
2332
|
+
initialValue: false
|
|
2333
|
+
})) {
|
|
2334
|
+
log.warn(`Skipped: ${relativePath}`);
|
|
2335
|
+
return;
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
await writeFileSafe(fullPath, content);
|
|
2339
|
+
files.push(fullPath);
|
|
2340
|
+
};
|
|
2341
|
+
const ctx = {
|
|
2342
|
+
kebab,
|
|
2343
|
+
pascal,
|
|
2344
|
+
plural,
|
|
2345
|
+
pluralPascal,
|
|
2346
|
+
moduleDir,
|
|
2347
|
+
repo,
|
|
2348
|
+
noEntity: noEntity ?? false,
|
|
2349
|
+
noTests: noTests ?? false,
|
|
2350
|
+
prismaClientPath: options.prismaClientPath ?? "@prisma/client",
|
|
2351
|
+
tokenScope: options.tokenScope ?? "app",
|
|
2352
|
+
write,
|
|
2353
|
+
files
|
|
2354
|
+
};
|
|
2355
|
+
switch (pattern) {
|
|
2356
|
+
case "minimal":
|
|
2357
|
+
await generateMinimalFiles(ctx);
|
|
2358
|
+
break;
|
|
2359
|
+
case "rest":
|
|
2360
|
+
await generateRestFiles(ctx);
|
|
2361
|
+
break;
|
|
2362
|
+
case "cqrs":
|
|
2363
|
+
await generateCqrsFiles(ctx);
|
|
2364
|
+
break;
|
|
2365
|
+
default:
|
|
2366
|
+
await generateDddFiles(ctx);
|
|
2367
|
+
break;
|
|
2368
|
+
}
|
|
2369
|
+
if (!dryRun) await autoRegisterModule(modulesDir, pascal, plural, kebab);
|
|
2370
|
+
return files;
|
|
2371
|
+
}
|
|
2372
|
+
/** Add the new module to src/modules/index.ts */
|
|
2373
|
+
async function autoRegisterModule(modulesDir, pascal, plural, kebab) {
|
|
2374
|
+
const indexPath = join(modulesDir, "index.ts");
|
|
2375
|
+
const exists = await fileExists(indexPath);
|
|
2376
|
+
const importPath = `./${plural}/${kebab}.module`;
|
|
2377
|
+
if (!exists) {
|
|
2378
|
+
await writeFileSafe(indexPath, `import type { AppModuleClass } from '@forinda/kickjs'
|
|
2379
|
+
import { ${pascal}Module } from '${importPath}'
|
|
2380
|
+
|
|
2381
|
+
export const modules: AppModuleClass[] = [${pascal}Module]
|
|
2382
|
+
`);
|
|
2383
|
+
return;
|
|
2384
|
+
}
|
|
2385
|
+
let content = await readFile(indexPath, "utf-8");
|
|
2386
|
+
const importLine = `import { ${pascal}Module } from '${importPath}'`;
|
|
2387
|
+
if (!content.includes(`${pascal}Module`)) {
|
|
2388
|
+
const lastImportIdx = content.lastIndexOf("import ");
|
|
2389
|
+
if (lastImportIdx !== -1) {
|
|
2390
|
+
const lineEnd = content.indexOf("\n", lastImportIdx);
|
|
2391
|
+
content = content.slice(0, lineEnd + 1) + importLine + "\n" + content.slice(lineEnd + 1);
|
|
2392
|
+
} else content = importLine + "\n" + content;
|
|
2393
|
+
content = content.replace(/(=\s*\[)([\s\S]*?)(])/, (_match, open, existing, close) => {
|
|
2394
|
+
const trimmed = existing.trim();
|
|
2395
|
+
if (!trimmed) return `${open}${pascal}Module${close}`;
|
|
2396
|
+
const needsComma = trimmed.endsWith(",") ? "" : ",";
|
|
2397
|
+
return `${open}${existing.trimEnd()}${needsComma} ${pascal}Module${close}`;
|
|
2398
|
+
});
|
|
2399
|
+
}
|
|
2400
|
+
await writeFile(indexPath, content, "utf-8");
|
|
2401
|
+
}
|
|
2402
|
+
//#endregion
|
|
2403
|
+
//#region src/generators/adapter.ts
|
|
2404
|
+
/**
|
|
2405
|
+
* Scaffold a `defineAdapter()` factory under `src/adapters/<name>.adapter.ts`.
|
|
2406
|
+
*
|
|
2407
|
+
* v4 dropped the `class implements AppAdapter` pattern in favour of the
|
|
2408
|
+
* `defineAdapter()` factory (architecture.md §21.3.4). The generated
|
|
2409
|
+
* template uses the new factory shape so adopters get a working
|
|
2410
|
+
* adapter with all four lifecycle hooks (beforeMount, beforeStart,
|
|
2411
|
+
* afterStart, shutdown), a typed config object with defaults, and the
|
|
2412
|
+
* factory's call / `.scoped()` / `.async()` surfaces — without
|
|
2413
|
+
* writing a single class.
|
|
2414
|
+
*/
|
|
2415
|
+
async function generateAdapter(options) {
|
|
2416
|
+
const { name, outDir } = options;
|
|
2417
|
+
const kebab = toKebabCase(name);
|
|
2418
|
+
const pascal = toPascalCase(name);
|
|
2419
|
+
const files = [];
|
|
2420
|
+
const filePath = join(outDir, `${kebab}.adapter.ts`);
|
|
2421
|
+
await writeFileSafe(filePath, `import {
|
|
2422
|
+
defineAdapter,
|
|
2423
|
+
type AdapterContext,
|
|
2424
|
+
type AdapterMiddleware,
|
|
2425
|
+
type ContributorRegistrations,
|
|
2426
|
+
type Constructor,
|
|
2427
|
+
} from '@forinda/kickjs'
|
|
2428
|
+
|
|
2429
|
+
/**
|
|
2430
|
+
* Configuration for the ${pascal} adapter.
|
|
2431
|
+
*
|
|
2432
|
+
* Adapters typically take a small config object so callers can tune
|
|
2433
|
+
* behaviour at bootstrap time. Keep the shape narrow — anything
|
|
2434
|
+
* derived from the environment should be read inside the build
|
|
2435
|
+
* function via getEnv(), not forced onto the caller.
|
|
2436
|
+
*/
|
|
2437
|
+
export interface ${pascal}AdapterConfig {
|
|
2438
|
+
// Add your adapter configuration here, e.g.:
|
|
2439
|
+
// enabled?: boolean
|
|
2440
|
+
// apiKey?: string
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
/**
|
|
2444
|
+
* ${pascal} adapter — built via \`defineAdapter()\` so callers get the
|
|
2445
|
+
* factory's call / \`.scoped()\` / \`.async()\` surfaces for free.
|
|
2446
|
+
*
|
|
2447
|
+
* Hooks into the Application lifecycle to add middleware, routes,
|
|
2448
|
+
* Context Contributors, or external service connections.
|
|
2449
|
+
*
|
|
2450
|
+
* Every lifecycle hook below is OPTIONAL. The scaffold emits all of
|
|
2451
|
+
* them so adopters can browse what's available and delete what they
|
|
2452
|
+
* don't need — \`build()\` returning \`{}\` is also valid for an adapter
|
|
2453
|
+
* that only contributes config defaults.
|
|
2454
|
+
*
|
|
2455
|
+
* @example
|
|
2456
|
+
* \`\`\`ts
|
|
2457
|
+
* import { bootstrap } from '@forinda/kickjs'
|
|
2458
|
+
* import { ${pascal}Adapter } from './adapters/${kebab}.adapter'
|
|
2459
|
+
*
|
|
2460
|
+
* bootstrap({
|
|
2461
|
+
* modules,
|
|
2462
|
+
* adapters: [${pascal}Adapter({ /* config overrides *\\/ })],
|
|
2463
|
+
* })
|
|
2464
|
+
* \`\`\`
|
|
2465
|
+
*/
|
|
2466
|
+
export const ${pascal}Adapter = defineAdapter<${pascal}AdapterConfig>({
|
|
2467
|
+
name: '${pascal}Adapter',
|
|
2468
|
+
defaults: {
|
|
2469
|
+
// Default config values go here. The adopter's overrides shallow-merge
|
|
2470
|
+
// on top of these before \`build()\` runs.
|
|
2471
|
+
},
|
|
2472
|
+
build: (_config, { name: _name }) => {
|
|
2473
|
+
// Closures inside \`build()\` are how each adapter instance owns its
|
|
2474
|
+
// own state (database client, Map, timer handle, …). The same
|
|
2475
|
+
// \`_config\` is visible to every hook below.
|
|
2476
|
+
|
|
2477
|
+
return {
|
|
2478
|
+
/**
|
|
2479
|
+
* Express middleware entries the Application mounts at named phases.
|
|
2480
|
+
*
|
|
2481
|
+
* \`phase\` controls where each handler sits in the pipeline:
|
|
2482
|
+
* 'beforeGlobal' | 'afterGlobal' | 'beforeRoutes' | 'afterRoutes'.
|
|
2483
|
+
*
|
|
2484
|
+
* \`path\` (optional) scopes the entry to a path prefix.
|
|
2485
|
+
*
|
|
2486
|
+
* Delete this hook entirely if you don't add middleware.
|
|
2487
|
+
*/
|
|
2488
|
+
middleware(): AdapterMiddleware[] {
|
|
2489
|
+
return [
|
|
2490
|
+
// Example: add a custom header to all responses
|
|
2491
|
+
// {
|
|
2492
|
+
// phase: 'beforeGlobal',
|
|
2493
|
+
// handler: (_req, res, next) => {
|
|
2494
|
+
// res.setHeader('X-${pascal}', 'true')
|
|
2495
|
+
// next()
|
|
2496
|
+
// },
|
|
2497
|
+
// },
|
|
2498
|
+
// Example: scope a rate limiter to one path prefix
|
|
2499
|
+
// {
|
|
2500
|
+
// phase: 'beforeRoutes',
|
|
2501
|
+
// path: '/api/v1/auth',
|
|
2502
|
+
// handler: rateLimit({ max: 10 }),
|
|
2503
|
+
// },
|
|
2504
|
+
]
|
|
2505
|
+
},
|
|
2506
|
+
|
|
2507
|
+
/**
|
|
2508
|
+
* Runs BEFORE global middleware. Mount routes that should bypass the
|
|
2509
|
+
* middleware stack — health checks, docs UI, static assets, OAuth
|
|
2510
|
+
* callbacks. Anything you want reachable even if a global middleware
|
|
2511
|
+
* later in the chain rejects requests.
|
|
2512
|
+
*
|
|
2513
|
+
* Delete this hook if you have no early routes.
|
|
2514
|
+
*/
|
|
2515
|
+
beforeMount(_ctx: AdapterContext): void {
|
|
2516
|
+
// Example:
|
|
2517
|
+
// _ctx.app.get('/${kebab}/status', (_req, res) => res.json({ status: 'ok' }))
|
|
2518
|
+
},
|
|
2519
|
+
|
|
2520
|
+
/**
|
|
2521
|
+
* Fires once per controller class as the router mounts. Use this to
|
|
2522
|
+
* collect route metadata for OpenAPI specs, dependency graphs, route
|
|
2523
|
+
* inventories, devtools dashboards.
|
|
2524
|
+
*
|
|
2525
|
+
* Delete this hook unless your adapter introspects the route registry.
|
|
2526
|
+
*/
|
|
2527
|
+
onRouteMount(_controllerClass: Constructor, _mountPath: string): void {
|
|
2528
|
+
// Example (Swagger-style): collect routes for the spec.
|
|
2529
|
+
// openApiSpec.addController(_controllerClass, _mountPath)
|
|
2530
|
+
},
|
|
2531
|
+
|
|
2532
|
+
/**
|
|
2533
|
+
* Runs AFTER modules + routes are wired, BEFORE the server starts.
|
|
2534
|
+
* Right place for late-stage DI registrations or final config validation.
|
|
2535
|
+
*
|
|
2536
|
+
* Delete this hook if there's nothing to wire post-modules.
|
|
2537
|
+
*/
|
|
2538
|
+
beforeStart(_ctx: AdapterContext): void {
|
|
2539
|
+
// Example: _ctx.container.registerInstance(MY_TOKEN, new MyService(_config))
|
|
2540
|
+
},
|
|
2541
|
+
|
|
2542
|
+
/**
|
|
2543
|
+
* Runs AFTER the HTTP server is listening. The raw \`http.Server\` is
|
|
2544
|
+
* available on \`ctx.server\` — attach upgrade handlers (Socket.IO,
|
|
2545
|
+
* gRPC, GraphQL subscriptions), warm caches, log a banner.
|
|
2546
|
+
*
|
|
2547
|
+
* Delete this hook if you don't need the running server reference.
|
|
2548
|
+
*/
|
|
2549
|
+
afterStart(_ctx: AdapterContext): void {
|
|
2550
|
+
// Example: const io = new Server(_ctx.server)
|
|
2551
|
+
},
|
|
2552
|
+
|
|
2553
|
+
/**
|
|
2554
|
+
* Returns Context Contributors to merge into every route's pipeline
|
|
2555
|
+
* at the \`'adapter'\` precedence level. Per-route handlers can
|
|
2556
|
+
* override the value at the method / class / module level.
|
|
2557
|
+
*
|
|
2558
|
+
* Delete this hook unless your adapter ships typed per-request values
|
|
2559
|
+
* (auth user, tenant, locale, feature flags, geo, etc).
|
|
2560
|
+
*/
|
|
2561
|
+
contributors(): ContributorRegistrations {
|
|
2562
|
+
return [
|
|
2563
|
+
// Example:
|
|
2564
|
+
// import { defineHttpContextDecorator } from '@forinda/kickjs'
|
|
2565
|
+
// declare module '@forinda/kickjs' { interface ContextMeta { ${kebab}: { id: string } } }
|
|
2566
|
+
// const Load${pascal} = defineHttpContextDecorator({
|
|
2567
|
+
// key: '${kebab}',
|
|
2568
|
+
// resolve: (ctx) => ({ id: ctx.req.headers['x-${kebab}-id'] as string }),
|
|
2569
|
+
// })
|
|
2570
|
+
// return [Load${pascal}.registration]
|
|
2571
|
+
]
|
|
2572
|
+
},
|
|
2573
|
+
|
|
2574
|
+
/**
|
|
2575
|
+
* Runs on graceful shutdown (SIGINT/SIGTERM). Clean up long-lived
|
|
2576
|
+
* resources the adapter owns: close connections, flush buffers,
|
|
2577
|
+
* cancel timers. The framework runs every adapter's \`shutdown\`
|
|
2578
|
+
* concurrently via \`Promise.allSettled\` — one failure won't block
|
|
2579
|
+
* sibling adapters.
|
|
2580
|
+
*
|
|
2581
|
+
* Delete this hook if your adapter holds no resources.
|
|
2582
|
+
*/
|
|
2583
|
+
async shutdown(): Promise<void> {
|
|
2584
|
+
// Example: await this.pool.end()
|
|
2585
|
+
// Example: clearInterval(this.heartbeatTimer)
|
|
2586
|
+
},
|
|
2587
|
+
}
|
|
2588
|
+
},
|
|
2589
|
+
})
|
|
2590
|
+
`);
|
|
2591
|
+
files.push(filePath);
|
|
2592
|
+
return files;
|
|
2593
|
+
}
|
|
2594
|
+
//#endregion
|
|
2595
|
+
//#region src/utils/resolve-out-dir.ts
|
|
2596
|
+
/**
|
|
2597
|
+
* DDD folder mapping — nested layered architecture.
|
|
2598
|
+
*/
|
|
2599
|
+
const DDD_FOLDER_MAP = {
|
|
2600
|
+
controller: "presentation",
|
|
2601
|
+
service: "domain/services",
|
|
2602
|
+
dto: "application/dtos",
|
|
2603
|
+
guard: "presentation/guards",
|
|
2604
|
+
middleware: "middleware"
|
|
2605
|
+
};
|
|
2606
|
+
/**
|
|
2607
|
+
* Flat folder mapping — REST/GraphQL/minimal patterns.
|
|
2608
|
+
* Files live at the module root or in minimal subdirectories.
|
|
2609
|
+
*/
|
|
2610
|
+
const FLAT_FOLDER_MAP = {
|
|
2611
|
+
controller: "",
|
|
2612
|
+
service: "",
|
|
2613
|
+
dto: "dtos",
|
|
2614
|
+
guard: "guards",
|
|
2615
|
+
middleware: "middleware"
|
|
2616
|
+
};
|
|
2617
|
+
/**
|
|
2618
|
+
* CQRS folder mapping — commands, queries, events.
|
|
2619
|
+
*/
|
|
2620
|
+
const CQRS_FOLDER_MAP = {
|
|
2621
|
+
controller: "",
|
|
2622
|
+
service: "",
|
|
2623
|
+
dto: "dtos",
|
|
2624
|
+
guard: "guards",
|
|
2625
|
+
middleware: "middleware",
|
|
2626
|
+
command: "commands",
|
|
2627
|
+
query: "queries",
|
|
2628
|
+
event: "events"
|
|
2629
|
+
};
|
|
2630
|
+
/**
|
|
2631
|
+
* Resolve the output directory for a generator artifact.
|
|
2632
|
+
*
|
|
2633
|
+
* Priority:
|
|
2634
|
+
* 1. Explicit --out flag (always wins)
|
|
2635
|
+
* 2. --module flag → maps into module's folder (DDD or flat based on pattern)
|
|
2636
|
+
* 3. Standalone default directory
|
|
2637
|
+
*/
|
|
2638
|
+
function resolveOutDir(options) {
|
|
2639
|
+
const { type, outDir, moduleName, modulesDir = "src/modules", defaultDir, pattern = "ddd", shouldPluralize = true } = options;
|
|
2640
|
+
if (outDir) return resolve(outDir);
|
|
2641
|
+
if (moduleName) {
|
|
2642
|
+
const folderMap = pattern === "ddd" ? DDD_FOLDER_MAP : pattern === "cqrs" ? CQRS_FOLDER_MAP : FLAT_FOLDER_MAP;
|
|
2643
|
+
const kebab = toKebabCase(moduleName);
|
|
2644
|
+
const folder = shouldPluralize ? pluralize(kebab) : kebab;
|
|
2645
|
+
const subfolder = folderMap[type] ?? "";
|
|
2646
|
+
const base = join(modulesDir, folder);
|
|
2647
|
+
return resolve(subfolder ? join(base, subfolder) : base);
|
|
2648
|
+
}
|
|
2649
|
+
return resolve(defaultDir);
|
|
2650
|
+
}
|
|
2651
|
+
//#endregion
|
|
2652
|
+
//#region src/generators/middleware.ts
|
|
2653
|
+
async function generateMiddleware(options) {
|
|
2654
|
+
const { name, moduleName, modulesDir, pattern } = options;
|
|
2655
|
+
const outDir = resolveOutDir({
|
|
2656
|
+
type: "middleware",
|
|
2657
|
+
outDir: options.outDir,
|
|
2658
|
+
moduleName,
|
|
2659
|
+
modulesDir,
|
|
2660
|
+
defaultDir: "src/middleware",
|
|
2661
|
+
pattern,
|
|
2662
|
+
shouldPluralize: options.pluralize ?? true
|
|
2663
|
+
});
|
|
2664
|
+
const kebab = toKebabCase(name);
|
|
2665
|
+
const camel = toCamelCase(name);
|
|
2666
|
+
const files = [];
|
|
2667
|
+
const filePath = join(outDir, `${kebab}.middleware.ts`);
|
|
2668
|
+
await writeFileSafe(filePath, `import type { Request, Response, NextFunction } from 'express'
|
|
2669
|
+
|
|
2670
|
+
export interface ${toPascalCase(name)}Options {
|
|
2671
|
+
// Add configuration options here
|
|
2672
|
+
}
|
|
2673
|
+
|
|
2674
|
+
/**
|
|
2675
|
+
* ${toPascalCase(name)} middleware.
|
|
2676
|
+
*
|
|
2677
|
+
* Usage in bootstrap:
|
|
2678
|
+
* middleware: [${camel}()]
|
|
2679
|
+
*
|
|
2680
|
+
* Usage with adapter:
|
|
2681
|
+
* middleware() { return [{ handler: ${camel}(), phase: 'afterGlobal' }] }
|
|
2682
|
+
*
|
|
2683
|
+
* Usage with @Middleware decorator:
|
|
2684
|
+
* @Middleware(${camel}())
|
|
2685
|
+
*/
|
|
2686
|
+
export function ${camel}(options: ${toPascalCase(name)}Options = {}) {
|
|
2687
|
+
return (req: Request, res: Response, next: NextFunction) => {
|
|
2688
|
+
// Implement your middleware logic here
|
|
2689
|
+
next()
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
`);
|
|
2693
|
+
files.push(filePath);
|
|
2694
|
+
return files;
|
|
2695
|
+
}
|
|
2696
|
+
//#endregion
|
|
2697
|
+
//#region src/generators/guard.ts
|
|
2698
|
+
async function generateGuard(options) {
|
|
2699
|
+
const { name, moduleName, modulesDir, pattern } = options;
|
|
2700
|
+
const outDir = resolveOutDir({
|
|
2701
|
+
type: "guard",
|
|
2702
|
+
outDir: options.outDir,
|
|
2703
|
+
moduleName,
|
|
2704
|
+
modulesDir,
|
|
2705
|
+
defaultDir: "src/guards",
|
|
2706
|
+
pattern,
|
|
2707
|
+
shouldPluralize: options.pluralize ?? true
|
|
2708
|
+
});
|
|
2709
|
+
const kebab = toKebabCase(name);
|
|
2710
|
+
const camel = toCamelCase(name);
|
|
2711
|
+
const pascal = toPascalCase(name);
|
|
2712
|
+
const files = [];
|
|
2713
|
+
const filePath = join(outDir, `${kebab}.guard.ts`);
|
|
2714
|
+
await writeFileSafe(filePath, `import { Container, HttpException } from '@forinda/kickjs'
|
|
2715
|
+
import type { RequestContext } from '@forinda/kickjs'
|
|
2716
|
+
|
|
2717
|
+
/**
|
|
2718
|
+
* ${pascal} guard.
|
|
2719
|
+
*
|
|
2720
|
+
* Guards protect routes by checking conditions before the handler runs.
|
|
2721
|
+
* Return early with an error response to block access.
|
|
2722
|
+
*
|
|
2723
|
+
* Usage:
|
|
2724
|
+
* @Middleware(${camel}Guard)
|
|
2725
|
+
* @Get('/protected')
|
|
2726
|
+
* async handler(ctx: RequestContext) { ... }
|
|
2727
|
+
*/
|
|
2728
|
+
export async function ${camel}Guard(ctx: RequestContext, next: () => void): Promise<void> {
|
|
2729
|
+
// Example: check for an authorization header
|
|
2730
|
+
const header = ctx.headers.authorization
|
|
2731
|
+
if (!header?.startsWith('Bearer ')) {
|
|
2732
|
+
ctx.res.status(401).json({ message: 'Missing or invalid authorization header' })
|
|
2733
|
+
return
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
const token = header.slice(7)
|
|
2737
|
+
|
|
2738
|
+
try {
|
|
2739
|
+
// Verify the token using a service from the DI container
|
|
2740
|
+
// const container = Container.getInstance()
|
|
2741
|
+
// const authService = container.resolve(AuthService)
|
|
2742
|
+
// const payload = authService.verifyToken(token)
|
|
2743
|
+
// ctx.set('auth', payload)
|
|
2744
|
+
|
|
2745
|
+
next()
|
|
2746
|
+
} catch {
|
|
2747
|
+
ctx.res.status(401).json({ message: 'Invalid or expired token' })
|
|
2748
|
+
}
|
|
2749
|
+
}
|
|
2750
|
+
`);
|
|
2751
|
+
files.push(filePath);
|
|
2752
|
+
return files;
|
|
2753
|
+
}
|
|
2754
|
+
//#endregion
|
|
2755
|
+
//#region src/generators/service.ts
|
|
2756
|
+
async function generateService(options) {
|
|
2757
|
+
const { name, moduleName, modulesDir, pattern } = options;
|
|
2758
|
+
const outDir = resolveOutDir({
|
|
2759
|
+
type: "service",
|
|
2760
|
+
outDir: options.outDir,
|
|
2761
|
+
moduleName,
|
|
2762
|
+
modulesDir,
|
|
2763
|
+
defaultDir: "src/services",
|
|
2764
|
+
pattern,
|
|
2765
|
+
shouldPluralize: options.pluralize ?? true
|
|
2766
|
+
});
|
|
2767
|
+
const kebab = toKebabCase(name);
|
|
2768
|
+
const pascal = toPascalCase(name);
|
|
2769
|
+
const files = [];
|
|
2770
|
+
const filePath = join(outDir, `${kebab}.service.ts`);
|
|
2771
|
+
await writeFileSafe(filePath, `import { Service } from '@forinda/kickjs'
|
|
2772
|
+
|
|
2773
|
+
@Service()
|
|
2774
|
+
export class ${pascal}Service {
|
|
2775
|
+
// Inject dependencies via constructor
|
|
2776
|
+
// constructor(
|
|
2777
|
+
// @Inject(MY_REPO) private readonly repo: IMyRepository,
|
|
2778
|
+
// ) {}
|
|
2779
|
+
}
|
|
2780
|
+
`);
|
|
2781
|
+
files.push(filePath);
|
|
2782
|
+
return files;
|
|
2783
|
+
}
|
|
2784
|
+
//#endregion
|
|
2785
|
+
//#region src/generators/controller.ts
|
|
2786
|
+
async function generateController(options) {
|
|
2787
|
+
const { name, moduleName, modulesDir, pattern } = options;
|
|
2788
|
+
const outDir = resolveOutDir({
|
|
2789
|
+
type: "controller",
|
|
2790
|
+
outDir: options.outDir,
|
|
2791
|
+
moduleName,
|
|
2792
|
+
modulesDir,
|
|
2793
|
+
defaultDir: "src/controllers",
|
|
2794
|
+
pattern,
|
|
2795
|
+
shouldPluralize: options.pluralize ?? true
|
|
2796
|
+
});
|
|
2797
|
+
const kebab = toKebabCase(name);
|
|
2798
|
+
const pascal = toPascalCase(name);
|
|
2799
|
+
const files = [];
|
|
2800
|
+
const filePath = join(outDir, `${kebab}.controller.ts`);
|
|
2801
|
+
await writeFileSafe(filePath, `import { Controller, Get, Post, type Ctx } from '@forinda/kickjs'
|
|
2802
|
+
|
|
2803
|
+
// \`Ctx<KickRoutes.${pascal}Controller['<method>']>\` is generated by
|
|
2804
|
+
// \`kick typegen\` (auto-run on \`kick dev\`). After the first run, your IDE
|
|
2805
|
+
// will autocomplete \`ctx.params\`, \`ctx.body\`, and \`ctx.query\`.
|
|
2806
|
+
// See https://forinda.github.io/kick-js/guide/typegen for details.
|
|
2807
|
+
|
|
2808
|
+
@Controller()
|
|
2809
|
+
export class ${pascal}Controller {
|
|
2810
|
+
// @Autowired() private readonly myService!: MyService
|
|
2811
|
+
|
|
2812
|
+
@Get('/')
|
|
2813
|
+
async list(ctx: Ctx<KickRoutes.${pascal}Controller['list']>) {
|
|
2814
|
+
ctx.json({ message: '${pascal} list' })
|
|
2815
|
+
}
|
|
2816
|
+
|
|
2817
|
+
@Post('/')
|
|
2818
|
+
async create(ctx: Ctx<KickRoutes.${pascal}Controller['create']>) {
|
|
2819
|
+
ctx.created({ message: '${pascal} created', data: ctx.body })
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
`);
|
|
2823
|
+
files.push(filePath);
|
|
2824
|
+
return files;
|
|
2825
|
+
}
|
|
2826
|
+
//#endregion
|
|
2827
|
+
//#region src/generators/dto.ts
|
|
2828
|
+
async function generateDto(options) {
|
|
2829
|
+
const { name, moduleName, modulesDir, pattern } = options;
|
|
2830
|
+
const outDir = resolveOutDir({
|
|
2831
|
+
type: "dto",
|
|
2832
|
+
outDir: options.outDir,
|
|
2833
|
+
moduleName,
|
|
2834
|
+
modulesDir,
|
|
2835
|
+
defaultDir: "src/dtos",
|
|
2836
|
+
pattern,
|
|
2837
|
+
shouldPluralize: options.pluralize ?? true
|
|
2838
|
+
});
|
|
2839
|
+
const kebab = toKebabCase(name);
|
|
2840
|
+
const pascal = toPascalCase(name);
|
|
2841
|
+
const camel = toCamelCase(name);
|
|
2842
|
+
const files = [];
|
|
2843
|
+
const filePath = join(outDir, `${kebab}.dto.ts`);
|
|
2844
|
+
await writeFileSafe(filePath, `import { z } from 'zod'
|
|
2845
|
+
|
|
2846
|
+
export const ${camel}Schema = z.object({
|
|
2847
|
+
// Define your schema fields here
|
|
2848
|
+
name: z.string().min(1).max(200),
|
|
2849
|
+
})
|
|
2850
|
+
|
|
2851
|
+
export type ${pascal}DTO = z.infer<typeof ${camel}Schema>
|
|
2852
|
+
`);
|
|
2853
|
+
files.push(filePath);
|
|
2854
|
+
return files;
|
|
2855
|
+
}
|
|
2856
|
+
//#endregion
|
|
2857
|
+
//#region src/generators/templates/project-config.ts
|
|
2858
|
+
/** Map of optional package names to their npm package identifiers */
|
|
2859
|
+
const PACKAGE_DEPS = {
|
|
2860
|
+
auth: "@forinda/kickjs-auth",
|
|
2861
|
+
swagger: "@forinda/kickjs-swagger",
|
|
2862
|
+
ws: "@forinda/kickjs-ws",
|
|
2863
|
+
queue: "@forinda/kickjs-queue",
|
|
2864
|
+
devtools: "@forinda/kickjs-devtools"
|
|
2865
|
+
};
|
|
2866
|
+
/** Generate package.json with template-aware dependencies */
|
|
2867
|
+
function generatePackageJson(name, template, kickjsVersion, packages = []) {
|
|
2868
|
+
const baseDeps = {
|
|
2869
|
+
"@forinda/kickjs": kickjsVersion,
|
|
2870
|
+
dotenv: "^17.3.1",
|
|
2871
|
+
express: "^5.1.0",
|
|
2872
|
+
"reflect-metadata": "^0.2.2",
|
|
2873
|
+
zod: "^4.3.6",
|
|
2874
|
+
pino: "^10.3.1",
|
|
2875
|
+
"pino-pretty": "^13.1.3"
|
|
2876
|
+
};
|
|
2877
|
+
for (const pkg of packages) {
|
|
2878
|
+
const dep = PACKAGE_DEPS[pkg];
|
|
2879
|
+
if (dep && !baseDeps[dep]) baseDeps[dep] = kickjsVersion;
|
|
2880
|
+
}
|
|
2881
|
+
return JSON.stringify({
|
|
2882
|
+
name,
|
|
2883
|
+
version: kickjsVersion.replace("^", ""),
|
|
2884
|
+
type: "module",
|
|
2885
|
+
scripts: {
|
|
2886
|
+
dev: "vite",
|
|
2887
|
+
"dev:debug": "kick dev:debug",
|
|
2888
|
+
build: "kick build",
|
|
2889
|
+
start: "kick start",
|
|
2890
|
+
test: "vitest run",
|
|
2891
|
+
"test:watch": "vitest",
|
|
2892
|
+
typecheck: "tsc --noEmit",
|
|
2893
|
+
typegen: "kick typegen",
|
|
2894
|
+
lint: "eslint src/",
|
|
2895
|
+
format: "prettier --write src/"
|
|
2896
|
+
},
|
|
2897
|
+
dependencies: baseDeps,
|
|
2898
|
+
devDependencies: {
|
|
2899
|
+
"@forinda/kickjs-cli": kickjsVersion,
|
|
2900
|
+
"@forinda/kickjs-vite": kickjsVersion,
|
|
2901
|
+
"@swc/core": "^1.15.21",
|
|
2902
|
+
"@types/express": "^5.0.6",
|
|
2903
|
+
"@types/node": "^25.0.0",
|
|
2904
|
+
"unplugin-swc": "^1.5.9",
|
|
2905
|
+
vite: "^8.0.3",
|
|
2906
|
+
vitest: "^4.1.2",
|
|
2907
|
+
typescript: "^6.0.3",
|
|
2908
|
+
prettier: "^3.8.1"
|
|
2909
|
+
}
|
|
2910
|
+
}, null, 2);
|
|
2911
|
+
}
|
|
2912
|
+
/**
|
|
2913
|
+
* Generate vite.config.ts with the KickJS Vite plugin.
|
|
2914
|
+
*
|
|
2915
|
+
* The plugin handles:
|
|
2916
|
+
* - SSR environment setup for backend Node.js code
|
|
2917
|
+
* - Virtual module generation (virtual:kickjs/app)
|
|
2918
|
+
* - Module auto-discovery (scans *.module.ts files)
|
|
2919
|
+
* - HMR with selective container invalidation
|
|
2920
|
+
* - Express mounting via configureServer() post-hook
|
|
2921
|
+
* - httpServer piping to adapters (WsAdapter, Socket.IO, etc.)
|
|
2922
|
+
*/
|
|
2923
|
+
function generateViteConfig() {
|
|
2924
|
+
return `import { defineConfig } from 'vite'
|
|
2925
|
+
import { resolve } from 'node:path'
|
|
2926
|
+
import swc from 'unplugin-swc'
|
|
2927
|
+
import { kickjsVitePlugin, envWatchPlugin } from '@forinda/kickjs-vite'
|
|
2928
|
+
|
|
2929
|
+
export default defineConfig({
|
|
2930
|
+
oxc: false,
|
|
2931
|
+
plugins: [
|
|
2932
|
+
swc.vite(),
|
|
2933
|
+
kickjsVitePlugin({ entry: 'src/index.ts' }),
|
|
2934
|
+
// Watches .env files and triggers a full reload on change so the
|
|
2935
|
+
// dev server picks up env tweaks without a manual restart.
|
|
2936
|
+
envWatchPlugin(),
|
|
2937
|
+
],
|
|
2938
|
+
resolve: {
|
|
2939
|
+
alias: {
|
|
2940
|
+
'@': resolve(__dirname, 'src'),
|
|
2941
|
+
},
|
|
2942
|
+
},
|
|
2943
|
+
ssr: {
|
|
2944
|
+
// Don't bundle pino — its worker-thread transport needs Node.js resolution
|
|
2945
|
+
// to find pino-pretty at runtime for colored log output
|
|
2946
|
+
external: ['pino', 'pino-pretty'],
|
|
2947
|
+
},
|
|
2948
|
+
build: {
|
|
2949
|
+
target: 'node20',
|
|
2950
|
+
ssr: true,
|
|
2951
|
+
outDir: 'dist',
|
|
2952
|
+
sourcemap: true,
|
|
2953
|
+
rollupOptions: {
|
|
2954
|
+
input: resolve(__dirname, 'src/index.ts'),
|
|
2955
|
+
output: { format: 'esm' },
|
|
2956
|
+
},
|
|
2957
|
+
},
|
|
2958
|
+
})
|
|
2959
|
+
`;
|
|
2960
|
+
}
|
|
2961
|
+
/** Generate tsconfig.json with decorator support */
|
|
2962
|
+
function generateTsConfig() {
|
|
2963
|
+
return JSON.stringify({
|
|
2964
|
+
compilerOptions: {
|
|
2965
|
+
target: "ES2022",
|
|
2966
|
+
module: "ESNext",
|
|
2967
|
+
moduleResolution: "bundler",
|
|
2968
|
+
lib: ["ES2022"],
|
|
2969
|
+
types: ["node", "vite/client"],
|
|
2970
|
+
strict: true,
|
|
2971
|
+
esModuleInterop: true,
|
|
2972
|
+
skipLibCheck: true,
|
|
2973
|
+
sourceMap: true,
|
|
2974
|
+
declaration: true,
|
|
2975
|
+
experimentalDecorators: true,
|
|
2976
|
+
emitDecoratorMetadata: true,
|
|
2977
|
+
outDir: "dist",
|
|
2978
|
+
paths: { "@/*": ["./src/*"] }
|
|
2979
|
+
},
|
|
2980
|
+
include: [
|
|
2981
|
+
"src",
|
|
2982
|
+
".kickjs/types/**/*.d.ts",
|
|
2983
|
+
".kickjs/types/**/*.ts"
|
|
2984
|
+
]
|
|
2985
|
+
}, null, 2);
|
|
2986
|
+
}
|
|
2987
|
+
/** Generate .prettierrc with project formatting rules */
|
|
2988
|
+
function generatePrettierConfig() {
|
|
2989
|
+
return JSON.stringify({
|
|
2990
|
+
semi: false,
|
|
2991
|
+
singleQuote: true,
|
|
2992
|
+
trailingComma: "all",
|
|
2993
|
+
printWidth: 100,
|
|
2994
|
+
tabWidth: 2
|
|
2995
|
+
}, null, 2);
|
|
2996
|
+
}
|
|
2997
|
+
/** Generate .editorconfig for consistent editor settings */
|
|
2998
|
+
function generateEditorConfig() {
|
|
2999
|
+
return `# https://editorconfig.org
|
|
3000
|
+
root = true
|
|
3001
|
+
|
|
3002
|
+
[*]
|
|
3003
|
+
indent_style = space
|
|
3004
|
+
indent_size = 2
|
|
3005
|
+
end_of_line = lf
|
|
3006
|
+
charset = utf-8
|
|
3007
|
+
trim_trailing_whitespace = true
|
|
3008
|
+
insert_final_newline = true
|
|
3009
|
+
|
|
3010
|
+
[*.md]
|
|
3011
|
+
trim_trailing_whitespace = false
|
|
3012
|
+
`;
|
|
3013
|
+
}
|
|
3014
|
+
/** Generate .gitignore with common Node.js patterns */
|
|
3015
|
+
function generateGitIgnore() {
|
|
3016
|
+
return `node_modules/
|
|
3017
|
+
dist/
|
|
3018
|
+
.env
|
|
3019
|
+
coverage/
|
|
3020
|
+
.DS_Store
|
|
3021
|
+
*.tsbuildinfo
|
|
3022
|
+
.kickjs/
|
|
3023
|
+
`;
|
|
3024
|
+
}
|
|
3025
|
+
/** Generate .gitattributes for consistent line endings */
|
|
3026
|
+
function generateGitAttributes() {
|
|
3027
|
+
return `# Auto-detect text files and normalise line endings to LF
|
|
3028
|
+
* text=auto eol=lf
|
|
3029
|
+
|
|
3030
|
+
# Explicitly mark generated / binary files
|
|
3031
|
+
*.png binary
|
|
3032
|
+
*.jpg binary
|
|
3033
|
+
*.jpeg binary
|
|
3034
|
+
*.gif binary
|
|
3035
|
+
*.ico binary
|
|
3036
|
+
*.woff binary
|
|
3037
|
+
*.woff2 binary
|
|
3038
|
+
*.ttf binary
|
|
3039
|
+
*.eot binary
|
|
3040
|
+
|
|
3041
|
+
# Lock files — treat as generated
|
|
3042
|
+
pnpm-lock.yaml -diff linguist-generated
|
|
3043
|
+
yarn.lock -diff linguist-generated
|
|
3044
|
+
package-lock.json -diff linguist-generated
|
|
3045
|
+
`;
|
|
3046
|
+
}
|
|
3047
|
+
/** Generate .env file with default environment variables */
|
|
3048
|
+
function generateEnv() {
|
|
3049
|
+
return `PORT=3000
|
|
3050
|
+
NODE_ENV=development
|
|
3051
|
+
`;
|
|
3052
|
+
}
|
|
3053
|
+
/** Generate .env.example file as a template */
|
|
3054
|
+
function generateEnvExample() {
|
|
3055
|
+
return `PORT=3000
|
|
3056
|
+
NODE_ENV=development
|
|
3057
|
+
`;
|
|
3058
|
+
}
|
|
3059
|
+
/** Generate vitest.config.ts for test configuration */
|
|
3060
|
+
function generateVitestConfig() {
|
|
3061
|
+
return `import { defineConfig } from 'vitest/config'
|
|
3062
|
+
import swc from 'unplugin-swc'
|
|
3063
|
+
|
|
3064
|
+
export default defineConfig({
|
|
3065
|
+
plugins: [swc.vite()],
|
|
3066
|
+
test: {
|
|
3067
|
+
globals: true,
|
|
3068
|
+
environment: 'node',
|
|
3069
|
+
include: ['src/**/*.test.ts'],
|
|
3070
|
+
},
|
|
3071
|
+
})
|
|
3072
|
+
`;
|
|
3073
|
+
}
|
|
3074
|
+
//#endregion
|
|
3075
|
+
//#region src/generators/templates/project-docs.ts
|
|
3076
|
+
/** Generate README.md with project documentation */
|
|
3077
|
+
function generateReadme(name, template, pm) {
|
|
3078
|
+
const templateLabels = {
|
|
3079
|
+
rest: "REST API",
|
|
3080
|
+
ddd: "Domain-Driven Design",
|
|
3081
|
+
cqrs: "CQRS + Event-Driven",
|
|
3082
|
+
minimal: "Minimal"
|
|
3083
|
+
};
|
|
3084
|
+
const packages = ["@forinda/kickjs", "@forinda/kickjs-vite"];
|
|
3085
|
+
if (template !== "minimal") packages.push("@forinda/kickjs-swagger", "@forinda/kickjs-devtools");
|
|
3086
|
+
if (template === "cqrs") packages.push("@forinda/kickjs-queue", "@forinda/kickjs-ws");
|
|
3087
|
+
return `# ${name}
|
|
3088
|
+
|
|
3089
|
+
A **${templateLabels[template] ?? "REST API"}** built with [KickJS](https://forinda.github.io/kick-js/) — a decorator-driven Node.js framework on Express 5 and TypeScript.
|
|
3090
|
+
|
|
3091
|
+
## Getting Started
|
|
3092
|
+
|
|
3093
|
+
\`\`\`bash
|
|
3094
|
+
${pm} install
|
|
3095
|
+
kick dev
|
|
3096
|
+
\`\`\`
|
|
3097
|
+
|
|
3098
|
+
## Scripts
|
|
3099
|
+
|
|
3100
|
+
| Command | Description |
|
|
3101
|
+
|---|---|
|
|
3102
|
+
| \`kick dev\` | Start dev server with Vite HMR |
|
|
3103
|
+
| \`kick build\` | Production build |
|
|
3104
|
+
| \`kick start\` | Run production build |
|
|
3105
|
+
| \`${pm} run test\` | Run tests with Vitest |
|
|
3106
|
+
| \`kick g module <name>\` | Generate a DDD module |
|
|
3107
|
+
| \`kick g scaffold <name> <fields...>\` | Generate CRUD from field definitions |
|
|
3108
|
+
| \`kick add <package>\` | Add a KickJS package |
|
|
3109
|
+
|
|
3110
|
+
## Project Structure
|
|
3111
|
+
|
|
3112
|
+
\`\`\`
|
|
3113
|
+
src/
|
|
3114
|
+
├── index.ts # Application entry point
|
|
3115
|
+
├── modules/ # Feature modules (controllers, services, repos)
|
|
3116
|
+
│ └── index.ts # Module registry
|
|
3117
|
+
└── ...
|
|
3118
|
+
\`\`\`
|
|
3119
|
+
|
|
3120
|
+
## Packages
|
|
3121
|
+
|
|
3122
|
+
${packages.map((p) => `- \`${p}\``).join("\n")}
|
|
3123
|
+
|
|
3124
|
+
## Adding Features
|
|
3125
|
+
|
|
3126
|
+
\`\`\`bash
|
|
3127
|
+
kick add auth # Authentication (JWT, API key, OAuth)
|
|
3128
|
+
kick add swagger # OpenAPI documentation
|
|
3129
|
+
kick add ws # WebSocket support
|
|
3130
|
+
kick add queue # Background job processing
|
|
3131
|
+
kick add --list # Show all available packages
|
|
3132
|
+
\`\`\`
|
|
3133
|
+
|
|
3134
|
+
For email, scheduled tasks, multi-tenancy, OpenTelemetry, GraphQL, and notifications use the BYO recipes in the [KickJS guides](https://forinda.github.io/kick-js/guide/) — they wire the upstream library through \`defineAdapter()\` / \`definePlugin()\` directly, so you keep control of the integration.
|
|
3135
|
+
|
|
3136
|
+
## Environment Variables
|
|
3137
|
+
|
|
3138
|
+
Copy \`.env.example\` to \`.env\` and configure:
|
|
3139
|
+
|
|
3140
|
+
| Variable | Default | Description |
|
|
3141
|
+
|---|---|---|
|
|
3142
|
+
| \`PORT\` | \`3000\` | Server port |
|
|
3143
|
+
| \`NODE_ENV\` | \`development\` | Environment |
|
|
3144
|
+
|
|
3145
|
+
## Learn More
|
|
3146
|
+
|
|
3147
|
+
- [KickJS Documentation](https://forinda.github.io/kick-js/)
|
|
3148
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
3149
|
+
`;
|
|
3150
|
+
}
|
|
3151
|
+
/**
|
|
3152
|
+
* Generate CLAUDE.md.
|
|
3153
|
+
*
|
|
3154
|
+
* v4 update: this file is intentionally thin. AGENTS.md is the
|
|
3155
|
+
* canonical, multi-agent project reference (Claude / Copilot /
|
|
3156
|
+
* Codex / Gemini / etc.) — duplicating it here meant two files
|
|
3157
|
+
* drifting out of sync after every framework change. The generated
|
|
3158
|
+
* CLAUDE.md now redirects there + adds Claude-specific affordances
|
|
3159
|
+
* only.
|
|
3160
|
+
*/
|
|
3161
|
+
function generateClaude(name, _template, pm) {
|
|
3162
|
+
return `# CLAUDE.md — ${name}
|
|
3163
|
+
|
|
3164
|
+
**Read \`./AGENTS.md\` first.** It is the canonical, multi-agent
|
|
3165
|
+
reference for this project (Claude, Copilot, Codex, Gemini, etc.) —
|
|
3166
|
+
project conventions, structure, decorator patterns, env wiring, CLI
|
|
3167
|
+
generators, every gotcha.
|
|
3168
|
+
|
|
3169
|
+
**Then read \`./kickjs-skills.md\`.** That file is the task-oriented
|
|
3170
|
+
skill index — short, rigid recipes keyed to triggers ("add-module",
|
|
3171
|
+
"write-controller-test", "bootstrap-export", "deny-list", …). Use it
|
|
3172
|
+
as the playbook when executing common KickJS workflows.
|
|
3173
|
+
|
|
3174
|
+
This file is a thin Claude-specific layer on top of those two; when
|
|
3175
|
+
they disagree on anything substantive, treat \`AGENTS.md\` as
|
|
3176
|
+
authoritative and flag the discrepancy.
|
|
3177
|
+
|
|
3178
|
+
## Why two files
|
|
3179
|
+
|
|
3180
|
+
\`AGENTS.md\` is what every agent reads. \`CLAUDE.md\` is what
|
|
3181
|
+
Claude Code automatically loads as project context on each
|
|
3182
|
+
conversation. Keeping CLAUDE.md slim avoids two files drifting; the
|
|
3183
|
+
redirect above ensures Claude pulls the canonical content without
|
|
3184
|
+
us copy-pasting.
|
|
3185
|
+
|
|
3186
|
+
## Claude-specific notes
|
|
3187
|
+
|
|
3188
|
+
- **Slash commands** — \`/help\` for Claude Code commands; \`/init\`
|
|
3189
|
+
to refresh project memory if AGENTS.md changes substantially.
|
|
3190
|
+
- **Feedback** — file issues at <https://github.com/anthropics/claude-code/issues>.
|
|
3191
|
+
- **Persistent memory** — Claude maintains user/feedback/project/
|
|
3192
|
+
reference memories under \`.claude/memory/\`. If you ask for
|
|
3193
|
+
something that contradicts a remembered preference, Claude flags
|
|
3194
|
+
it before acting; corrections update memory automatically.
|
|
3195
|
+
- **Long-running tasks** — \`/loop\` and \`/schedule\` for recurring
|
|
3196
|
+
or background work. Useful for "wait for the deploy then open a
|
|
3197
|
+
cleanup PR" or "every Monday triage the issue board" patterns.
|
|
3198
|
+
|
|
3199
|
+
## Quick reference (full version in AGENTS.md)
|
|
3200
|
+
|
|
3201
|
+
\`\`\`bash
|
|
3202
|
+
${pm} install # Install dependencies
|
|
3203
|
+
kick dev # Dev server with HMR + typegen
|
|
3204
|
+
kick build && kick start # Production
|
|
3205
|
+
${pm} run test # Vitest
|
|
3206
|
+
${pm} run typecheck # tsc --noEmit
|
|
3207
|
+
${pm} run format # Prettier
|
|
3208
|
+
\`\`\`
|
|
3209
|
+
|
|
3210
|
+
## v4 framework reminders
|
|
3211
|
+
|
|
3212
|
+
When generating or modifying code in this project, stay aligned with the v4 conventions documented in \`AGENTS.md\`:
|
|
3213
|
+
|
|
3214
|
+
- **Adapters**: \`defineAdapter()\` factory — never \`class implements AppAdapter\`.
|
|
3215
|
+
- **Plugins**: \`definePlugin()\` factory — never plain function returning \`KickPlugin\`.
|
|
3216
|
+
- **DI tokens**: slash-delimited \`<scope>/<area>/<key>\` (e.g. \`'app/users/repository'\`). First-party uses the reserved \`'kick/'\` prefix; this project owns its own scope.
|
|
3217
|
+
- **Decorators**: \`@Controller()\` (no path arg — mount prefix comes from \`routes().path\`).
|
|
3218
|
+
- **Module entry file** MUST be named \`<name>.module.ts\` and live under \`src/modules/<name>/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed \`projects.ts\` silently degrades every save into a full restart.
|
|
3219
|
+
- **Env**: schema lives in \`src/config/index.ts\`; \`import './config'\` MUST be the first import in \`src/index.ts\` (side-effect registers the schema before any \`@Value\` resolves).
|
|
3220
|
+
- **Assets**: drop new template files into \`src/templates/<namespace>/\`; the dev watcher auto-rebuilds the \`KickAssets\` augmentation + \`assets.x.y()\` re-walks on next call. No restart, no manual build.
|
|
3221
|
+
- **Context Contributors** (\`defineContextDecorator\`) over \`@Middleware()\` for ctx-population work.
|
|
3222
|
+
- **Repos under tests**: \`Container.create()\` for isolation — never \`new Container()\` or \`getInstance().reset()\`.
|
|
3223
|
+
- **Bootstrap export**: \`src/index.ts\` must end with \`export const app = await bootstrap({ ... })\`. The Vite plugin and \`createTestApp\` import the named \`app\`; without the export, HMR silently degrades to full restarts.
|
|
3224
|
+
- **Thin entry file**: aggregate \`modules\`, \`middleware\`, \`plugins\`, \`adapters\` in their own folders (\`src/modules/index.ts\`, \`src/middleware/index.ts\`, …) and pass them by name to \`bootstrap()\` — never inline the lists in \`src/index.ts\`.
|
|
3225
|
+
- **Refresh these files**: \`kick g agents -f\` regenerates \`AGENTS.md\` + \`CLAUDE.md\` from the latest CLI templates. Hand-edited content is overwritten — keep customisation in \`AGENTS.local.md\`.
|
|
3226
|
+
|
|
3227
|
+
For everything else (controllers, services, modules, RequestContext API, generators, CLI commands, package additions, env wiring, troubleshooting) → \`AGENTS.md\`.
|
|
3228
|
+
`;
|
|
3229
|
+
}
|
|
3230
|
+
/** Generate AGENTS.md with AI agent guide */
|
|
3231
|
+
function generateAgents(name, template, pm) {
|
|
3232
|
+
return `# AGENTS.md — AI Agent Guide for ${name}
|
|
3233
|
+
|
|
3234
|
+
This guide is the **canonical, multi-agent reference** for this KickJS
|
|
3235
|
+
application — Claude, Copilot, Codex, Gemini, etc. all read it first.
|
|
3236
|
+
Per-agent files (\`CLAUDE.md\`, \`GEMINI.md\`, etc.) are thin layers that
|
|
3237
|
+
add tool-specific affordances on top.
|
|
3238
|
+
|
|
3239
|
+
## Before You Start
|
|
3240
|
+
|
|
3241
|
+
1. Run \`${pm} install\` to install dependencies
|
|
3242
|
+
2. Run \`kick dev\` to verify the app starts
|
|
3243
|
+
3. Read the [KickJS documentation](https://forinda.github.io/kick-js/) for framework details
|
|
3244
|
+
|
|
3245
|
+
## v4 Conventions (don't skip)
|
|
3246
|
+
|
|
3247
|
+
KickJS v4 made a handful of structural changes from v3. Internalise these
|
|
3248
|
+
before generating or modifying code — they are the source of most agent
|
|
3249
|
+
mistakes:
|
|
3250
|
+
|
|
3251
|
+
- **Adapters** — \`defineAdapter()\` factory. Never write \`class Foo implements AppAdapter\`.
|
|
3252
|
+
|
|
3253
|
+
\`\`\`ts
|
|
3254
|
+
export const MyAdapter = defineAdapter<MyOptions>({
|
|
3255
|
+
name: 'MyAdapter',
|
|
3256
|
+
defaults: { ... },
|
|
3257
|
+
build: (config) => ({
|
|
3258
|
+
beforeMount({ app }) { /* ... */ },
|
|
3259
|
+
afterStart({ server }) { /* ... */ },
|
|
3260
|
+
}),
|
|
3261
|
+
})
|
|
3262
|
+
\`\`\`
|
|
3263
|
+
|
|
3264
|
+
- **Plugins** — \`definePlugin()\` factory. Same shape, never plain function returning \`KickPlugin\`.
|
|
3265
|
+
|
|
3266
|
+
- **DI tokens** — slash-delimited \`<scope>/<area>/<key>\`, lower-case, no \`:\` separators:
|
|
3267
|
+
|
|
3268
|
+
\`\`\`ts
|
|
3269
|
+
const USERS_REPO = createToken<UsersRepo>('app/users/repository')
|
|
3270
|
+
const DB = createToken<Database>('app/db/connection')
|
|
3271
|
+
\`\`\`
|
|
3272
|
+
|
|
3273
|
+
The \`kick/\` prefix is reserved for first-party packages; this project
|
|
3274
|
+
owns its own scope (\`app/\`, your domain name, etc.).
|
|
3275
|
+
|
|
3276
|
+
- **\`@Controller()\`** takes **no path argument**. Mount prefix comes from
|
|
3277
|
+
the module's \`routes()\` return value, not the decorator. \`@Controller('/users')\`
|
|
3278
|
+
is a v3 leftover; the linter and codegen reject it.
|
|
3279
|
+
|
|
3280
|
+
- **Env wiring** — \`src/config/index.ts\` calls \`loadEnv(envSchema)\` as a
|
|
3281
|
+
side effect. \`src/index.ts\` MUST have \`import './config'\` as its **first**
|
|
3282
|
+
import (before \`bootstrap()\`). Without it, \`ConfigService.get('YOUR_KEY')\`
|
|
3283
|
+
returns \`undefined\` and \`@Value()\` only works via raw \`process.env\` fallback
|
|
3284
|
+
(Zod coercion + defaults silently skipped).
|
|
3285
|
+
|
|
3286
|
+
- **Module entry files MUST be named \`<name>.module.ts\`** — see the Vite
|
|
3287
|
+
HMR contract at the top of "Module Pattern" below. The CLI enforces this;
|
|
3288
|
+
hand-rolled files must too.
|
|
3289
|
+
|
|
3290
|
+
- **Assets** — drop new template files into \`src/templates/<namespace>/\`
|
|
3291
|
+
(or wherever \`kick.config.ts\` points). The dev watcher auto-rebuilds the
|
|
3292
|
+
\`KickAssets\` augmentation; \`assets.x.y()\` re-walks on next call. No restart,
|
|
3293
|
+
no manual build step.
|
|
3294
|
+
|
|
3295
|
+
- **Context over \`@Middleware()\`** — when a middleware's only job is to
|
|
3296
|
+
populate \`ctx.set('key', value)\`, use \`defineHttpContextDecorator()\`
|
|
3297
|
+
(HTTP) or \`defineContextDecorator()\` (transport-agnostic) instead.
|
|
3298
|
+
Typed via \`ContextMeta\`, ordered via \`dependsOn\`, validated at boot.
|
|
3299
|
+
Reserve \`@Middleware()\` for response short-circuit / stream mutation /
|
|
3300
|
+
pre-route-matching work.
|
|
3301
|
+
|
|
3302
|
+
Two ground rules around the data flow — both stem from the fact that
|
|
3303
|
+
every per-request stage gets its OWN \`RequestContext\` instance, all
|
|
3304
|
+
reading/writing the SAME \`AsyncLocalStorage\`-backed Map:
|
|
3305
|
+
- **\`resolve\` and \`onError\` must RETURN the value.** The runner
|
|
3306
|
+
writes it via \`ctx.set(reg.key, value)\` on your behalf. Direct
|
|
3307
|
+
property assignment (\`ctx.tenant = …\`) sticks to the contributor
|
|
3308
|
+
instance only — the handler instance never sees it.
|
|
3309
|
+
- **Read across instances via \`ctx.set\` / \`ctx.get\`** (or
|
|
3310
|
+
\`getRequestValue(key)\` from a service that has no \`ctx\` reference
|
|
3311
|
+
— typed via \`MetaValue<K>\`). \`ctx.req\` works because the underlying
|
|
3312
|
+
Express request is shared; bespoke property assignments don't.
|
|
3313
|
+
|
|
3314
|
+
- **Test isolation** — default to \`Container.create()\` for fresh DI state.
|
|
3315
|
+
Never \`new Container()\` and never \`getInstance().reset()\` — both leak
|
|
3316
|
+
registrations between tests.
|
|
3317
|
+
|
|
3318
|
+
\`\`\`ts
|
|
3319
|
+
const container = Container.create()
|
|
3320
|
+
// ... register test-scoped providers, run, discard
|
|
3321
|
+
\`\`\`
|
|
3322
|
+
|
|
3323
|
+
- **Bootstrap export** — \`src/index.ts\` MUST end with
|
|
3324
|
+
\`export const app = await bootstrap({ ... })\`. The Vite plugin imports
|
|
3325
|
+
the named \`app\` symbol to drive HMR module swaps; testing helpers
|
|
3326
|
+
(\`createTestApp\`) and the OpenAPI introspector also rely on it. Drop
|
|
3327
|
+
the \`export\` and \`kick dev\` will silently fall back to a full restart
|
|
3328
|
+
on every save while \`createTestApp\` complains about a missing handle.
|
|
3329
|
+
|
|
3330
|
+
- **Keep \`src/index.ts\` thin** — collect plugins, modules, middleware, and
|
|
3331
|
+
adapters in dedicated folders and re-export aggregated arrays. Do **not**
|
|
3332
|
+
inline registration in the entry file:
|
|
3333
|
+
|
|
3334
|
+
\`\`\`ts
|
|
3335
|
+
// src/modules/index.ts
|
|
3336
|
+
export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
|
|
3337
|
+
|
|
3338
|
+
// src/middleware/index.ts
|
|
3339
|
+
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
3340
|
+
|
|
3341
|
+
// src/plugins/index.ts
|
|
3342
|
+
export const plugins = [MetricsPlugin(), AuditPlugin()]
|
|
3343
|
+
|
|
3344
|
+
// src/adapters/index.ts
|
|
3345
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
3346
|
+
\`\`\`
|
|
3347
|
+
|
|
3348
|
+
\`\`\`ts
|
|
3349
|
+
// src/index.ts — stays small; one import per category
|
|
3350
|
+
import 'reflect-metadata'
|
|
3351
|
+
import './config'
|
|
3352
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
3353
|
+
import { modules } from './modules'
|
|
3354
|
+
import { middleware } from './middleware'
|
|
3355
|
+
import { plugins } from './plugins'
|
|
3356
|
+
import { adapters } from './adapters'
|
|
3357
|
+
|
|
3358
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
3359
|
+
\`\`\`
|
|
3360
|
+
|
|
3361
|
+
This keeps the entry file diff-friendly, scales to dozens of modules
|
|
3362
|
+
without git churn, and lets each domain own its own registration list.
|
|
3363
|
+
The generators (\`kick g module\`, \`kick g middleware\`, \`kick g plugin\`,
|
|
3364
|
+
\`kick g adapter\`) follow this layout — manual additions should too.
|
|
3365
|
+
|
|
3366
|
+
Everything else (controllers, services, modules, RequestContext API, generators,
|
|
3367
|
+
package additions, env access patterns, troubleshooting) is detailed below.
|
|
3368
|
+
|
|
3369
|
+
## Where to Find Things
|
|
3370
|
+
|
|
3371
|
+
### Application Structure
|
|
3372
|
+
|
|
3373
|
+
| What | Where |
|
|
3374
|
+
|------|-------|
|
|
3375
|
+
| Entry point | \`src/index.ts\` |
|
|
3376
|
+
| Module registry | \`src/modules/index.ts\` |
|
|
3377
|
+
| Feature modules | \`src/modules/<module-name>/\` |
|
|
3378
|
+
| **Module entry file** | \`src/modules/<name>/<name>.module.ts\` (filename suffix is required — see Vite HMR contract below) |
|
|
3379
|
+
| Env values | \`.env\` |
|
|
3380
|
+
| Env schema (Zod) | \`src/config/index.ts\` |
|
|
3381
|
+
| TypeScript config | \`tsconfig.json\` |
|
|
3382
|
+
| Vite config (HMR) | \`vite.config.ts\` |
|
|
3383
|
+
| Vitest config | \`vitest.config.ts\` |
|
|
3384
|
+
| Prettier config | \`.prettierrc\` |
|
|
3385
|
+
| CLI config | \`kick.config.ts\` |
|
|
3386
|
+
|
|
3387
|
+
### Module Pattern (${template.toUpperCase()})
|
|
3388
|
+
|
|
3389
|
+
> **Vite HMR auto-discovery contract:** module files **must** be named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and live under \`src/modules/\`. The Vite plugin scans for \`*.module.[tj]sx?\` to drive graceful HMR rebuilds; renaming a file to \`projects.ts\` (no \`.module\`) silently breaks HMR — saves trigger a full restart instead of a swap. The CLI generator (\`kick g module <name>\`) follows the convention; manual files must too.
|
|
3390
|
+
|
|
3391
|
+
Each module in \`src/modules/<name>/\` typically contains:
|
|
3392
|
+
|
|
3393
|
+
${template === "ddd" ? `\`\`\`
|
|
3394
|
+
<name>/
|
|
3395
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
3396
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
3397
|
+
├── <name>.repository.ts # Data access (@Repository)
|
|
3398
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
3399
|
+
├── <name>.entity.ts # Domain entity (optional)
|
|
3400
|
+
└── <name>.module.ts # Module definition (implements AppModule)
|
|
3401
|
+
\`\`\`
|
|
3402
|
+
` : template === "cqrs" ? `\`\`\`
|
|
3403
|
+
<name>/
|
|
3404
|
+
├── commands/ # Write operations
|
|
3405
|
+
│ ├── create-<name>.command.ts
|
|
3406
|
+
│ └── create-<name>.handler.ts
|
|
3407
|
+
├── queries/ # Read operations
|
|
3408
|
+
│ ├── get-<name>.query.ts
|
|
3409
|
+
│ └── get-<name>.handler.ts
|
|
3410
|
+
├── events/ # Domain events
|
|
3411
|
+
│ └── <name>-created.event.ts
|
|
3412
|
+
├── <name>.controller.ts # HTTP routes
|
|
3413
|
+
├── <name>.repository.ts # Data access
|
|
3414
|
+
└── <name>.module.ts # Module definition (implements AppModule)
|
|
3415
|
+
\`\`\`
|
|
3416
|
+
` : template === "rest" ? `\`\`\`
|
|
3417
|
+
<name>/
|
|
3418
|
+
├── <name>.controller.ts # HTTP routes (@Controller)
|
|
3419
|
+
├── <name>.service.ts # Business logic (@Service)
|
|
3420
|
+
├── <name>.dto.ts # Request/response schemas (Zod)
|
|
3421
|
+
└── <name>.module.ts # Module definition (implements AppModule)
|
|
3422
|
+
\`\`\`
|
|
3423
|
+
` : `\`\`\`
|
|
3424
|
+
src/
|
|
3425
|
+
├── index.ts # Add routes here
|
|
3426
|
+
└── ... # Custom structure
|
|
3427
|
+
\`\`\`
|
|
3428
|
+
`}
|
|
3429
|
+
|
|
3430
|
+
## Checklist: Adding a Feature
|
|
3431
|
+
|
|
3432
|
+
### New Module (Recommended)
|
|
3433
|
+
|
|
3434
|
+
Use the CLI generator for consistency:
|
|
3435
|
+
|
|
3436
|
+
\`\`\`bash
|
|
3437
|
+
kick g module <name> # Generate full module
|
|
3438
|
+
# or
|
|
3439
|
+
kick g scaffold <name> <fields> # Generate CRUD from fields
|
|
3440
|
+
\`\`\`
|
|
3441
|
+
|
|
3442
|
+
Then:
|
|
3443
|
+
- [ ] Review generated files in \`src/modules/<name>/\`
|
|
3444
|
+
- [ ] Verify module is registered in \`src/modules/index.ts\`
|
|
3445
|
+
- [ ] Update DTOs in \`<name>.dto.ts\` if needed
|
|
3446
|
+
- [ ] Implement business logic in \`<name>.service.ts\`
|
|
3447
|
+
- [ ] Run \`kick dev\` to test with HMR
|
|
3448
|
+
- [ ] Write tests in \`<name>.test.ts\`
|
|
3449
|
+
|
|
3450
|
+
### Manual Controller
|
|
3451
|
+
|
|
3452
|
+
If not using generators:
|
|
3453
|
+
|
|
3454
|
+
- [ ] Create \`src/modules/<name>/<name>.controller.ts\`
|
|
3455
|
+
- [ ] Add \`@Controller()\` decorator
|
|
3456
|
+
- [ ] Add route handlers with \`@Get()\`, \`@Post()\`, etc.
|
|
3457
|
+
- [ ] Create module file implementing \`AppModule\` with \`routes()\` returning \`{ path, router: buildRoutes(Controller), controller }\`
|
|
3458
|
+
- [ ] Register module in \`src/modules/index.ts\` (\`AppModuleClass[]\` array)
|
|
3459
|
+
- [ ] Test with \`kick dev\`
|
|
3460
|
+
|
|
3461
|
+
### Manual Service
|
|
3462
|
+
|
|
3463
|
+
- [ ] Create \`src/modules/<name>/<name>.service.ts\`
|
|
3464
|
+
- [ ] Add \`@Service()\` decorator
|
|
3465
|
+
- [ ] Inject dependencies with \`@Autowired()\`
|
|
3466
|
+
- [ ] Inject via \`@Autowired()\` where needed
|
|
3467
|
+
- [ ] Write unit tests
|
|
3468
|
+
|
|
3469
|
+
### New Middleware
|
|
3470
|
+
|
|
3471
|
+
- [ ] Create \`src/middleware/<name>.middleware.ts\`
|
|
3472
|
+
- [ ] Export middleware function (Express format)
|
|
3473
|
+
- [ ] Register in \`src/index.ts\` or attach to routes with \`@Middleware()\`
|
|
3474
|
+
- [ ] Test with sample requests
|
|
3475
|
+
|
|
3476
|
+
### Adding a Package
|
|
3477
|
+
|
|
3478
|
+
Use \`kick add\` to install KickJS packages with correct peer dependencies:
|
|
3479
|
+
|
|
3480
|
+
- [ ] Run \`kick add <package>\` (e.g., \`kick add auth\`)
|
|
3481
|
+
- [ ] Follow package-specific setup in terminal output
|
|
3482
|
+
- [ ] Update \`src/index.ts\` to register adapter (if needed)
|
|
3483
|
+
- [ ] Configure environment variables in \`.env\`
|
|
3484
|
+
- [ ] Test integration with \`kick dev\`
|
|
3485
|
+
|
|
3486
|
+
## Common Tasks
|
|
3487
|
+
|
|
3488
|
+
### Generate CRUD Module
|
|
3489
|
+
|
|
3490
|
+
\`\`\`bash
|
|
3491
|
+
kick g scaffold user name:string email:string:optional age:number
|
|
3492
|
+
\`\`\`
|
|
3493
|
+
|
|
3494
|
+
Append \`:optional\` for optional fields (shell-safe, no quoting needed).
|
|
3495
|
+
Quoted \`?\` syntax also works: \`"email:string?"\` or \`"email?:string"\`.
|
|
3496
|
+
|
|
3497
|
+
This creates a full CRUD module with:
|
|
3498
|
+
- Controller with GET, POST, PUT, DELETE routes
|
|
3499
|
+
- Service with business logic
|
|
3500
|
+
- Repository with data access
|
|
3501
|
+
- DTOs with Zod validation
|
|
3502
|
+
|
|
3503
|
+
### Add Authentication
|
|
3504
|
+
|
|
3505
|
+
\`\`\`bash
|
|
3506
|
+
kick add auth
|
|
3507
|
+
\`\`\`
|
|
3508
|
+
|
|
3509
|
+
Then configure in \`src/index.ts\`:
|
|
3510
|
+
|
|
3511
|
+
\`\`\`ts
|
|
3512
|
+
import { AuthAdapter, JwtStrategy } from '@forinda/kickjs-auth'
|
|
3513
|
+
|
|
3514
|
+
bootstrap({
|
|
3515
|
+
modules,
|
|
3516
|
+
adapters: [
|
|
3517
|
+
AuthAdapter({
|
|
3518
|
+
strategies: [JwtStrategy({ secret: process.env.JWT_SECRET! })],
|
|
3519
|
+
}),
|
|
3520
|
+
],
|
|
3521
|
+
})
|
|
3522
|
+
\`\`\`
|
|
3523
|
+
|
|
3524
|
+
### Add Database (Prisma)
|
|
3525
|
+
|
|
3526
|
+
\`\`\`bash
|
|
3527
|
+
kick add prisma
|
|
3528
|
+
${pm} install prisma @prisma/client
|
|
3529
|
+
npx prisma init
|
|
3530
|
+
# Edit prisma/schema.prisma
|
|
3531
|
+
npx prisma migrate dev --name init
|
|
3532
|
+
kick g module user --repo prisma
|
|
3533
|
+
\`\`\`
|
|
3534
|
+
|
|
3535
|
+
### Add WebSocket Support
|
|
3536
|
+
|
|
3537
|
+
\`\`\`bash
|
|
3538
|
+
kick add ws
|
|
3539
|
+
\`\`\`
|
|
3540
|
+
|
|
3541
|
+
Then add adapter in \`src/index.ts\`:
|
|
3542
|
+
|
|
3543
|
+
\`\`\`ts
|
|
3544
|
+
import { WsAdapter } from '@forinda/kickjs-ws'
|
|
3545
|
+
|
|
3546
|
+
bootstrap({
|
|
3547
|
+
modules,
|
|
3548
|
+
adapters: [WsAdapter()],
|
|
3549
|
+
})
|
|
3550
|
+
\`\`\`
|
|
3551
|
+
|
|
3552
|
+
Create WebSocket controller:
|
|
3553
|
+
|
|
3554
|
+
\`\`\`bash
|
|
3555
|
+
kick g controller chat --ws
|
|
3556
|
+
\`\`\`
|
|
3557
|
+
|
|
3558
|
+
## Testing Guidelines
|
|
3559
|
+
|
|
3560
|
+
All tests use Vitest:
|
|
3561
|
+
|
|
3562
|
+
\`\`\`ts
|
|
3563
|
+
import { describe, it, expect, beforeEach } from 'vitest'
|
|
3564
|
+
import { Container } from '@forinda/kickjs'
|
|
3565
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
3566
|
+
|
|
3567
|
+
describe('UserController', () => {
|
|
3568
|
+
it('should return users', async () => {
|
|
3569
|
+
// Container.create() — isolated DI state per test, never new Container()
|
|
3570
|
+
// and never getInstance().reset() (both leak registrations between tests).
|
|
3571
|
+
const container = Container.create()
|
|
3572
|
+
const app = await createTestApp([UserModule], { container })
|
|
3573
|
+
const res = await app.get('/users')
|
|
3574
|
+
|
|
3575
|
+
expect(res.status).toBe(200)
|
|
3576
|
+
expect(res.body).toHaveProperty('users')
|
|
3577
|
+
})
|
|
3578
|
+
})
|
|
3579
|
+
\`\`\`
|
|
3580
|
+
|
|
3581
|
+
Run tests:
|
|
3582
|
+
- \`${pm} run test\` — run all tests once
|
|
3583
|
+
- \`${pm} run test:watch\` — watch mode
|
|
3584
|
+
- Individual file: \`${pm} run test src/modules/user/user.test.ts\`
|
|
3585
|
+
|
|
3586
|
+
## Environment Variables
|
|
3587
|
+
|
|
3588
|
+
Schema is declared in \`src/config/index.ts\` (extends the base
|
|
3589
|
+
\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` shape via \`defineEnv\`) and registered
|
|
3590
|
+
with kickjs at module load. \`src/index.ts\` imports it via
|
|
3591
|
+
\`import './config'\` **before** \`bootstrap()\` so the cache is populated
|
|
3592
|
+
in time for DI. Add new keys to the schema, drop their values into
|
|
3593
|
+
\`.env\`, and they're typed everywhere.
|
|
3594
|
+
|
|
3595
|
+
Access patterns:
|
|
3596
|
+
|
|
3597
|
+
1. **@Value() decorator** (recommended for known-at-construction keys):
|
|
3598
|
+
\`\`\`ts
|
|
3599
|
+
@Value('DATABASE_URL')
|
|
3600
|
+
private dbUrl!: string
|
|
3601
|
+
\`\`\`
|
|
3602
|
+
|
|
3603
|
+
2. **ConfigService** (recommended for dynamic / method-scoped access):
|
|
3604
|
+
\`\`\`ts
|
|
3605
|
+
@Autowired()
|
|
3606
|
+
private config!: ConfigService
|
|
3607
|
+
|
|
3608
|
+
const port = this.config.get('PORT') // typed: number
|
|
3609
|
+
\`\`\`
|
|
3610
|
+
|
|
3611
|
+
3. **Standalone utilities** (no DI — works in scripts, CLI, plain files):
|
|
3612
|
+
\`\`\`ts
|
|
3613
|
+
import { loadEnv, getEnv, reloadEnv, resetEnvCache } from '@forinda/kickjs/config'
|
|
3614
|
+
|
|
3615
|
+
const env = loadEnv(schema) // Parse + validate all vars
|
|
3616
|
+
const port = getEnv('PORT') // Single value lookup
|
|
3617
|
+
reloadEnv() // Re-read .env from disk
|
|
3618
|
+
resetEnvCache() // Full reset (for tests)
|
|
3619
|
+
\`\`\`
|
|
3620
|
+
|
|
3621
|
+
4. **Direct \`process.env\`** — avoid in app code; bypasses Zod
|
|
3622
|
+
coercion and the typed \`KickEnv\` registry.
|
|
3623
|
+
|
|
3624
|
+
> **Pitfall**: never delete \`import './config'\` from \`src/index.ts\`.
|
|
3625
|
+
> If the schema is not registered before DI runs, \`config.get()\`
|
|
3626
|
+
> returns \`undefined\` for user keys (the base shape only) and
|
|
3627
|
+
> \`@Value()\` only works because of its raw \`process.env\` fallback —
|
|
3628
|
+
> Zod coercion + schema defaults are silently skipped.
|
|
3629
|
+
|
|
3630
|
+
## Standalone Utilities (No DI Required)
|
|
3631
|
+
|
|
3632
|
+
These work anywhere — scripts, plain files, outside \`@Service\`/\`@Controller\`:
|
|
3633
|
+
|
|
3634
|
+
| Utility | Import | Example |
|
|
3635
|
+
|---------|--------|---------|
|
|
3636
|
+
| \`Logger.for(name)\` | \`@forinda/kickjs\` | \`const log = Logger.for('MyScript')\` |
|
|
3637
|
+
| \`createLogger(name)\` | \`@forinda/kickjs\` | \`const log = createLogger('Worker')\` |
|
|
3638
|
+
| \`createToken<T>(name)\` | \`@forinda/kickjs\` | \`const TOKEN = createToken<string>('app/db/url')\` |
|
|
3639
|
+
| \`ref(value)\` | \`@forinda/kickjs\` | \`const count = ref(0)\` |
|
|
3640
|
+
| \`computed(fn)\` | \`@forinda/kickjs\` | \`const doubled = computed(() => count.value * 2)\` |
|
|
3641
|
+
| \`watch(source, cb)\` | \`@forinda/kickjs\` | \`watch(() => count.value, (v) => log(v))\` |
|
|
3642
|
+
| \`reactive(obj)\` | \`@forinda/kickjs\` | \`const state = reactive({ count: 0 })\` |
|
|
3643
|
+
| \`HttpException\` | \`@forinda/kickjs\` | \`throw new HttpException(404, 'Not found')\` |
|
|
3644
|
+
| \`HttpStatus\` | \`@forinda/kickjs\` | \`HttpStatus.NOT_FOUND // 404\` |
|
|
3645
|
+
|
|
3646
|
+
## Key Decorators
|
|
3647
|
+
|
|
3648
|
+
### HTTP Routes
|
|
3649
|
+
| Decorator | Purpose |
|
|
3650
|
+
|-----------|---------|
|
|
3651
|
+
| \`@Controller()\` | Define route prefix |
|
|
3652
|
+
| \`@Get('/'), @Post('/')\` | HTTP method handlers |
|
|
3653
|
+
| \`@Middleware(fn)\` | Attach middleware |
|
|
3654
|
+
| \`@Public()\` | Skip auth (requires auth adapter) |
|
|
3655
|
+
| \`@Roles('admin')\` | Role-based access |
|
|
3656
|
+
|
|
3657
|
+
### Dependency Injection
|
|
3658
|
+
| Decorator | Purpose |
|
|
3659
|
+
|-----------|---------|
|
|
3660
|
+
| \`AppModule\` interface | Define feature module (implements \`routes()\`) |
|
|
3661
|
+
| \`@Service()\` | Register singleton service |
|
|
3662
|
+
| \`@Repository()\` | Register repository |
|
|
3663
|
+
| \`@Autowired()\` | Property injection |
|
|
3664
|
+
| \`@Inject('token')\` | Token-based injection |
|
|
3665
|
+
| \`@Value('VAR')\` | Inject env variable |
|
|
3666
|
+
|
|
3667
|
+
### Context Decorators
|
|
3668
|
+
|
|
3669
|
+
Typed, ordered way to populate \`ctx.set/get\` keys before the handler runs.
|
|
3670
|
+
Use this **instead of \`@Middleware()\`** when the middleware's only output
|
|
3671
|
+
is a value other code reads off \`ctx\`.
|
|
3672
|
+
|
|
3673
|
+
| Concept | Where it lives |
|
|
3674
|
+
|---------|----------------|
|
|
3675
|
+
| \`defineContextDecorator({ key, deps, dependsOn, optional, onError, resolve })\` | \`@forinda/kickjs\` |
|
|
3676
|
+
| Method/class decorator | \`@LoadX\` on a controller method/class |
|
|
3677
|
+
| Module hook | \`AppModule.contributors?(): ContributorRegistration[]\` |
|
|
3678
|
+
| Adapter hook | \`AppAdapter.contributors?(): ContributorRegistration[]\` |
|
|
3679
|
+
| Global registration | \`bootstrap({ contributors: [LoadX.registration] })\` |
|
|
3680
|
+
| Type augmentation | \`declare module '@forinda/kickjs' { interface ContextMeta { ... } }\` |
|
|
3681
|
+
|
|
3682
|
+
Precedence high → low: **method > class > module > adapter > global**.
|
|
3683
|
+
Cycles and missing \`dependsOn\` keys throw at \`app.setup()\` (boot fails
|
|
3684
|
+
fast). The \`onError\` hook is async-permitted.
|
|
3685
|
+
|
|
3686
|
+
Full guide: <https://forinda.github.io/kick-js/guide/context-decorators>.
|
|
3687
|
+
|
|
3688
|
+
${template === "cqrs" ? `### Background Jobs
|
|
3689
|
+
| Decorator | Purpose |
|
|
3690
|
+
|-----------|---------|
|
|
3691
|
+
| \`@Job('name')\` | Queue job handler |
|
|
3692
|
+
| \`@Process('queue')\` | Queue processor |
|
|
3693
|
+
| \`@Cron('0 * * * *')\` | Cron schedule |
|
|
3694
|
+
| \`@WsController()\` | WebSocket controller |
|
|
3695
|
+
|
|
3696
|
+
` : ""}## Common Pitfalls
|
|
3697
|
+
|
|
3698
|
+
1. **Forgot to register module** — Add to \`src/modules/index.ts\` exports array
|
|
3699
|
+
2. **DI not working** — Ensure \`reflect-metadata\` is imported in \`src/index.ts\`
|
|
3700
|
+
3. **Tests failing randomly** — Sharing the global container between tests. Default to \`Container.create()\` per test (or per \`beforeEach\`) instead of \`new Container()\` / \`getInstance().reset()\`
|
|
3701
|
+
4. **Routes not found** — Check controller path and module registration
|
|
3702
|
+
5. **HMR not working** — Two checks: (a) \`vite.config.ts\` has \`hmr: true\`; (b) module file is named \`<name>.module.ts\` (or \`.tsx\`/\`.js\`/\`.jsx\`) and lives under \`src/modules/\`. The Vite plugin auto-discovers \`*.module.[tj]sx?\` for graceful HMR — a misnamed module file (e.g., \`projects.ts\`) silently degrades to a full restart on every save.
|
|
3703
|
+
6. **Decorators not working** — Check \`tsconfig.json\` has \`experimentalDecorators: true\`
|
|
3704
|
+
7. **\`config.get('YOUR_KEY')\` returns \`undefined\`** — \`src/index.ts\` is missing \`import './config'\`. That side-effect import registers the env schema with kickjs (\`loadEnv(envSchema)\` runs at module load). Without it, \`ConfigService\` falls back to the base schema (\`PORT\`/\`NODE_ENV\`/\`LOG_LEVEL\` only) and every user-defined key reads as \`undefined\`. \`@Value()\` may *appear* to work because of a raw \`process.env\` fallback, but Zod coercion and schema defaults are silently skipped — investigate \`src/index.ts\` and \`src/config/index.ts\` first.
|
|
3705
|
+
8. **Used \`@Middleware()\` to compute a value for \`ctx\`** — prefer \`defineContextDecorator()\` (see Context Decorators above). It's typed via \`ContextMeta\`, supports \`dependsOn\` for ordering, and validates the pipeline at boot. \`@Middleware()\` is for response short-circuiting, stream mutation, and pre-route-matching work.
|
|
3706
|
+
9. **Context contributor's \`dependsOn\` key not produced anywhere** — boot throws \`MissingContributorError\` naming the dependent and the route. Either remove the dep or register a contributor that produces the key (at any precedence level: method/class/module/adapter/global).
|
|
3707
|
+
10. **\`bootstrap()\` not exported** — \`src/index.ts\` calls \`await bootstrap({ ... })\` but discards the return value (no \`export const app = ...\`). Vite HMR can't locate the running instance, so module saves degrade to full restarts; \`createTestApp\`/\`@forinda/kickjs-testing\` consumers can't import the handle either. Always: \`export const app = await bootstrap({ ... })\`.
|
|
3708
|
+
11. **Refresh AGENTS.md / CLAUDE.md after a framework upgrade** — these files are scaffolded by the CLI and don't auto-update. Run \`kick g agents -f\` (or \`kick g agent-docs -f\`) to regenerate from the latest CLI templates after \`kick add\` / version bumps. Hand-edited sections will be overwritten — keep customisation in a separate file like \`AGENTS.local.md\`.
|
|
3709
|
+
|
|
3710
|
+
## CLI Commands Reference
|
|
3711
|
+
|
|
3712
|
+
| Command | Description |
|
|
3713
|
+
|---------|-------------|
|
|
3714
|
+
| \`kick dev\` | Dev server with HMR |
|
|
3715
|
+
| \`kick dev:debug\` | Dev server with debugger |
|
|
3716
|
+
| \`kick build\` | Production build |
|
|
3717
|
+
| \`kick start\` | Run production build |
|
|
3718
|
+
| \`kick g module <names...>\` | Generate one or more modules |
|
|
3719
|
+
| \`kick g scaffold <name> <fields>\` | Generate CRUD |
|
|
3720
|
+
| \`kick g controller <name>\` | Generate controller |
|
|
3721
|
+
| \`kick g service <name>\` | Generate service |
|
|
3722
|
+
| \`kick g middleware <name>\` | Generate middleware |
|
|
3723
|
+
| \`kick add <package>\` | Add KickJS package |
|
|
3724
|
+
| \`kick add --list\` | List available packages |
|
|
3725
|
+
| \`kick rm module <names...>\` | Remove one or more modules |
|
|
3726
|
+
|
|
3727
|
+
> **Note:** When using \`kick new\` in scripts or CI, pass \`-t\` (or \`--template\`) and \`-r\` (or \`--repo\`) flags to bypass interactive prompts:
|
|
3728
|
+
> \`\`\`bash
|
|
3729
|
+
> kick new my-api -t ddd -r prisma --pm ${pm} --no-git --no-install -f
|
|
3730
|
+
> \`\`\`
|
|
3731
|
+
|
|
3732
|
+
## Learn More
|
|
3733
|
+
|
|
3734
|
+
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
3735
|
+
- [CLI Reference](https://forinda.github.io/kick-js/api/cli.html)
|
|
3736
|
+
- [Decorators Guide](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
3737
|
+
- [DI System](https://forinda.github.io/kick-js/guide/dependency-injection.html)
|
|
3738
|
+
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
3739
|
+
`;
|
|
3740
|
+
}
|
|
3741
|
+
/**
|
|
3742
|
+
* Generate `kickjs-skills.md` — task-oriented "skill" recipes for AI
|
|
3743
|
+
* agents (Claude superpowers, Copilot, etc.). Where AGENTS.md is the
|
|
3744
|
+
* narrative reference, this file lists short, rigid workflows the agent
|
|
3745
|
+
* should follow when it sees the corresponding trigger.
|
|
3746
|
+
*/
|
|
3747
|
+
function generateKickJsSkills(name, _template, pm) {
|
|
3748
|
+
return `# kickjs-skills.md — Task Skills for AI Agents (${name})
|
|
3749
|
+
|
|
3750
|
+
This file is the agent-facing **skills index** for KickJS work in this
|
|
3751
|
+
repo. Each block below is a short, rigid workflow keyed to a specific
|
|
3752
|
+
trigger ("user wants to add a module", "tests are leaking state", etc.).
|
|
3753
|
+
|
|
3754
|
+
- Reference docs (narrative, exhaustive) → \`AGENTS.md\`.
|
|
3755
|
+
- Tool-specific notes → \`CLAUDE.md\`, \`GEMINI.md\`, etc.
|
|
3756
|
+
- **This file** → step-by-step recipes the agent should *execute*.
|
|
3757
|
+
|
|
3758
|
+
Re-run \`kick g agents -f --only skills\` after framework upgrades to refresh.
|
|
3759
|
+
|
|
3760
|
+
---
|
|
3761
|
+
|
|
3762
|
+
## Skill: add-module
|
|
3763
|
+
|
|
3764
|
+
\`\`\`yaml
|
|
3765
|
+
name: kickjs-add-module
|
|
3766
|
+
description: Use when the user asks to add a new feature module (controller + service + repo + DTOs).
|
|
3767
|
+
\`\`\`
|
|
3768
|
+
|
|
3769
|
+
**Trigger phrases**: "add a users module", "scaffold tasks", "new feature for X".
|
|
3770
|
+
|
|
3771
|
+
**Steps**:
|
|
3772
|
+
1. Run \`kick g module <name>\` (use plural form if the project pluralizes — check \`kick.config.ts\`).
|
|
3773
|
+
2. Verify the new folder under \`src/modules/<name>/\` contains \`<name>.module.ts\` (filename suffix is mandatory for HMR).
|
|
3774
|
+
3. Confirm the module appears in \`src/modules/index.ts\` exports — generator does this automatically; verify if you bypassed it.
|
|
3775
|
+
4. Open \`<name>.dto.ts\` and tighten the Zod schemas to real fields (the generator emits placeholders).
|
|
3776
|
+
5. Run \`${pm} run typecheck\` and \`${pm} run test\` before claiming done.
|
|
3777
|
+
|
|
3778
|
+
**Red flags** (stop and ask):
|
|
3779
|
+
- File created as \`<name>.ts\` instead of \`<name>.module.ts\` — Vite won't HMR it.
|
|
3780
|
+
- Module not registered in \`src/modules/index.ts\`.
|
|
3781
|
+
- \`@Controller('/path')\` with a path argument — that's a v3 pattern; remove it (mount comes from \`routes().path\`).
|
|
3782
|
+
|
|
3783
|
+
---
|
|
3784
|
+
|
|
3785
|
+
## Skill: add-adapter
|
|
3786
|
+
|
|
3787
|
+
\`\`\`yaml
|
|
3788
|
+
name: kickjs-add-adapter
|
|
3789
|
+
description: Use when wiring a new lifecycle integration (Swagger, DevTools, Auth, custom).
|
|
3790
|
+
\`\`\`
|
|
3791
|
+
|
|
3792
|
+
**Steps**:
|
|
3793
|
+
1. \`kick g adapter <name>\` to scaffold the boilerplate, OR install via \`kick add <package>\` for first-party adapters.
|
|
3794
|
+
2. The generated file uses \`defineAdapter()\` — never \`class implements AppAdapter\`.
|
|
3795
|
+
3. Add the adapter instance to \`src/adapters/index.ts\` (don't inline in \`src/index.ts\`).
|
|
3796
|
+
4. If the adapter contributes to \`ctx.set/get\`, prefer \`AppAdapter.contributors?()\` over a wrapping middleware.
|
|
3797
|
+
5. Verify with \`kick dev\` that the adapter's lifecycle logs fire.
|
|
3798
|
+
|
|
3799
|
+
**Red flags**:
|
|
3800
|
+
- Inlining the adapter list directly in \`src/index.ts\` (entry file should stay thin).
|
|
3801
|
+
- Returning a plain object instead of going through \`defineAdapter()\` — type inference for \`config\` will be wrong.
|
|
3802
|
+
|
|
3803
|
+
---
|
|
3804
|
+
|
|
3805
|
+
## Skill: write-controller-test
|
|
3806
|
+
|
|
3807
|
+
\`\`\`yaml
|
|
3808
|
+
name: kickjs-write-controller-test
|
|
3809
|
+
description: Use when adding a Vitest test that exercises an HTTP route or DI graph.
|
|
3810
|
+
\`\`\`
|
|
3811
|
+
|
|
3812
|
+
**Template** (copy/paste, adjust):
|
|
3813
|
+
|
|
3814
|
+
\`\`\`ts
|
|
3815
|
+
import { describe, it, expect } from 'vitest'
|
|
3816
|
+
import { Container } from '@forinda/kickjs'
|
|
3817
|
+
import { createTestApp } from '@forinda/kickjs-testing'
|
|
3818
|
+
|
|
3819
|
+
describe('UserController', () => {
|
|
3820
|
+
it('returns users', async () => {
|
|
3821
|
+
const container = Container.create() // isolated DI per test
|
|
3822
|
+
const app = await createTestApp([UserModule], { container })
|
|
3823
|
+
const res = await app.get('/users')
|
|
3824
|
+
expect(res.status).toBe(200)
|
|
3825
|
+
})
|
|
3826
|
+
})
|
|
3827
|
+
\`\`\`
|
|
3828
|
+
|
|
3829
|
+
**Red flags**:
|
|
3830
|
+
- \`new Container()\` — wrong; use \`Container.create()\`.
|
|
3831
|
+
- \`Container.getInstance().reset()\` — wrong; same fix.
|
|
3832
|
+
- Sharing a container across \`it()\` blocks — leaks registrations.
|
|
3833
|
+
|
|
3834
|
+
---
|
|
3835
|
+
|
|
3836
|
+
## Skill: env-wiring-check
|
|
3837
|
+
|
|
3838
|
+
\`\`\`yaml
|
|
3839
|
+
name: kickjs-env-wiring-check
|
|
3840
|
+
description: Use when ConfigService.get('SOME_KEY') returns undefined or @Value silently falls back to process.env.
|
|
3841
|
+
\`\`\`
|
|
3842
|
+
|
|
3843
|
+
**Diagnosis**:
|
|
3844
|
+
1. Open \`src/index.ts\`. The **first non-\`reflect-metadata\`** import MUST be \`import './config'\`.
|
|
3845
|
+
2. Open \`src/config/index.ts\`. It MUST call \`loadEnv(envSchema)\` as a top-level side effect.
|
|
3846
|
+
3. The new key MUST be declared in the Zod schema there. \`@Value('NEW_KEY')\` won't work without a schema entry (it'll fall back to raw \`process.env\` and skip Zod coercion silently).
|
|
3847
|
+
|
|
3848
|
+
**Fix**: add the key to the schema; ensure both side-effect imports above are present.
|
|
3849
|
+
|
|
3850
|
+
---
|
|
3851
|
+
|
|
3852
|
+
## Skill: bootstrap-export
|
|
3853
|
+
|
|
3854
|
+
\`\`\`yaml
|
|
3855
|
+
name: kickjs-bootstrap-export
|
|
3856
|
+
description: Use when HMR is silently doing full restarts on every save, or createTestApp can't find the app handle.
|
|
3857
|
+
\`\`\`
|
|
3858
|
+
|
|
3859
|
+
**Check** \`src/index.ts\`'s last line:
|
|
3860
|
+
|
|
3861
|
+
\`\`\`ts
|
|
3862
|
+
// CORRECT
|
|
3863
|
+
export const app = await bootstrap({ ... })
|
|
3864
|
+
|
|
3865
|
+
// WRONG (HMR degrades to full restart, createTestApp loses the handle)
|
|
3866
|
+
await bootstrap({ ... })
|
|
3867
|
+
\`\`\`
|
|
3868
|
+
|
|
3869
|
+
The Vite plugin imports the named \`app\` symbol; testing helpers do too.
|
|
3870
|
+
|
|
3871
|
+
---
|
|
3872
|
+
|
|
3873
|
+
## Skill: thin-entry-file
|
|
3874
|
+
|
|
3875
|
+
\`\`\`yaml
|
|
3876
|
+
name: kickjs-thin-entry-file
|
|
3877
|
+
description: Use when src/index.ts is accumulating module/middleware/plugin/adapter literals.
|
|
3878
|
+
\`\`\`
|
|
3879
|
+
|
|
3880
|
+
**Refactor target**:
|
|
3881
|
+
|
|
3882
|
+
\`\`\`ts
|
|
3883
|
+
// src/modules/index.ts
|
|
3884
|
+
export const modules: AppModuleClass[] = [HelloModule, UsersModule, ...]
|
|
3885
|
+
|
|
3886
|
+
// src/middleware/index.ts
|
|
3887
|
+
export const middleware = [helmet(), cors(), requestId(), ...]
|
|
3888
|
+
|
|
3889
|
+
// src/plugins/index.ts
|
|
3890
|
+
export const plugins = [MetricsPlugin(), ...]
|
|
3891
|
+
|
|
3892
|
+
// src/adapters/index.ts
|
|
3893
|
+
export const adapters = [SwaggerAdapter({ ... }), DevToolsAdapter()]
|
|
3894
|
+
|
|
3895
|
+
// src/index.ts — stays small
|
|
3896
|
+
import 'reflect-metadata'
|
|
3897
|
+
import './config'
|
|
3898
|
+
import { bootstrap } from '@forinda/kickjs'
|
|
3899
|
+
import { modules } from './modules'
|
|
3900
|
+
import { middleware } from './middleware'
|
|
3901
|
+
import { plugins } from './plugins'
|
|
3902
|
+
import { adapters } from './adapters'
|
|
3903
|
+
export const app = await bootstrap({ modules, middleware, plugins, adapters })
|
|
3904
|
+
\`\`\`
|
|
3905
|
+
|
|
3906
|
+
**Red flags**: any \`new SomeAdapter()\` or \`SomePlugin()\` literal inside \`bootstrap({ ... })\` instead of imported from a category folder.
|
|
3907
|
+
|
|
3908
|
+
---
|
|
3909
|
+
|
|
3910
|
+
## Skill: context-contributor
|
|
3911
|
+
|
|
3912
|
+
\`\`\`yaml
|
|
3913
|
+
name: kickjs-context-contributor
|
|
3914
|
+
description: Use when a middleware's only job is to set ctx values consumed elsewhere — replace with defineHttpContextDecorator (HTTP) or defineContextDecorator (transport-agnostic).
|
|
3915
|
+
\`\`\`
|
|
3916
|
+
|
|
3917
|
+
**Pattern** (HTTP — most common):
|
|
3918
|
+
|
|
3919
|
+
\`\`\`ts
|
|
3920
|
+
import { defineHttpContextDecorator, type RequestContext } from '@forinda/kickjs'
|
|
3921
|
+
|
|
3922
|
+
const LoadTenant = defineHttpContextDecorator({
|
|
3923
|
+
key: 'tenant',
|
|
3924
|
+
deps: { repo: TENANT_REPO },
|
|
3925
|
+
resolve: (ctx, { repo }) => repo.findById(ctx.req.headers['x-tenant-id'] as string),
|
|
3926
|
+
})
|
|
3927
|
+
|
|
3928
|
+
const LoadProject = defineHttpContextDecorator({
|
|
3929
|
+
key: 'project',
|
|
3930
|
+
dependsOn: ['tenant'],
|
|
3931
|
+
resolve: (ctx) => projectsRepo.find(ctx.get('tenant')!.id, ctx.params.id),
|
|
3932
|
+
})
|
|
3933
|
+
|
|
3934
|
+
@LoadTenant
|
|
3935
|
+
@LoadProject
|
|
3936
|
+
@Get('/projects/:id')
|
|
3937
|
+
getProject(ctx: RequestContext) { ctx.json(ctx.get('project')) }
|
|
3938
|
+
\`\`\`
|
|
3939
|
+
|
|
3940
|
+
Use \`defineContextDecorator\` (no Http prefix) when authoring a contributor that must run across HTTP, WebSocket, queue, and cron transports — \`Ctx\` defaults to the smaller \`ExecutionContext\` surface (\`get\` / \`set\` / \`requestId\` only, no \`req\`).
|
|
3941
|
+
|
|
3942
|
+
Precedence high → low: **method > class > module > adapter > global**.
|
|
3943
|
+
Cycles or unmet \`dependsOn\` keys throw \`MissingContributorError\` at boot.
|
|
3944
|
+
|
|
3945
|
+
**Critical rules — all stem from the same shared-via-ALS instance model**:
|
|
3946
|
+
- Every per-request stage (middleware → contributors → handler) gets its OWN \`RequestContext\` instance, but they all read/write the SAME \`AsyncLocalStorage\`-backed bag.
|
|
3947
|
+
- **\`resolve\` and \`onError\` must RETURN the value** — the runner writes it via \`ctx.set(key, value)\`. Direct property assignment (\`ctx.tenant = …\`) sticks to one instance only and the handler instance never sees it.
|
|
3948
|
+
- \`ctx.set('tenant', x)\` then \`ctx.get('tenant')\` works across instances. \`ctx.req.headers[...]\` works (the underlying Express request is shared).
|
|
3949
|
+
- Services with no \`ctx\` reference: \`getRequestValue('tenant')\` returns \`MetaValue<'tenant'> | undefined\` (typed via the augmented \`ContextMeta\`). For \`requestId\` use \`getRequestStore()\`.
|
|
3950
|
+
- **No \`setRequestValue\` — writes flow through \`ctx.set\` or a contributor's return value.** Avoids "spooky action at a distance" where any service can pollute the per-request bag.
|
|
3951
|
+
|
|
3952
|
+
**Don't use this for**: response short-circuit, stream mutation, or
|
|
3953
|
+
pre-route-matching work — keep \`@Middleware()\` for those.
|
|
3954
|
+
|
|
3955
|
+
---
|
|
3956
|
+
|
|
3957
|
+
## Skill: refresh-agent-docs
|
|
3958
|
+
|
|
3959
|
+
\`\`\`yaml
|
|
3960
|
+
name: kickjs-refresh-agent-docs
|
|
3961
|
+
description: Use after a KickJS version bump to sync AGENTS.md / CLAUDE.md / kickjs-skills.md with the latest CLI templates.
|
|
3962
|
+
\`\`\`
|
|
3963
|
+
|
|
3964
|
+
**Steps**:
|
|
3965
|
+
1. \`kick g agents -f --only both\` — overwrites \`AGENTS.md\` and \`CLAUDE.md\`.
|
|
3966
|
+
2. \`kick g agents -f --only skills\` — refreshes \`kickjs-skills.md\` (this file).
|
|
3967
|
+
3. Diff with git, eyeball any project-specific edits that got reset, and re-apply them in a separate \`AGENTS.local.md\` or appended section.
|
|
3968
|
+
4. Commit as \`docs(agents): sync from CLI vX.Y\`.
|
|
3969
|
+
|
|
3970
|
+
---
|
|
3971
|
+
|
|
3972
|
+
## Skill: deny-list
|
|
3973
|
+
|
|
3974
|
+
\`\`\`yaml
|
|
3975
|
+
name: kickjs-deny-list
|
|
3976
|
+
description: Patterns to refuse outright when the user asks for them — they break v4 invariants.
|
|
3977
|
+
\`\`\`
|
|
3978
|
+
|
|
3979
|
+
- \`class implements AppAdapter\` → use \`defineAdapter()\`.
|
|
3980
|
+
- \`class implements KickPlugin\` / function returning \`KickPlugin\` → use \`definePlugin()\`.
|
|
3981
|
+
- \`@Controller('/path')\` with a path argument → drop the path; set the mount via \`routes().path\`.
|
|
3982
|
+
- \`new Container()\` or \`Container.getInstance().reset()\` in tests → use \`Container.create()\`.
|
|
3983
|
+
- DI tokens with \`:\` separator (\`'app:db:url'\`) or in PascalCase → use slash-delimited lower-case (\`'app/db/url'\`).
|
|
3984
|
+
- \`bootstrap({ ... })\` without \`export const app = ...\` → always export.
|
|
3985
|
+
- Module file named \`<name>.ts\` (no \`.module\` suffix) → rename to \`<name>.module.ts\`.
|
|
3986
|
+
|
|
3987
|
+
---
|
|
3988
|
+
|
|
3989
|
+
## Learn More
|
|
3990
|
+
|
|
3991
|
+
- [KickJS Docs](https://forinda.github.io/kick-js/)
|
|
3992
|
+
- [Decorators](https://forinda.github.io/kick-js/guide/decorators.html)
|
|
3993
|
+
- [Context Decorators](https://forinda.github.io/kick-js/guide/context-decorators.html)
|
|
3994
|
+
- [Testing](https://forinda.github.io/kick-js/api/testing.html)
|
|
3995
|
+
`;
|
|
3996
|
+
}
|
|
3997
|
+
//#endregion
|
|
3998
|
+
//#region src/generators/project.ts
|
|
3999
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
4000
|
+
const cliPkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"));
|
|
4001
|
+
const KICKJS_VERSION = `^${cliPkg.version}`;
|
|
4002
|
+
/** Scaffold a new KickJS project */
|
|
4003
|
+
async function initProject(options) {
|
|
4004
|
+
const { name, directory, packageManager = "pnpm", template = "rest", defaultRepo = "inmemory", packages = [] } = options;
|
|
4005
|
+
const dir = directory;
|
|
4006
|
+
const log = (msg) => console.log(` ${msg}`);
|
|
4007
|
+
console.log(`\n Creating KickJS project: ${name}\n`);
|
|
4008
|
+
await writeFileSafe(join(dir, "package.json"), generatePackageJson(name, template, KICKJS_VERSION, packages));
|
|
4009
|
+
await writeFileSafe(join(dir, "vite.config.ts"), generateViteConfig());
|
|
4010
|
+
await writeFileSafe(join(dir, "tsconfig.json"), generateTsConfig());
|
|
4011
|
+
await writeFileSafe(join(dir, ".prettierrc"), generatePrettierConfig());
|
|
4012
|
+
await writeFileSafe(join(dir, ".editorconfig"), generateEditorConfig());
|
|
4013
|
+
await writeFileSafe(join(dir, ".gitignore"), generateGitIgnore());
|
|
4014
|
+
await writeFileSafe(join(dir, ".gitattributes"), generateGitAttributes());
|
|
4015
|
+
await writeFileSafe(join(dir, ".env"), generateEnv());
|
|
4016
|
+
await writeFileSafe(join(dir, ".env.example"), generateEnvExample());
|
|
4017
|
+
await writeFileSafe(join(dir, "src/config/index.ts"), generateEnvFile());
|
|
4018
|
+
await writeFileSafe(join(dir, "src/index.ts"), generateEntryFile(name, template, cliPkg.version, packages));
|
|
4019
|
+
await writeFileSafe(join(dir, "src/modules/index.ts"), generateModulesIndex());
|
|
4020
|
+
await writeFileSafe(join(dir, "src/modules/hello/hello.service.ts"), generateHelloService());
|
|
4021
|
+
await writeFileSafe(join(dir, "src/modules/hello/hello.controller.ts"), generateHelloController());
|
|
4022
|
+
await writeFileSafe(join(dir, "src/modules/hello/hello.module.ts"), generateHelloModule());
|
|
4023
|
+
await writeFileSafe(join(dir, "kick.config.ts"), generateKickConfig(template, defaultRepo, packageManager));
|
|
4024
|
+
await writeFileSafe(join(dir, "vitest.config.ts"), generateVitestConfig());
|
|
4025
|
+
await writeFileSafe(join(dir, "README.md"), generateReadme(name, template, packageManager));
|
|
4026
|
+
await writeFileSafe(join(dir, "CLAUDE.md"), generateClaude(name, template, packageManager));
|
|
4027
|
+
await writeFileSafe(join(dir, "AGENTS.md"), generateAgents(name, template, packageManager));
|
|
4028
|
+
await writeFileSafe(join(dir, "kickjs-skills.md"), generateKickJsSkills(name, template, packageManager));
|
|
4029
|
+
if (options.installDeps) {
|
|
4030
|
+
console.log(`\n Installing dependencies with ${packageManager}...\n`);
|
|
4031
|
+
try {
|
|
4032
|
+
execSync(`${packageManager} install`, {
|
|
4033
|
+
cwd: dir,
|
|
4034
|
+
stdio: "inherit"
|
|
4035
|
+
});
|
|
4036
|
+
console.log("\n Dependencies installed successfully!");
|
|
4037
|
+
} catch {
|
|
4038
|
+
console.log(`\n Warning: ${packageManager} install failed. Run it manually.`);
|
|
4039
|
+
}
|
|
4040
|
+
}
|
|
4041
|
+
try {
|
|
4042
|
+
const { runTypegen } = await import("./typegen-DugZmi-0.mjs").then((n) => n.n);
|
|
4043
|
+
await runTypegen({
|
|
4044
|
+
cwd: dir,
|
|
4045
|
+
allowDuplicates: true,
|
|
4046
|
+
silent: true
|
|
4047
|
+
});
|
|
4048
|
+
} catch {}
|
|
4049
|
+
if (options.initGit) try {
|
|
4050
|
+
execSync("git init", {
|
|
4051
|
+
cwd: dir,
|
|
4052
|
+
stdio: "pipe"
|
|
4053
|
+
});
|
|
4054
|
+
execSync("git branch -M main", {
|
|
4055
|
+
cwd: dir,
|
|
4056
|
+
stdio: "pipe"
|
|
4057
|
+
});
|
|
4058
|
+
execSync("git add -A", {
|
|
4059
|
+
cwd: dir,
|
|
4060
|
+
stdio: "pipe"
|
|
4061
|
+
});
|
|
4062
|
+
execSync("git commit -m \"chore: initial commit from kick new\"", {
|
|
4063
|
+
cwd: dir,
|
|
4064
|
+
stdio: "pipe"
|
|
4065
|
+
});
|
|
4066
|
+
log("Git repository initialized");
|
|
4067
|
+
} catch {
|
|
4068
|
+
log("Warning: git init failed (git may not be installed)");
|
|
4069
|
+
}
|
|
4070
|
+
console.log("\n Project scaffolded successfully!");
|
|
4071
|
+
console.log();
|
|
4072
|
+
const needsCd = dir !== process.cwd();
|
|
4073
|
+
log("Next steps:");
|
|
4074
|
+
if (needsCd) log(` cd ${name}`);
|
|
4075
|
+
if (!options.installDeps) log(` ${packageManager} install`);
|
|
4076
|
+
const genHint = {
|
|
4077
|
+
rest: "kick g module user",
|
|
4078
|
+
ddd: "kick g module user --repo drizzle",
|
|
4079
|
+
cqrs: "kick g module user --pattern cqrs",
|
|
4080
|
+
minimal: "# add your routes to src/index.ts"
|
|
4081
|
+
};
|
|
4082
|
+
log(` ${genHint[template] ?? genHint.rest}`);
|
|
4083
|
+
log(" kick dev");
|
|
4084
|
+
log("");
|
|
4085
|
+
log("Commands:");
|
|
4086
|
+
log(" kick dev Start dev server with Vite HMR");
|
|
4087
|
+
log(" kick build Production build via Vite");
|
|
4088
|
+
log(" kick start Run production build");
|
|
4089
|
+
log("");
|
|
4090
|
+
log("Generators:");
|
|
4091
|
+
log(" kick g module <name> Full DDD module (controller, DTOs, use-cases, repo)");
|
|
4092
|
+
log(" kick g scaffold <n> <f..> CRUD module from field definitions");
|
|
4093
|
+
log(" kick g controller <name> Standalone controller");
|
|
4094
|
+
log(" kick g service <name> @Service() class");
|
|
4095
|
+
log(" kick g middleware <name> Express middleware");
|
|
4096
|
+
log(" kick g guard <name> Route guard (auth, roles, etc.)");
|
|
4097
|
+
log(" kick g adapter <name> AppAdapter with lifecycle hooks");
|
|
4098
|
+
log(" kick g dto <name> Zod DTO schema");
|
|
4099
|
+
if (template === "cqrs") log(" kick g job <name> Queue job processor");
|
|
4100
|
+
log(" kick g config Generate kick.config.ts");
|
|
4101
|
+
log("");
|
|
4102
|
+
log("Add packages:");
|
|
4103
|
+
log(" kick add <pkg> Install a KickJS package + peers");
|
|
4104
|
+
log(" kick add --list Show all available packages");
|
|
4105
|
+
log("");
|
|
4106
|
+
log("Available: auth, swagger, drizzle, prisma, ws, queue, devtools, mcp, testing");
|
|
4107
|
+
log("");
|
|
4108
|
+
}
|
|
4109
|
+
//#endregion
|
|
4110
|
+
//#region src/generator-extension/define.ts
|
|
4111
|
+
/**
|
|
4112
|
+
* Identity factory — returns the spec verbatim. Exists for type
|
|
4113
|
+
* inference and forward-compatibility (future fields can be added with
|
|
4114
|
+
* defaults).
|
|
4115
|
+
*
|
|
4116
|
+
* @example
|
|
4117
|
+
* ```ts
|
|
4118
|
+
* import { defineGenerator } from '@forinda/kickjs-cli'
|
|
4119
|
+
*
|
|
4120
|
+
* export default [
|
|
4121
|
+
* defineGenerator({
|
|
4122
|
+
* name: 'command',
|
|
4123
|
+
* description: 'Generate a CQRS command + handler',
|
|
4124
|
+
* files: (ctx) => [
|
|
4125
|
+
* {
|
|
4126
|
+
* path: `src/modules/${ctx.kebab}/commands/${ctx.kebab}.command.ts`,
|
|
4127
|
+
* content: `// command for ${ctx.pascal}`,
|
|
4128
|
+
* },
|
|
4129
|
+
* ],
|
|
4130
|
+
* }),
|
|
4131
|
+
* ]
|
|
4132
|
+
* ```
|
|
4133
|
+
*/
|
|
4134
|
+
function defineGenerator(spec) {
|
|
4135
|
+
return spec;
|
|
4136
|
+
}
|
|
4137
|
+
//#endregion
|
|
4138
|
+
//#region src/generator-extension/context.ts
|
|
4139
|
+
/** Convert any string to snake_case (`UserPost` / `user-post` → `user_post`). */
|
|
4140
|
+
function toSnakeCase(name) {
|
|
4141
|
+
return toKebabCase(name).replace(/-/g, "_");
|
|
4142
|
+
}
|
|
4143
|
+
/**
|
|
4144
|
+
* Build a {@link GeneratorContext} from the raw name + invocation
|
|
4145
|
+
* arguments. Centralises the case-transformation logic so every plugin
|
|
4146
|
+
* generator sees the same shape regardless of how the name was typed
|
|
4147
|
+
* on the command line (`Post` vs `post` vs `user_post`).
|
|
4148
|
+
*/
|
|
4149
|
+
function buildGeneratorContext(input) {
|
|
4150
|
+
const cwd = input.cwd ?? process.cwd();
|
|
4151
|
+
const usePlural = input.pluralize ?? true;
|
|
4152
|
+
const pascal = toPascalCase(input.name);
|
|
4153
|
+
const camel = toCamelCase(input.name);
|
|
4154
|
+
const kebab = toKebabCase(input.name);
|
|
4155
|
+
const snake = toSnakeCase(input.name);
|
|
4156
|
+
const ctx = {
|
|
4157
|
+
name: input.name,
|
|
4158
|
+
pascal,
|
|
4159
|
+
camel,
|
|
4160
|
+
kebab,
|
|
4161
|
+
snake,
|
|
4162
|
+
modulesDir: input.modulesDir ?? "src/modules",
|
|
4163
|
+
cwd,
|
|
4164
|
+
args: input.args ?? [],
|
|
4165
|
+
flags: input.flags ?? {}
|
|
4166
|
+
};
|
|
4167
|
+
if (usePlural) {
|
|
4168
|
+
const pluralKebab = pluralize(kebab);
|
|
4169
|
+
ctx.pluralKebab = pluralKebab;
|
|
4170
|
+
ctx.pluralPascal = toPascalCase(pluralKebab);
|
|
4171
|
+
ctx.pluralCamel = toCamelCase(pluralKebab);
|
|
4172
|
+
}
|
|
4173
|
+
return ctx;
|
|
4174
|
+
}
|
|
4175
|
+
/** Resolve a generator output path against the context's cwd. */
|
|
4176
|
+
function resolveGeneratorPath(ctx, path) {
|
|
4177
|
+
return resolve(ctx.cwd, path);
|
|
4178
|
+
}
|
|
4179
|
+
/**
|
|
4180
|
+
* Dynamic-import a generator manifest file. Wraps `pathToFileURL` so
|
|
4181
|
+
* callers don't have to think about Windows/Unix path quirks.
|
|
4182
|
+
*/
|
|
4183
|
+
async function importManifest(absPath) {
|
|
4184
|
+
return import(pathToFileURL(absPath).href);
|
|
4185
|
+
}
|
|
4186
|
+
//#endregion
|
|
4187
|
+
//#region src/generator-extension/discover.ts
|
|
4188
|
+
/**
|
|
4189
|
+
* Discover generator manifests shipped by every kickjs plugin in the
|
|
4190
|
+
* project's direct deps. Spec rationale: walking the
|
|
4191
|
+
* `node_modules/@scope/kickjs-name/` tree is one option, but reading
|
|
4192
|
+
* the project's own `package.json` and resolving each dep through
|
|
4193
|
+
* Node's module resolver gives:
|
|
4194
|
+
*
|
|
4195
|
+
* 1. Predictable scoping — only deps the project actually declared
|
|
4196
|
+
* get scanned, no surprises from transitive packages
|
|
4197
|
+
* 2. pnpm `.pnpm` store compatibility — `createRequire().resolve()`
|
|
4198
|
+
* handles the symlinked layout correctly
|
|
4199
|
+
* 3. Clear error attribution — the source package name is always
|
|
4200
|
+
* known before the import happens
|
|
4201
|
+
*
|
|
4202
|
+
* The walk is shallow (direct deps only). Transitive plugins that want
|
|
4203
|
+
* to expose generators must be re-exported by a direct dep.
|
|
4204
|
+
*
|
|
4205
|
+
* Caches per-cwd inside one CLI invocation so a single `kick g` call
|
|
4206
|
+
* does the disk + import work exactly once even when multiple
|
|
4207
|
+
* generators dispatch through the same registry.
|
|
4208
|
+
*/
|
|
4209
|
+
const cache = /* @__PURE__ */ new Map();
|
|
4210
|
+
async function discoverPluginGenerators(cwd) {
|
|
4211
|
+
const cached = cache.get(cwd);
|
|
4212
|
+
if (cached) return cached;
|
|
4213
|
+
const promise = doDiscover(cwd);
|
|
4214
|
+
cache.set(cwd, promise);
|
|
4215
|
+
return promise;
|
|
4216
|
+
}
|
|
4217
|
+
async function doDiscover(cwd) {
|
|
4218
|
+
const projectPkgPath = resolve(cwd, "package.json");
|
|
4219
|
+
if (!existsSync(projectPkgPath)) return {
|
|
4220
|
+
generators: [],
|
|
4221
|
+
loaded: [],
|
|
4222
|
+
failed: []
|
|
4223
|
+
};
|
|
4224
|
+
const depNames = collectDepNames(JSON.parse(await readFile(projectPkgPath, "utf-8")));
|
|
4225
|
+
const require = createRequire(resolve(cwd, "package.json"));
|
|
4226
|
+
const generators = [];
|
|
4227
|
+
const loaded = [];
|
|
4228
|
+
const failed = [];
|
|
4229
|
+
for (const depName of depNames) {
|
|
4230
|
+
let depPkgPath;
|
|
4231
|
+
try {
|
|
4232
|
+
depPkgPath = require.resolve(`${depName}/package.json`);
|
|
4233
|
+
} catch {
|
|
4234
|
+
continue;
|
|
4235
|
+
}
|
|
4236
|
+
let depPkg;
|
|
4237
|
+
try {
|
|
4238
|
+
depPkg = JSON.parse(await readFile(depPkgPath, "utf-8"));
|
|
4239
|
+
} catch (err) {
|
|
4240
|
+
failed.push({
|
|
4241
|
+
source: depName,
|
|
4242
|
+
reason: `failed to parse package.json: ${err}`
|
|
4243
|
+
});
|
|
4244
|
+
continue;
|
|
4245
|
+
}
|
|
4246
|
+
if (!depPkg.kickjs?.generators) continue;
|
|
4247
|
+
const entryRel = depPkg.kickjs.generators;
|
|
4248
|
+
const entryAbs = resolve(dirname(depPkgPath), entryRel);
|
|
4249
|
+
if (!existsSync(entryAbs)) {
|
|
4250
|
+
failed.push({
|
|
4251
|
+
source: depName,
|
|
4252
|
+
reason: `kickjs.generators points to missing file: ${entryRel}`
|
|
4253
|
+
});
|
|
4254
|
+
continue;
|
|
4255
|
+
}
|
|
4256
|
+
let mod;
|
|
4257
|
+
try {
|
|
4258
|
+
mod = await importManifest(entryAbs);
|
|
4259
|
+
} catch (err) {
|
|
4260
|
+
failed.push({
|
|
4261
|
+
source: depName,
|
|
4262
|
+
reason: `failed to import manifest: ${err}`
|
|
4263
|
+
});
|
|
4264
|
+
continue;
|
|
4265
|
+
}
|
|
4266
|
+
const manifest = mod.default;
|
|
4267
|
+
if (!Array.isArray(manifest)) {
|
|
4268
|
+
failed.push({
|
|
4269
|
+
source: depName,
|
|
4270
|
+
reason: `manifest's default export is not an array of GeneratorSpec`
|
|
4271
|
+
});
|
|
4272
|
+
continue;
|
|
4273
|
+
}
|
|
4274
|
+
for (const entry of manifest) {
|
|
4275
|
+
if (!isGeneratorSpec(entry)) {
|
|
4276
|
+
failed.push({
|
|
4277
|
+
source: depName,
|
|
4278
|
+
reason: `manifest entry is not a valid GeneratorSpec (missing name/files)`
|
|
4279
|
+
});
|
|
4280
|
+
continue;
|
|
4281
|
+
}
|
|
4282
|
+
generators.push({
|
|
4283
|
+
source: depName,
|
|
4284
|
+
spec: entry
|
|
4285
|
+
});
|
|
4286
|
+
}
|
|
4287
|
+
loaded.push(depName);
|
|
4288
|
+
}
|
|
4289
|
+
return {
|
|
4290
|
+
generators,
|
|
4291
|
+
loaded,
|
|
4292
|
+
failed
|
|
4293
|
+
};
|
|
4294
|
+
}
|
|
4295
|
+
function collectDepNames(pkg) {
|
|
4296
|
+
const set = /* @__PURE__ */ new Set();
|
|
4297
|
+
for (const block of [
|
|
4298
|
+
pkg.dependencies,
|
|
4299
|
+
pkg.devDependencies,
|
|
4300
|
+
pkg.peerDependencies
|
|
4301
|
+
]) {
|
|
4302
|
+
if (!block) continue;
|
|
4303
|
+
for (const name of Object.keys(block)) set.add(name);
|
|
4304
|
+
}
|
|
4305
|
+
return Array.from(set);
|
|
4306
|
+
}
|
|
4307
|
+
function isGeneratorSpec(entry) {
|
|
4308
|
+
if (!entry || typeof entry !== "object") return false;
|
|
4309
|
+
const e = entry;
|
|
4310
|
+
return typeof e.name === "string" && typeof e.files === "function";
|
|
4311
|
+
}
|
|
4312
|
+
//#endregion
|
|
4313
|
+
//#region src/generator-extension/dispatch.ts
|
|
4314
|
+
/**
|
|
4315
|
+
* Look up a plugin generator by name and run it. Returns `null` when
|
|
4316
|
+
* no plugin generator matches — callers can then fall through to the
|
|
4317
|
+
* built-in dispatch (module / scaffold / etc.).
|
|
4318
|
+
*
|
|
4319
|
+
* Resolution order:
|
|
4320
|
+
* 1. `additional` — generators sourced from `KickCliPlugin.generators`
|
|
4321
|
+
* via `kick.config.ts > plugins[]`. Authoritative; the canonical
|
|
4322
|
+
* path going forward.
|
|
4323
|
+
* 2. `package.json > kickjs.generators` discovery — first-match-wins
|
|
4324
|
+
* in dependency declaration order. Deprecated path retained for
|
|
4325
|
+
* packages that haven't migrated yet.
|
|
4326
|
+
*
|
|
4327
|
+
* Adopters with conflicts should rename the generator on their side or
|
|
4328
|
+
* pin one of the plugins to a different version.
|
|
4329
|
+
*/
|
|
4330
|
+
async function tryDispatchPluginGenerator(input, additional = []) {
|
|
4331
|
+
const cwd = input.cwd ?? process.cwd();
|
|
4332
|
+
const fromConfig = additional.find((g) => g.spec.name === input.generatorName);
|
|
4333
|
+
if (fromConfig) return runGenerator(fromConfig.spec, fromConfig.source, input, cwd);
|
|
4334
|
+
const match = findGenerator(await discoverPluginGenerators(cwd), input.generatorName);
|
|
4335
|
+
if (!match) return null;
|
|
4336
|
+
return runGenerator(match.spec, match.source, input, cwd);
|
|
4337
|
+
}
|
|
4338
|
+
/**
|
|
4339
|
+
* Public helper for `kick g --list` — returns every plugin generator
|
|
4340
|
+
* the CLI knows about, merging config-supplied entries on top of the
|
|
4341
|
+
* package.json discovery result. Config entries always come first.
|
|
4342
|
+
*/
|
|
4343
|
+
async function listPluginGenerators(cwd, additional = []) {
|
|
4344
|
+
const discovered = await discoverPluginGenerators(cwd);
|
|
4345
|
+
const configNames = new Set(additional.map((g) => g.spec.name));
|
|
4346
|
+
const filteredDiscovered = discovered.generators.filter((g) => !configNames.has(g.spec.name));
|
|
4347
|
+
return {
|
|
4348
|
+
generators: [...additional, ...filteredDiscovered],
|
|
4349
|
+
loaded: discovered.loaded,
|
|
4350
|
+
failed: discovered.failed
|
|
4351
|
+
};
|
|
4352
|
+
}
|
|
4353
|
+
function findGenerator(discovery, name) {
|
|
4354
|
+
return discovery.generators.find((g) => g.spec.name === name);
|
|
4355
|
+
}
|
|
4356
|
+
async function runGenerator(spec, source, input, cwd) {
|
|
4357
|
+
const ctx = buildGeneratorContext({
|
|
4358
|
+
name: input.itemName,
|
|
4359
|
+
args: input.args,
|
|
4360
|
+
flags: input.flags,
|
|
4361
|
+
modulesDir: input.modulesDir,
|
|
4362
|
+
pluralize: input.pluralize,
|
|
4363
|
+
cwd
|
|
4364
|
+
});
|
|
4365
|
+
const files = await spec.files(ctx);
|
|
4366
|
+
const written = [];
|
|
4367
|
+
for (const file of files) {
|
|
4368
|
+
const absPath = resolveGeneratorPath(ctx, file.path);
|
|
4369
|
+
await writeFileSafe(absPath, file.content);
|
|
4370
|
+
written.push(absPath);
|
|
4371
|
+
}
|
|
4372
|
+
return {
|
|
4373
|
+
files: written,
|
|
4374
|
+
source
|
|
4375
|
+
};
|
|
4376
|
+
}
|
|
4377
|
+
//#endregion
|
|
4378
|
+
export { httpMethodColor as A, intro as C, select as D, outro as E, writeFileSafe as F, severityColor as M, fileExists as N, spinner as O, setDryRun as P, confirm as S, multiSelect as T, pluralize as _, initProject as a, toKebabCase as b, generateKickJsSkills as c, generateService as d, generateGuard as f, resolveRepoType as g, generateModule as h, defineGenerator as i, pc as j, text as k, generateDto as l, generateAdapter as m, tryDispatchPluginGenerator as n, generateAgents as o, generateMiddleware as p, buildGeneratorContext as r, generateClaude as s, listPluginGenerators as t, generateController as u, pluralizePascal as v, log as w, toPascalCase as x, toCamelCase as y };
|
|
4379
|
+
|
|
4380
|
+
//# sourceMappingURL=generator-extension-DRNQpoZP.mjs.map
|