@sdxc/kit 2026.10.17 → 2026.10.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +390 -20
  2. package/changelog.jsonl +1160 -1092
  3. package/config.schema.json +47 -1
  4. package/dist/cli.js +12 -0
  5. package/dist/commands/deploy.d.ts +23 -0
  6. package/dist/commands/deploy.js +167 -0
  7. package/dist/commands/destroy.d.ts +22 -0
  8. package/dist/commands/destroy.js +92 -0
  9. package/dist/commands/doctor.d.ts +26 -0
  10. package/dist/commands/doctor.js +65 -0
  11. package/dist/commands/initializers.d.ts +16 -0
  12. package/dist/commands/initializers.js +23 -0
  13. package/dist/commands/make.d.ts +72 -6
  14. package/dist/commands/make.js +127 -19
  15. package/dist/commands/middleware.d.ts +16 -0
  16. package/dist/commands/middleware.js +21 -0
  17. package/dist/commands/models.d.ts +18 -0
  18. package/dist/commands/models.js +29 -0
  19. package/dist/commands/notes.d.ts +17 -0
  20. package/dist/commands/notes.js +27 -0
  21. package/dist/commands/routes.d.ts +25 -0
  22. package/dist/commands/routes.js +50 -0
  23. package/dist/commands/run.d.ts +16 -0
  24. package/dist/commands/run.js +32 -11
  25. package/dist/commands/scaffold.d.ts +29 -0
  26. package/dist/commands/scaffold.js +33 -0
  27. package/dist/commands/schedule.d.ts +16 -0
  28. package/dist/commands/schedule.js +21 -0
  29. package/dist/commands/stats.d.ts +16 -0
  30. package/dist/commands/stats.js +21 -0
  31. package/dist/commands/ui/update.d.ts +6 -3
  32. package/dist/commands/ui/update.js +24 -7
  33. package/dist/commands/upgrade.d.ts +3 -1
  34. package/dist/commands/upgrade.js +88 -23
  35. package/dist/config.d.ts +18 -0
  36. package/dist/config.js +28 -1
  37. package/dist/contract.d.ts +97 -3
  38. package/dist/contract.js +360 -26
  39. package/dist/create/templates.js +3 -2
  40. package/dist/dependencies.d.ts +4 -1
  41. package/dist/dependencies.js +13 -1
  42. package/dist/deploy/plan.d.ts +49 -0
  43. package/dist/deploy/plan.js +68 -0
  44. package/dist/destroy.d.ts +40 -0
  45. package/dist/destroy.js +311 -0
  46. package/dist/doctor/check.d.ts +71 -0
  47. package/dist/doctor/check.js +53 -0
  48. package/dist/doctor/checks.d.ts +23 -0
  49. package/dist/doctor/checks.js +68 -0
  50. package/dist/doctor/define.d.ts +59 -0
  51. package/dist/doctor/define.js +16 -0
  52. package/dist/doctor/emails.d.ts +18 -0
  53. package/dist/doctor/emails.js +243 -0
  54. package/dist/doctor/env.d.ts +26 -0
  55. package/dist/doctor/env.js +88 -0
  56. package/dist/doctor/files.d.ts +14 -0
  57. package/dist/doctor/files.js +34 -0
  58. package/dist/doctor/fixture.d.ts +23 -0
  59. package/dist/doctor/fixture.js +46 -0
  60. package/dist/doctor/install.d.ts +17 -0
  61. package/dist/doctor/install.js +37 -0
  62. package/dist/doctor/installed.d.ts +11 -0
  63. package/dist/doctor/installed.js +79 -0
  64. package/dist/doctor/layout.d.ts +23 -0
  65. package/dist/doctor/layout.js +83 -0
  66. package/dist/doctor/migrations.d.ts +16 -0
  67. package/dist/doctor/migrations.js +96 -0
  68. package/dist/doctor/models.d.ts +13 -0
  69. package/dist/doctor/models.js +69 -0
  70. package/dist/doctor/pins.d.ts +15 -0
  71. package/dist/doctor/pins.js +79 -0
  72. package/dist/doctor/project.d.ts +58 -0
  73. package/dist/doctor/project.js +261 -0
  74. package/dist/doctor/remix.d.ts +14 -0
  75. package/dist/doctor/remix.js +44 -0
  76. package/dist/doctor/routes.d.ts +11 -0
  77. package/dist/doctor/routes.js +49 -0
  78. package/dist/doctor/typegen.d.ts +13 -0
  79. package/dist/doctor/typegen.js +57 -0
  80. package/dist/doctor/ui.d.ts +14 -0
  81. package/dist/doctor/ui.js +51 -0
  82. package/dist/initializers.d.ts +25 -0
  83. package/dist/initializers.js +89 -0
  84. package/dist/lock.d.ts +2 -2
  85. package/dist/make/actions.d.ts +23 -0
  86. package/dist/make/actions.js +82 -0
  87. package/dist/make/declare.d.ts +31 -3
  88. package/dist/make/declare.js +284 -9
  89. package/dist/make/email.d.ts +23 -0
  90. package/dist/make/email.js +111 -0
  91. package/dist/make/from-fields.d.ts +30 -0
  92. package/dist/make/from-fields.js +162 -0
  93. package/dist/make/from-model.d.ts +39 -0
  94. package/dist/make/from-model.js +161 -0
  95. package/dist/make/generate.d.ts +16 -5
  96. package/dist/make/generate.js +38 -15
  97. package/dist/make/guard.d.ts +35 -0
  98. package/dist/make/guard.js +73 -0
  99. package/dist/make/imports.d.ts +6 -0
  100. package/dist/make/imports.js +19 -0
  101. package/dist/make/index.d.ts +47 -4
  102. package/dist/make/index.js +287 -29
  103. package/dist/make/kinds.d.ts +29 -2
  104. package/dist/make/kinds.js +79 -7
  105. package/dist/make/mount.d.ts +25 -0
  106. package/dist/make/mount.js +135 -0
  107. package/dist/make/schema-diff.d.ts +58 -0
  108. package/dist/make/schema-diff.js +609 -0
  109. package/dist/make/schema.d.ts +76 -0
  110. package/dist/make/schema.js +206 -0
  111. package/dist/make/stubs.d.ts +7 -5
  112. package/dist/make/stubs.js +16 -5
  113. package/dist/make/test.d.ts +43 -0
  114. package/dist/make/test.js +149 -0
  115. package/dist/make/trigger.d.ts +31 -0
  116. package/dist/make/trigger.js +163 -0
  117. package/dist/models.d.ts +42 -0
  118. package/dist/models.js +149 -0
  119. package/dist/notes.d.ts +28 -0
  120. package/dist/notes.js +66 -0
  121. package/dist/reference.d.ts +27 -0
  122. package/dist/reference.js +103 -0
  123. package/dist/releases.d.ts +9 -0
  124. package/dist/releases.js +29 -8
  125. package/dist/routes/chains.d.ts +34 -0
  126. package/dist/routes/chains.js +95 -0
  127. package/dist/routes/filter.d.ts +53 -0
  128. package/dist/routes/filter.js +147 -0
  129. package/dist/routes/format.d.ts +23 -0
  130. package/dist/routes/format.js +123 -0
  131. package/dist/routes/helpers.d.ts +21 -0
  132. package/dist/routes/helpers.js +165 -0
  133. package/dist/routes/index.d.ts +56 -0
  134. package/dist/routes/index.js +167 -0
  135. package/dist/routes/modules.d.ts +116 -0
  136. package/dist/routes/modules.js +235 -0
  137. package/dist/routes/parse.d.ts +161 -0
  138. package/dist/routes/parse.js +621 -0
  139. package/dist/routes/routers.d.ts +69 -0
  140. package/dist/routes/routers.js +327 -0
  141. package/dist/scaffold/fields.d.ts +129 -0
  142. package/dist/scaffold/fields.js +421 -0
  143. package/dist/scaffold/index.d.ts +37 -0
  144. package/dist/scaffold/index.js +613 -0
  145. package/dist/scaffold/render.d.ts +51 -0
  146. package/dist/scaffold/render.js +332 -0
  147. package/dist/schedule.d.ts +45 -0
  148. package/dist/schedule.js +124 -0
  149. package/dist/stats.d.ts +37 -0
  150. package/dist/stats.js +126 -0
  151. package/dist/ui/commands.d.ts +10 -3
  152. package/dist/ui/commands.js +85 -15
  153. package/dist/ui/registry.d.ts +8 -8
  154. package/dist/upgrade/agents.d.ts +49 -0
  155. package/dist/upgrade/agents.js +110 -0
  156. package/dist/upgrade/changelog.d.ts +2 -2
  157. package/dist/upgrade/project.d.ts +4 -0
  158. package/dist/upgrade/project.js +11 -1
  159. package/dist/upgrade/prompt.d.ts +11 -0
  160. package/dist/upgrade/prompt.js +50 -7
  161. package/package.json +6 -4
  162. package/registry/ui/alert-dialog.json +2 -2
  163. package/registry/ui/attachment.json +2 -2
  164. package/registry/ui/calendar.json +2 -2
  165. package/registry/ui/color-picker.json +2 -2
  166. package/registry/ui/command.json +2 -2
  167. package/registry/ui/date-picker.json +2 -2
  168. package/registry/ui/date-range-picker.json +2 -2
  169. package/registry/ui/dialog.json +2 -2
  170. package/registry/ui/file-trigger.json +2 -2
  171. package/registry/ui/heading-scope.json +2 -2
  172. package/registry/ui/message-scroller.json +2 -2
  173. package/registry/ui/number-field.json +2 -2
  174. package/registry/ui/range-calendar.json +2 -2
  175. package/registry/ui/resizable.json +2 -2
  176. package/registry/ui/select.json +2 -2
  177. package/registry/ui/shared-element.json +2 -2
  178. package/stubs/controller.api.resource.stub +23 -0
  179. package/stubs/controller.form.stub +2 -2
  180. package/stubs/controller.form.test.stub +2 -2
  181. package/stubs/controller.resource.form.stub +67 -0
  182. package/stubs/controller.resource.stub +28 -0
  183. package/stubs/email.stub +9 -14
  184. package/stubs/email.test.stub +9 -9
  185. package/stubs/factory.stub +1 -1
  186. package/stubs/model.stub +3 -3
  187. package/stubs/policy.test.stub +34 -8
  188. package/stubs/scaffold.api.create.stub +34 -0
  189. package/stubs/scaffold.api.create.test.stub +37 -0
  190. package/stubs/scaffold.api.destroy.stub +34 -0
  191. package/stubs/scaffold.api.destroy.test.stub +44 -0
  192. package/stubs/scaffold.api.index.stub +23 -0
  193. package/stubs/scaffold.api.index.test.stub +31 -0
  194. package/stubs/scaffold.api.show.stub +27 -0
  195. package/stubs/scaffold.api.show.test.stub +41 -0
  196. package/stubs/scaffold.api.update.stub +44 -0
  197. package/stubs/scaffold.api.update.test.stub +46 -0
  198. package/stubs/scaffold.command.create.stub +22 -0
  199. package/stubs/scaffold.command.create.test.stub +30 -0
  200. package/stubs/scaffold.command.delete.stub +20 -0
  201. package/stubs/scaffold.command.delete.test.stub +39 -0
  202. package/stubs/scaffold.command.list.stub +18 -0
  203. package/stubs/scaffold.command.list.test.stub +31 -0
  204. package/stubs/scaffold.command.show.stub +19 -0
  205. package/stubs/scaffold.command.show.test.stub +37 -0
  206. package/stubs/scaffold.controller.destroy.stub +35 -0
  207. package/stubs/scaffold.controller.destroy.test.stub +65 -0
  208. package/stubs/scaffold.controller.edit.stub +97 -0
  209. package/stubs/scaffold.controller.edit.test.stub +91 -0
  210. package/stubs/scaffold.controller.index.stub +55 -0
  211. package/stubs/scaffold.controller.index.test.stub +32 -0
  212. package/stubs/scaffold.controller.new.stub +70 -0
  213. package/stubs/scaffold.controller.new.test.stub +81 -0
  214. package/stubs/scaffold.controller.show.stub +59 -0
  215. package/stubs/scaffold.controller.show.test.stub +43 -0
  216. package/stubs/scaffold.factory.stub +16 -0
  217. package/stubs/scaffold.form.stub +75 -0
  218. package/stubs/scaffold.mcp.create.stub +24 -0
  219. package/stubs/scaffold.mcp.create.test.stub +36 -0
  220. package/stubs/scaffold.mcp.delete.stub +31 -0
  221. package/stubs/scaffold.mcp.delete.test.stub +43 -0
  222. package/stubs/scaffold.mcp.get.stub +21 -0
  223. package/stubs/scaffold.mcp.get.test.stub +31 -0
  224. package/stubs/scaffold.mcp.list.stub +23 -0
  225. package/stubs/scaffold.mcp.list.test.stub +25 -0
  226. package/stubs/scaffold.mcp.update.stub +37 -0
  227. package/stubs/scaffold.mcp.update.test.stub +40 -0
  228. package/stubs/scaffold.migration.stub +2 -0
  229. package/stubs/scaffold.model.stub +35 -0
  230. package/stubs/scaffold.model.test.stub +25 -0
  231. package/stubs/scaffold.test-database.stub +33 -0
  232. package/stubs/scaffold.test-mcp.stub +92 -0
  233. package/stubs/scaffold.validator.stub +18 -0
  234. package/stubs/scaffold.validator.test.stub +26 -0
  235. package/templates/app/AGENTS.md +163 -0
  236. package/templates/app/CLAUDE.md +1 -0
  237. package/templates/app/README.md +28 -13
  238. package/templates/app/app/commands/console.test.ts +26 -0
  239. package/templates/app/app/commands/console.ts +19 -0
  240. package/templates/app/app/commands/db/fresh.test.ts +57 -0
  241. package/templates/app/app/commands/db/fresh.ts +37 -0
  242. package/templates/app/app/commands/db/migrate.test.ts +17 -1
  243. package/templates/app/app/commands/db/migrate.ts +51 -18
  244. package/templates/app/app/commands/db/prepare.test.ts +39 -0
  245. package/templates/app/app/commands/db/prepare.ts +35 -0
  246. package/templates/app/app/commands/db/seed.test.ts +38 -0
  247. package/templates/app/app/commands/db/seed.ts +26 -0
  248. package/templates/app/app/commands/deploy.test.ts +34 -0
  249. package/templates/app/app/commands/deploy.ts +18 -0
  250. package/templates/app/app/commands/emails/preview.test.tsx +63 -0
  251. package/templates/app/app/commands/emails/preview.ts +24 -0
  252. package/templates/app/app/commands/index.ts +57 -2
  253. package/templates/app/app/emails/index.ts +10 -0
  254. package/templates/app/app/http/middleware/access.test.ts +43 -0
  255. package/templates/app/app/http/middleware/access.ts +41 -0
  256. package/templates/app/app/http/middleware/api.ts +12 -3
  257. package/templates/app/app/http/middleware/page.test.ts +4 -1
  258. package/templates/app/app/http/middleware/page.ts +7 -5
  259. package/templates/app/app/initializers/cli.ts +28 -2
  260. package/templates/app/app/initializers/dispatcher.ts +9 -1
  261. package/templates/app/app/initializers/mail-transport.test.ts +27 -0
  262. package/templates/app/app/initializers/mail-transport.ts +26 -0
  263. package/templates/app/app/initializers/mail.test.ts +17 -17
  264. package/templates/app/app/initializers/mail.ts +15 -7
  265. package/templates/app/app/initializers/router.test.ts +7 -0
  266. package/templates/app/app/initializers/router.tsx +13 -3
  267. package/templates/app/app/jobs/email.test.tsx +70 -0
  268. package/templates/app/app/jobs/email.ts +16 -0
  269. package/templates/app/app/jobs/index.ts +6 -2
  270. package/templates/app/app/policies/abilities.ts +13 -0
  271. package/templates/app/app/policies/policy.test.ts +15 -0
  272. package/templates/app/app/policies/policy.ts +30 -0
  273. package/templates/app/app/services/commands.ts +30 -0
  274. package/templates/app/app/services/migrations.test.ts +48 -1
  275. package/templates/app/app/services/migrations.ts +66 -9
  276. package/templates/app/app/test/local-database.ts +67 -0
  277. package/templates/app/app/test/session.ts +28 -0
  278. package/templates/app/bootstrap/console.ts +13 -0
  279. package/templates/app/cloudflare.config.ts +3 -3
  280. package/templates/app/database/seed.ts +12 -0
  281. package/templates/app/package.json +2 -1
  282. package/stubs/policy.stub +0 -16
