@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
@@ -0,0 +1,332 @@
1
+ /**
2
+ * The placeholder values `sdxc scaffold` renders its stubs with: the resource's names in every
3
+ * spelling a stub needs, and the blocks written field by field, such as the model's columns or
4
+ * the form's controls, so a stub stays plain text with no loop in it.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { literal, memberAccess } from "../make/generate.js";
10
+ import { createTableStatement } from "../make/schema.js";
11
+ import { columnSource, factorySource, fieldIndexes, FIELD_TYPES, fieldsTable } from "./fields.js";
12
+ /**
13
+ * Every placeholder the scaffold's stubs may use. `header` is the module JSDoc's author tags;
14
+ * the rest derive from `resource`, the copy keys from its plural key (`posts.index.title`).
15
+ */
16
+ export function placeholders(resource, header) {
17
+ let { singular, plural, fields } = resource;
18
+ let copy = plural.key;
19
+ let types = new Set(fields.map((field) => field.type));
20
+ let table = plural.snake;
21
+ let changed = fields.find((field) => field.type !== "boolean") ?? fields[0];
22
+ let labelled = types.has("text") || types.has("timestamp");
23
+ return {
24
+ header,
25
+ CONSTANT: singular.snake.toUpperCase(),
26
+ PLURAL_CONSTANT: plural.snake.toUpperCase(),
27
+ name: singular.base,
28
+ key: singular.key,
29
+ path: singular.key,
30
+ Name: singular.pascal,
31
+ title: singular.title,
32
+ snake: singular.snake,
33
+ words: singular.title.toLowerCase(),
34
+ plural: plural.base,
35
+ pluralKey: plural.key,
36
+ Plural: plural.pascal,
37
+ pluralTitle: plural.title,
38
+ pluralSnake: plural.snake,
39
+ pluralWords: plural.title.toLowerCase(),
40
+ pluralMember: memberAccess([plural.base]),
41
+ table: plural.snake,
42
+ statement: [
43
+ createTableStatement(fieldsTable(table, fields)),
44
+ ...fieldIndexes(table, fields),
45
+ ].join("\n\n"),
46
+ firstColumn: fields[0]?.column ?? "id",
47
+ columns: lines(fields, 2, (field) => `${field.column}: ${columnSource(field, table)},`),
48
+ attributes: lines(fields, 1, (field) => `${field.column}: ${factorySource(field)},`),
49
+ schemaImports: [
50
+ 'import * as s from "remix/data-schema";',
51
+ types.has("boolean") ? 'import * as coerce from "remix/data-schema/coerce";' : null,
52
+ 'import * as f from "remix/data-schema/form-data";',
53
+ ]
54
+ .filter((line) => line !== null)
55
+ .join("\n"),
56
+ schemaFields: lines(fields, 1, (field) => `${field.column}: ${formSchema(field)},`),
57
+ formSample: entries(fields, (field) => literal(typeOf(field).formSample)),
58
+ invalidForm: entries(fields, (field) => literal(typeOf(field).invalidSample)),
59
+ jsonSample: entries(fields, (field) => typeOf(field).jsonSample),
60
+ changedJson: changed === undefined ? "" : `${changed.column}: ${typeOf(changed).changedSample}`,
61
+ formImports: [
62
+ 'import { HoneypotFields } from "@sdxc/honeypot/ui";',
63
+ 'import { Button } from "@sdxc/ui/button";',
64
+ types.has("boolean") ? 'import { Checkbox } from "@sdxc/ui/checkbox";' : null,
65
+ types.has("date") ? 'import { DateField } from "@sdxc/ui/date-field";' : null,
66
+ 'import { Form } from "@sdxc/ui/form";',
67
+ types.has("timestamp") ? 'import { Input } from "@sdxc/ui/input";' : null,
68
+ labelled ? 'import { Label } from "@sdxc/ui/label";' : null,
69
+ ["string", "integer", "email", "url"].some((type) => types.has(type))
70
+ ? 'import { TextField } from "@sdxc/ui/text-field";'
71
+ : null,
72
+ types.has("text") ? 'import { TextArea } from "@sdxc/ui/textarea";' : null,
73
+ labelled ? 'import { css } from "remix/component";' : null,
74
+ ]
75
+ .filter((line) => line !== null)
76
+ .join("\n"),
77
+ formFields: fields.map((field) => indent(formControl(field, copy, plural.base), 5)).join("\n"),
78
+ rowValues: lines(fields, 2, (field) => `${field.column}: ${formValue(field)},`),
79
+ tableColumns: lines(fields, 8, (field) => `<Table.Column>{ctx.intl.t("${copy}.fields.${field.column}")}</Table.Column>`),
80
+ tableCells: fields
81
+ .map((field, index) => {
82
+ let shown = display(field, copy);
83
+ let content = index === 0
84
+ ? `<Link href={routes.${copy}.show.href({ id: row.id })}>{${shown}}</Link>`
85
+ : `{${shown}}`;
86
+ return indent(`<Table.Cell>${content}</Table.Cell>`, 9);
87
+ })
88
+ .join("\n"),
89
+ detailRows: fields
90
+ .map((field) => indent(`<dt>{ctx.intl.t("${copy}.fields.${field.column}")}</dt>\n<dd>{${display(field, copy)}}</dd>`, 5))
91
+ .join("\n"),
92
+ listValues: fields
93
+ .map((field) => {
94
+ let value = field.nullable ? `row.${field.column} ?? ""` : `row.${field.column}`;
95
+ return typeOf(field).flag === "string" ? value : `String(${value})`;
96
+ })
97
+ .join(", "),
98
+ createValues: lines(fields, 2, (field) => `${field.column}: ctx.flags.${field.key}${field.nullable ? " ?? null" : ""},`),
99
+ createArgv: fields
100
+ .map((field) => field.type === "boolean"
101
+ ? literal(`--${field.flag}`)
102
+ : `${literal(`--${field.flag}`)}, ${literal(typeOf(field).flagSample)}`)
103
+ .join(", "),
104
+ };
105
+ }
106
+ /**
107
+ * The OpenAPI operations `scaffold --api` appends to `routes/api.ts`: the schema of a row as the
108
+ * API answers it, then one operation per endpoint, typing each body the endpoint parses and
109
+ * each response it sends, so `/api/openapi.json` documents exactly what the handlers do.
110
+ */
111
+ export function apiOperations(resource, locals) {
112
+ let { singular, plural, fields } = resource;
113
+ let { s, defineOperation, routes } = locals;
114
+ let one = singular.snake.toUpperCase();
115
+ let many = plural.snake.toUpperCase();
116
+ let words = singular.title.toLowerCase();
117
+ let pluralWords = plural.title.toLowerCase();
118
+ let schema = `${one}_SCHEMA`;
119
+ let route = `${routes}.api.${plural.key}`;
120
+ let tags = `tags: [${literal(plural.title)}],`;
121
+ let params = `params: ${s}.object({ id: ${s}.string() }),`;
122
+ let data = (inner) => `${s}.object({ data: ${inner} })`;
123
+ let body = (optional) => [
124
+ `body: ${s}.object({`,
125
+ ...jsonProperties(fields, s, optional),
126
+ "}),",
127
+ ];
128
+ let operation = (name, id, action, doc, lines) => [
129
+ `/** ${doc} */`,
130
+ `export const ${name} = ${defineOperation}(${literal(id)}, ${route}.${action}, {`,
131
+ ...lines.map((line) => `\t${line}`),
132
+ "});",
133
+ ].join("\n");
134
+ let row = [
135
+ `/** A ${words} as the API answers it. */`,
136
+ `export const ${schema} = ${s}`,
137
+ "\t.object({",
138
+ `\t\tid: ${s}.string(),`,
139
+ ...jsonProperties(fields, s, false).map((line) => `\t${line}`),
140
+ `\t\tcreated_at: ${s}.integer(),`,
141
+ `\t\tupdated_at: ${s}.integer(),`,
142
+ "\t})",
143
+ `\t.meta({ id: ${literal(singular.pascal)} });`,
144
+ ].join("\n");
145
+ return [
146
+ row,
147
+ operation(`${many}_INDEX`, `${plural.key}Index`, "index", `Every ${words} the caller may read, newest first.`, [
148
+ `summary: ${literal(`List ${pluralWords}`)},`,
149
+ tags,
150
+ `responses: { 200: { description: ${literal(`The ${pluralWords}`)}, body: ${data(`${s}.array(${schema})`)} } },`,
151
+ ]),
152
+ operation(`${one}_SHOW`, `${singular.key}Show`, "show", `One ${words} by its id.`, [
153
+ `summary: ${literal(`Show a ${words}`)},`,
154
+ tags,
155
+ params,
156
+ `responses: { 200: { description: ${literal(`The ${words}`)}, body: ${data(schema)} } },`,
157
+ 'problems: ["notFound"],',
158
+ ]),
159
+ operation(`${one}_CREATE`, `${singular.key}Create`, "create", `A new ${words} from every field.`, [
160
+ `summary: ${literal(`Create a ${words}`)},`,
161
+ tags,
162
+ ...body(false),
163
+ `responses: { 201: { description: ${literal(`The created ${words}`)}, body: ${data(schema)} } },`,
164
+ 'problems: ["validationError"],',
165
+ ]),
166
+ operation(`${one}_UPDATE`, `${singular.key}Update`, "update", `The fields the body names on one ${words}; the rest keep their values.`, [
167
+ `summary: ${literal(`Update a ${words}`)},`,
168
+ tags,
169
+ params,
170
+ ...body(true),
171
+ `responses: { 200: { description: ${literal(`The saved ${words}`)}, body: ${data(schema)} } },`,
172
+ 'problems: ["validationError", "notFound"],',
173
+ ]),
174
+ operation(`${one}_DESTROY`, `${singular.key}Destroy`, "destroy", `Deletes one ${words} by its id.`, [
175
+ `summary: ${literal(`Delete a ${words}`)},`,
176
+ tags,
177
+ params,
178
+ `responses: { 204: { description: ${literal(`The ${words} is gone`)} } },`,
179
+ 'problems: ["notFound"],',
180
+ ]),
181
+ ].join("\n\n");
182
+ }
183
+ /** The operation names `apiOperations` exports, in the order it writes them. */
184
+ export function apiOperationNames(resource) {
185
+ let one = resource.singular.snake.toUpperCase();
186
+ let many = resource.plural.snake.toUpperCase();
187
+ return [`${many}_INDEX`, `${one}_SHOW`, `${one}_CREATE`, `${one}_UPDATE`, `${one}_DESTROY`];
188
+ }
189
+ /**
190
+ * The copy every `resources/locales/*.json` gains under the plural key: each page's title and
191
+ * buttons, a label per field, and the words a ticked and an unticked box read as.
192
+ */
193
+ export function localeBlock(resource) {
194
+ let words = resource.singular.title.toLowerCase();
195
+ let pluralWords = resource.plural.title.toLowerCase();
196
+ return {
197
+ index: { title: resource.plural.title, new: `New ${words}`, empty: `No ${pluralWords} yet.` },
198
+ new: { title: `New ${words}`, submit: `Create ${words}` },
199
+ show: {
200
+ title: resource.singular.title,
201
+ edit: `Edit ${words}`,
202
+ delete: `Delete ${words}`,
203
+ back: `Back to ${pluralWords}`,
204
+ },
205
+ edit: { title: `Edit ${words}`, submit: `Save ${words}` },
206
+ fields: Object.fromEntries(resource.fields.map((field) => [field.column, field.label])),
207
+ yes: "Yes",
208
+ no: "No",
209
+ };
210
+ }
211
+ /**
212
+ * The tool input's properties, one line each, every one optional when `optional` says so; a
213
+ * nullable field also takes `null`.
214
+ */
215
+ export function jsonProperties(fields, s, optional) {
216
+ return fields.map((field) => {
217
+ let schema = typeOf(field).json.replace(/^s\./, `${s}.`);
218
+ if (field.nullable)
219
+ schema = `${s}.nullable(${schema})`;
220
+ return `\t${field.column}: ${optional ? `${s}.optional(${schema})` : schema},`;
221
+ });
222
+ }
223
+ /** A command flag per field, one line each, written with the contract's `flag` local. */
224
+ export function flagProperties(fields, flag) {
225
+ return fields.map((field) => {
226
+ let options = `{ description: ${literal(field.label)} }`;
227
+ let required = `{ required: true, description: ${literal(field.label)} }`;
228
+ let kind = typeOf(field).flag;
229
+ let declared = `${flag}.${kind}(${literal(field.flag)}, ${kind === "boolean" || field.nullable ? options : required})`;
230
+ return `\t${field.key}: ${declared},`;
231
+ });
232
+ }
233
+ /** The type `field` is written as on a page; the scaffold refuses a reference before rendering. */
234
+ function typeOf(field) {
235
+ return FIELD_TYPES[field.type];
236
+ }
237
+ /**
238
+ * The form schema of `field`: a box through `coerce.boolean()`, anything else read as text that
239
+ * passes its type's test and is converted to the column's value. A nullable field reads a blank
240
+ * or missing input as `null`.
241
+ */
242
+ function formSchema(field) {
243
+ if (field.type === "boolean")
244
+ return "f.field(s.defaulted(coerce.boolean(), false))";
245
+ let { test, convert } = typeOf(field);
246
+ let refine = (expression, message) => `.refine((value) => ${expression}, ${literal(message)})`;
247
+ if (!field.nullable) {
248
+ let checked = test === null ? "" : refine(test.expression, test.message);
249
+ let converted = convert === null ? "" : `.transform((value) => ${convert})`;
250
+ return `f.field(s.string()${checked}${converted})`;
251
+ }
252
+ let blank = 'value.trim() === ""';
253
+ let checked = test === null || test.expression === 'value.trim() !== ""'
254
+ ? ""
255
+ : refine(`${blank} || (${test.expression})`, test.message);
256
+ return `f.field(s.defaulted(s.string(), "")${checked}.transform((value) => (${blank} ? null : ${convert ?? "value"})))`;
257
+ }
258
+ /** How a row's value reads in the edit form, as the text a submission would carry. */
259
+ function formValue(field) {
260
+ let value = `row.${field.column}`;
261
+ if (field.type === "boolean")
262
+ return `${value} ? "true" : "false"`;
263
+ let text = value;
264
+ if (field.type === "integer")
265
+ text = `String(${value})`;
266
+ if (field.type === "timestamp")
267
+ text = `new Date(${value}).toISOString().slice(0, 16)`;
268
+ if (!field.nullable)
269
+ return text;
270
+ return text === value ? `${value} ?? ""` : `${value} === null ? "" : ${text}`;
271
+ }
272
+ /**
273
+ * How a row's value reads on a page: a box as the copy's yes or no, a timestamp as its UTC ISO
274
+ * text, anything else as it is, and a missing value as nothing.
275
+ */
276
+ function display(field, copy) {
277
+ let value = `row.${field.column}`;
278
+ if (field.type === "boolean") {
279
+ return `${value} ? ctx.intl.t("${copy}.yes") : ctx.intl.t("${copy}.no")`;
280
+ }
281
+ if (field.type !== "timestamp")
282
+ return value;
283
+ let shown = `new Date(${value}).toISOString()`;
284
+ return field.nullable ? `${value} === null ? "" : ${shown}` : shown;
285
+ }
286
+ /** The `@sdxc/ui` control a field is edited with, filled from the form's `values`. */
287
+ function formControl(field, copy, plural) {
288
+ let label = `intl.t("${copy}.fields.${field.column}")`;
289
+ let value = `values.${field.column}`;
290
+ let name = JSON.stringify(field.column);
291
+ let required = field.nullable ? "" : " required";
292
+ if (field.type === "boolean") {
293
+ return `<Checkbox name=${name} value="true" defaultChecked={${value} === "true"}>\n\t{${label}}\n</Checkbox>`;
294
+ }
295
+ if (field.type === "date") {
296
+ return `<DateField label={${label}} name=${name} defaultValue={${value}}${required} />`;
297
+ }
298
+ if (field.type === "text" || field.type === "timestamp") {
299
+ let id = JSON.stringify(`${plural}-${field.column}`);
300
+ let control = field.type === "text"
301
+ ? `<TextArea id=${id} name=${name} defaultValue={${value}}${required} />`
302
+ : `<Input id=${id} type="datetime-local" name=${name} defaultValue={${value}}${required} />`;
303
+ return [
304
+ `<div mix={css({ display: "grid", gap: "0.375rem" })}>`,
305
+ `\t<Label htmlFor=${id}>{${label}}</Label>`,
306
+ `\t${control}`,
307
+ "</div>",
308
+ ].join("\n");
309
+ }
310
+ let types = {
311
+ integer: "number",
312
+ email: "email",
313
+ url: "url",
314
+ };
315
+ let type = types[field.type] === undefined ? "" : ` type="${types[field.type]}"`;
316
+ return `<TextField${type} label={${label}} name=${name} defaultValue={${value}}${required} />`;
317
+ }
318
+ /** One line per field, each indented by `depth` tabs. */
319
+ function lines(fields, depth, line) {
320
+ return fields.map((field) => indent(line(field), depth)).join("\n");
321
+ }
322
+ /** The fields as object-literal entries on one line, each value from `value`. */
323
+ function entries(fields, value) {
324
+ return fields.map((field) => `${field.column}: ${value(field)}`).join(", ");
325
+ }
326
+ /** Every line of `text` indented by `depth` tabs. */
327
+ function indent(text, depth) {
328
+ return text
329
+ .split("\n")
330
+ .map((line) => `${"\t".repeat(depth)}${line}`)
331
+ .join("\n");
332
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * `sdxc schedule`: every scheduled job `app/jobs/index.ts` declares, when it runs next, and the
3
+ * Worker trigger that fires it. A cron job runs only when a trigger delivers its exact
4
+ * expression, so a job no trigger fires, and a trigger no job takes, are both shown.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ /** The files a Worker's cron triggers are declared in, `cloudflare.config.ts` first. */
10
+ export declare const TRIGGER_FILES: string[];
11
+ /** One scheduled job. */
12
+ export interface ScheduledJob {
13
+ /** Its key path in the declarations, `reports.daily`. */
14
+ job: string;
15
+ cron: string;
16
+ /** The next run after now, in UTC; `null` when the expression does not parse. */
17
+ next: string | null;
18
+ /** The file whose trigger delivers this expression, or `null` when none does. */
19
+ trigger: string | null;
20
+ }
21
+ /** What `sdxc schedule` reports. */
22
+ export interface ScheduleListing {
23
+ jobs: ScheduledJob[];
24
+ /** Each trigger expression no job declares, with the file it is in. */
25
+ unused: Array<{
26
+ cron: string;
27
+ file: string;
28
+ }>;
29
+ }
30
+ /** The scheduled jobs the project's job declarations hold, in source order. */
31
+ export declare function declaredJobs(root: string): Promise<Array<{
32
+ job: string;
33
+ cron: string;
34
+ }>>;
35
+ /** Every cron expression a trigger file declares, by file. */
36
+ export declare function triggerCrons(root: string): Promise<Array<{
37
+ cron: string;
38
+ file: string;
39
+ }>>;
40
+ /** `cron` as `@sdxc/cron` prints it, so `0 9 * * MON-FRI` and `0 9 * * 1-5` compare equal. */
41
+ export declare function normalized(cron: string): string;
42
+ /** Lists the project's scheduled jobs and triggers, the next runs counted from `now`. */
43
+ export declare function listSchedule(root: string, now?: Date): Promise<ScheduleListing>;
44
+ /** The listing as a table, then a line per trigger no job takes. */
45
+ export declare function formatSchedule(listing: ScheduleListing): string;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * `sdxc schedule`: every scheduled job `app/jobs/index.ts` declares, when it runs next, and the
3
+ * Worker trigger that fires it. A cron job runs only when a trigger delivers its exact
4
+ * expression, so a job no trigger fires, and a trigger no job takes, are both shown.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { Schedule } from "@sdxc/cron";
12
+ import { isFailure, wrap } from "@sdxc/result";
13
+ import { Project } from "./routes/modules.js";
14
+ /** The module `sdxc make job` declares jobs in. */
15
+ const JOBS_MODULE = "app/jobs/index.ts";
16
+ /** The files a Worker's cron triggers are declared in, `cloudflare.config.ts` first. */
17
+ export const TRIGGER_FILES = ["cloudflare.config.ts", "wrangler.jsonc", "wrangler.json"];
18
+ /** Every `job({ cron })` under `node`, a `jobs({ … })` object, with its key path. */
19
+ function cronJobs(node, path, job) {
20
+ let found = [];
21
+ for (let entry of node.entries) {
22
+ if ("spread" in entry)
23
+ continue;
24
+ let { value } = entry;
25
+ if (value.kind === "object")
26
+ found.push(...cronJobs(value, [...path, entry.key], job));
27
+ if (value.kind !== "call" || value.callee.kind !== "identifier" || value.callee.name !== job) {
28
+ continue;
29
+ }
30
+ let options = value.args[0]?.node;
31
+ if (options?.kind !== "object")
32
+ continue;
33
+ let cron = options.entries.find((option) => !("spread" in option) && option.key === "cron")?.value;
34
+ if (cron?.kind === "string")
35
+ found.push({ job: [...path, entry.key].join("."), cron: cron.value });
36
+ }
37
+ return found;
38
+ }
39
+ /** The scheduled jobs the project's job declarations hold, in source order. */
40
+ export async function declaredJobs(root) {
41
+ let project = new Project(root);
42
+ let module = await project.load(JOBS_MODULE);
43
+ if (module === null)
44
+ return [];
45
+ let exported = await project.exported(module, "default");
46
+ if (exported === null)
47
+ return [];
48
+ let node = exported.node;
49
+ if (node.kind === "identifier") {
50
+ let binding = await project.bind(exported.module, node.name);
51
+ if (binding.kind !== "local")
52
+ return [];
53
+ node = binding.node;
54
+ }
55
+ if (node.kind !== "call")
56
+ return [];
57
+ let declarations = node.args[0]?.node;
58
+ if (declarations?.kind !== "object")
59
+ return [];
60
+ let job = [...exported.module.imports].find(([, imported]) => imported.imported === "job")?.[0] ?? "job";
61
+ return cronJobs(declarations, [], job);
62
+ }
63
+ /** Every cron expression a trigger file declares, by file. */
64
+ export async function triggerCrons(root) {
65
+ let crons = [];
66
+ for (let file of TRIGGER_FILES) {
67
+ let text = await wrap(() => readFile(join(root, file), "utf8"));
68
+ if (isFailure(text))
69
+ continue;
70
+ let pattern = file.endsWith(".ts")
71
+ ? /triggers\.scheduled\(\s*\{\s*schedule:\s*["'`]([^"'`]+)["'`]/g
72
+ : /"crons"\s*:\s*\[([^\]]*)\]/g;
73
+ for (let match of text.data.matchAll(pattern)) {
74
+ let found = file.endsWith(".ts")
75
+ ? [match[1] ?? ""]
76
+ : [...(match[1] ?? "").matchAll(/"([^"]+)"/g)].map((entry) => entry[1] ?? "");
77
+ for (let cron of found)
78
+ crons.push({ cron, file });
79
+ }
80
+ }
81
+ return crons;
82
+ }
83
+ /** `cron` as `@sdxc/cron` prints it, so `0 9 * * MON-FRI` and `0 9 * * 1-5` compare equal. */
84
+ export function normalized(cron) {
85
+ let parsed = Schedule.parse(cron);
86
+ return isFailure(parsed) ? cron.trim() : parsed.data.toString();
87
+ }
88
+ /** Lists the project's scheduled jobs and triggers, the next runs counted from `now`. */
89
+ export async function listSchedule(root, now = new Date()) {
90
+ let triggers = await triggerCrons(root);
91
+ let jobs = (await declaredJobs(root)).map(({ job, cron }) => {
92
+ let parsed = Schedule.parse(cron);
93
+ let next = isFailure(parsed)
94
+ ? null
95
+ : parsed.data.next({ from: now, timeZone: "UTC" }).toISOString();
96
+ let trigger = triggers.find((entry) => normalized(entry.cron) === normalized(cron))?.file ?? null;
97
+ return { job, cron, next, trigger };
98
+ });
99
+ let taken = new Set(jobs.map((job) => normalized(job.cron)));
100
+ return { jobs, unused: triggers.filter((entry) => !taken.has(normalized(entry.cron))) };
101
+ }
102
+ /** The listing as a table, then a line per trigger no job takes. */
103
+ export function formatSchedule(listing) {
104
+ if (listing.jobs.length === 0 && listing.unused.length === 0) {
105
+ return `No scheduled jobs in ${JOBS_MODULE}; sdxc make job <name> --cron "<expression>" writes one.\n`;
106
+ }
107
+ let rows = listing.jobs.map((job) => [
108
+ job.job,
109
+ job.cron,
110
+ job.next === null ? "invalid expression" : `${job.next.slice(0, 16).replace("T", " ")} UTC`,
111
+ job.trigger ?? `none; add triggers.scheduled({ schedule: ${JSON.stringify(job.cron)} })`,
112
+ ]);
113
+ let header = ["Job", "Schedule", "Next run", "Trigger"];
114
+ let widths = header.map((title, column) => Math.max(title.length, ...rows.map((row) => row[column]?.length ?? 0)));
115
+ let line = (row) => row
116
+ .map((cell, column) => cell.padEnd(widths[column] ?? 0))
117
+ .join(" ")
118
+ .trimEnd();
119
+ let lines = rows.length === 0 ? [] : [line(header), ...rows.map(line)];
120
+ for (let entry of listing.unused) {
121
+ lines.push(`${entry.file} fires ${JSON.stringify(entry.cron)}, which no job declares`);
122
+ }
123
+ return `${lines.join("\n")}\n`;
124
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * `sdxc stats`: lines of code per kind of code the app layout names, counted like `cloc`
3
+ * without blank lines and comments, and the ratio of test code to app code. The layout gives
4
+ * every kind its folder, so the table needs no configuration.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ /** The folders the app layout keeps code in, which `stats` and `notes` read. */
10
+ export declare const PROJECT_FOLDERS: string[];
11
+ /** One row of the table. */
12
+ export interface StatsRow {
13
+ kind: string;
14
+ files: number;
15
+ /** Every line, blank and comment lines included. */
16
+ lines: number;
17
+ /** The lines left without blank lines and comments. */
18
+ code: number;
19
+ }
20
+ /** What `sdxc stats` reports. */
21
+ export interface Stats {
22
+ /** One row per kind that has files, in layout order, then Tests. */
23
+ rows: StatsRow[];
24
+ /** The code lines outside tests. */
25
+ code: number;
26
+ /** The code lines in tests. */
27
+ tests: number;
28
+ }
29
+ /**
30
+ * The lines of `text` that hold code: blank lines and comment lines are left out, a comment
31
+ * being a line inside `/* … *\/` or starting with `//`, or with `--` in SQL.
32
+ */
33
+ export declare function codeLines(text: string, sql: boolean): number;
34
+ /** Counts every code file under the project's layout folders, by kind. */
35
+ export declare function projectStats(root: string): Promise<Stats>;
36
+ /** The table `sdxc stats` prints, with a total and the code to test ratio. */
37
+ export declare function formatStats(stats: Stats): string;
package/dist/stats.js ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * `sdxc stats`: lines of code per kind of code the app layout names, counted like `cloc`
3
+ * without blank lines and comments, and the ratio of test code to app code. The layout gives
4
+ * every kind its folder, so the table needs no configuration.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { isFailure, wrap } from "@sdxc/result";
12
+ import { listFiles } from "./doctor/files.js";
13
+ /** The folders the app layout keeps code in, which `stats` and `notes` read. */
14
+ export const PROJECT_FOLDERS = ["app", "bootstrap", "config", "database", "resources", "routes"];
15
+ /** The files counted: source, SQL and stylesheets, which hold code a reader maintains. */
16
+ const COUNTED = /\.(?:[cm]?[jt]sx?|sql|css)$/;
17
+ /** A test file, counted under Tests whatever folder it sits in. */
18
+ const TEST = /\.test\.[cm]?[jt]sx?$/;
19
+ /**
20
+ * Each kind's folder, most specific first, so `app/mcp/resources` counts as MCP before `app`
21
+ * counts the rest as other app code.
22
+ */
23
+ const KINDS = [
24
+ ["Controllers", "app/http/controllers/"],
25
+ ["Middleware", "app/http/middleware/"],
26
+ ["Validators", "app/http/validators/"],
27
+ ["Jobs", "app/jobs/"],
28
+ ["Models", "app/models/"],
29
+ ["Services", "app/services/"],
30
+ ["Policies", "app/policies/"],
31
+ ["Initializers", "app/initializers/"],
32
+ ["MCP", "app/mcp/"],
33
+ ["Commands", "app/commands/"],
34
+ ["Emails", "app/emails/"],
35
+ ["Test helpers", "app/test/"],
36
+ ["Other app code", "app/"],
37
+ ["Entry points", "bootstrap/"],
38
+ ["Config", "config/"],
39
+ ["Migrations", "database/migrations/"],
40
+ ["Factories", "database/factories/"],
41
+ ["Other database code", "database/"],
42
+ ["Resources", "resources/"],
43
+ ["Routes", "routes/"],
44
+ ];
45
+ /**
46
+ * The lines of `text` that hold code: blank lines and comment lines are left out, a comment
47
+ * being a line inside `/* … *\/` or starting with `//`, or with `--` in SQL.
48
+ */
49
+ export function codeLines(text, sql) {
50
+ let count = 0;
51
+ let inBlock = false;
52
+ for (let raw of text.split("\n")) {
53
+ let line = raw.trim();
54
+ if (inBlock) {
55
+ if (line.includes("*/")) {
56
+ inBlock = false;
57
+ if (line.slice(line.indexOf("*/") + 2).trim() !== "")
58
+ count += 1;
59
+ }
60
+ continue;
61
+ }
62
+ if (line === "" || line.startsWith("//") || (sql && line.startsWith("--")))
63
+ continue;
64
+ if (line.startsWith("/*") || line.startsWith("{/*")) {
65
+ if (!line.includes("*/"))
66
+ inBlock = true;
67
+ continue;
68
+ }
69
+ count += 1;
70
+ }
71
+ return count;
72
+ }
73
+ /** Counts every code file under the project's layout folders, by kind. */
74
+ export async function projectStats(root) {
75
+ let rows = new Map();
76
+ let add = (kind, lines, code) => {
77
+ let row = rows.get(kind) ?? { kind, files: 0, lines: 0, code: 0 };
78
+ row.files += 1;
79
+ row.lines += lines;
80
+ row.code += code;
81
+ rows.set(kind, row);
82
+ };
83
+ for (let folder of PROJECT_FOLDERS) {
84
+ for (let path of await listFiles(root, folder)) {
85
+ if (!COUNTED.test(path))
86
+ continue;
87
+ let text = await wrap(() => readFile(join(root, path), "utf8"));
88
+ if (isFailure(text))
89
+ continue;
90
+ let lines = text.data.split("\n").length - (text.data.endsWith("\n") ? 1 : 0);
91
+ let code = codeLines(text.data, path.endsWith(".sql"));
92
+ let kind = TEST.test(path)
93
+ ? "Tests"
94
+ : (KINDS.find(([, prefix]) => path.startsWith(prefix))?.[0] ?? "Other");
95
+ add(kind, lines, code);
96
+ }
97
+ }
98
+ let order = [...KINDS.map(([kind]) => kind), "Other", "Tests"];
99
+ let sorted = order.flatMap((kind) => {
100
+ let row = rows.get(kind);
101
+ return row === undefined ? [] : [row];
102
+ });
103
+ let tests = rows.get("Tests")?.code ?? 0;
104
+ let code = sorted.reduce((sum, row) => sum + row.code, 0) - tests;
105
+ return { rows: sorted, code, tests };
106
+ }
107
+ /** The table `sdxc stats` prints, with a total and the code to test ratio. */
108
+ export function formatStats(stats) {
109
+ let header = ["Kind", "Files", "Lines", "Code"];
110
+ let total = stats.rows.reduce((sum, row) => ({
111
+ kind: "Total",
112
+ files: sum.files + row.files,
113
+ lines: sum.lines + row.lines,
114
+ code: sum.code + row.code,
115
+ }), { kind: "Total", files: 0, lines: 0, code: 0 });
116
+ let cells = [...stats.rows, total].map((row) => [row.kind, String(row.files), String(row.lines), String(row.code)]);
117
+ let widths = header.map((title, column) => Math.max(title.length, ...cells.map((row) => row[column]?.length ?? 0)));
118
+ let line = (row) => row
119
+ .map((cell, column) => column === 0 ? cell.padEnd(widths[0] ?? 0) : cell.padStart(widths[column] ?? 0))
120
+ .join(" ")
121
+ .trimEnd();
122
+ let rule = widths.map((width) => "-".repeat(width)).join(" ");
123
+ let body = cells.slice(0, -1).map(line);
124
+ let ratio = stats.code === 0 ? "no app code" : `1:${(stats.tests / stats.code).toFixed(1)}`;
125
+ return `${[line(header), rule, ...body, rule, line(cells.at(-1) ?? [])].join("\n")}\n\nCode: ${stats.code} Tests: ${stats.tests} Code to test ratio: ${ratio}\n`;
126
+ }