@getstrata/cli 2.2.47 → 2.2.49

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @getstrata/cli changelog
2
2
 
3
+ ## 2.2.49
4
+
5
+ - Align core/bootstrap requirements with the 2.2.49 compatible HTTP, model and runtime correction batch. Existing module generation and permission boundaries remain unchanged.
6
+ - Installing the CLI does not rewrite existing application-owned generated sources.
7
+
8
+ ## 2.2.48
9
+
10
+ - Separate pure module rendering from filesystem orchestration while retaining generated file paths and behavior.
11
+ - Preserve generated model-bound `id` request contracts through the existing generic kernel wrappers; remove four generated double casts and explicitly type show/delete requests. Existing generated application files are not rewritten by installing the new CLI.
12
+ - Align bootstrap/core peer requirements with 2.2.48.
13
+
3
14
  ## 2.2.47
4
15
 
5
16
  - Keep companion module API routes under API_PREFIX and HTML routes separate; render through the public namespaced ViewRenderer with layout data and HTMX handling. Plain module paths remain unchanged.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@getstrata/cli",
3
- "version": "2.2.47",
3
+ "version": "2.2.49",
4
4
  "description": "Strata CLI: framework commands for Bun apps (dev, start, migrate, run)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -54,8 +54,8 @@
54
54
  ],
55
55
  "scripts": {},
56
56
  "peerDependencies": {
57
- "@getstrata/bootstrap": "^2.2.47",
58
- "@getstrata/core": "^2.2.47"
57
+ "@getstrata/bootstrap": "^2.2.49",
58
+ "@getstrata/core": "^2.2.49"
59
59
  },
