@sdxc/kit 2026.10.16 → 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 (358) hide show
  1. package/README.md +391 -20
  2. package/changelog.jsonl +1160 -1035
  3. package/config.schema.json +47 -1
  4. package/dist/author.d.ts +36 -0
  5. package/dist/author.js +107 -0
  6. package/dist/cli.js +12 -0
  7. package/dist/commands/create.js +9 -4
  8. package/dist/commands/deploy.d.ts +23 -0
  9. package/dist/commands/deploy.js +167 -0
  10. package/dist/commands/destroy.d.ts +22 -0
  11. package/dist/commands/destroy.js +92 -0
  12. package/dist/commands/doctor.d.ts +26 -0
  13. package/dist/commands/doctor.js +65 -0
  14. package/dist/commands/initializers.d.ts +16 -0
  15. package/dist/commands/initializers.js +23 -0
  16. package/dist/commands/make.d.ts +72 -6
  17. package/dist/commands/make.js +127 -19
  18. package/dist/commands/middleware.d.ts +16 -0
  19. package/dist/commands/middleware.js +21 -0
  20. package/dist/commands/models.d.ts +18 -0
  21. package/dist/commands/models.js +29 -0
  22. package/dist/commands/notes.d.ts +17 -0
  23. package/dist/commands/notes.js +27 -0
  24. package/dist/commands/routes.d.ts +25 -0
  25. package/dist/commands/routes.js +50 -0
  26. package/dist/commands/run.d.ts +18 -2
  27. package/dist/commands/run.js +35 -12
  28. package/dist/commands/scaffold.d.ts +29 -0
  29. package/dist/commands/scaffold.js +33 -0
  30. package/dist/commands/schedule.d.ts +16 -0
  31. package/dist/commands/schedule.js +21 -0
  32. package/dist/commands/stats.d.ts +16 -0
  33. package/dist/commands/stats.js +21 -0
  34. package/dist/commands/ui/update.d.ts +6 -3
  35. package/dist/commands/ui/update.js +24 -7
  36. package/dist/commands/upgrade.d.ts +3 -1
  37. package/dist/commands/upgrade.js +88 -23
  38. package/dist/config.d.ts +18 -0
  39. package/dist/config.js +28 -1
  40. package/dist/contract.d.ts +97 -3
  41. package/dist/contract.js +360 -26
  42. package/dist/create/templates.d.ts +8 -1
  43. package/dist/create/templates.js +26 -2
  44. package/dist/dependencies.d.ts +4 -1
  45. package/dist/dependencies.js +13 -1
  46. package/dist/deploy/plan.d.ts +49 -0
  47. package/dist/deploy/plan.js +68 -0
  48. package/dist/destroy.d.ts +40 -0
  49. package/dist/destroy.js +311 -0
  50. package/dist/doctor/check.d.ts +71 -0
  51. package/dist/doctor/check.js +53 -0
  52. package/dist/doctor/checks.d.ts +23 -0
  53. package/dist/doctor/checks.js +68 -0
  54. package/dist/doctor/define.d.ts +59 -0
  55. package/dist/doctor/define.js +16 -0
  56. package/dist/doctor/emails.d.ts +18 -0
  57. package/dist/doctor/emails.js +243 -0
  58. package/dist/doctor/env.d.ts +26 -0
  59. package/dist/doctor/env.js +88 -0
  60. package/dist/doctor/files.d.ts +14 -0
  61. package/dist/doctor/files.js +34 -0
  62. package/dist/doctor/fixture.d.ts +23 -0
  63. package/dist/doctor/fixture.js +46 -0
  64. package/dist/doctor/install.d.ts +17 -0
  65. package/dist/doctor/install.js +37 -0
  66. package/dist/doctor/installed.d.ts +11 -0
  67. package/dist/doctor/installed.js +79 -0
  68. package/dist/doctor/layout.d.ts +23 -0
  69. package/dist/doctor/layout.js +83 -0
  70. package/dist/doctor/migrations.d.ts +16 -0
  71. package/dist/doctor/migrations.js +96 -0
  72. package/dist/doctor/models.d.ts +13 -0
  73. package/dist/doctor/models.js +69 -0
  74. package/dist/doctor/pins.d.ts +15 -0
  75. package/dist/doctor/pins.js +79 -0
  76. package/dist/doctor/project.d.ts +58 -0
  77. package/dist/doctor/project.js +261 -0
  78. package/dist/doctor/remix.d.ts +14 -0
  79. package/dist/doctor/remix.js +44 -0
  80. package/dist/doctor/routes.d.ts +11 -0
  81. package/dist/doctor/routes.js +49 -0
  82. package/dist/doctor/typegen.d.ts +13 -0
  83. package/dist/doctor/typegen.js +57 -0
  84. package/dist/doctor/ui.d.ts +14 -0
  85. package/dist/doctor/ui.js +51 -0
  86. package/dist/init.d.ts +5 -3
  87. package/dist/init.js +15 -7
  88. package/dist/initializers.d.ts +25 -0
  89. package/dist/initializers.js +89 -0
  90. package/dist/lock.d.ts +2 -2
  91. package/dist/make/actions.d.ts +23 -0
  92. package/dist/make/actions.js +82 -0
  93. package/dist/make/declare.d.ts +32 -4
  94. package/dist/make/declare.js +405 -27
  95. package/dist/make/email.d.ts +23 -0
  96. package/dist/make/email.js +111 -0
  97. package/dist/make/from-fields.d.ts +30 -0
  98. package/dist/make/from-fields.js +162 -0
  99. package/dist/make/from-model.d.ts +39 -0
  100. package/dist/make/from-model.js +161 -0
  101. package/dist/make/generate.d.ts +16 -5
  102. package/dist/make/generate.js +43 -14
  103. package/dist/make/guard.d.ts +35 -0
  104. package/dist/make/guard.js +73 -0
  105. package/dist/make/imports.d.ts +6 -0
  106. package/dist/make/imports.js +19 -0
  107. package/dist/make/index.d.ts +47 -4
  108. package/dist/make/index.js +287 -25
  109. package/dist/make/kinds.d.ts +31 -3
  110. package/dist/make/kinds.js +82 -9
  111. package/dist/make/mount.d.ts +25 -0
  112. package/dist/make/mount.js +135 -0
  113. package/dist/make/schema-diff.d.ts +58 -0
  114. package/dist/make/schema-diff.js +609 -0
  115. package/dist/make/schema.d.ts +76 -0
  116. package/dist/make/schema.js +206 -0
  117. package/dist/make/stubs.d.ts +7 -5
  118. package/dist/make/stubs.js +16 -5
  119. package/dist/make/test.d.ts +43 -0
  120. package/dist/make/test.js +149 -0
  121. package/dist/make/trigger.d.ts +31 -0
  122. package/dist/make/trigger.js +163 -0
  123. package/dist/models.d.ts +42 -0
  124. package/dist/models.js +149 -0
  125. package/dist/notes.d.ts +28 -0
  126. package/dist/notes.js +66 -0
  127. package/dist/reference.d.ts +27 -0
  128. package/dist/reference.js +103 -0
  129. package/dist/releases.d.ts +9 -0
  130. package/dist/releases.js +29 -8
  131. package/dist/routes/chains.d.ts +34 -0
  132. package/dist/routes/chains.js +95 -0
  133. package/dist/routes/filter.d.ts +53 -0
  134. package/dist/routes/filter.js +147 -0
  135. package/dist/routes/format.d.ts +23 -0
  136. package/dist/routes/format.js +123 -0
  137. package/dist/routes/helpers.d.ts +21 -0
  138. package/dist/routes/helpers.js +165 -0
  139. package/dist/routes/index.d.ts +56 -0
  140. package/dist/routes/index.js +167 -0
  141. package/dist/routes/modules.d.ts +116 -0
  142. package/dist/routes/modules.js +235 -0
  143. package/dist/routes/parse.d.ts +161 -0
  144. package/dist/routes/parse.js +621 -0
  145. package/dist/routes/routers.d.ts +69 -0
  146. package/dist/routes/routers.js +327 -0
  147. package/dist/scaffold/fields.d.ts +129 -0
  148. package/dist/scaffold/fields.js +421 -0
  149. package/dist/scaffold/index.d.ts +37 -0
  150. package/dist/scaffold/index.js +613 -0
  151. package/dist/scaffold/render.d.ts +51 -0
  152. package/dist/scaffold/render.js +332 -0
  153. package/dist/schedule.d.ts +45 -0
  154. package/dist/schedule.js +124 -0
  155. package/dist/stats.d.ts +37 -0
  156. package/dist/stats.js +126 -0
  157. package/dist/testing.d.ts +12 -2
  158. package/dist/testing.js +22 -3
  159. package/dist/ui/commands.d.ts +10 -3
  160. package/dist/ui/commands.js +85 -15
  161. package/dist/ui/registry.d.ts +8 -8
  162. package/dist/upgrade/agents.d.ts +49 -0
  163. package/dist/upgrade/agents.js +110 -0
  164. package/dist/upgrade/changelog.d.ts +2 -2
  165. package/dist/upgrade/project.d.ts +4 -0
  166. package/dist/upgrade/project.js +11 -1
  167. package/dist/upgrade/prompt.d.ts +11 -0
  168. package/dist/upgrade/prompt.js +50 -7
  169. package/package.json +6 -4
  170. package/registry/ui/alert-dialog.json +2 -2
  171. package/registry/ui/attachment.json +2 -2
  172. package/registry/ui/calendar.json +2 -2
  173. package/registry/ui/color-picker.json +2 -2
  174. package/registry/ui/command.json +2 -2
  175. package/registry/ui/date-picker.json +2 -2
  176. package/registry/ui/date-range-picker.json +2 -2
  177. package/registry/ui/dialog.json +2 -2
  178. package/registry/ui/file-trigger.json +2 -2
  179. package/registry/ui/heading-scope.json +2 -2
  180. package/registry/ui/message-scroller.json +2 -2
  181. package/registry/ui/number-field.json +2 -2
  182. package/registry/ui/range-calendar.json +2 -2
  183. package/registry/ui/resizable.json +2 -2
  184. package/registry/ui/select.json +2 -2
  185. package/registry/ui/shared-element.json +2 -2
  186. package/stubs/command.stub +4 -0
  187. package/stubs/command.test.stub +3 -0
  188. package/stubs/controller.api.resource.stub +23 -0
  189. package/stubs/controller.api.stub +21 -0
  190. package/stubs/controller.api.test.stub +18 -0
  191. package/stubs/controller.form.stub +40 -10
  192. package/stubs/controller.form.test.stub +61 -0
  193. package/stubs/controller.resource.form.stub +67 -0
  194. package/stubs/controller.resource.stub +28 -0
  195. package/stubs/controller.stub +15 -8
  196. package/stubs/controller.test.stub +3 -0
  197. package/stubs/email.stub +15 -38
  198. package/stubs/email.test.stub +12 -7
  199. package/stubs/factory.stub +4 -1
  200. package/stubs/initializer.stub +2 -0
  201. package/stubs/initializer.test.stub +3 -0
  202. package/stubs/job.cron.stub +4 -0
  203. package/stubs/job.stub +4 -0
  204. package/stubs/job.test.stub +3 -0
  205. package/stubs/mcp.resource.stub +3 -0
  206. package/stubs/mcp.stub +3 -0
  207. package/stubs/mcp.test.stub +3 -0
  208. package/stubs/middleware.stub +6 -1
  209. package/stubs/middleware.test.stub +3 -0
  210. package/stubs/model.stub +12 -3
  211. package/stubs/model.test.stub +3 -0
  212. package/stubs/policy.test.stub +36 -7
  213. package/stubs/scaffold.api.create.stub +34 -0
  214. package/stubs/scaffold.api.create.test.stub +37 -0
  215. package/stubs/scaffold.api.destroy.stub +34 -0
  216. package/stubs/scaffold.api.destroy.test.stub +44 -0
  217. package/stubs/scaffold.api.index.stub +23 -0
  218. package/stubs/scaffold.api.index.test.stub +31 -0
  219. package/stubs/scaffold.api.show.stub +27 -0
  220. package/stubs/scaffold.api.show.test.stub +41 -0
  221. package/stubs/scaffold.api.update.stub +44 -0
  222. package/stubs/scaffold.api.update.test.stub +46 -0
  223. package/stubs/scaffold.command.create.stub +22 -0
  224. package/stubs/scaffold.command.create.test.stub +30 -0
  225. package/stubs/scaffold.command.delete.stub +20 -0
  226. package/stubs/scaffold.command.delete.test.stub +39 -0
  227. package/stubs/scaffold.command.list.stub +18 -0
  228. package/stubs/scaffold.command.list.test.stub +31 -0
  229. package/stubs/scaffold.command.show.stub +19 -0
  230. package/stubs/scaffold.command.show.test.stub +37 -0
  231. package/stubs/scaffold.controller.destroy.stub +35 -0
  232. package/stubs/scaffold.controller.destroy.test.stub +65 -0
  233. package/stubs/scaffold.controller.edit.stub +97 -0
  234. package/stubs/scaffold.controller.edit.test.stub +91 -0
  235. package/stubs/scaffold.controller.index.stub +55 -0
  236. package/stubs/scaffold.controller.index.test.stub +32 -0
  237. package/stubs/scaffold.controller.new.stub +70 -0
  238. package/stubs/scaffold.controller.new.test.stub +81 -0
  239. package/stubs/scaffold.controller.show.stub +59 -0
  240. package/stubs/scaffold.controller.show.test.stub +43 -0
  241. package/stubs/scaffold.factory.stub +16 -0
  242. package/stubs/scaffold.form.stub +75 -0
  243. package/stubs/scaffold.mcp.create.stub +24 -0
  244. package/stubs/scaffold.mcp.create.test.stub +36 -0
  245. package/stubs/scaffold.mcp.delete.stub +31 -0
  246. package/stubs/scaffold.mcp.delete.test.stub +43 -0
  247. package/stubs/scaffold.mcp.get.stub +21 -0
  248. package/stubs/scaffold.mcp.get.test.stub +31 -0
  249. package/stubs/scaffold.mcp.list.stub +23 -0
  250. package/stubs/scaffold.mcp.list.test.stub +25 -0
  251. package/stubs/scaffold.mcp.update.stub +37 -0
  252. package/stubs/scaffold.mcp.update.test.stub +40 -0
  253. package/stubs/scaffold.migration.stub +2 -0
  254. package/stubs/scaffold.model.stub +35 -0
  255. package/stubs/scaffold.model.test.stub +25 -0
  256. package/stubs/scaffold.test-database.stub +33 -0
  257. package/stubs/scaffold.test-mcp.stub +92 -0
  258. package/stubs/scaffold.validator.stub +18 -0
  259. package/stubs/scaffold.validator.test.stub +26 -0
  260. package/stubs/service.stub +4 -0
  261. package/stubs/service.test.stub +3 -0
  262. package/stubs/validator.stub +3 -0
  263. package/stubs/validator.test.stub +3 -0
  264. package/templates/app/.env.example +16 -0
  265. package/templates/app/AGENTS.md +163 -0
  266. package/templates/app/CLAUDE.md +1 -0
  267. package/templates/app/README.md +79 -37
  268. package/templates/app/app/commands/about.test.ts +1 -1
  269. package/templates/app/app/commands/console.test.ts +26 -0
  270. package/templates/app/app/commands/console.ts +19 -0
  271. package/templates/app/app/commands/db/console.ts +6 -0
  272. package/templates/app/app/commands/db/fresh.test.ts +57 -0
  273. package/templates/app/app/commands/db/fresh.ts +37 -0
  274. package/templates/app/app/commands/db/migrate.test.ts +46 -0
  275. package/templates/app/app/commands/db/migrate.ts +88 -0
  276. package/templates/app/app/commands/db/prepare.test.ts +39 -0
  277. package/templates/app/app/commands/db/prepare.ts +35 -0
  278. package/templates/app/app/commands/db/seed.test.ts +38 -0
  279. package/templates/app/app/commands/db/seed.ts +26 -0
  280. package/templates/app/app/commands/deploy.test.ts +34 -0
  281. package/templates/app/app/commands/deploy.ts +18 -0
  282. package/templates/app/app/commands/emails/preview.test.tsx +63 -0
  283. package/templates/app/app/commands/emails/preview.ts +24 -0
  284. package/templates/app/app/commands/index.ts +72 -1
  285. package/templates/app/app/commands/typegen.test.ts +17 -0
  286. package/templates/app/app/commands/typegen.ts +16 -0
  287. package/templates/app/app/emails/index.ts +10 -0
  288. package/templates/app/app/http/controllers/api/health.tsx +15 -0
  289. package/templates/app/app/http/controllers/api/not-found.tsx +16 -0
  290. package/templates/app/app/http/controllers/api/openapi.tsx +17 -0
  291. package/templates/app/app/http/controllers/home.tsx +21 -13
  292. package/templates/app/app/http/controllers/mcp.tsx +16 -0
  293. package/templates/app/app/http/controllers/not-found.tsx +23 -18
  294. package/templates/app/app/http/controllers/robots.test.ts +18 -0
  295. package/templates/app/app/http/controllers/robots.ts +24 -0
  296. package/templates/app/app/http/controllers/sitemap.test.ts +28 -0
  297. package/templates/app/app/http/controllers/sitemap.ts +25 -0
  298. package/templates/app/app/http/middleware/access.test.ts +43 -0
  299. package/templates/app/app/http/middleware/access.ts +41 -0
  300. package/templates/app/app/http/middleware/api.ts +19 -0
  301. package/templates/app/app/http/middleware/page.test.ts +43 -0
  302. package/templates/app/app/http/middleware/page.ts +51 -0
  303. package/templates/app/app/http/middleware/server-timing.test.ts +15 -0
  304. package/templates/app/app/http/middleware/server-timing.ts +42 -0
  305. package/templates/app/app/initializers/assets.ts +1 -1
  306. package/templates/app/app/initializers/captcha.ts +11 -0
  307. package/templates/app/app/initializers/cli.ts +68 -2
  308. package/templates/app/app/initializers/database.test.ts +18 -0
  309. package/templates/app/app/initializers/database.ts +18 -0
  310. package/templates/app/app/initializers/dispatcher.ts +26 -0
  311. package/templates/app/app/initializers/honeypot.ts +11 -0
  312. package/templates/app/app/initializers/i18n.test.ts +16 -0
  313. package/templates/app/app/initializers/i18n.ts +28 -0
  314. package/templates/app/app/initializers/local-database.test.ts +33 -0
  315. package/templates/app/app/initializers/local-database.ts +53 -0
  316. package/templates/app/app/initializers/mail-transport.test.ts +27 -0
  317. package/templates/app/app/initializers/mail-transport.ts +26 -0
  318. package/templates/app/app/initializers/mail.test.ts +27 -0
  319. package/templates/app/app/initializers/mail.ts +19 -0
  320. package/templates/app/app/initializers/mcp.ts +1 -1
  321. package/templates/app/app/initializers/openapi.ts +21 -0
  322. package/templates/app/app/initializers/router.test.ts +68 -0
  323. package/templates/app/app/initializers/router.tsx +81 -25
  324. package/templates/app/app/initializers/seo.ts +15 -0
  325. package/templates/app/app/initializers/session.test.ts +34 -0
  326. package/templates/app/app/initializers/session.ts +29 -0
  327. package/templates/app/app/initializers/spam.ts +10 -0
  328. package/templates/app/app/jobs/email.test.tsx +70 -0
  329. package/templates/app/app/jobs/email.ts +16 -0
  330. package/templates/app/app/jobs/index.ts +6 -2
  331. package/templates/app/app/models/index.ts +10 -0
  332. package/templates/app/app/policies/abilities.ts +13 -0
  333. package/templates/app/app/policies/policy.test.ts +15 -0
  334. package/templates/app/app/policies/policy.ts +30 -0
  335. package/templates/app/app/services/commands.ts +30 -0
  336. package/templates/app/app/services/migrations.test.ts +92 -0
  337. package/templates/app/app/services/migrations.ts +117 -0
  338. package/templates/app/app/test/cloudflare-workers.ts +25 -0
  339. package/templates/app/app/test/local-database.ts +67 -0
  340. package/templates/app/app/test/session.ts +28 -0
  341. package/templates/app/bootstrap/cli.ts +1 -1
  342. package/templates/app/bootstrap/console.ts +13 -0
  343. package/templates/app/bootstrap/worker.ts +4 -4
  344. package/templates/app/cloudflare.config.ts +30 -2
  345. package/templates/app/config/constants.ts +19 -0
  346. package/templates/app/config/problems.ts +24 -0
  347. package/templates/app/config/security-policy.ts +34 -0
  348. package/templates/app/config/security-txt.ts +28 -0
  349. package/templates/app/database/migrations/.gitkeep +0 -0
  350. package/templates/app/database/seed.ts +12 -0
  351. package/templates/app/package.json +37 -6
  352. package/templates/app/resources/layouts/document.tsx +28 -7
  353. package/templates/app/resources/locales/en.json +10 -0
  354. package/templates/app/routes/api.ts +29 -0
  355. package/templates/app/routes/web.ts +6 -4
  356. package/templates/app/vite.config.ts +4 -0
  357. package/stubs/policy.stub +0 -13
  358. package/templates/app/config/router-context.d.ts +0 -20