@@ -28,6 +28,12 @@ export type ImportKind = {
28
28
  * after the last import, joining an existing named import list of `specifier` when there is one.
29
29
  */
30
30
  export declare function ensureImport(filename: string, source: string, what: ImportKind, matches: (specifier: string) => boolean, specifier: string, preferred: string): Result<Imported, Error>;
31
+ /**
32
+ * `source` importing the type `name` from `specifier`. An existing binding of it, as a type or a
33
+ * value, is reused under its local name; otherwise `import type { … }` is added after the last
34
+ * import, since a declaration that only names the type keeps the module out of the bundle.
35
+ */
36
+ export declare function ensureTypeImport(filename: string, source: string, name: string, specifier: string): Result<Imported, Error>;
31
37
  /**
32
38
  * Whether `specifier`, written in `fromFile`, names the module at `target`: through the `~/`
33
39
  * alias or a relative path, with or without an extension or a trailing `/index`. Both paths
@@ -47,6 +47,25 @@ export function ensureImport(filename, source, what, matches, specifier, preferr
47
47
  let statement = `import ${clause} from ${literal(specifier)};`;
48
48
  return success({ source: insertImport(source, references.data, statement), local });
49
49
  }
50
+ /**
51
+ * `source` importing the type `name` from `specifier`. An existing binding of it, as a type or a
52
+ * value, is reused under its local name; otherwise `import type { … }` is added after the last
53
+ * import, since a declaration that only names the type keeps the module out of the bundle.
54
+ */
55
+ export function ensureTypeImport(filename, source, name, specifier) {
56
+ let references = findModuleReferences(filename, source);
57
+ if (isFailure(references))
58
+ return references;
59
+ for (let reference of references.data) {
60
+ if (reference.kind !== "import" || reference.specifier !== specifier)
61
+ continue;
62
+ let bound = reference.names.find((each) => each.imported === name);
63
+ if (bound !== undefined)
64
+ return success({ source, local: bound.local });
65
+ }
66
+ let statement = `import type { ${name} } from ${literal(specifier)};`;
67
+ return success({ source: insertImport(source, references.data, statement), local: name });
68
+ }
50
69
  /** Whether a bound import name is the kind of binding `what` asks for. */
51
70
  function bindsAs(imported, what) {
52
71
  if (what.kind === "namespace")
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * What one `sdxc make <kind>` run does: writes a file of the kind from its stub at the folder
3
- * the app layout gives it, with a test beside it, declares and maps it where the kind needs it,
4
- * lists any `@sdxc/*` package it imports in `package.json`, and runs the project's `format`.
5
- * Every file is planned before any is written, and none is ever overwritten.
3
+ * the app layout gives it, with a test beside it, declares and maps it where the kind needs it
4
+ * (a policy's abilities and grants included), lists any `@sdxc/*` package it imports in
5
+ * `package.json`, and runs the project's `format`.
6
+ * Every file is planned before any is written, and none is overwritten unless `--force` asks
7
+ * to replace the file and its test, which keeps the declarations they already have.
6
8
  *
7
9
  * @author [Sergio Xalambrí](https://sergiodxa.com)
8
10
  * @copyright Sergio Xalambrí 2026
@@ -10,7 +12,8 @@
10
12
  import type { AnyCommandContext } from "@sdxc/cli";
11
13
  import type { Result } from "@sdxc/result";
12
14
  import type { Project } from "../middleware.js";
13
- import type { KindName } from "./kinds.js";
15
+ import type { ResourceAction } from "./guard.js";
16
+ import type { KindName, ModelCompanion } from "./kinds.js";
14
17
  /** One file to make, as the command line or the prompts gave it. */
15
18
  export interface MakeInput {
16
19
  kind: KindName;
@@ -26,10 +29,31 @@ export interface MakeInput {
26
29
  path?: string | undefined;
27
30
  /** `make controller`: the route contract in `routes/`; `undefined` takes `make.routes`. */
28
31
  routes?: string | undefined;
32
+ /** `make controller`: the resource whose ability the method implies guards every handler. */
33
+ guardedBy?: string | undefined;
34
+ /** `make controller --actions`: the ability to check instead of the one the method implies. */
35
+ ability?: ResourceAction | undefined;
29
36
  /** `make mcp`: a resource instead of a tool. */
30
37
  resource?: boolean | undefined;
31
38
  /** `make migration`: the chain in `make.migrations`. */
32
39
  chain?: string | undefined;
40
+ /** `make migration`: the model whose tables the migration brings the chain in step with. */
41
+ fromModel?: string | undefined;
42
+ /** `make middleware`: the router initializer or chain module to call it last in. */
43
+ mount?: string | undefined;
44
+ /**
45
+ * `make model`: each field as `sdxc scaffold` takes it, written as a column, a factory value
46
+ * and a column of its migration. `make migration`: the columns its name adds or drops.
47
+ * `make email`: the props its schema declares and its template renders.
48
+ */
49
+ fields?: readonly string[] | undefined;
50
+ /** `make model`: the companions to leave out. */
51
+ skip?: readonly ModelCompanion[] | undefined;
52
+ /**
53
+ * Replace the file and its test when they exist. A file that existed keeps its declaration,
54
+ * mapping and mount, and an existing model keeps its migrations.
55
+ */
56
+ force?: boolean | undefined;
33
57
  }
34
58
  /** What `make` writes through: the command's output, child processes and tasks. */
35
59
  export type MakeContext = Pick<AnyCommandContext, "stdout" | "exec" | "task">;
@@ -41,3 +65,22 @@ export type MakeContext = Pick<AnyCommandContext, "stdout" | "exec" | "task">;
41
65
  * @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
42
66
  */
43
67
  export declare function make(ctx: MakeContext, project: Project, packageRoot: string, input: MakeInput): Promise<Result<void, Error>>;
68
+ /** What a run wrote and edited, and the notes it prints once the files are formatted. */
69
+ export interface Made {
70
+ changed: string[];
71
+ /**
72
+ * Each edit left for the user to make and each piece left out, printed after the formatter's
73
+ * own output, so a long run ends with what still needs the user.
74
+ */
75
+ notes: string[];
76
+ }
77
+ /** Formats every changed path once, then prints the notes, which end the run's output. */
78
+ export declare function finish(ctx: MakeContext, project: Project, made: Made): Promise<Result<void, Error>>;
79
+ /**
80
+ * {@link make} up to the project's `format` and its notes, which the caller runs and prints
81
+ * once with {@link finish}, so a command making several files formats them together.
82
+ *
83
+ * @returns Every path written or edited and the notes to print; none of either under `dryRun`,
84
+ * which prints its notes itself
85
+ */
86
+ export declare function makeUnformatted(ctx: MakeContext, project: Project, packageRoot: string, input: MakeInput): Promise<Result<Made, Error>>;
@@ -1,23 +1,34 @@
1
1
  /**
2
2
  * What one `sdxc make <kind>` run does: writes a file of the kind from its stub at the folder
3
- * the app layout gives it, with a test beside it, declares and maps it where the kind needs it,
4
- * lists any `@sdxc/*` package it imports in `package.json`, and runs the project's `format`.
5
- * Every file is planned before any is written, and none is ever overwritten.
3
+ * the app layout gives it, with a test beside it, declares and maps it where the kind needs it
4
+ * (a policy's abilities and grants included), lists any `@sdxc/*` package it imports in
5
+ * `package.json`, and runs the project's `format`.
6
+ * Every file is planned before any is written, and none is overwritten unless `--force` asks
7
+ * to replace the file and its test, which keeps the declarations they already have.
6
8
  *
7
9
  * @author [Sergio Xalambrí](https://sergiodxa.com)
8
10
  * @copyright Sergio Xalambrí 2026
9
11
  */
10
12
  import { mkdir, writeFile } from "node:fs/promises";
11
13
  import { dirname, join } from "node:path";
12
- import { isFailure, success, wrap } from "@sdxc/result";
14
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
13
15
  import { missingDependencies } from "../dependencies.js";
14
16
  import { unifiedDiff } from "../diff.js";
15
17
  import { formatFiles } from "../format.js";
16
18
  import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
19
+ import { columnSource, factorySource, parseFields, pluralize, resolveReferences, } from "../scaffold/fields.js";
17
20
  import { readManifest } from "../upgrade/project.js";
18
- import { declare } from "./declare.js";
19
- import { folderOf, plan, resourceScheme } from "./generate.js";
20
- import { parseName } from "./names.js";
21
+ import { declare, declaresAbilities, findRow } from "./declare.js";
22
+ import { planEmail } from "./email.js";
23
+ import { fieldMigration } from "./from-fields.js";
24
+ import { modelMigration } from "./from-model.js";
25
+ import { exists, folderOf, plan, resourceScheme } from "./generate.js";
26
+ import { planGuard } from "./guard.js";
27
+ import { KINDS } from "./kinds.js";
28
+ import { chainFolder } from "./migrations.js";
29
+ import { mount } from "./mount.js";
30
+ import { camel, parseName } from "./names.js";
31
+ import { planTrigger } from "./trigger.js";
21
32
  /**
22
33
  * Plans, writes, declares and formats one file of `input.kind`, printing each path written and
23
34
  * edited and each package added with the install command; under `dryRun` it prints the files
@@ -26,26 +37,92 @@ import { parseName } from "./names.js";
26
37
  * @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
27
38
  */
28
39
  export async function make(ctx, project, packageRoot, input) {
40
+ let made = await makeUnformatted(ctx, project, packageRoot, input);
41
+ if (isFailure(made))
42
+ return made;
43
+ return finish(ctx, project, made.data);
44
+ }
45
+ /** Formats every changed path once, then prints the notes, which end the run's output. */
46
+ export async function finish(ctx, project, made) {
47
+ let formatted = made.changed.length === 0
48
+ ? success(undefined)
49
+ : await formatFiles(ctx, project.config.format, made.changed, project.root);
50
+ for (let note of made.notes)
51
+ ctx.stdout(note);
52
+ return formatted;
53
+ }
54
+ /**
55
+ * {@link make} up to the project's `format` and its notes, which the caller runs and prints
56
+ * once with {@link finish}, so a command making several files formats them together.
57
+ *
58
+ * @returns Every path written or edited and the notes to print; none of either under `dryRun`,
59
+ * which prints its notes itself
60
+ */
61
+ export async function makeUnformatted(ctx, project, packageRoot, input) {
29
62
  let { root, config } = project;
30
63
  let { kind } = input;
31
64
  let name = parseName(input.name);
32
65
  if (isFailure(name))
33
66
  return name;
34
67
  let method = input.method ?? "get";
68
+ let pattern = input.path;
69
+ let overrides = {};
70
+ let notes = [];
71
+ if (kind === "controller" && input.guardedBy !== undefined) {
72
+ let resource = parseName(input.guardedBy);
73
+ if (isFailure(resource))
74
+ return resource;
75
+ let model = (await findRow(root, resource.data)) !== null;
76
+ let guard = planGuard(name.data, resource.data, method, pattern, model, input.ability);
77
+ if (isFailure(guard))
78
+ return guard;
79
+ pattern = guard.data.pattern;
80
+ overrides.ability = guard.data.ability;
81
+ overrides.access = guard.data.access;
82
+ overrides.pageAccess = guard.data.pageAccess;
83
+ if (!(await declaresAbilities(root, guard.data.catalogPath))) {
84
+ notes.push(`app/policies/abilities.ts declares no ${guard.data.catalogPath.join(".")} abilities yet; run sdxc make policy ${resource.data.segments.join("/")} so ${guard.data.ability} exists\n`);
85
+ }
86
+ }
87
+ if (kind === "controller") {
88
+ let names = [...(pattern ?? "").matchAll(/:(\w+)/g)].map((match) => match[1]);
89
+ if (names.length > 0) {
90
+ overrides.params = "ctx.params";
91
+ overrides.sampleParams = `{ ${names.map((param) => `${param}: "1"`).join(", ")} }`;
92
+ }
93
+ }
35
94
  let request = {
36
95
  kind,
37
96
  name: name.data,
38
- variant: variantOf(kind, { cron: input.cron, method, resource: input.resource }),
97
+ variant: variantOf(kind, {
98
+ cron: input.cron,
99
+ method,
100
+ resource: input.resource,
101
+ guarded: input.guardedBy !== undefined,
102
+ }),
39
103
  tests: input.test ?? config.make.tests,
40
104
  chain: input.chain,
41
105
  routes: input.routes ?? config.make.routes,
106
+ replace: input.force === true,
42
107
  };
108
+ let replacing = input.force === true && (await existsAlready(root, request));
109
+ if (replacing) {
110
+ notes.push(`Kept the declaration, mapping and mount ${request.name.segments.join("/")} already has; --force replaces files only\n`);
111
+ }
112
+ let email = kind === "email" ? planEmail(input.fields ?? [], name.data) : null;
113
+ if (email !== null && isFailure(email))
114
+ return email;
115
+ if (email !== null)
116
+ Object.assign(overrides, email.data.placeholders);
43
117
  let declared = null;
44
- if (kind === "job" ||
45
- kind === "controller" ||
46
- kind === "mcp" ||
47
- kind === "command" ||
48
- kind === "model") {
118
+ if (!replacing &&
119
+ (kind === "job" ||
120
+ kind === "controller" ||
121
+ kind === "mcp" ||
122
+ kind === "command" ||
123
+ kind === "model" ||
124
+ kind === "policy" ||
125
+ kind === "email")) {
49
126
  let segments = request.name.segments;
50
127
  declared = await declare({
51
128
  kind,
@@ -53,19 +130,100 @@ export async function make(ctx, project, packageRoot, input) {
53
130
  variant: request.variant,
54
131
  cron: input.cron,
55
132
  method,
56
- pattern: input.path,
133
+ pattern,
57
134
  routes: request.routes,
58
135
  handler: `${folderOf(kind, request.variant)}/${segments.join("/")}`,
59
136
  tool: segments.map((segment) => segment.replaceAll("-", "_")).join("_"),
60
137
  uri: `${await resourceScheme(root)}://${segments.join("/")}`,
61
138
  title: request.name.title,
139
+ options: email === null
140
+ ? undefined
141
+ : { imports: ["s"], lines: ({ s = "s" }) => email.data.declaration(s) },
62
142
  }, root);
63
143
  }
64
- let overrides = declared === null ? {} : { path: declared.path };
144
+ if (declared !== null)
145
+ overrides.path = declared.path;
146
+ let columns = null;
147
+ let fields = [];
148
+ let table = pluralize(name.data.snake);
149
+ if (kind === "model") {
150
+ let parsed = parseFields(input.fields ?? []);
151
+ if (isFailure(parsed))
152
+ return parsed;
153
+ fields = await resolveReferences(root, parsed.data);
154
+ columns = modelColumns(fields, table);
155
+ overrides.columns = columns;
156
+ overrides.table = table;
157
+ }
158
+ if (kind === "middleware" && input.mount !== undefined && !replacing) {
159
+ let handler = `${folderOf(kind, null)}/${request.name.segments.join("/")}`;
160
+ let mounted = await mount({ name: request.name, target: input.mount, handler }, root);
161
+ if (isFailure(mounted))
162
+ return mounted;
163
+ declared = mounted.data;
164
+ }
165
+ let migrationSql = null;
166
+ let specs = input.fields ?? [];
167
+ if (kind === "migration" && input.fromModel !== undefined && specs.length > 0) {
168
+ return failure(new Error("--from-model writes the columns the model declares; give the fields or --from-model, not both"));
169
+ }
170
+ if (kind === "migration" && input.fromModel !== undefined) {
171
+ let sql = await modelMigration(ctx, project, input.fromModel, input.chain, request.name);
172
+ if (isFailure(sql))
173
+ return sql;
174
+ if (sql.data === null)
175
+ return success({ changed: [], notes: [] });
176
+ migrationSql = sql.data;
177
+ }
178
+ if (kind === "migration" && specs.length > 0) {
179
+ let folder = chainFolder(config.make.migrations, input.chain);
180
+ if (isFailure(folder))
181
+ return folder;
182
+ let sql = await fieldMigration(root, folder.data, request.name, specs);
183
+ if (isFailure(sql))
184
+ return sql;
185
+ migrationSql = sql.data;
186
+ }
65
187
  let planned = await plan(request, root, config, packageRoot, overrides);
66
188
  if (isFailure(planned))
67
189
  return planned;
190
+ let model = planned.data.files[0];
191
+ if (columns !== null && (input.fields ?? []).length > 0 && !model?.content.includes(columns)) {
192
+ return failure(new Error(`The model stub has no {{columns}} placeholder, so its fields have nowhere to go; add it inside the table's columns`));
193
+ }
194
+ if (migrationSql !== null) {
195
+ let content = migrationSql;
196
+ planned.data.files = planned.data.files.map((file) => ({ ...file, content }));
197
+ }
198
+ if (kind === "model") {
199
+ let companions = await modelCompanions(project, packageRoot, {
200
+ request,
201
+ fields,
202
+ specs,
203
+ table: tableOf(model?.content) ?? table,
204
+ chain: input.chain,
205
+ skip: replacing ? [...(input.skip ?? []), "migration"] : (input.skip ?? []),
206
+ });
207
+ if (isFailure(companions))
208
+ return companions;
209
+ planned.data.files.push(...companions.data.files);
210
+ notes.push(...companions.data.notes);
211
+ let skipped = (input.skip ?? []).filter((companion) => companion !== "migration" || !replacing);
212
+ if (skipped.length > 0) {
213
+ notes.push(`Wrote no ${skipped.join(" or ")}, as --skip asked\n`);
214
+ }
215
+ if (replacing && !(input.skip ?? []).includes("migration")) {
216
+ notes.push(`Wrote no migration, since the model existed; add its new columns with sdxc make migration add-<columns>-to-${tableOf(model?.content) ?? table}\n`);
217
+ }
218
+ }
68
219
  let edits = declared?.kind === "edits" ? [...declared.edits] : [];
220
+ if (kind === "job" && input.cron !== undefined && !replacing) {
221
+ let trigger = await planTrigger(root, input.cron);
222
+ if (trigger.edit !== null)
223
+ edits.push(trigger.edit);
224
+ if (trigger.note !== null)
225
+ notes.push(trigger.note);
226
+ }
69
227
  let dependencies = await missingDependencies(root, [
70
228
  ...planned.data.files,
71
229
  ...edits.map((edit) => ({ path: edit.path, content: edit.after })),
@@ -81,15 +239,22 @@ export async function make(ctx, project, packageRoot, input) {
81
239
  for (let edit of edits)
82
240
  ctx.stdout(unifiedDiff(edit.path, edit.before, edit.after));
83
241
  if (declared?.kind === "manual")
84
- ctx.stdout(manualNote(declared));
85
- return success(undefined);
242
+ ctx.stdout(manualNote(kind, declared));
243
+ for (let note of notes)
244
+ ctx.stdout(note);
245
+ return success({ changed: [], notes: [] });
246
+ }
247
+ let replaced = new Set();
248
+ for (let file of planned.data.files) {
249
+ if (await exists(root, file.path))
250
+ replaced.add(file.path);
86
251
  }
87
- let written = await writeFiles(root, planned.data.files);
252
+ let written = await writeFiles(root, planned.data.files, input.force === true);
88
253
  if (isFailure(written))
89
254
  return written;
90
255
  let paths = planned.data.files.map((file) => file.path);
91
256
  for (let path of paths)
92
- ctx.stdout(`Wrote ${path}\n`);
257
+ ctx.stdout(`${replaced.has(path) ? "Replaced" : "Wrote"} ${path}\n`);
93
258
  let edited = await wrap(async () => {
94
259
  for (let edit of edits)
95
260
  await writeFile(join(root, edit.path), edit.after);
@@ -109,32 +274,125 @@ export async function make(ctx, project, packageRoot, input) {
109
274
  let added = dependencies.data.added.map(({ name, version }) => `${name}@${version}`);
110
275
  ctx.stdout(`Added ${added.join(", ")} to package.json; run ${manager.install.join(" ")}\n`);
111
276
  }
112
- if (declared?.kind === "manual")
113
- ctx.stdout(manualNote(declared));
277
+ let printed = declared?.kind === "manual" ? [manualNote(kind, declared), ...notes] : notes;
114
278
  let changed = [...paths, ...edits.map((edit) => edit.path)];
115
- return formatFiles(ctx, config.format, changed, root);
279
+ return success({ changed, notes: printed });
116
280
  }
117
- /** What `make` prints when a declaration and its mapping are left for the user to make. */
118
- function manualNote(declared) {
119
- return `Declare and map it by hand, since ${declared.reason}:\n${declared.instructions}\n`;
281
+ /**
282
+ * What `make` prints when a declaration and its mapping, or a middleware's mount, are left for
283
+ * the user to make.
284
+ */
285
+ function manualNote(kind, declared) {
286
+ let action = kind === "middleware" ? "Mount it" : "Declare and map it";
287
+ return `${action} by hand, since ${declared.reason}:\n${declared.instructions}\n`;
120
288
  }
121
- /** The stub variant a request's flags select, or `null` for the kind's own stub. */
289
+ /**
290
+ * The stub variant a request's flags select, or `null` for the kind's own stub. A controller
291
+ * guarded by a resource's abilities takes `resource`, or `resource.form` for a form.
292
+ */
122
293
  function variantOf(kind, flags) {
123
294
  if (kind === "job" && flags.cron !== undefined)
124
295
  return "cron";
296
+ if (kind === "controller" && flags.guarded) {
297
+ return flags.method === "form" ? "resource.form" : "resource";
298
+ }
125
299
  if (kind === "controller" && flags.method === "form")
126
300
  return "form";
127
301
  if (kind === "mcp" && flags.resource === true)
128
302
  return "resource";
129
303
  return null;
130
304
  }
131
- /** Writes every planned file, creating its folders; an existing file fails the write. */
132
- function writeFiles(root, files) {
305
+ /**
306
+ * The column lines `{{columns}}` renders in a model stub: one per field, inside a table named
307
+ * `table`, or a reminder to add them when the command line named none.
308
+ */
309
+ function modelColumns(fields, table) {
310
+ if (fields.length === 0)
311
+ return "\t\t// TODO: add the columns the migration creates";
312
+ return fields.map((field) => `\t\t${field.column}: ${columnSource(field, table)},`).join("\n");
313
+ }
314
+ /**
315
+ * The migration that creates the model's table, named `create-<table>`, and the factory with a
316
+ * value per field, each unless skipped, planned so an existing file stops the run before any
317
+ * write. A required reference has no value a factory can make up, which a note says.
318
+ */
319
+ async function modelCompanions(project, packageRoot, companion) {
320
+ let { root, config } = project;
321
+ let { request, fields, table } = companion;
322
+ let files = [];
323
+ let notes = [];
324
+ if (!companion.skip.includes("migration")) {
325
+ let name = parseName(`create-${table}`);
326
+ if (isFailure(name))
327
+ return name;
328
+ let folder = chainFolder(config.make.migrations, companion.chain);
329
+ if (isFailure(folder))
330
+ return folder;
331
+ let sql = await fieldMigration(root, folder.data, name.data, companion.specs);
332
+ if (isFailure(sql))
333
+ return sql;
334
+ let migration = await plan({
335
+ ...request,
336
+ kind: "migration",
337
+ name: name.data,
338
+ variant: null,
339
+ tests: false,
340
+ chain: companion.chain,
341
+ }, root, config, packageRoot);
342
+ if (isFailure(migration))
343
+ return migration;
344
+ files.push(...migration.data.files.map((file) => ({ ...file, content: sql.data })));
345
+ }
346
+ if (!companion.skip.includes("factory")) {
347
+ let values = fields.flatMap((field) => {
348
+ let source = factorySource(field);
349
+ return source === null ? [] : [`\t${field.column}: ${source},`];
350
+ });
351
+ let attributes = values.length === 0 ? "" : `\n${values.join("\n")}\n`;
352
+ let factory = await plan({ ...request, kind: "factory", variant: null, tests: false }, root, config, packageRoot, { attributes });
353
+ if (isFailure(factory))
354
+ return factory;
355
+ let [file] = factory.data.files;
356
+ if (attributes !== "" && file !== undefined && !file.content.includes(attributes)) {
357
+ return failure(new Error("The factory stub has no {{attributes}} placeholder, so its fields have nowhere to go; add it as defineFactory's second argument, or pass --skip factory"));
358
+ }
359
+ files.push(...factory.data.files);
360
+ let omitted = fields.filter((field) => factorySource(field) === null);
361
+ for (let field of omitted) {
362
+ notes.push(`${file?.path ?? "The factory"} leaves ${field.column} out, since only a test knows which row it points at; pass it when creating one\n`);
363
+ }
364
+ }
365
+ return success({ files, notes });
366
+ }
367
+ /** The table name a model's source declares, or `null` when it declares none. */
368
+ function tableOf(source) {
369
+ return /\btable\(\s*\{\s*name:\s*["']([^"']+)["']/.exec(source ?? "")?.[1] ?? null;
370
+ }
371
+ /**
372
+ * Writes every planned file, creating its folders; an existing file fails the write unless
373
+ * `replace` lets it be overwritten.
374
+ */
375
+ function writeFiles(root, files, replace) {
133
376
  return wrap(async () => {
134
377
  for (let file of files) {
135
378
  let target = join(root, file.path);
136
379
  await mkdir(dirname(target), { recursive: true });
137
- await writeFile(target, file.content, { flag: "wx" });
380
+ await writeFile(target, file.content, { flag: replace ? "w" : "wx" });
138
381
  }
139
382
  });
140
383
  }
384
+ /**
385
+ * Whether what `request` names exists already, so a `--force` run replaces its files and keeps
386
+ * its declarations: the file itself, or for a policy, its abilities in the catalog.
387
+ */
388
+ async function existsAlready(root, request) {
389
+ let kind = KINDS[request.kind];
390
+ if (request.kind === "policy") {
391
+ let { segments, key } = request.name;
392
+ return declaresAbilities(root, [...segments.slice(0, -1).map(camel), key]);
393
+ }
394
+ if (request.kind === "migration" || kind.testOnly === true)
395
+ return false;
396
+ let file = `${folderOf(request.kind, request.variant)}/${request.name.segments.join("/")}`;
397
+ return exists(root, `${file}${kind.extension}`);
398
+ }
@@ -15,6 +15,11 @@ export interface Kind {
15
15
  extension: ".ts" | ".tsx" | ".sql";
16
16
  /** Whether `make.tests` writes a test beside the file. */
17
17
  tests: boolean;
18
+ /**
19
+ * Whether the kind writes its test alone: a policy's abilities and grants are edits to the
20
+ * app's catalog and policy, so the only file it writes is the test that checks them.
21
+ */
22
+ testOnly?: boolean;
18
23
  /** Whether the name may hold folders. */
19
24
  nested: boolean;
20
25
  /** Placeholders beyond {@link COMMON_PLACEHOLDERS}. */
@@ -28,12 +33,34 @@ export interface Kind {
28
33
  export declare const COMMON_PLACEHOLDERS: string[];
29
34
  /**
30
35
  * Every kind, in the order `sdxc make --help` lists them. `path` is the declaration's key path
31
- * in its map (`trials.expire`), `routes` the route contract's specifier, `tool` the MCP tool
36
+ * in its map (`trials.expire`, or a policy's ability group `billing.invoice`), `routes` the route contract's specifier, `tool` the MCP tool
32
37
  * name, `uri` an MCP resource's pattern, `model` the factory's model specifier. A command's
33
38
  * `command` is the words typed to run it (`users grant`), `member` the property access that
34
- * reaches its declaration (`.users.grant`), and `words` those words as string literals.
39
+ * reaches its declaration (`.users.grant`), and `words` those words as string literals. A
40
+ * model's `columns` are the column lines of the fields `make model` was given and `table` the
41
+ * plural its table is named; a factory's `attributes` are a value per field, empty without fields.
42
+ * A `--resource` controller's `ability` is the one it checks, `access` the guard answering a
43
+ * refusal with an empty response and `pageAccess` the one rendering the not-found page. A form's
44
+ * `params` is what its handlers pass to `href()`, `ctx.params` when its route has params, and
45
+ * `sampleParams` the values its test passes instead. An email's `subject`, `layoutTitle`, `body` and
46
+ * `preview` are its template's members written from its fields, and `sample`, `subjectSample` and
47
+ * `textSample` what its test renders and expects.
35
48
  */
36
49
  export declare const KINDS: Readonly<Record<KindName, Kind>>;
50
+ /** What `make model` writes beside the model unless `--skip` names it. */
51
+ export declare const MODEL_COMPANIONS: readonly ["migration", "factory"];
52
+ /** One of {@link MODEL_COMPANIONS}. */
53
+ export type ModelCompanion = (typeof MODEL_COMPANIONS)[number];
54
+ /** Every action `--actions` accepts in either contract, and `all`. */
55
+ export declare const ACTION_NAMES: readonly ["all", "index", "new", "show", "edit", "create", "update", "destroy"];
56
+ /** The pieces `--skip` can leave out of a scaffold. */
57
+ export declare const SCAFFOLD_PIECES: readonly ["model", "migration", "factory", "validator", "policy", "pages"];
58
+ /** One piece of a scaffold. */
59
+ export type ScaffoldPiece = (typeof SCAFFOLD_PIECES)[number];
60
+ /** The kinds `destroy` undoes; a migration may have run and a policy is edits alone, so neither is. */
61
+ export declare const DESTROY_KINDS: readonly ["controller", "middleware", "validator", "job", "model", "factory", "service", "initializer", "email", "mcp", "command"];
62
+ /** One of {@link DESTROY_KINDS}. */
63
+ export type DestroyKind = (typeof DESTROY_KINDS)[number];
37
64
  /** Where `make mcp --resource` writes, beside the tools. */
38
65
  export declare const MCP_RESOURCES_FOLDER = "app/mcp/resources";
39
66
  /** Whether `value` names a kind. */