60
60
  "publishConfig": {
61
61
  "access": "public"
@@ -1,5 +1,6 @@
1
1
  import { access } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { renderModuleScaffold } from "./renderModule";
3
4
  import {
4
5
  ensureDirectory,
5
6
  moduleDirectory,
@@ -20,7 +21,6 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
20
21
  const moduleSlug = toKebabCase(name);
21
22
  const moduleName = toPascalCase(name);
22
23
  const moduleIdentifier = toCamelCase(name);
23
- const moduleVariable = `${moduleIdentifier}Module`;
24
24
 
25
25
  if (!moduleName || !moduleIdentifier || !moduleSlug) {
26
26
  throw new Error("make:module requires a valid module name.");
@@ -42,463 +42,13 @@ async function makeModuleCommand(...args: string[]): Promise<void> {
42
42
 
43
43
  await ensureDirectory(directory);
44
44
 
45
- const pluralSlug = `${moduleSlug}s`;
46
-
47
- const files = new Map<string, string>([
48
- [
49
- "types.ts",
50
- `interface ${moduleName}Record {
51
- id: number;
52
- name: string;
53
- }
54
-
55
- export type { ${moduleName}Record };
56
- `,
57
- ],
58
- [
59
- "table.ts",
60
- `import { defineTable } from "@getstrata/core/database/table";
61
- import type { ${moduleName}Record } from "./types";
62
-
63
- const ${moduleIdentifier}Table = defineTable<${moduleName}Record, "id">({
64
- name: "${moduleSlug}",
65
- primaryKey: "id",
66
- columns: ["id", "name"],
67
- defaultOrderBy: { column: "id", direction: "ASC" },
68
- });
69
-
70
- export { ${moduleIdentifier}Table };
71
- `,
72
- ],
73
- [
74
- "repository.ts",
75
- `import { BaseRepository } from "@getstrata/core/database/baseRepository";
76
- import { ${moduleIdentifier}Table } from "./table";
77
- import type { ${moduleName}Record } from "./types";
78
-
79
- class ${moduleName}Repository extends BaseRepository<${moduleName}Record, "id"> {
80
- constructor() {
81
- super(${moduleIdentifier}Table);
82
- }
83
- }
84
-
85
- export default ${moduleName}Repository;
86
- `,
87
- ],
88
- [
89
- "service.ts",
90
- `import { NotFoundError } from "@getstrata/core/errors/http";
91
- import ${moduleName}Repository from "./repository";
92
- import type { ${moduleName}Record } from "./types";
93
- import type { PaginatedResult } from "@getstrata/core/pagination";
94
-
95
- class ${moduleName}Service {
96
- constructor(private readonly repository: ${moduleName}Repository) {}
97
-
98
- paginate(options: {
99
- page: number;
100
- perPage: number;
101
- }): Promise<PaginatedResult<${moduleName}Record>> {
102
- return this.repository.paginate(options);
103
- }
104
-
105
- findByIdOrThrow(id: number): Promise<${moduleName}Record> {
106
- return this.repository.findByIdOrThrow(id, () => new NotFoundError("${moduleName} not found."));
107
- }
108
-
109
- create(input: { name: string }): Promise<${moduleName}Record> {
110
- return this.repository.create(input);
111
- }
112
-
113
- update(id: number, input: { name?: string }): Promise<${moduleName}Record> {
114
- return this.repository.updateByIdOrThrow(id, input, () => new NotFoundError("${moduleName} not found."));
115
- }
116
-
117
- async delete(id: number): Promise<void> {
118
- if (!(await this.repository.deleteById(id))) {
119
- throw new NotFoundError("${moduleName} not found.");
120
- }
121
- }
122
- }
123
-
124
- export default ${moduleName}Service;
125
- `,
126
- ],
127
- [
128
- "policy.ts",
129
- `import type { AuthUser } from "@getstrata/core/auth/authContext";
130
- import { Policy } from "@getstrata/core/auth/policy";
131
- import type { ${moduleName}Record } from "./types";
132
-
133
- class ${moduleName}Policy extends Policy {
134
- override create(_user: AuthUser | null): boolean {
135
- return true;
136
- }
137
-
138
- override update(_user: AuthUser | null, _resource: ${moduleName}Record): boolean {
139
- return true;
140
- }
141
-
142
- override delete(user: AuthUser | null, _resource: ${moduleName}Record): boolean {
143
- return user?.role === "admin" || user?.role === "member";
144
- }
145
- }
146
-
147
- export default ${moduleName}Policy;
148
- `,
149
- ],
150
- [
151
- "provider.ts",
152
- `import type { ServiceProvider } from "@getstrata/core/contracts/di";
153
- import { CORE_POLICY_GATE_TOKEN } from "@getstrata/bootstrap/config";
154
- import ${moduleName}Repository from "./repository";
155
- import ${moduleName}Service from "./service";
156
- import ${moduleName}Policy from "./policy";
157
-
158
- const ${moduleIdentifier}RepositoryToken = "${moduleSlug}.repository";
159
- const ${moduleIdentifier}ServiceToken = "${moduleSlug}.service";
160
- const ${moduleIdentifier}PolicyToken = "${moduleSlug}.policy";
161
-
162
- const ${moduleIdentifier}Provider: ServiceProvider = {
163
- name: "${moduleSlug}.provider",
164
- register({ container }) {
165
- container.singleton(${moduleIdentifier}RepositoryToken, () => new ${moduleName}Repository());
166
- container.singleton(${moduleIdentifier}PolicyToken, () => new ${moduleName}Policy());
167
- },
168
- boot({ container }) {
169
- container.singleton(${moduleIdentifier}ServiceToken, () => {
170
- const repository = container.resolve<${moduleName}Repository>(${moduleIdentifier}RepositoryToken);
171
- return new ${moduleName}Service(repository);
172
- });
173
-
174
- const gate = container.resolve<{ register: (resource: string, policy: unknown) => void }>(
175
- CORE_POLICY_GATE_TOKEN,
176
- );
177
- gate.register("${moduleSlug}", container.resolve(${moduleIdentifier}PolicyToken));
178
- },
179
- };
180
-
181
- export default ${moduleIdentifier}Provider;
182
- export {
183
- ${moduleIdentifier}PolicyToken,
184
- ${moduleIdentifier}RepositoryToken,
185
- ${moduleIdentifier}ServiceToken,
186
- };
187
- `,
188
- ],
189
- [
190
- "requests.ts",
191
- `import { parseJsonBody, parsePositiveIntParam } from "@getstrata/core/http/validation";
192
- import { parsePaginationQuery } from "@getstrata/core/http/pagination";
193
- import {
194
- maxLength,
195
- minLength,
196
- required,
197
- stringRule,
198
- validateObject,
199
- } from "@getstrata/core/validation/rules";
200
-
201
- type ${moduleName}IdParams = { id: string };
202
-
203
- interface ${moduleName}ListQueryDto {
204
- page: number;
205
- perPage: number;
206
- }
207
-
208
- interface Create${moduleName}BodyDto {
209
- name: string;
210
- }
211
-
212
- interface Update${moduleName}BodyDto {
213
- name?: string;
214
- }
215
-
216
- function parse${moduleName}IdParams(params: ${moduleName}IdParams): { id: number } {
217
- return {
218
- id: parsePositiveIntParam(params.id, "${moduleSlug} id"),
219
- };
220
- }
221
-
222
- function parse${moduleName}ListQuery(request?: Request): ${moduleName}ListQueryDto {
223
- return parsePaginationQuery(request);
224
- }
225
-
226
- async function parseCreate${moduleName}Body(
227
- request: Request,
228
- ): Promise<Create${moduleName}BodyDto> {
229
- return await parseJsonBody(request, (payload) => {
230
- const body = validateObject(payload, {
231
- name: [required(), stringRule(), minLength(1), maxLength(120)],
232
- });
233
-
234
- return {
235
- name: body.name as string,
236
- };
237
- });
238
- }
239
-
240
- async function parseUpdate${moduleName}Body(
241
- request: Request,
242
- ): Promise<Update${moduleName}BodyDto> {
243
- return await parseJsonBody(request, (payload) => {
244
- const body = validateObject(payload, {
245
- name: [stringRule(), minLength(1), maxLength(120)],
246
- });
247
-
248
- return {
249
- ...(body.name === undefined ? {} : { name: body.name as string }),
250
- };
251
- });
252
- }
253
-
254
- export {
255
- parseCreate${moduleName}Body,
256
- parse${moduleName}IdParams,
257
- parse${moduleName}ListQuery,
258
- parseUpdate${moduleName}Body,
259
- };
260
- export type {
261
- Create${moduleName}BodyDto,
262
- ${moduleName}IdParams,
263
- ${moduleName}ListQueryDto,
264
- Update${moduleName}BodyDto,
265
- };
266
- `,
267
- ],
268
- [
269
- "resources.ts",
270
- `import { toPaginatedResourceCollection, toResourceCollection } from "@getstrata/core/http/resources";
271
- import type { PaginationMeta } from "@getstrata/core/pagination";
272
- import type { ${moduleName}Record } from "./types";
273
-
274
- interface ${moduleName}Resource {
275
- id: number;
276
- name: string;
277
- }
278
-
279
- function to${moduleName}Resource(record: ${moduleName}Record): ${moduleName}Resource {
280
- return {
281
- id: record.id,
282
- name: record.name,
283
- };
284
- }
285
-
286
- function to${moduleName}ResourceCollection(
287
- records: readonly ${moduleName}Record[],
288
- ): ${moduleName}Resource[] {
289
- return toResourceCollection(records, to${moduleName}Resource);
290
- }
291
-
292
- function to${moduleName}PaginatedResourceCollection(
293
- records: readonly ${moduleName}Record[],
294
- meta: PaginationMeta,
295
- ) {
296
- return toPaginatedResourceCollection(records, meta, to${moduleName}Resource);
297
- }
298
-
299
- export {
300
- to${moduleName}PaginatedResourceCollection,
301
- to${moduleName}Resource,
302
- to${moduleName}ResourceCollection,
303
- };
304
- export type { ${moduleName}Resource };
305
- `,
306
- ],
307
- [
308
- "controller.ts",
309
- `import type { AppDependencies, CachedJson } from "@getstrata/core/contracts/di";
310
- import { resolveService } from "@getstrata/core/contracts/di";
311
- import { bindRouteModel } from "@getstrata/core/http/routeModelBinding";
312
- import { buildRequestCacheKey } from "@getstrata/core/http/validation";
313
- import { securedBindRouteModel } from "@getstrata/core/http/securedRouteModelBinding";
314
- import type { RouteRequest } from "@getstrata/core/http/route";
315
- import { createdResponse, jsonResponse, noContentResponse, withErrorHandling } from "@getstrata/core/http/response";
316
- import ${moduleName}Service from "./service";
317
- import { ${moduleIdentifier}ServiceToken } from "./provider";
318
- import {
319
- parseCreate${moduleName}Body,
320
- parse${moduleName}ListQuery,
321
- parseUpdate${moduleName}Body,
322
- type ${moduleName}IdParams,
323
- } from "./requests";
324
- import {
325
- to${moduleName}PaginatedResourceCollection,
326
- to${moduleName}Resource,
327
- } from "./resources";
328
-
329
- const ${moduleIdentifier.toUpperCase()}_CACHE_TAG = "${pluralSlug}";
330
-
331
- class ${moduleName}Controller {
332
- constructor(
333
- private readonly dependencies: AppDependencies,
334
- private readonly cachedJson: CachedJson,
335
- ) {}
336
-
337
- private get service(): ${moduleName}Service {
338
- return resolveService(this.dependencies, ${moduleIdentifier}ServiceToken);
339
- }
340
-
341
- readonly index = withErrorHandling(async (request?: Request) => {
342
- const query = parse${moduleName}ListQuery(request);
343
- const cacheKey = buildRequestCacheKey("/${pluralSlug}", request);
344
-
345
- return await this.cachedJson(
346
- cacheKey,
347
- async () => {
348
- const result = await this.service.paginate(query);
349
- return to${moduleName}PaginatedResourceCollection(result.data, result.meta);
350
- },
351
- [${moduleIdentifier.toUpperCase()}_CACHE_TAG],
352
- request,
353
- );
45
+ const { files, webFiles, viewFiles, pluralSlug } = renderModuleScaffold({
46
+ moduleSlug,
47
+ moduleName,
48
+ moduleIdentifier,
49
+ withWeb,
354
50
  });
355
51
 
356
- readonly show = withErrorHandling(
357
- bindRouteModel(
358
- "id",
359
- (id) => this.service.findByIdOrThrow(id),
360
- async (_request, record) => {
361
- return jsonResponse(to${moduleName}Resource(record));
362
- },
363
- ),
364
- );
365
-
366
- readonly store = withErrorHandling(async (request: Request) => {
367
- const body = await parseCreate${moduleName}Body(request);
368
- const record = await this.service.create(body);
369
- return createdResponse(to${moduleName}Resource(record));
370
- });
371
-
372
- readonly update = withErrorHandling(
373
- securedBindRouteModel(
374
- "id",
375
- (id) => this.service.findByIdOrThrow(id),
376
- { resource: "${moduleSlug}", action: "update" },
377
- async (req: RouteRequest<${moduleName}IdParams>, record) => {
378
- const body = await parseUpdate${moduleName}Body(req);
379
- const updated = await this.service.update(record.id, body);
380
- return jsonResponse(to${moduleName}Resource(updated));
381
- },
382
- ),
383
- );
384
-
385
- readonly destroy = withErrorHandling(
386
- securedBindRouteModel(
387
- "id",
388
- (id) => this.service.findByIdOrThrow(id),
389
- { resource: "${moduleSlug}", action: "delete" },
390
- async (_request, record) => {
391
- await this.service.delete(record.id);
392
- return noContentResponse();
393
- },
394
- ),
395
- );
396
- }
397
-
398
- export default ${moduleName}Controller;
399
- `,
400
- ],
401
- [
402
- "routes.ts",
403
- `import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
404
- import type { AppDependencies, CachedJson } from "@getstrata/core/contracts/di";
405
- import type { RouteHandler } from "@getstrata/core/http/middleware";
406
- ${withWeb ? 'import { apiPrefix } from "@getstrata/core/runtime/appKeyPrefix";\n' : ""}import ${moduleName}Controller from "./controller";
407
-
408
- function create${moduleName}Routes(
409
- dependencies: AppDependencies,
410
- cachedJson: CachedJson,
411
- kernel: HttpKernel,
412
- ) {
413
- const controller = new ${moduleName}Controller(dependencies, cachedJson);
414
- ${withWeb ? ` const apiBase = \`\${apiPrefix()}/${pluralSlug}\`;\n` : ""}
415
-
416
- return {
417
- ${withWeb ? "[apiBase]" : `"/${pluralSlug}"`}: {
418
- GET: controller.index,
419
- POST: kernel.wrapAbility(
420
- "${pluralSlug}:create",
421
- controller.store as unknown as RouteHandler,
422
- ),
423
- },
424
- ${withWeb ? `[\`\${apiBase}/:id\`]` : `"/${pluralSlug}/:id"`}: {
425
- GET: controller.show,
426
- PATCH: kernel.wrapAbility(
427
- "${pluralSlug}:update",
428
- controller.update as unknown as RouteHandler,
429
- ),
430
- DELETE: kernel.wrapAbility(
431
- "${pluralSlug}:delete",
432
- controller.destroy as unknown as RouteHandler,
433
- ),
434
- },
435
- };
436
- }
437
-
438
- export { create${moduleName}Routes };
439
- `,
440
- ],
441
- [
442
- "index.ts",
443
- `import { type AppModule } from "@getstrata/bootstrap/contracts";
444
- import ${moduleName}Controller from "./controller";
445
- import ${moduleIdentifier}Provider, {
446
- ${moduleIdentifier}RepositoryToken,
447
- ${moduleIdentifier}ServiceToken,
448
- } from "./provider";
449
- import { create${moduleName}Routes } from "./routes";${
450
- withWeb
451
- ? `
452
- import { create${moduleName}WebRoutes } from "./webRoutes";`
453
- : ""
454
- }
455
- import { ${moduleIdentifier}Table } from "./table";
456
-
457
- const ${moduleVariable}: AppModule = {
458
- name: "${moduleSlug}",
459
- order: 100,
460
- tableName: ${moduleIdentifier}Table.name,
461
- cacheTags: ["${pluralSlug}"],
462
- providers: [${moduleIdentifier}Provider],
463
- routes({ dependencies, cachedJson, kernel }) {
464
- return create${moduleName}Routes(dependencies, cachedJson, kernel);
465
- },${
466
- withWeb
467
- ? `
468
- webRoutes({ dependencies, kernel }) {
469
- return create${moduleName}WebRoutes(dependencies, kernel);
470
- },`
471
- : ""
472
- }
473
- };
474
-
475
- export default ${moduleVariable};
476
- export {
477
- ${moduleIdentifier}Provider,
478
- ${moduleIdentifier}RepositoryToken,
479
- ${moduleIdentifier}ServiceToken,
480
- };
481
- export { ${moduleName}Controller };
482
- export { parse${moduleName}IdParams, parse${moduleName}ListQuery } from "./requests";
483
- export {
484
- to${moduleName}PaginatedResourceCollection,
485
- to${moduleName}Resource,
486
- to${moduleName}ResourceCollection,
487
- } from "./resources";
488
- export { create${moduleName}Routes } from "./routes";${
489
- withWeb
490
- ? `
491
- export { create${moduleName}WebRoutes } from "./webRoutes";`
492
- : ""
493
- }
494
- export { default as ${moduleName}Repository } from "./repository";
495
- export { default as ${moduleName}Service } from "./service";
496
- export { ${moduleIdentifier}Table } from "./table";
497
- export type { ${moduleName}Record } from "./types";
498
- `,
499
- ],
500
- ]);
501
-
502
52
  for (const [fileName, content] of files) {
503
53
  await Bun.write(join(directory, fileName), content);
504
54
  }
@@ -509,74 +59,12 @@ export type { ${moduleName}Record } from "./types";
509
59
  const viewsDirectory = webViewsDirectory(pluralSlug);
510
60
  createdViewsDirectory = viewsDirectory;
511
61
  await ensureDirectory(viewsDirectory);
512
- await Bun.write(
513
- join(viewsDirectory, "index.eta"),
514
- `<section class="page-header">
515
- <h1>${moduleName}s</h1>
516
- </section>
517
-
518
- <p class="hint">Generated web view for ${pluralSlug}. Wire up ${moduleName}WebController next.</p>
519
- `,
520
- );
521
-
522
- await Bun.write(
523
- join(directory, "webController.ts"),
524
- `import type { AppDependencies } from "@getstrata/core/contracts/di";
525
- import { resolveService } from "@getstrata/core/contracts/di";
526
- import { withErrorHandling } from "@getstrata/core/http/response";
527
- import { CORE_VIEW_RENDERER_TOKEN, type NamespacedViewRenderer } from "@getstrata/core/view";
528
- import { ${moduleIdentifier}ServiceToken } from "./provider";
529
- import { parse${moduleName}ListQuery } from "./requests";
530
- import type ${moduleName}Service from "./service";
531
-
532
- class ${moduleName}WebController {
533
- constructor(private readonly dependencies: AppDependencies) {}
534
-
535
- private get service(): ${moduleName}Service {
536
- return resolveService(this.dependencies, ${moduleIdentifier}ServiceToken);
537
- }
538
-
539
- private get views(): NamespacedViewRenderer {
540
- return resolveService(this.dependencies, CORE_VIEW_RENDERER_TOKEN).namespace("${pluralSlug}");
541
- }
542
-
543
- readonly index = withErrorHandling(async (request?: Request) => {
544
- const query = parse${moduleName}ListQuery(request);
545
- const result = await this.service.paginate(query);
546
-
547
- return this.views.renderHtmx("index.eta", {
548
- layout: { title: "${moduleName}s" },
549
- records: result.data,
550
- meta: result.meta,
551
- }, { request },
552
- );
553
- });
554
- }
555
-
556
- export default ${moduleName}WebController;
557
- `,
558
- );
559
-
560
- await Bun.write(
561
- join(directory, "webRoutes.ts"),
562
- `import type { AppDependencies } from "@getstrata/core/contracts/di";
563
- import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
564
- import type { RouteHandler } from "@getstrata/core/http/middleware";
565
- import ${moduleName}WebController from "./webController";
566
-
567
- function create${moduleName}WebRoutes(dependencies: AppDependencies, kernel: HttpKernel) {
568
- const controller = new ${moduleName}WebController(dependencies);
569
-
570
- return {
571
- "/${pluralSlug}": {
572
- GET: kernel.wrapWebPublicRead(controller.index as unknown as RouteHandler),
573
- },
574
- };
575
- }
576
-
577
- export { create${moduleName}WebRoutes };
578
- `,
579
- );
62
+ for (const [fileName, content] of viewFiles) {
63
+ await Bun.write(join(viewsDirectory, fileName), content);
64
+ }
65
+ for (const [fileName, content] of webFiles) {
66
+ await Bun.write(join(directory, fileName), content);
67
+ }
580
68
  }
581
69
 
582
70
  console.log(`Created module scaffold in: ${directory}`);
@@ -0,0 +1,548 @@
1
+ type ModuleRenderOptions = {
2
+ moduleSlug: string;
3
+ moduleName: string;
4
+ moduleIdentifier: string;
5
+ withWeb: boolean;
6
+ };
7
+
8
+ /** Render module sources without consulting or changing the application filesystem. */
9
+ function renderModuleScaffold({
10
+ moduleSlug,
11
+ moduleName,
12
+ moduleIdentifier,
13
+ withWeb,
14
+ }: ModuleRenderOptions) {
15
+ const moduleVariable = `${moduleIdentifier}Module`;
16
+ const pluralSlug = `${moduleSlug}s`;
17
+
18
+ const files = new Map<string, string>([
19
+ [
20
+ "types.ts",
21
+ `interface ${moduleName}Record {
22
+ id: number;
23
+ name: string;
24
+ }
25
+
26
+ export type { ${moduleName}Record };
27
+ `,
28
+ ],
29
+ [
30
+ "table.ts",
31
+ `import { defineTable } from "@getstrata/core/database/table";
32
+ import type { ${moduleName}Record } from "./types";
33
+
34
+ const ${moduleIdentifier}Table = defineTable<${moduleName}Record, "id">({
35
+ name: "${moduleSlug}",
36
+ primaryKey: "id",
37
+ columns: ["id", "name"],
38
+ defaultOrderBy: { column: "id", direction: "ASC" },
39
+ });
40
+
41
+ export { ${moduleIdentifier}Table };
42
+ `,
43
+ ],
44
+ [
45
+ "repository.ts",
46
+ `import { BaseRepository } from "@getstrata/core/database/baseRepository";
47
+ import { ${moduleIdentifier}Table } from "./table";
48
+ import type { ${moduleName}Record } from "./types";
49
+
50
+ class ${moduleName}Repository extends BaseRepository<${moduleName}Record, "id"> {
51
+ constructor() {
52
+ super(${moduleIdentifier}Table);
53
+ }
54
+ }
55
+
56
+ export default ${moduleName}Repository;
57
+ `,
58
+ ],
59
+ [
60
+ "service.ts",
61
+ `import { NotFoundError } from "@getstrata/core/errors/http";
62
+ import ${moduleName}Repository from "./repository";
63
+ import type { ${moduleName}Record } from "./types";
64
+ import type { PaginatedResult } from "@getstrata/core/pagination";
65
+
66
+ class ${moduleName}Service {
67
+ constructor(private readonly repository: ${moduleName}Repository) {}
68
+
69
+ paginate(options: {
70
+ page: number;
71
+ perPage: number;
72
+ }): Promise<PaginatedResult<${moduleName}Record>> {
73
+ return this.repository.paginate(options);
74
+ }
75
+
76
+ findByIdOrThrow(id: number): Promise<${moduleName}Record> {
77
+ return this.repository.findByIdOrThrow(id, () => new NotFoundError("${moduleName} not found."));
78
+ }
79
+
80
+ create(input: { name: string }): Promise<${moduleName}Record> {
81
+ return this.repository.create(input);
82
+ }
83
+
84
+ update(id: number, input: { name?: string }): Promise<${moduleName}Record> {
85
+ return this.repository.updateByIdOrThrow(id, input, () => new NotFoundError("${moduleName} not found."));
86
+ }
87
+
88
+ async delete(id: number): Promise<void> {
89
+ if (!(await this.repository.deleteById(id))) {
90
+ throw new NotFoundError("${moduleName} not found.");
91
+ }
92
+ }
93
+ }
94
+
95
+ export default ${moduleName}Service;
96
+ `,
97
+ ],
98
+ [
99
+ "policy.ts",
100
+ `import type { AuthUser } from "@getstrata/core/auth/authContext";
101
+ import { Policy } from "@getstrata/core/auth/policy";
102
+ import type { ${moduleName}Record } from "./types";
103
+
104
+ class ${moduleName}Policy extends Policy {
105
+ override create(_user: AuthUser | null): boolean {
106
+ return true;
107
+ }
108
+
109
+ override update(_user: AuthUser | null, _resource: ${moduleName}Record): boolean {
110
+ return true;
111
+ }
112
+
113
+ override delete(user: AuthUser | null, _resource: ${moduleName}Record): boolean {
114
+ return user?.role === "admin" || user?.role === "member";
115
+ }
116
+ }
117
+
118
+ export default ${moduleName}Policy;
119
+ `,
120
+ ],
121
+ [
122
+ "provider.ts",
123
+ `import type { ServiceProvider } from "@getstrata/core/contracts/di";
124
+ import { CORE_POLICY_GATE_TOKEN } from "@getstrata/bootstrap/config";
125
+ import ${moduleName}Repository from "./repository";
126
+ import ${moduleName}Service from "./service";
127
+ import ${moduleName}Policy from "./policy";
128
+
129
+ const ${moduleIdentifier}RepositoryToken = "${moduleSlug}.repository";
130
+ const ${moduleIdentifier}ServiceToken = "${moduleSlug}.service";
131
+ const ${moduleIdentifier}PolicyToken = "${moduleSlug}.policy";
132
+
133
+ const ${moduleIdentifier}Provider: ServiceProvider = {
134
+ name: "${moduleSlug}.provider",
135
+ register({ container }) {
136
+ container.singleton(${moduleIdentifier}RepositoryToken, () => new ${moduleName}Repository());
137
+ container.singleton(${moduleIdentifier}PolicyToken, () => new ${moduleName}Policy());
138
+ },
139
+ boot({ container }) {
140
+ container.singleton(${moduleIdentifier}ServiceToken, () => {
141
+ const repository = container.resolve<${moduleName}Repository>(${moduleIdentifier}RepositoryToken);
142
+ return new ${moduleName}Service(repository);
143
+ });
144
+
145
+ const gate = container.resolve<{ register: (resource: string, policy: unknown) => void }>(
146
+ CORE_POLICY_GATE_TOKEN,
147
+ );
148
+ gate.register("${moduleSlug}", container.resolve(${moduleIdentifier}PolicyToken));
149
+ },
150
+ };
151
+
152
+ export default ${moduleIdentifier}Provider;
153
+ export {
154
+ ${moduleIdentifier}PolicyToken,
155
+ ${moduleIdentifier}RepositoryToken,
156
+ ${moduleIdentifier}ServiceToken,
157
+ };
158
+ `,
159
+ ],
160
+ [
161
+ "requests.ts",
162
+ `import { parseJsonBody, parsePositiveIntParam } from "@getstrata/core/http/validation";
163
+ import { parsePaginationQuery } from "@getstrata/core/http/pagination";
164
+ import {
165
+ maxLength,
166
+ minLength,
167
+ required,
168
+ stringRule,
169
+ validateObject,
170
+ } from "@getstrata/core/validation/rules";
171
+
172
+ type ${moduleName}IdParams = { id: string };
173
+
174
+ interface ${moduleName}ListQueryDto {
175
+ page: number;
176
+ perPage: number;
177
+ }
178
+
179
+ interface Create${moduleName}BodyDto {
180
+ name: string;
181
+ }
182
+
183
+ interface Update${moduleName}BodyDto {
184
+ name?: string;
185
+ }
186
+
187
+ function parse${moduleName}IdParams(params: ${moduleName}IdParams): { id: number } {
188
+ return {
189
+ id: parsePositiveIntParam(params.id, "${moduleSlug} id"),
190
+ };
191
+ }
192
+
193
+ function parse${moduleName}ListQuery(request?: Request): ${moduleName}ListQueryDto {
194
+ return parsePaginationQuery(request);
195
+ }
196
+
197
+ async function parseCreate${moduleName}Body(
198
+ request: Request,
199
+ ): Promise<Create${moduleName}BodyDto> {
200
+ return await parseJsonBody(request, (payload) => {
201
+ const body = validateObject(payload, {
202
+ name: [required(), stringRule(), minLength(1), maxLength(120)],
203
+ });
204
+
205
+ return {
206
+ name: body.name as string,
207
+ };
208
+ });
209
+ }
210
+
211
+ async function parseUpdate${moduleName}Body(
212
+ request: Request,
213
+ ): Promise<Update${moduleName}BodyDto> {
214
+ return await parseJsonBody(request, (payload) => {
215
+ const body = validateObject(payload, {
216
+ name: [stringRule(), minLength(1), maxLength(120)],
217
+ });
218
+
219
+ return {
220
+ ...(body.name === undefined ? {} : { name: body.name as string }),
221
+ };
222
+ });
223
+ }
224
+
225
+ export {
226
+ parseCreate${moduleName}Body,
227
+ parse${moduleName}IdParams,
228
+ parse${moduleName}ListQuery,
229
+ parseUpdate${moduleName}Body,
230
+ };
231
+ export type {
232
+ Create${moduleName}BodyDto,
233
+ ${moduleName}IdParams,
234
+ ${moduleName}ListQueryDto,
235
+ Update${moduleName}BodyDto,
236
+ };
237
+ `,
238
+ ],
239
+ [
240
+ "resources.ts",
241
+ `import { toPaginatedResourceCollection, toResourceCollection } from "@getstrata/core/http/resources";
242
+ import type { PaginationMeta } from "@getstrata/core/pagination";
243
+ import type { ${moduleName}Record } from "./types";
244
+
245
+ interface ${moduleName}Resource {
246
+ id: number;
247
+ name: string;
248
+ }
249
+
250
+ function to${moduleName}Resource(record: ${moduleName}Record): ${moduleName}Resource {
251
+ return {
252
+ id: record.id,
253
+ name: record.name,
254
+ };
255
+ }
256
+
257
+ function to${moduleName}ResourceCollection(
258
+ records: readonly ${moduleName}Record[],
259
+ ): ${moduleName}Resource[] {
260
+ return toResourceCollection(records, to${moduleName}Resource);
261
+ }
262
+
263
+ function to${moduleName}PaginatedResourceCollection(
264
+ records: readonly ${moduleName}Record[],
265
+ meta: PaginationMeta,
266
+ ) {
267
+ return toPaginatedResourceCollection(records, meta, to${moduleName}Resource);
268
+ }
269
+
270
+ export {
271
+ to${moduleName}PaginatedResourceCollection,
272
+ to${moduleName}Resource,
273
+ to${moduleName}ResourceCollection,
274
+ };
275
+ export type { ${moduleName}Resource };
276
+ `,
277
+ ],
278
+ [
279
+ "controller.ts",
280
+ `import type { AppDependencies, CachedJson } from "@getstrata/core/contracts/di";
281
+ import { resolveService } from "@getstrata/core/contracts/di";
282
+ import { bindRouteModel } from "@getstrata/core/http/routeModelBinding";
283
+ import { buildRequestCacheKey } from "@getstrata/core/http/validation";
284
+ import { securedBindRouteModel } from "@getstrata/core/http/securedRouteModelBinding";
285
+ import type { RouteRequest } from "@getstrata/core/http/route";
286
+ import { createdResponse, jsonResponse, noContentResponse, withErrorHandling } from "@getstrata/core/http/response";
287
+ import ${moduleName}Service from "./service";
288
+ import { ${moduleIdentifier}ServiceToken } from "./provider";
289
+ import {
290
+ parseCreate${moduleName}Body,
291
+ parse${moduleName}ListQuery,
292
+ parseUpdate${moduleName}Body,
293
+ type ${moduleName}IdParams,
294
+ } from "./requests";
295
+ import {
296
+ to${moduleName}PaginatedResourceCollection,
297
+ to${moduleName}Resource,
298
+ } from "./resources";
299
+
300
+ const ${moduleIdentifier.toUpperCase()}_CACHE_TAG = "${pluralSlug}";
301
+
302
+ class ${moduleName}Controller {
303
+ constructor(
304
+ private readonly dependencies: AppDependencies,
305
+ private readonly cachedJson: CachedJson,
306
+ ) {}
307
+
308
+ private get service(): ${moduleName}Service {
309
+ return resolveService(this.dependencies, ${moduleIdentifier}ServiceToken);
310
+ }
311
+
312
+ readonly index = withErrorHandling(async (request?: Request) => {
313
+ const query = parse${moduleName}ListQuery(request);
314
+ const cacheKey = buildRequestCacheKey("/${pluralSlug}", request);
315
+
316
+ return await this.cachedJson(
317
+ cacheKey,
318
+ async () => {
319
+ const result = await this.service.paginate(query);
320
+ return to${moduleName}PaginatedResourceCollection(result.data, result.meta);
321
+ },
322
+ [${moduleIdentifier.toUpperCase()}_CACHE_TAG],
323
+ request,
324
+ );
325
+ });
326
+
327
+ readonly show = withErrorHandling(
328
+ bindRouteModel(
329
+ "id",
330
+ (id) => this.service.findByIdOrThrow(id),
331
+ async (_request: RouteRequest<${moduleName}IdParams>, record) => {
332
+ return jsonResponse(to${moduleName}Resource(record));
333
+ },
334
+ ),
335
+ );
336
+
337
+ readonly store = withErrorHandling(async (request: Request) => {
338
+ const body = await parseCreate${moduleName}Body(request);
339
+ const record = await this.service.create(body);
340
+ return createdResponse(to${moduleName}Resource(record));
341
+ });
342
+
343
+ readonly update = withErrorHandling(
344
+ securedBindRouteModel(
345
+ "id",
346
+ (id) => this.service.findByIdOrThrow(id),
347
+ { resource: "${moduleSlug}", action: "update" },
348
+ async (req: RouteRequest<${moduleName}IdParams>, record) => {
349
+ const body = await parseUpdate${moduleName}Body(req);
350
+ const updated = await this.service.update(record.id, body);
351
+ return jsonResponse(to${moduleName}Resource(updated));
352
+ },
353
+ ),
354
+ );
355
+
356
+ readonly destroy = withErrorHandling(
357
+ securedBindRouteModel(
358
+ "id",
359
+ (id) => this.service.findByIdOrThrow(id),
360
+ { resource: "${moduleSlug}", action: "delete" },
361
+ async (_request: RouteRequest<${moduleName}IdParams>, record) => {
362
+ await this.service.delete(record.id);
363
+ return noContentResponse();
364
+ },
365
+ ),
366
+ );
367
+ }
368
+
369
+ export default ${moduleName}Controller;
370
+ `,
371
+ ],
372
+ [
373
+ "routes.ts",
374
+ `import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
375
+ import type { AppDependencies, CachedJson } from "@getstrata/core/contracts/di";
376
+ ${withWeb ? 'import { apiPrefix } from "@getstrata/core/runtime/appKeyPrefix";\n' : ""}import ${moduleName}Controller from "./controller";
377
+
378
+ function create${moduleName}Routes(
379
+ dependencies: AppDependencies,
380
+ cachedJson: CachedJson,
381
+ kernel: HttpKernel,
382
+ ) {
383
+ const controller = new ${moduleName}Controller(dependencies, cachedJson);
384
+ ${withWeb ? ` const apiBase = \`\${apiPrefix()}/${pluralSlug}\`;\n` : ""}
385
+
386
+ return {
387
+ ${withWeb ? "[apiBase]" : `"/${pluralSlug}"`}: {
388
+ GET: controller.index,
389
+ POST: kernel.wrapAbility(
390
+ "${pluralSlug}:create",
391
+ controller.store,
392
+ ),
393
+ },
394
+ ${withWeb ? `[\`\${apiBase}/:id\`]` : `"/${pluralSlug}/:id"`}: {
395
+ GET: controller.show,
396
+ PATCH: kernel.wrapAbility(
397
+ "${pluralSlug}:update",
398
+ controller.update,
399
+ ),
400
+ DELETE: kernel.wrapAbility(
401
+ "${pluralSlug}:delete",
402
+ controller.destroy,
403
+ ),
404
+ },
405
+ };
406
+ }
407
+
408
+ export { create${moduleName}Routes };
409
+ `,
410
+ ],
411
+ [
412
+ "index.ts",
413
+ `import { type AppModule } from "@getstrata/bootstrap/contracts";
414
+ import ${moduleName}Controller from "./controller";
415
+ import ${moduleIdentifier}Provider, {
416
+ ${moduleIdentifier}RepositoryToken,
417
+ ${moduleIdentifier}ServiceToken,
418
+ } from "./provider";
419
+ import { create${moduleName}Routes } from "./routes";${
420
+ withWeb
421
+ ? `
422
+ import { create${moduleName}WebRoutes } from "./webRoutes";`
423
+ : ""
424
+ }
425
+ import { ${moduleIdentifier}Table } from "./table";
426
+
427
+ const ${moduleVariable}: AppModule = {
428
+ name: "${moduleSlug}",
429
+ order: 100,
430
+ tableName: ${moduleIdentifier}Table.name,
431
+ cacheTags: ["${pluralSlug}"],
432
+ providers: [${moduleIdentifier}Provider],
433
+ routes({ dependencies, cachedJson, kernel }) {
434
+ return create${moduleName}Routes(dependencies, cachedJson, kernel);
435
+ },${
436
+ withWeb
437
+ ? `
438
+ webRoutes({ dependencies, kernel }) {
439
+ return create${moduleName}WebRoutes(dependencies, kernel);
440
+ },`
441
+ : ""
442
+ }
443
+ };
444
+
445
+ export default ${moduleVariable};
446
+ export {
447
+ ${moduleIdentifier}Provider,
448
+ ${moduleIdentifier}RepositoryToken,
449
+ ${moduleIdentifier}ServiceToken,
450
+ };
451
+ export { ${moduleName}Controller };
452
+ export { parse${moduleName}IdParams, parse${moduleName}ListQuery } from "./requests";
453
+ export {
454
+ to${moduleName}PaginatedResourceCollection,
455
+ to${moduleName}Resource,
456
+ to${moduleName}ResourceCollection,
457
+ } from "./resources";
458
+ export { create${moduleName}Routes } from "./routes";${
459
+ withWeb
460
+ ? `
461
+ export { create${moduleName}WebRoutes } from "./webRoutes";`
462
+ : ""
463
+ }
464
+ export { default as ${moduleName}Repository } from "./repository";
465
+ export { default as ${moduleName}Service } from "./service";
466
+ export { ${moduleIdentifier}Table } from "./table";
467
+ export type { ${moduleName}Record } from "./types";
468
+ `,
469
+ ],
470
+ ]);
471
+
472
+ const webFiles = new Map<string, string>();
473
+ const viewFiles = new Map<string, string>();
474
+
475
+ if (withWeb) {
476
+ viewFiles.set(
477
+ "index.eta",
478
+ `<section class="page-header">
479
+ <h1>${moduleName}s</h1>
480
+ </section>
481
+
482
+ <p class="hint">Generated web view for ${pluralSlug}. Wire up ${moduleName}WebController next.</p>
483
+ `,
484
+ );
485
+
486
+ webFiles.set(
487
+ "webController.ts",
488
+ `import type { AppDependencies } from "@getstrata/core/contracts/di";
489
+ import { resolveService } from "@getstrata/core/contracts/di";
490
+ import { withErrorHandling } from "@getstrata/core/http/response";
491
+ import { CORE_VIEW_RENDERER_TOKEN, type NamespacedViewRenderer } from "@getstrata/core/view";
492
+ import { ${moduleIdentifier}ServiceToken } from "./provider";
493
+ import { parse${moduleName}ListQuery } from "./requests";
494
+ import type ${moduleName}Service from "./service";
495
+
496
+ class ${moduleName}WebController {
497
+ constructor(private readonly dependencies: AppDependencies) {}
498
+
499
+ private get service(): ${moduleName}Service {
500
+ return resolveService(this.dependencies, ${moduleIdentifier}ServiceToken);
501
+ }
502
+
503
+ private get views(): NamespacedViewRenderer {
504
+ return resolveService(this.dependencies, CORE_VIEW_RENDERER_TOKEN).namespace("${pluralSlug}");
505
+ }
506
+
507
+ readonly index = withErrorHandling(async (request?: Request) => {
508
+ const query = parse${moduleName}ListQuery(request);
509
+ const result = await this.service.paginate(query);
510
+
511
+ return this.views.renderHtmx("index.eta", {
512
+ layout: { title: "${moduleName}s" },
513
+ records: result.data,
514
+ meta: result.meta,
515
+ }, { request },
516
+ );
517
+ });
518
+ }
519
+
520
+ export default ${moduleName}WebController;
521
+ `,
522
+ );
523
+
524
+ webFiles.set(
525
+ "webRoutes.ts",
526
+ `import type { AppDependencies } from "@getstrata/core/contracts/di";
527
+ import type { HttpKernel } from "@getstrata/bootstrap/httpKernel";
528
+ import ${moduleName}WebController from "./webController";
529
+
530
+ function create${moduleName}WebRoutes(dependencies: AppDependencies, kernel: HttpKernel) {
531
+ const controller = new ${moduleName}WebController(dependencies);
532
+
533
+ return {
534
+ "/${pluralSlug}": {
535
+ GET: kernel.wrapWebPublicRead(controller.index),
536
+ },
537
+ };
538
+ }
539
+
540
+ export { create${moduleName}WebRoutes };
541
+ `,
542
+ );
543
+ }
544
+
545
+ return { files, webFiles, viewFiles, pluralSlug };
546
+ }
547
+
548
+ export { renderModuleScaffold };