@@ -1,19 +1,20 @@
1
1
  /**
2
2
  * Declares and maps what `make job`, `make controller`, `make mcp` and `make command` generate:
3
3
  * the entry in the job map, route contract, MCP or command declaration module, and the mapping
4
- * in the initializer that serves it, so the new handler answers as soon as the command finishes. Both edits are
5
- * computed before anything is written; when either cannot be placed, neither is made and the
6
- * command prints them for the user instead, so a declaration never ships without its mapping.
4
+ * in the initializer that serves it, plus a page's sitemap decision; `make model` registers the
5
+ * model in `app/models/index.ts` and `make policy` a resource's abilities and grants the same
6
+ * way. Every edit is computed before anything is written; when one cannot be placed, none is
7
+ * made and the command prints them for the user instead.
7
8
  *
8
9
  * @author [Sergio Xalambrí](https://sergiodxa.com)
9
10
  * @copyright Sergio Xalambrí 2026
10
11
  */
11
12
  import { readdir, readFile } from "node:fs/promises";
12
13
  import { dirname, join, posix } from "node:path";
13
- import { addProperty, findModuleReferences, insertAfterLast } from "@sdxc/codemod";
14
+ import { addElement, addProperty, findModuleReferences, insertAfterLast } from "@sdxc/codemod";
14
15
  import { failure, isFailure, isSuccess, success, wrap } from "@sdxc/result";
15
16
  import { literal, memberAccess } from "./generate.js";
16
- import { ensureImport, resolvesTo, specifierFor } from "./imports.js";
17
+ import { ensureImport, ensureTypeImport, resolvesTo, specifierFor } from "./imports.js";
17
18
  import { camel } from "./names.js";
18
19
  /** The `remix/routes` helper each `--method` declares with; `form` adds a page and an action. */
19
20
  const ROUTE_HELPERS = {
@@ -24,11 +25,14 @@ const ROUTE_HELPERS = {
24
25
  delete: "del",
25
26
  form: "form",
26
27
  };
28
+ /** The route helpers that declare a page, which a sitemap built with `fromRoutes` must decide. */
29
+ const PAGE_HELPERS = new Set(["get", "form"]);
27
30
  /** The name an instance gets when the initializer that creates it cannot be read, by factory. */
28
31
  const INSTANCE_NAMES = {
29
32
  createRouter: "router",
30
33
  createHandler: "mcp",
31
34
  createCLI: "cli",
35
+ createMail: "mail",
32
36
  };
33
37
  /** Plans the declaration and mapping for `request` in the project at `root`. */
34
38
  export async function declare(request, root) {
@@ -38,6 +42,12 @@ export async function declare(request, root) {
38
42
  return declareController(request, root);
39
43
  if (request.kind === "command")
40
44
  return declareCommand(request, root);
45
+ if (request.kind === "model")
46
+ return declareModel(request, root);
47
+ if (request.kind === "policy")
48
+ return declarePolicy(request, root);
49
+ if (request.kind === "email")
50
+ return declareEmail(request, root);
41
51
  return declareMcp(request, root);
42
52
  }
43
53
  /** Declares a job in `app/jobs/index.ts` and maps it on the job dispatcher. */
@@ -107,7 +117,7 @@ async function declareController(request, root) {
107
117
  let { name } = request;
108
118
  let module = `routes/${request.routes}`;
109
119
  let contract = await findContract(root, module);
110
- let initializer = await findInitializer(root, module, null);
120
+ let initializer = await findInitializer(root, module, "createRouter", "required");
111
121
  let instance = initializer === null ? "router" : instanceOf(initializer, "createRouter");
112
122
  let local = initializer === null ? "routes" : (defaultLocal(initializer, module) ?? "routes");
113
123
  let path = [...name.segments.slice(0, -1).map(camel), name.key];
@@ -117,11 +127,23 @@ async function declareController(request, root) {
117
127
  let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
118
128
  let lazyLocal = "lazy";
119
129
  let statement = (lazy) => `${instance}.map(${local}.${path.join(".")}, ${lazy}(() => import(${literal(handler)})));`;
130
+ let sitemap = PAGE_HELPERS.has(helper) ? await findSitemap(root, module) : null;
131
+ let decision = request.sitemap ?? sitemapDecision(helper, pattern);
120
132
  let manual = (reason) => ({
121
133
  kind: "manual",
122
134
  path: path.join("."),
123
135
  reason,
124
- instructions: instructions(`${contract ?? `${module}.ts`}, in route({ … })${groupNote(path)}`, `${path.at(-1)}: ${value},`, initializer?.path ?? `the initializer that maps ${module}`, statement(lazyLocal)),
136
+ instructions: [
137
+ instructions(`${contract ?? `${module}.ts`}, in route({ … })${groupNote(path)}`, `${path.at(-1)}: ${value},`, initializer?.path ?? `the initializer that maps ${module}`, statement(lazyLocal)),
138
+ sitemap === null
139
+ ? null
140
+ : [
141
+ `In ${sitemap.path}, in fromRoutes(…)'s decisions${groupNote(path)}:`,
142
+ indent(`${path.at(-1)}: ${decision},`),
143
+ ].join("\n"),
144
+ ]
145
+ .filter((text) => text !== null)
146
+ .join("\n"),
125
147
  });
126
148
  if (contract === null)
127
149
  return manual(`there is no route contract ${module}.ts`);
@@ -150,14 +172,60 @@ async function declareController(request, root) {
150
172
  let mapped = mapAfter(withLazy, module, local, statement(lazyLocal), `${instance}.map`, "createRouter");
151
173
  if (isFailure(mapped))
152
174
  return manual(mapped.error.message);
153
- return {
154
- kind: "edits",
155
- path: path.join("."),
156
- edits: [
157
- { path: contract, before: file.data.source, after: added.data.source },
158
- { path: initializer.path, before: initializer.source, after: mapped.data },
159
- ],
160
- };
175
+ let edits = [
176
+ { path: contract, before: file.data.source, after: added.data.source },
177
+ { path: initializer.path, before: initializer.source, after: mapped.data },
178
+ ];
179
+ if (sitemap !== null) {
180
+ let decided = addProperty(sitemap.path, sitemap.source, {
181
+ call: "fromRoutes",
182
+ argument: 2,
183
+ path: path.slice(0, -1),
184
+ key: name.key,
185
+ value: decision,
186
+ });
187
+ if (isSuccess(decided)) {
188
+ edits.push({ path: sitemap.path, before: sitemap.source, after: decided.data.source });
189
+ }
190
+ else if (decided.error.code === "invalid-output") {
191
+ return manual(decided.error.message);
192
+ }
193
+ }
194
+ return { kind: "edits", path: path.join("."), edits };
195
+ }
196
+ /**
197
+ * The sitemap decision a new page starts with: listed, or an empty list of pages when its pattern
198
+ * has required params, so it is in the sitemap until the developer changes it. A `form` route
199
+ * decides its page under `index`.
200
+ */
201
+ function sitemapDecision(helper, pattern) {
202
+ let required = /[:*][A-Za-z_$]/.test(pattern.replace(/\([^)]*\)/g, ""));
203
+ let page = required ? "[]" : "true";
204
+ return helper === "form" ? `{ index: ${page} }` : page;
205
+ }
206
+ /**
207
+ * The controller that builds a sitemap with `fromRoutes` over the contract `module`, which needs
208
+ * a decision for every page the contract declares; `null` when the app has none.
209
+ */
210
+ async function findSitemap(root, module) {
211
+ let folder = "app/http/controllers";
212
+ let entries = await wrap(() => readdir(join(root, folder), { recursive: true }));
213
+ if (isFailure(entries))
214
+ return null;
215
+ for (let entry of entries.data.sort()) {
216
+ if (!/\.tsx?$/.test(entry) || /\.test\.tsx?$/.test(entry))
217
+ continue;
218
+ let file = await readSource(root, posix.join(folder, entry.split("\\").join("/")));
219
+ if (isFailure(file) || !file.data.source.includes("fromRoutes("))
220
+ continue;
221
+ let local = defaultLocal(file.data, module);
222
+ if (local === null)
223
+ continue;
224
+ if (new RegExp(`\\bfromRoutes\\(\\s*${escape(local)}\\s*,`).test(file.data.source)) {
225
+ return file.data;
226
+ }
227
+ }
228
+ return null;
161
229
  }
162
230
  /** Declares an MCP tool or resource beside the others and maps it on the MCP handler. */
163
231
  async function declareMcp(request, root) {
@@ -205,6 +273,8 @@ async function declareMcp(request, root) {
205
273
  return manual(schema.error.message);
206
274
  source = schema.data.source;
207
275
  body[1] = `input: ${schema.data.local}.object({}),`;
276
+ if (request.options !== undefined)
277
+ body = request.options.lines({ s: schema.data.local });
208
278
  }
209
279
  let added = addProperty(declarations, source, {
210
280
  call: group,
@@ -234,6 +304,73 @@ async function declareMcp(request, root) {
234
304
  ],
235
305
  };
236
306
  }
307
+ /**
308
+ * Declares an email in `app/emails/index.ts`, with the props its fields describe, and maps its
309
+ * template on the email registry through `lazy()`, imported from the package that provides
310
+ * `createMail`.
311
+ */
312
+ async function declareEmail(request, root) {
313
+ let module = "app/emails/index";
314
+ let declarations = `${module}.ts`;
315
+ let { name } = request;
316
+ let initializer = await findInitializer(root, module, "createMail");
317
+ let instance = initializer === null ? "mail" : instanceOf(initializer, "createMail");
318
+ let local = initializer === null ? "emails" : (defaultLocal(initializer, module) ?? "emails");
319
+ let path = [...name.segments.slice(0, -1).map(camel), name.key];
320
+ let lines = (s) => request.options?.lines({ s }) ?? [`props: ${s}.object({}),`];
321
+ let valueWith = (callee, s) => `${callee}({\n${lines(s)
322
+ .map((line) => `\t${line}`)
323
+ .join("\n")}\n})`;
324
+ let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
325
+ let statement = (lazy) => `${instance}.map(${local}.${path.join(".")}, ${lazy}(() => import(${literal(handler)})));`;
326
+ let manual = (reason) => ({
327
+ kind: "manual",
328
+ path: path.join("."),
329
+ reason,
330
+ instructions: instructions(`${declarations}, in emails({ … })${groupNote(path)}`, `${path.at(-1)}: ${valueWith("email", "s")},`, initializer?.path ?? "the email registry's initializer", statement("lazy")),
331
+ });
332
+ if (initializer === null)
333
+ return manual("no initializer in app/initializers/ creates the email registry");
334
+ let file = await readSource(root, declarations);
335
+ if (isFailure(file))
336
+ return manual(`${declarations} could not be read`);
337
+ let mailSpecifier = file.data.references.find((reference) => reference.kind === "import" && reference.names.some((bound) => bound.imported === "emails"))?.specifier;
338
+ if (mailSpecifier === undefined)
339
+ return manual(`${declarations} does not import emails()`);
340
+ let builder = ensureImport(declarations, file.data.source, { kind: "named", name: "email" }, (specifier) => specifier === mailSpecifier, mailSpecifier, "email");
341
+ if (isFailure(builder))
342
+ return manual(builder.error.message);
343
+ let schema = ensureImport(declarations, builder.data.source, { kind: "namespace" }, (specifier) => specifier === "remix/data-schema", "remix/data-schema", "s");
344
+ if (isFailure(schema))
345
+ return manual(schema.error.message);
346
+ let added = addProperty(declarations, schema.data.source, {
347
+ call: "emails",
348
+ path: path.slice(0, -1),
349
+ key: name.key,
350
+ value: valueWith(builder.data.local, schema.data.local),
351
+ });
352
+ if (isFailure(added))
353
+ return manual(added.error.message);
354
+ let mailSource = initializer.references.find((reference) => reference.kind === "import" &&
355
+ reference.names.some((bound) => bound.imported === "createMail"))?.specifier;
356
+ if (mailSource === undefined)
357
+ return manual(`${initializer.path} does not import createMail`);
358
+ let lazy = ensureImport(initializer.path, initializer.source, { kind: "named", name: "lazy" }, (specifier) => specifier === mailSource, mailSource, "lazy");
359
+ if (isFailure(lazy))
360
+ return manual(lazy.error.message);
361
+ let withLazy = { ...initializer, source: lazy.data.source };
362
+ let mapped = mapAfter(withLazy, module, local, statement(lazy.data.local), `${instance}.map`, "createMail");
363
+ if (isFailure(mapped))
364
+ return manual(mapped.error.message);
365
+ return {
366
+ kind: "edits",
367
+ path: path.join("."),
368
+ edits: [
369
+ { path: declarations, before: file.data.source, after: added.data.source },
370
+ { path: initializer.path, before: initializer.source, after: mapped.data },
371
+ ],
372
+ };
373
+ }
237
374
  /**
238
375
  * Declares a command in `app/commands/index.ts` and maps it on the command line. Each folder of
239
376
  * the name is a `commands({ … })` group, created when missing, and the command's key is the
@@ -288,13 +425,28 @@ async function declareCommand(request, root) {
288
425
  return manual(`\`${groups.slice(0, depth + 1).join(".")}\` is a command, not a group`);
289
426
  }
290
427
  }
291
- let entry = `${keyText(leaf)}: ${builder.data.local}({ description: ${description} })`;
428
+ let value = `${builder.data.local}({ description: ${description} })`;
429
+ if (request.options !== undefined) {
430
+ let locals = {};
431
+ for (let wanted of request.options.imports) {
432
+ let imported = wanted === "s"
433
+ ? ensureImport(declarations, source, { kind: "namespace" }, (specifier) => specifier === "remix/data-schema", "remix/data-schema", "s")
434
+ : ensureImport(declarations, source, { kind: "named", name: wanted }, (specifier) => specifier === group.specifier, group.specifier, wanted);
435
+ if (isFailure(imported))
436
+ return manual(imported.error.message);
437
+ source = imported.data.source;
438
+ locals[wanted] = imported.data.local;
439
+ }
440
+ let lines = [`description: ${description},`, ...request.options.lines(locals)];
441
+ value = `${builder.data.local}({\n${indentTab(lines.join("\n"))}\n})`;
442
+ }
443
+ let entry = `${keyText(leaf)}: ${value}`;
292
444
  let added = depth === groups.length
293
445
  ? addProperty(declarations, source, {
294
446
  call: groupLocal,
295
447
  path: groups,
296
448
  key: leaf,
297
- value: `${builder.data.local}({ description: ${description} })`,
449
+ value,
298
450
  })
299
451
  : addProperty(declarations, source, {
300
452
  call: groupLocal,
@@ -324,6 +476,231 @@ async function declareCommand(request, root) {
324
476
  ],
325
477
  };
326
478
  }
479
+ /**
480
+ * Registers a model in `app/models/index.ts`'s `createModels({ … })` under its key, as an import
481
+ * the registry runs on first use, so `ctx.models.<key>` reaches it on every request, job and
482
+ * command once the command finishes.
483
+ */
484
+ async function declareModel(request, root) {
485
+ let declarations = "app/models/index.ts";
486
+ let key = request.name.key;
487
+ let file = await readSource(root, declarations);
488
+ let specifier = isFailure(file)
489
+ ? `./${request.name.segments.join("/")}`
490
+ : specifierFor(declarations, request.handler, staticSpecifiers(file.data), false);
491
+ let value = `() => import(${literal(specifier)})`;
492
+ let manual = (reason) => ({
493
+ kind: "manual",
494
+ path: key,
495
+ reason,
496
+ instructions: [
497
+ `In ${declarations}, in createModels({ … }):`,
498
+ indent(`${keyText(key)}: ${value},`),
499
+ ].join("\n"),
500
+ });
501
+ if (isFailure(file))
502
+ return manual(`${declarations} could not be read`);
503
+ let call = file.data.references
504
+ .find((reference) => reference.kind === "import" &&
505
+ reference.names.some((bound) => bound.imported === "createModels"))
506
+ ?.names.find((bound) => bound.imported === "createModels")?.local;
507
+ if (call === undefined)
508
+ return manual(`${declarations} does not import createModels()`);
509
+ let added = addProperty(declarations, file.data.source, { call, path: [], key, value });
510
+ if (isFailure(added))
511
+ return manual(added.error.message);
512
+ return {
513
+ kind: "edits",
514
+ path: key,
515
+ edits: [{ path: declarations, before: file.data.source, after: added.data.source }],
516
+ };
517
+ }
518
+ /** The abilities of a resource `make policy` grants to `member`; its `read` goes to `everyone`. */
519
+ const WRITE_ACTIONS = ["create", "update", "delete"];
520
+ /**
521
+ * Declares a resource's `create`, `read`, `update` and `delete` abilities in
522
+ * `app/policies/abilities.ts` and grants them in `app/policies/policy.ts`, reads to `everyone` and
523
+ * writes to `member`. A refused read answers as not found, so a hidden row looks like a missing one.
524
+ */
525
+ async function declarePolicy(request, root) {
526
+ let catalog = "app/policies/abilities.ts";
527
+ let policyFile = "app/policies/policy.ts";
528
+ let { name } = request;
529
+ let groups = name.segments.slice(0, -1).map(camel);
530
+ let path = [...groups, name.key];
531
+ let ability = path.join(".");
532
+ let id = name.segments.join("-");
533
+ let row = await findRow(root, name);
534
+ let rowType = row?.type ?? "{ id: string }";
535
+ let group = (abilityLocal, contextLocal, type) => {
536
+ let context = `${contextLocal}<{ ${name.key}: ${type} }>(${literal(name.key)})`;
537
+ return [
538
+ "{",
539
+ ` create: ${abilityLocal}(),`,
540
+ ` read: ${abilityLocal}({ context: ${context}, deniedAs: "notFound" }),`,
541
+ ` update: ${abilityLocal}({ context: ${context} }),`,
542
+ ` delete: ${abilityLocal}({ context: ${context} }),`,
543
+ "}",
544
+ ].join("\n");
545
+ };
546
+ let reads = (allow) => `${allow}(${literal(`${ability}.read`)}, { id: ${literal(`${id}-read`)} })`;
547
+ let writes = (allow) => {
548
+ let names = WRITE_ACTIONS.map((action) => literal(`${ability}.${action}`)).join(", ");
549
+ return `${allow}([${names}], { id: ${literal(`${id}-write`)} })`;
550
+ };
551
+ let manual = (reason) => ({
552
+ kind: "manual",
553
+ path: ability,
554
+ reason,
555
+ instructions: [
556
+ ...(row === null
557
+ ? []
558
+ : [`In ${catalog}:`, indent(`import type { ${row.type} } from "~/${row.path}";`)]),
559
+ `In ${catalog}, in abilities({ … })${groupNote(path)}:`,
560
+ indent(`${name.key}: ${group("ability", "context", rowType)},`),
561
+ `In ${policyFile}, in definePolicy(…)'s everyone:`,
562
+ indent(`${reads("allow")},`),
563
+ `In ${policyFile}, in definePolicy(…)'s roles.member:`,
564
+ indent(`${writes("allow")},`),
565
+ ].join("\n"),
566
+ });
567
+ let file = await readSource(root, catalog);
568
+ if (isFailure(file))
569
+ return manual(`${catalog} could not be read`);
570
+ let catalogImport = importOf(file.data, "abilities");
571
+ if (catalogImport === null)
572
+ return manual(`${catalog} does not import abilities()`);
573
+ let source = file.data.source;
574
+ let locals = {};
575
+ for (let helper of ["ability", "context"]) {
576
+ let imported = ensureImport(catalog, source, { kind: "named", name: helper }, (specifier) => specifier === catalogImport.specifier, catalogImport.specifier, helper);
577
+ if (isFailure(imported))
578
+ return manual(imported.error.message);
579
+ source = imported.data.source;
580
+ locals[helper] = imported.data.local;
581
+ }
582
+ let type = rowType;
583
+ if (row !== null) {
584
+ let aliased = await declaresAlias(root);
585
+ let specifier = specifierFor(catalog, row.path, staticSpecifiers(file.data), aliased);
586
+ let imported = ensureTypeImport(catalog, source, row.type, specifier);
587
+ if (isFailure(imported))
588
+ return manual(imported.error.message);
589
+ source = imported.data.source;
590
+ type = imported.data.local;
591
+ }
592
+ let declared = addProperty(catalog, source, {
593
+ call: catalogImport.local,
594
+ path: groups,
595
+ key: name.key,
596
+ value: group(locals.ability ?? "ability", locals.context ?? "context", type),
597
+ });
598
+ if (isFailure(declared))
599
+ return manual(declared.error.message);
600
+ let policy = await readSource(root, policyFile);
601
+ if (isFailure(policy))
602
+ return manual(`${policyFile} could not be read`);
603
+ let defined = importOf(policy.data, "definePolicy");
604
+ if (defined === null)
605
+ return manual(`${policyFile} does not import definePolicy()`);
606
+ let allow = ensureImport(policyFile, policy.data.source, { kind: "named", name: "allow" }, (specifier) => specifier === defined.specifier, defined.specifier, "allow");
607
+ if (isFailure(allow))
608
+ return manual(allow.error.message);
609
+ let granted = grant(policyFile, allow.data.source, defined.local, [["everyone"]], reads(allow.data.local));
610
+ if (isFailure(granted))
611
+ return manual(granted.error.message);
612
+ granted = grant(policyFile, granted.data, defined.local, [
613
+ ["roles", "member"],
614
+ ["roles", "member", "grants"],
615
+ ], writes(allow.data.local));
616
+ if (isFailure(granted))
617
+ return manual(granted.error.message);
618
+ return {
619
+ kind: "edits",
620
+ path: ability,
621
+ edits: [
622
+ { path: catalog, before: file.data.source, after: declared.data.source },
623
+ { path: policyFile, before: policy.data.source, after: granted.data },
624
+ ],
625
+ };
626
+ }
627
+ /**
628
+ * Whether `app/policies/abilities.ts` declares a group at `path` in its `abilities({ … })`, as
629
+ * `make policy` does for a resource. An unreadable catalog, or one without the call, declares none.
630
+ */
631
+ export async function declaresAbilities(root, path) {
632
+ let catalog = "app/policies/abilities.ts";
633
+ let file = await readSource(root, catalog);
634
+ if (isFailure(file))
635
+ return false;
636
+ let call = importOf(file.data, "abilities");
637
+ if (call === null)
638
+ return false;
639
+ let [key = "", ...rest] = [...path].reverse();
640
+ let probe = addProperty(catalog, file.data.source, {
641
+ call: call.local,
642
+ path: rest.reverse(),
643
+ key,
644
+ value: "{}",
645
+ });
646
+ return isFailure(probe) && probe.error.code === "duplicate-key";
647
+ }
648
+ /**
649
+ * `source` with `value` appended to the first of `lists` the policy's options hold, each a key
650
+ * path in `definePolicy`'s second argument; with none of them, the first is created holding it.
651
+ */
652
+ function grant(filename, source, call, lists, value) {
653
+ for (let path of lists) {
654
+ let added = addElement(filename, source, { call, argument: 1, path: [...path], value });
655
+ if (isSuccess(added))
656
+ return success(added.data.source);
657
+ if (added.error.code !== "not-found")
658
+ return added;
659
+ }
660
+ let [first = []] = lists;
661
+ let created = addProperty(filename, source, {
662
+ call,
663
+ argument: 1,
664
+ path: first.slice(0, -1),
665
+ key: first.at(-1) ?? "",
666
+ value: `[${value}]`,
667
+ });
668
+ if (isFailure(created))
669
+ return created;
670
+ return success(created.data.source);
671
+ }
672
+ /**
673
+ * The row type a resource's model exports, `PostRow` from `app/models/post.ts`, or `null` when
674
+ * the resource has no model or its model exports no such type.
675
+ */
676
+ export async function findRow(root, name) {
677
+ let path = `app/models/${name.segments.join("/")}`;
678
+ let type = `${name.pascal}Row`;
679
+ for (let extension of [".ts", ".tsx"]) {
680
+ let source = await wrap(() => readFile(join(root, `${path}${extension}`), "utf8"));
681
+ if (isFailure(source))
682
+ continue;
683
+ let exported = new RegExp(`export\\s+(?:type|interface)\\s+${escape(type)}\\b`);
684
+ return exported.test(source.data) ? { path, type } : null;
685
+ }
686
+ return null;
687
+ }
688
+ /** The local name and specifier `file` imports the named export `name` under, or `null`. */
689
+ function importOf(file, name) {
690
+ for (let reference of file.references) {
691
+ if (reference.kind !== "import")
692
+ continue;
693
+ let bound = reference.names.find((each) => each.imported === name && !each.typeOnly);
694
+ if (bound !== undefined)
695
+ return { local: bound.local, specifier: reference.specifier };
696
+ }
697
+ return null;
698
+ }
699
+ /** Whether the project's `tsconfig.json` declares the `~/app/*` alias. */
700
+ async function declaresAlias(root) {
701
+ let tsconfig = await wrap(() => readFile(join(root, "tsconfig.json"), "utf8"));
702
+ return !isFailure(tsconfig) && tsconfig.data.includes('"~/app/*"');
703
+ }
327
704
  /**
328
705
  * A `commands({ … })` group holding `entry`, wrapped in one more group for each of `levels`,
329
706
  * outermost first, for the folders of a command name that have no group yet.
@@ -367,10 +744,11 @@ function mapAfter(file, module, local, statement, call, factory) {
367
744
  return success(inserted.data.source);
368
745
  }
369
746
  /**
370
- * The first initializer in `app/initializers/` that imports `module`, or failing that, one that
371
- * calls `factory`; `null` when none does. Test files are skipped.
747
+ * The initializer in `app/initializers/` that imports `module` and calls `factory`, else the
748
+ * first that imports it, else (unless `importing` is required) one that calls `factory`; `null`
749
+ * when none does. Test files are skipped.
372
750
  */
373
- async function findInitializer(root, module, factory) {
751
+ async function findInitializer(root, module, factory, importing = "preferred") {
374
752
  let folder = "app/initializers";
375
753
  let entries = await wrap(() => readdir(join(root, folder)));
376
754
  if (isFailure(entries))
@@ -383,16 +761,16 @@ async function findInitializer(root, module, factory) {
383
761
  if (isSuccess(file))
384
762
  files.push(file.data);
385
763
  }
386
- let tsconfig = await wrap(() => readFile(join(root, "tsconfig.json"), "utf8"));
387
- let aliased = !isFailure(tsconfig) && tsconfig.data.includes('"~/app/*"');
764
+ let aliased = await declaresAlias(root);
388
765
  for (let file of files)
389
766
  file.aliased = aliased;
390
- let importing = files.find((file) => file.references.some((reference) => reference.kind === "import" && resolvesTo(reference.specifier, file.path, module)));
391
- if (importing !== undefined)
392
- return importing;
393
- if (factory === null)
767
+ let calling = factory === null ? null : new RegExp(`\\b${factory}\\(`);
768
+ let importers = files.filter((file) => file.references.some((reference) => reference.kind === "import" && resolvesTo(reference.specifier, file.path, module)));
769
+ let found = importers.find((file) => calling?.test(file.source) ?? true) ?? importers[0];
770
+ if (found !== undefined)
771
+ return found;
772
+ if (calling === null || importing === "required")
394
773
  return null;
395
- let calling = new RegExp(`\\b${factory}\\(`);
396
774
  return files.find((file) => calling.test(file.source)) ?? null;
397
775
  }
398
776
  /** The route contract file for `module` (`routes/web`), `.ts` or `.tsx`, or `null`. */
@@ -0,0 +1,23 @@
1
+ /**
2
+ * `sdxc make email <name> field ...`: the fields become the email's props, typed by the
3
+ * conventions `make model` uses, and each one is declared in the props schema, rendered in the
4
+ * template's body, and given a sample its `preview()` and its test share.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Result } from "@sdxc/result";
10
+ import type { Name } from "./names.js";
11
+ /** What `make email` writes from its fields. */
12
+ export interface EmailPlan {
13
+ /** The lines inside `email({ … })`, given the local the schema builder is imported as. */
14
+ declaration: (s: string) => string[];
15
+ /** The stub placeholders the template and its test read. */
16
+ placeholders: Record<string, string>;
17
+ }
18
+ /**
19
+ * Plans the email `name` with the props `specs` describe, or `heading` and `body` without any.
20
+ * A reference, an index and a unique field describe a table rather than an email, so each is
21
+ * refused naming the spec.
22
+ */
23
+ export declare function planEmail(specs: readonly string[], name: Name): Result<EmailPlan, Error>;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `sdxc make email <name> field ...`: the fields become the email's props, typed by the
3
+ * conventions `make model` uses, and each one is declared in the props schema, rendered in the
4
+ * template's body, and given a sample its `preview()` and its test share.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { failure, isFailure, success } from "@sdxc/result";
10
+ import { parseFields } from "../scaffold/fields.js";
11
+ import { literal } from "./generate.js";
12
+ /** The fields an email given none is built from: a heading that is its subject, and a body. */
13
+ const DEFAULT_FIELDS = ["heading", "body:text"];
14
+ /** The `remix/data-schema` builder each field type's prop is declared with. */
15
+ const SCHEMAS = {
16
+ string: "string()",
17
+ text: "string()",
18
+ integer: "number()",
19
+ boolean: "boolean()",
20
+ date: "string()",
21
+ timestamp: "number()",
22
+ email: "string()",
23
+ url: "string()",
24
+ };
25
+ /** The types whose value is text, the first of which is the email's subject and heading. */
26
+ const TEXT_TYPES = new Set(["string", "text"]);
27
+ /**
28
+ * Plans the email `name` with the props `specs` describe, or `heading` and `body` without any.
29
+ * A reference, an index and a unique field describe a table rather than an email, so each is
30
+ * refused naming the spec.
31
+ */
32
+ export function planEmail(specs, name) {
33
+ let parsed = parseFields(specs.length === 0 ? DEFAULT_FIELDS : specs);
34
+ if (isFailure(parsed))
35
+ return parsed;
36
+ for (let [position, field] of parsed.data.entries()) {
37
+ let spec = specs[position] ?? field.column;
38
+ if (field.type === "references") {
39
+ return failure(new Error(`"${spec}" references a table; an email's props hold values`));
40
+ }
41
+ if (field.index !== null) {
42
+ return failure(new Error(`"${spec}" indexes a column; an email's props have none`));
43
+ }
44
+ }
45
+ let fields = parsed.data;
46
+ let heading = fields.find((field) => TEXT_TYPES.has(field.type) && !field.nullable) ?? null;
47
+ let samples = new Map(fields.map((field) => [field.key, sample(field)]));
48
+ let preview = `{ ${fields.map((field) => `${field.key}: ${samples.get(field.key)}`).join(", ")} }`;
49
+ let shown = fields.find((field) => field !== heading && TEXT_TYPES.has(field.type)) ?? heading;
50
+ let subjectSample = heading === null ? literal(name.title) : (samples.get(heading.key) ?? "");
51
+ return success({
52
+ declaration: (s) => [
53
+ `props: ${s}.object({`,
54
+ ...fields.map((field) => `\t${field.key}: ${schema(field, s)},`),
55
+ "}),",
56
+ ],
57
+ placeholders: {
58
+ subject: heading === null
59
+ ? `() => ${literal(name.title)}`
60
+ : `({ ${heading.key} }) => ${heading.key}`,
61
+ layoutTitle: heading === null ? literal(name.title) : `{handle.props.${heading.key}}`,
62
+ body: [...(heading === null ? [] : [heading]), ...fields.filter((field) => field !== heading)]
63
+ .map((field) => `\t\t\t${element(field, field === heading)}`)
64
+ .join("\n"),
65
+ preview,
66
+ sample: preview,
67
+ subjectSample,
68
+ textSample: shown === null ? subjectSample : (samples.get(shown.key) ?? subjectSample),
69
+ },
70
+ });
71
+ }
72
+ /** The prop's schema, optional when its spec ended in `?`. */
73
+ function schema(field, s) {
74
+ let builder = `${s}.${SCHEMAS[field.type]}`;
75
+ return field.nullable ? `${s}.optional(${builder})` : builder;
76
+ }
77
+ /** A value of the prop's type, distinct per text field so a test can tell them apart. */
78
+ function sample(field) {
79
+ if (field.type === "integer")
80
+ return "42";
81
+ if (field.type === "timestamp")
82
+ return "1769851800000";
83
+ if (field.type === "boolean")
84
+ return "true";
85
+ if (field.type === "date")
86
+ return literal("2026-01-31");
87
+ if (field.type === "email")
88
+ return literal("ada@example.com");
89
+ if (field.type === "url")
90
+ return literal("https://example.com/");
91
+ return literal(`Sample ${field.label.toLowerCase()}`);
92
+ }
93
+ /** The JSX one prop renders as, guarded when the prop is optional. */
94
+ function element(field, heading) {
95
+ let value = `handle.props.${field.key}`;
96
+ if (field.type === "boolean")
97
+ return `{${value} ? <Email.Text>${field.label}</Email.Text> : null}`;
98
+ let shown = shape(field, value, heading);
99
+ return field.nullable ? `{${value} === undefined ? null : ${shown}}` : shown;
100
+ }
101
+ /** The element a present prop renders as, by its type. */
102
+ function shape(field, value, heading) {
103
+ if (heading)
104
+ return `<Email.Heading>{${value}}</Email.Heading>`;
105
+ if (field.type === "url")
106
+ return `<Email.Button href={${value}}>${field.label}</Email.Button>`;
107
+ if (field.type === "email") {
108
+ return `<Email.Text>\n\t\t\t\t<Email.Link href={\`mailto:\${${value}}\`}>{${value}}</Email.Link>\n\t\t\t</Email.Text>`;
109
+ }
110
+ return `<Email.Text>{${value}}</Email.Text>`;
111
+ }