@sdxc/kit 0.0.0-pre.1

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 (144) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +93 -0
  3. package/config.schema.json +89 -0
  4. package/dist/bin.d.ts +9 -0
  5. package/dist/bin.js +10 -0
  6. package/dist/cli.d.ts +33 -0
  7. package/dist/cli.js +58 -0
  8. package/dist/commands/create.d.ts +20 -0
  9. package/dist/commands/create.js +164 -0
  10. package/dist/commands/init.d.ts +16 -0
  11. package/dist/commands/init.js +27 -0
  12. package/dist/commands/make.d.ts +335 -0
  13. package/dist/commands/make.js +152 -0
  14. package/dist/commands/run.d.ts +23 -0
  15. package/dist/commands/run.js +51 -0
  16. package/dist/commands/ui/add.d.ts +23 -0
  17. package/dist/commands/ui/add.js +50 -0
  18. package/dist/commands/ui/diff.d.ts +20 -0
  19. package/dist/commands/ui/diff.js +28 -0
  20. package/dist/commands/ui/list.d.ts +24 -0
  21. package/dist/commands/ui/list.js +45 -0
  22. package/dist/commands/ui/remove.d.ts +22 -0
  23. package/dist/commands/ui/remove.js +48 -0
  24. package/dist/commands/ui/update.d.ts +23 -0
  25. package/dist/commands/ui/update.js +37 -0
  26. package/dist/commands/upgrade.d.ts +30 -0
  27. package/dist/commands/upgrade.js +184 -0
  28. package/dist/config.d.ts +81 -0
  29. package/dist/config.js +157 -0
  30. package/dist/contract.d.ts +161 -0
  31. package/dist/contract.js +308 -0
  32. package/dist/create/github.d.ts +63 -0
  33. package/dist/create/github.js +172 -0
  34. package/dist/create/target.d.ts +31 -0
  35. package/dist/create/target.js +56 -0
  36. package/dist/create/templates.d.ts +62 -0
  37. package/dist/create/templates.js +228 -0
  38. package/dist/dependencies.d.ts +34 -0
  39. package/dist/dependencies.js +76 -0
  40. package/dist/diff.d.ts +14 -0
  41. package/dist/diff.js +103 -0
  42. package/dist/format.d.ts +21 -0
  43. package/dist/format.js +40 -0
  44. package/dist/init.d.ts +38 -0
  45. package/dist/init.js +92 -0
  46. package/dist/lock.d.ts +74 -0
  47. package/dist/lock.js +214 -0
  48. package/dist/make/declare.d.ts +54 -0
  49. package/dist/make/declare.js +495 -0
  50. package/dist/make/generate.d.ts +56 -0
  51. package/dist/make/generate.js +139 -0
  52. package/dist/make/imports.d.ts +43 -0
  53. package/dist/make/imports.js +104 -0
  54. package/dist/make/index.d.ts +43 -0
  55. package/dist/make/index.js +136 -0
  56. package/dist/make/kinds.d.ts +39 -0
  57. package/dist/make/kinds.js +95 -0
  58. package/dist/make/migrations.d.ts +21 -0
  59. package/dist/make/migrations.js +48 -0
  60. package/dist/make/names.d.ts +31 -0
  61. package/dist/make/names.js +47 -0
  62. package/dist/make/stubs.d.ts +44 -0
  63. package/dist/make/stubs.js +89 -0
  64. package/dist/middleware.d.ts +44 -0
  65. package/dist/middleware.js +49 -0
  66. package/dist/package-manager.d.ts +41 -0
  67. package/dist/package-manager.js +80 -0
  68. package/dist/project.d.ts +19 -0
  69. package/dist/project.js +42 -0
  70. package/dist/releases.d.ts +40 -0
  71. package/dist/releases.js +110 -0
  72. package/dist/testing.d.ts +47 -0
  73. package/dist/testing.js +126 -0
  74. package/dist/ui/commands.d.ts +114 -0
  75. package/dist/ui/commands.js +432 -0
  76. package/dist/ui/imports.d.ts +46 -0
  77. package/dist/ui/imports.js +160 -0
  78. package/dist/ui/layout.d.ts +48 -0
  79. package/dist/ui/layout.js +138 -0
  80. package/dist/ui/registry.d.ts +58 -0
  81. package/dist/ui/registry.js +82 -0
  82. package/dist/upgrade/changelog.d.ts +50 -0
  83. package/dist/upgrade/changelog.js +69 -0
  84. package/dist/upgrade/project.d.ts +62 -0
  85. package/dist/upgrade/project.js +132 -0
  86. package/dist/upgrade/prompt.d.ts +51 -0
  87. package/dist/upgrade/prompt.js +227 -0
  88. package/dist/upgrade/registry.d.ts +33 -0
  89. package/dist/upgrade/registry.js +50 -0
  90. package/lock.schema.json +60 -0
  91. package/package.json +45 -0
  92. package/stubs/command.stub +12 -0
  93. package/stubs/command.test.stub +18 -0
  94. package/stubs/controller.form.stub +33 -0
  95. package/stubs/controller.stub +17 -0
  96. package/stubs/controller.test.stub +15 -0
  97. package/stubs/email.stub +44 -0
  98. package/stubs/email.test.stub +16 -0
  99. package/stubs/factory.stub +10 -0
  100. package/stubs/initializer.stub +7 -0
  101. package/stubs/initializer.test.stub +13 -0
  102. package/stubs/job.cron.stub +12 -0
  103. package/stubs/job.stub +11 -0
  104. package/stubs/job.test.stub +15 -0
  105. package/stubs/mcp.resource.stub +12 -0
  106. package/stubs/mcp.stub +10 -0
  107. package/stubs/mcp.test.stub +15 -0
  108. package/stubs/middleware.stub +11 -0
  109. package/stubs/middleware.test.stub +13 -0
  110. package/stubs/migration.stub +1 -0
  111. package/stubs/model.stub +24 -0
  112. package/stubs/model.test.stub +15 -0
  113. package/stubs/policy.stub +13 -0
  114. package/stubs/policy.test.stub +17 -0
  115. package/stubs/service.stub +13 -0
  116. package/stubs/service.test.stub +14 -0
  117. package/stubs/validator.stub +14 -0
  118. package/stubs/validator.test.stub +22 -0
  119. package/templates/app/README.md +57 -0
  120. package/templates/app/app/commands/about.test.ts +29 -0
  121. package/templates/app/app/commands/about.ts +34 -0
  122. package/templates/app/app/commands/index.ts +15 -0
  123. package/templates/app/app/http/controllers/home.tsx +22 -0
  124. package/templates/app/app/http/controllers/not-found.tsx +25 -0
  125. package/templates/app/app/initializers/assets.ts +11 -0
  126. package/templates/app/app/initializers/cli.ts +35 -0
  127. package/templates/app/app/initializers/dispatcher.ts +18 -0
  128. package/templates/app/app/initializers/logger.ts +10 -0
  129. package/templates/app/app/initializers/mcp.ts +16 -0
  130. package/templates/app/app/initializers/router.tsx +65 -0
  131. package/templates/app/app/jobs/index.ts +10 -0
  132. package/templates/app/app/mcp/resources/index.ts +9 -0
  133. package/templates/app/app/mcp/tools/index.ts +10 -0
  134. package/templates/app/bootstrap/browser.ts +27 -0
  135. package/templates/app/bootstrap/cli.ts +9 -0
  136. package/templates/app/bootstrap/worker.ts +31 -0
  137. package/templates/app/cloudflare.config.ts +28 -0
  138. package/templates/app/config/router-context.d.ts +20 -0
  139. package/templates/app/gitignore +9 -0
  140. package/templates/app/package.json +38 -0
  141. package/templates/app/resources/layouts/document.tsx +58 -0
  142. package/templates/app/routes/web.ts +12 -0
  143. package/templates/app/tsconfig.json +40 -0
  144. package/templates/app/vite.config.ts +40 -0
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Plans the files one `sdxc make` run writes: the file of the requested kind at the folder the
3
+ * layout gives it and, when tests are on, its test beside it, each rendered from its stub.
4
+ * Nothing is written while planning, and a file that already exists stops the plan.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile, stat } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { failure, isFailure, isSuccess, success, wrap } from "@sdxc/result";
12
+ import { COMMON_PLACEHOLDERS, KINDS, MCP_RESOURCES_FOLDER } from "./kinds.js";
13
+ import { chainFolder, nextMigrationNumber } from "./migrations.js";
14
+ import { camel } from "./names.js";
15
+ import { loadStub, renderStub, stubName } from "./stubs.js";
16
+ /**
17
+ * Plans `request` in the project at `root`. Every planned path must be free; an existing file
18
+ * is a failure naming it, before any stub is read.
19
+ *
20
+ * @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
21
+ * @param overrides - Placeholder values a declaration decided, such as a job's reused group.
22
+ */
23
+ export async function plan(request, root, config, packageRoot, overrides = {}) {
24
+ let kind = KINDS[request.kind];
25
+ let { name } = request;
26
+ if (!kind.nested && name.segments.length > 1) {
27
+ return failure(new Error(`A ${request.kind} name cannot hold folders: ${name.segments.join("/")}`));
28
+ }
29
+ let folder = folderOf(request.kind, request.variant);
30
+ let file = name.segments.join("/");
31
+ if (request.kind === "migration") {
32
+ let chain = chainFolder(config.make.migrations, request.chain);
33
+ if (isFailure(chain))
34
+ return chain;
35
+ folder = chain.data;
36
+ let number = await nextMigrationNumber(root, folder);
37
+ if (isFailure(number))
38
+ return number;
39
+ file = `${number.data}_${name.pascal}`;
40
+ }
41
+ let path = `${folder}/${file}${kind.extension}`;
42
+ let testPath = `${folder}/${file}.test${kind.extension}`;
43
+ let writesTest = kind.tests && request.tests;
44
+ let paths = writesTest ? [path, testPath] : [path];
45
+ for (let candidate of paths) {
46
+ if (isSuccess(await wrap(() => stat(join(root, candidate))))) {
47
+ return failure(new Error(`${candidate} already exists; sdxc make leaves it as it is`));
48
+ }
49
+ }
50
+ let values = await placeholders(request, root, `${folder}/${file}`);
51
+ Object.assign(values, overrides);
52
+ let files = [];
53
+ let main = await renderFile(request, values, false, root, config, packageRoot);
54
+ if (isFailure(main))
55
+ return main;
56
+ files.push({ path, content: main.data });
57
+ if (writesTest) {
58
+ let test = await renderFile(request, values, true, root, config, packageRoot);
59
+ if (isFailure(test))
60
+ return test;
61
+ files.push({ path: testPath, content: test.data });
62
+ }
63
+ return success({ files, values });
64
+ }
65
+ /** The folder a kind's files go in; a migration's comes from its chain instead. */
66
+ export function folderOf(kind, variant) {
67
+ return kind === "mcp" && variant === "resource" ? MCP_RESOURCES_FOLDER : KINDS[kind].folder;
68
+ }
69
+ /**
70
+ * Renders the kind's stub, or its test stub, with `values`. A variant's own stub wins; a
71
+ * variant without its own test stub uses the kind's.
72
+ */
73
+ async function renderFile(request, values, test, root, config, packageRoot) {
74
+ let names = [stubName(request.kind, request.variant, test)];
75
+ if (request.variant !== null && test)
76
+ names.push(stubName(request.kind, null, true));
77
+ let stub = await loadStub(names, root, config.make.stubs, packageRoot);
78
+ if (isFailure(stub))
79
+ return stub;
80
+ return renderStub(stub.data, values);
81
+ }
82
+ /**
83
+ * The placeholder values for `request`: the common set every kind gets, plus the ones its kind
84
+ * defines. `file` is the generated file's path without its extension.
85
+ */
86
+ async function placeholders(request, root, file) {
87
+ let { name } = request;
88
+ let common = {
89
+ name: name.base,
90
+ key: name.key,
91
+ Name: name.pascal,
92
+ snake: name.snake,
93
+ title: name.title,
94
+ specifier: `~/${file}`,
95
+ };
96
+ let declarationPath = name.segments.map(camel).join(".");
97
+ let extra = {
98
+ path: declarationPath,
99
+ routes: `~/routes/${request.routes}`,
100
+ tool: name.segments.map((segment) => segment.replaceAll("-", "_")).join("_"),
101
+ uri: `${await resourceScheme(root)}://${name.segments.join("/")}`,
102
+ model: `~/app/models/${name.segments.join("/")}`,
103
+ command: name.segments.join(" "),
104
+ member: memberAccess(name.segments),
105
+ words: name.segments.map((segment) => JSON.stringify(segment)).join(", "),
106
+ };
107
+ let values = {};
108
+ for (let key of [...COMMON_PLACEHOLDERS, ...KINDS[request.kind].placeholders]) {
109
+ let value = common[key] ?? extra[key];
110
+ if (value !== undefined)
111
+ values[key] = value;
112
+ }
113
+ return values;
114
+ }
115
+ /**
116
+ * The property access that reaches a command's declaration from its contract: `.users.grant`,
117
+ * with a segment that is no identifier read by its quoted key (`["send-digest"]`), since a
118
+ * command's key is the word typed to run it.
119
+ */
120
+ export function memberAccess(segments) {
121
+ return segments
122
+ .map((segment) => /^[A-Za-z_$][\w$]*$/.test(segment) ? `.${segment}` : `[${JSON.stringify(segment)}]`)
123
+ .join("");
124
+ }
125
+ /**
126
+ * The URI scheme an MCP resource is declared under: the project's package name without its
127
+ * scope, reduced to the characters a scheme allows, or `app` when nothing usable is left.
128
+ */
129
+ export async function resourceScheme(root) {
130
+ let text = await wrap(() => readFile(join(root, "package.json"), "utf8"));
131
+ let parsed = isFailure(text) ? null : wrap(() => JSON.parse(text.data));
132
+ let name = parsed !== null && isSuccess(parsed) ? parsed.data.name : undefined;
133
+ let cleaned = (typeof name === "string" ? name : "")
134
+ .replace(/^@[^/]+\//, "")
135
+ .toLowerCase()
136
+ .replace(/[^a-z0-9+.-]+/g, "-")
137
+ .replace(/^[^a-z]+/, "");
138
+ return cleaned === "" ? "app" : cleaned;
139
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The imports a declaration or mapping needs in the file it edits: a namespace for a schema
3
+ * builder, the default export of a declaration module, a named helper such as `lazy`. Each is
4
+ * reused when the file already imports it, under whatever name it uses there, and added after
5
+ * the file's last import otherwise.
6
+ *
7
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
8
+ * @copyright Sergio Xalambrí 2026
9
+ */
10
+ import type { Result } from "@sdxc/result";
11
+ /** A source with an import ensured, and the local name that import binds. */
12
+ export interface Imported {
13
+ source: string;
14
+ local: string;
15
+ }
16
+ /** What to import: a namespace, the default export, or one named export. */
17
+ export type ImportKind = {
18
+ kind: "namespace";
19
+ } | {
20
+ kind: "default";
21
+ } | {
22
+ kind: "named";
23
+ name: string;
24
+ };
25
+ /**
26
+ * `source` importing `what` from a module `matches` accepts, as a value. An existing import is
27
+ * reused under its local name; otherwise `import … from "<specifier>"` is added as `preferred`
28
+ * after the last import, joining an existing named import list of `specifier` when there is one.
29
+ */
30
+ export declare function ensureImport(filename: string, source: string, what: ImportKind, matches: (specifier: string) => boolean, specifier: string, preferred: string): Result<Imported, Error>;
31
+ /**
32
+ * Whether `specifier`, written in `fromFile`, names the module at `target`: through the `~/`
33
+ * alias or a relative path, with or without an extension or a trailing `/index`. Both paths
34
+ * are relative to the project root.
35
+ */
36
+ export declare function resolvesTo(specifier: string, fromFile: string, target: string): boolean;
37
+ /**
38
+ * How `fromFile` should import `target` (a project-relative path without extension), following
39
+ * `examples`, the specifiers of the same kind the file already writes: through the `~/` alias
40
+ * when they use it, relatively when they do, with a `.js` extension when theirs carry one.
41
+ * Without examples, `aliased` decides, which is whether the project declares the `~/` alias.
42
+ */
43
+ export declare function specifierFor(fromFile: string, target: string, examples: readonly string[], aliased: boolean): string;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The imports a declaration or mapping needs in the file it edits: a namespace for a schema
3
+ * builder, the default export of a declaration module, a named helper such as `lazy`. Each is
4
+ * reused when the file already imports it, under whatever name it uses there, and added after
5
+ * the file's last import otherwise.
6
+ *
7
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
8
+ * @copyright Sergio Xalambrí 2026
9
+ */
10
+ import { dirname, posix } from "node:path";
11
+ import { findModuleReferences } from "@sdxc/codemod";
12
+ import { isFailure, success } from "@sdxc/result";
13
+ /**
14
+ * `source` importing `what` from a module `matches` accepts, as a value. An existing import is
15
+ * reused under its local name; otherwise `import … from "<specifier>"` is added as `preferred`
16
+ * after the last import, joining an existing named import list of `specifier` when there is one.
17
+ */
18
+ export function ensureImport(filename, source, what, matches, specifier, preferred) {
19
+ let references = findModuleReferences(filename, source);
20
+ if (isFailure(references))
21
+ return references;
22
+ let imports = references.data.filter((reference) => reference.kind === "import" && !reference.typeOnly && matches(reference.specifier));
23
+ for (let reference of imports) {
24
+ let bound = reference.names.find((name) => !name.typeOnly && bindsAs(name.imported, what));
25
+ if (bound !== undefined)
26
+ return success({ source, local: bound.local });
27
+ }
28
+ if (what.kind === "named") {
29
+ let list = imports.find((reference) => reference.braces !== null);
30
+ if (list?.braces) {
31
+ let inner = source.slice(list.braces.start + 1, list.braces.end - 1);
32
+ let at = list.braces.start + 1 + inner.replace(/[\s,]*$/, "").length;
33
+ let text = inner.trim() === "" ? ` ${what.name} ` : `, ${what.name}`;
34
+ return success({
35
+ source: `${source.slice(0, at)}${text}${source.slice(at)}`,
36
+ local: what.name,
37
+ });
38
+ }
39
+ }
40
+ let clause = what.kind === "namespace"
41
+ ? `* as ${preferred}`
42
+ : what.kind === "default"
43
+ ? preferred
44
+ : `{ ${what.name} }`;
45
+ let local = what.kind === "named" ? what.name : preferred;
46
+ let statement = `import ${clause} from ${JSON.stringify(specifier)};`;
47
+ return success({ source: insertImport(source, references.data, statement), local });
48
+ }
49
+ /** Whether a bound import name is the kind of binding `what` asks for. */
50
+ function bindsAs(imported, what) {
51
+ if (what.kind === "namespace")
52
+ return imported === "*";
53
+ if (what.kind === "default")
54
+ return imported === "default";
55
+ return imported === what.name;
56
+ }
57
+ /** `source` with `statement` on its own line after the last static import, or first. */
58
+ function insertImport(source, references, statement) {
59
+ let last = references.filter((reference) => reference.kind === "import").at(-1);
60
+ if (last === undefined)
61
+ return `${statement}\n${source}`;
62
+ let end = source.indexOf("\n", last.range.end);
63
+ let at = end === -1 ? source.length : end;
64
+ return `${source.slice(0, at)}\n${statement}${source.slice(at)}`;
65
+ }
66
+ /**
67
+ * Whether `specifier`, written in `fromFile`, names the module at `target`: through the `~/`
68
+ * alias or a relative path, with or without an extension or a trailing `/index`. Both paths
69
+ * are relative to the project root.
70
+ */
71
+ export function resolvesTo(specifier, fromFile, target) {
72
+ let path;
73
+ if (specifier.startsWith("~/"))
74
+ path = specifier.slice(2);
75
+ else if (specifier.startsWith("."))
76
+ path = posix.join(dirname(fromFile), specifier);
77
+ else
78
+ return false;
79
+ return moduleKey(path) === moduleKey(target);
80
+ }
81
+ /** A module path without its extension or a trailing `/index`, for comparing two spellings. */
82
+ function moduleKey(path) {
83
+ return posix
84
+ .normalize(path)
85
+ .replace(/\.(?:[cm]?[jt]sx?)$/, "")
86
+ .replace(/\/index$/, "");
87
+ }
88
+ /**
89
+ * How `fromFile` should import `target` (a project-relative path without extension), following
90
+ * `examples`, the specifiers of the same kind the file already writes: through the `~/` alias
91
+ * when they use it, relatively when they do, with a `.js` extension when theirs carry one.
92
+ * Without examples, `aliased` decides, which is whether the project declares the `~/` alias.
93
+ */
94
+ export function specifierFor(fromFile, target, examples, aliased) {
95
+ let relative = examples.filter((example) => example.startsWith("."));
96
+ let alias = examples.some((example) => example.startsWith("~/"));
97
+ if (alias || (relative.length === 0 && aliased))
98
+ return `~/${target.replace(/\/index$/, "")}`;
99
+ let withJs = relative.some((example) => example.endsWith(".js"));
100
+ let path = posix.relative(dirname(fromFile), target);
101
+ if (!path.startsWith("."))
102
+ path = `./${path}`;
103
+ return withJs ? `${path}.js` : path.replace(/\/index$/, "");
104
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * What one `sdxc make <kind>` run does: writes a file of the kind from its stub at the folder
3
+ * the app layout gives it, with a test beside it, declares and maps it where the kind needs it,
4
+ * lists any `@sdxc/*` package it imports in `package.json`, and runs the project's `format`.
5
+ * Every file is planned before any is written, and none is ever overwritten.
6
+ *
7
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
8
+ * @copyright Sergio Xalambrí 2026
9
+ */
10
+ import type { AnyCommandContext } from "@sdxc/cli";
11
+ import type { Result } from "@sdxc/result";
12
+ import type { Project } from "../middleware.js";
13
+ import type { KindName } from "./kinds.js";
14
+ /** One file to make, as the command line or the prompts gave it. */
15
+ export interface MakeInput {
16
+ kind: KindName;
17
+ name: string;
18
+ /** Whether to write a test beside the file; `undefined` takes `make.tests`. */
19
+ test: boolean | undefined;
20
+ dryRun: boolean;
21
+ /** `make job`: a scheduled job with this expression. */
22
+ cron?: string | undefined;
23
+ /** `make controller`: the route method, `form` declaring a GET page with a POST action. */
24
+ method?: string | undefined;
25
+ /** `make controller`: the route's pattern. */
26
+ path?: string | undefined;
27
+ /** `make controller`: the route contract in `routes/`; `undefined` takes `make.routes`. */
28
+ routes?: string | undefined;
29
+ /** `make mcp`: a resource instead of a tool. */
30
+ resource?: boolean | undefined;
31
+ /** `make migration`: the chain in `make.migrations`. */
32
+ chain?: string | undefined;
33
+ }
34
+ /** What `make` writes through: the command's output, child processes and tasks. */
35
+ export type MakeContext = Pick<AnyCommandContext, "stdout" | "exec" | "task">;
36
+ /**
37
+ * Plans, writes, declares and formats one file of `input.kind`, printing each path written and
38
+ * edited and each package added with the install command; under `dryRun` it prints the files
39
+ * and the diff of each edit, `package.json` included, instead.
40
+ *
41
+ * @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
42
+ */
43
+ export declare function make(ctx: MakeContext, project: Project, packageRoot: string, input: MakeInput): Promise<Result<void, Error>>;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * What one `sdxc make <kind>` run does: writes a file of the kind from its stub at the folder
3
+ * the app layout gives it, with a test beside it, declares and maps it where the kind needs it,
4
+ * lists any `@sdxc/*` package it imports in `package.json`, and runs the project's `format`.
5
+ * Every file is planned before any is written, and none is ever overwritten.
6
+ *
7
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
8
+ * @copyright Sergio Xalambrí 2026
9
+ */
10
+ import { mkdir, writeFile } from "node:fs/promises";
11
+ import { dirname, join } from "node:path";
12
+ import { isFailure, success, wrap } from "@sdxc/result";
13
+ import { missingDependencies } from "../dependencies.js";
14
+ import { unifiedDiff } from "../diff.js";
15
+ import { formatFiles } from "../format.js";
16
+ import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
17
+ import { readManifest } from "../upgrade/project.js";
18
+ import { declare } from "./declare.js";
19
+ import { folderOf, plan, resourceScheme } from "./generate.js";
20
+ import { parseName } from "./names.js";
21
+ /**
22
+ * Plans, writes, declares and formats one file of `input.kind`, printing each path written and
23
+ * edited and each package added with the install command; under `dryRun` it prints the files
24
+ * and the diff of each edit, `package.json` included, instead.
25
+ *
26
+ * @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
27
+ */
28
+ export async function make(ctx, project, packageRoot, input) {
29
+ let { root, config } = project;
30
+ let { kind } = input;
31
+ let name = parseName(input.name);
32
+ if (isFailure(name))
33
+ return name;
34
+ let method = input.method ?? "get";
35
+ let request = {
36
+ kind,
37
+ name: name.data,
38
+ variant: variantOf(kind, { cron: input.cron, method, resource: input.resource }),
39
+ tests: input.test ?? config.make.tests,
40
+ chain: input.chain,
41
+ routes: input.routes ?? config.make.routes,
42
+ };
43
+ let declared = null;
44
+ if (kind === "job" || kind === "controller" || kind === "mcp" || kind === "command") {
45
+ let segments = request.name.segments;
46
+ declared = await declare({
47
+ kind,
48
+ name: request.name,
49
+ variant: request.variant,
50
+ cron: input.cron,
51
+ method,
52
+ pattern: input.path,
53
+ routes: request.routes,
54
+ handler: `${folderOf(kind, request.variant)}/${segments.join("/")}`,
55
+ tool: segments.map((segment) => segment.replaceAll("-", "_")).join("_"),
56
+ uri: `${await resourceScheme(root)}://${segments.join("/")}`,
57
+ title: request.name.title,
58
+ }, root);
59
+ }
60
+ let overrides = declared === null ? {} : { path: declared.path };
61
+ let planned = await plan(request, root, config, packageRoot, overrides);
62
+ if (isFailure(planned))
63
+ return planned;
64
+ let edits = declared?.kind === "edits" ? [...declared.edits] : [];
65
+ let dependencies = await missingDependencies(root, [
66
+ ...planned.data.files,
67
+ ...edits.map((edit) => ({ path: edit.path, content: edit.after })),
68
+ ]);
69
+ if (isFailure(dependencies))
70
+ return dependencies;
71
+ if (dependencies.data !== null)
72
+ edits.push(dependencies.data);
73
+ if (input.dryRun) {
74
+ for (let file of planned.data.files) {
75
+ ctx.stdout(`Would write ${file.path}:\n\n${file.content}\n`);
76
+ }
77
+ for (let edit of edits)
78
+ ctx.stdout(unifiedDiff(edit.path, edit.before, edit.after));
79
+ if (declared?.kind === "manual")
80
+ ctx.stdout(manualNote(declared));
81
+ return success(undefined);
82
+ }
83
+ let written = await writeFiles(root, planned.data.files);
84
+ if (isFailure(written))
85
+ return written;
86
+ let paths = planned.data.files.map((file) => file.path);
87
+ for (let path of paths)
88
+ ctx.stdout(`Wrote ${path}\n`);
89
+ let edited = await wrap(async () => {
90
+ for (let edit of edits)
91
+ await writeFile(join(root, edit.path), edit.after);
92
+ });
93
+ if (isFailure(edited))
94
+ return edited;
95
+ for (let edit of edits) {
96
+ if (edit !== dependencies.data)
97
+ ctx.stdout(`Edited ${edit.path}\n`);
98
+ }
99
+ if (dependencies.data !== null) {
100
+ let read = await readManifest(root);
101
+ let manager = await packageManager({
102
+ declared: isFailure(read) ? undefined : read.data.manifest.packageManager,
103
+ findLockFile: lockFileAtOrAbove(root),
104
+ });
105
+ let added = dependencies.data.added.map(({ name, version }) => `${name}@${version}`);
106
+ ctx.stdout(`Added ${added.join(", ")} to package.json; run ${manager.install.join(" ")}\n`);
107
+ }
108
+ if (declared?.kind === "manual")
109
+ ctx.stdout(manualNote(declared));
110
+ let changed = [...paths, ...edits.map((edit) => edit.path)];
111
+ return formatFiles(ctx, config.format, changed, root);
112
+ }
113
+ /** What `make` prints when a declaration and its mapping are left for the user to make. */
114
+ function manualNote(declared) {
115
+ return `Declare and map it by hand, since ${declared.reason}:\n${declared.instructions}\n`;
116
+ }
117
+ /** The stub variant a request's flags select, or `null` for the kind's own stub. */
118
+ function variantOf(kind, flags) {
119
+ if (kind === "job" && flags.cron !== undefined)
120
+ return "cron";
121
+ if (kind === "controller" && flags.method === "form")
122
+ return "form";
123
+ if (kind === "mcp" && flags.resource === true)
124
+ return "resource";
125
+ return null;
126
+ }
127
+ /** Writes every planned file, creating its folders; an existing file fails the write. */
128
+ function writeFiles(root, files) {
129
+ return wrap(async () => {
130
+ for (let file of files) {
131
+ let target = join(root, file.path);
132
+ await mkdir(dirname(target), { recursive: true });
133
+ await writeFile(target, file.content, { flag: "wx" });
134
+ }
135
+ });
136
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Every kind of file `sdxc make` writes: the folder the app layout gives it, its extension,
3
+ * whether a test goes beside it, and the placeholders its stubs may use. The folders are
4
+ * fixed, so a generated file always lands where the layout expects to find it.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ /** A kind `sdxc make` writes. */
10
+ export type KindName = "controller" | "middleware" | "validator" | "job" | "model" | "migration" | "factory" | "service" | "policy" | "initializer" | "email" | "mcp" | "command";
11
+ /** Where one kind's files go and which placeholders their stubs may use. */
12
+ export interface Kind {
13
+ /** The folder under the project root; a migration's folder comes from its chain instead. */
14
+ folder: string;
15
+ extension: ".ts" | ".tsx" | ".sql";
16
+ /** Whether `make.tests` writes a test beside the file. */
17
+ tests: boolean;
18
+ /** Whether the name may hold folders. */
19
+ nested: boolean;
20
+ /** Placeholders beyond {@link COMMON_PLACEHOLDERS}. */
21
+ placeholders: readonly string[];
22
+ }
23
+ /**
24
+ * The placeholders every stub may use: the file's base name (`name`), its camelCase `key`, its
25
+ * PascalCase `Name`, its `snake` and `title` spellings, and the import `specifier` of the file.
26
+ */
27
+ export declare const COMMON_PLACEHOLDERS: string[];
28
+ /**
29
+ * Every kind, in the order `sdxc make --help` lists them. `path` is the declaration's key path
30
+ * in its map (`trials.expire`), `routes` the route contract's specifier, `tool` the MCP tool
31
+ * name, `uri` an MCP resource's pattern, `model` the factory's model specifier. A command's
32
+ * `command` is the words typed to run it (`users grant`), `member` the property access that
33
+ * reaches its declaration (`.users.grant`), and `words` those words as string literals.
34
+ */
35
+ export declare const KINDS: Readonly<Record<KindName, Kind>>;
36
+ /** Where `make mcp --resource` writes, beside the tools. */
37
+ export declare const MCP_RESOURCES_FOLDER = "app/mcp/resources";
38
+ /** Whether `value` names a kind. */
39
+ export declare function isKind(value: string): value is KindName;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Every kind of file `sdxc make` writes: the folder the app layout gives it, its extension,
3
+ * whether a test goes beside it, and the placeholders its stubs may use. The folders are
4
+ * fixed, so a generated file always lands where the layout expects to find it.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ /**
10
+ * The placeholders every stub may use: the file's base name (`name`), its camelCase `key`, its
11
+ * PascalCase `Name`, its `snake` and `title` spellings, and the import `specifier` of the file.
12
+ */
13
+ export const COMMON_PLACEHOLDERS = ["name", "key", "Name", "snake", "title", "specifier"];
14
+ /**
15
+ * Every kind, in the order `sdxc make --help` lists them. `path` is the declaration's key path
16
+ * in its map (`trials.expire`), `routes` the route contract's specifier, `tool` the MCP tool
17
+ * name, `uri` an MCP resource's pattern, `model` the factory's model specifier. A command's
18
+ * `command` is the words typed to run it (`users grant`), `member` the property access that
19
+ * reaches its declaration (`.users.grant`), and `words` those words as string literals.
20
+ */
21
+ export const KINDS = {
22
+ controller: {
23
+ folder: "app/http/controllers",
24
+ extension: ".tsx",
25
+ tests: true,
26
+ nested: true,
27
+ placeholders: ["path", "routes"],
28
+ },
29
+ middleware: {
30
+ folder: "app/http/middleware",
31
+ extension: ".ts",
32
+ tests: true,
33
+ nested: true,
34
+ placeholders: [],
35
+ },
36
+ validator: {
37
+ folder: "app/http/validators",
38
+ extension: ".ts",
39
+ tests: true,
40
+ nested: true,
41
+ placeholders: [],
42
+ },
43
+ job: { folder: "app/jobs", extension: ".ts", tests: true, nested: true, placeholders: ["path"] },
44
+ model: { folder: "app/models", extension: ".ts", tests: true, nested: true, placeholders: [] },
45
+ migration: {
46
+ folder: "database/migrations",
47
+ extension: ".sql",
48
+ tests: false,
49
+ nested: false,
50
+ placeholders: [],
51
+ },
52
+ factory: {
53
+ folder: "database/factories",
54
+ extension: ".ts",
55
+ tests: false,
56
+ nested: true,
57
+ placeholders: ["model"],
58
+ },
59
+ service: {
60
+ folder: "app/services",
61
+ extension: ".ts",
62
+ tests: true,
63
+ nested: true,
64
+ placeholders: [],
65
+ },
66
+ policy: { folder: "app/policies", extension: ".ts", tests: true, nested: true, placeholders: [] },
67
+ initializer: {
68
+ folder: "app/initializers",
69
+ extension: ".ts",
70
+ tests: true,
71
+ nested: true,
72
+ placeholders: [],
73
+ },
74
+ email: { folder: "app/emails", extension: ".tsx", tests: true, nested: true, placeholders: [] },
75
+ mcp: {
76
+ folder: "app/mcp/tools",
77
+ extension: ".ts",
78
+ tests: true,
79
+ nested: true,
80
+ placeholders: ["path", "tool", "uri"],
81
+ },
82
+ command: {
83
+ folder: "app/commands",
84
+ extension: ".ts",
85
+ tests: true,
86
+ nested: true,
87
+ placeholders: ["command", "member", "words"],
88
+ },
89
+ };
90
+ /** Where `make mcp --resource` writes, beside the tools. */
91
+ export const MCP_RESOURCES_FOLDER = "app/mcp/resources";
92
+ /** Whether `value` names a kind. */
93
+ export function isKind(value) {
94
+ return Object.hasOwn(KINDS, value);
95
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Migration chains: each configured chain is a folder of numbered SQL files applied in order,
3
+ * so a new migration takes the number after the highest one in its chain's folder. A project
4
+ * with a second schema, such as a Durable Object's own database, keeps it as a second chain.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Result } from "@sdxc/result";
10
+ /** The chain `make migration` writes into without `--chain`. */
11
+ export declare const DEFAULT_CHAIN = "default";
12
+ /**
13
+ * The folder of `chain` among the configured `chains`. An unknown chain is a failure listing
14
+ * the configured ones.
15
+ */
16
+ export declare function chainFolder(chains: Readonly<Record<string, string>>, chain: string | undefined): Result<string, Error>;
17
+ /**
18
+ * The number the next migration in `folder` takes, zero-padded: one after the highest number
19
+ * a file there starts with, or `0001` for a missing or empty folder.
20
+ */
21
+ export declare function nextMigrationNumber(root: string, folder: string): Promise<Result<string, Error>>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Migration chains: each configured chain is a folder of numbered SQL files applied in order,
3
+ * so a new migration takes the number after the highest one in its chain's folder. A project
4
+ * with a second schema, such as a Durable Object's own database, keeps it as a second chain.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readdir } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ /** The chain `make migration` writes into without `--chain`. */
13
+ export const DEFAULT_CHAIN = "default";
14
+ /** How many digits a migration number is padded to. */
15
+ const NUMBER_WIDTH = 4;
16
+ /**
17
+ * The folder of `chain` among the configured `chains`. An unknown chain is a failure listing
18
+ * the configured ones.
19
+ */
20
+ export function chainFolder(chains, chain) {
21
+ let name = chain ?? DEFAULT_CHAIN;
22
+ let folder = chains[name];
23
+ if (folder === undefined) {
24
+ let configured = Object.keys(chains).sort().join(", ");
25
+ return failure(new Error(`No migration chain "${name}" in make.migrations; configured: ${configured}`));
26
+ }
27
+ return success(folder);
28
+ }
29
+ /**
30
+ * The number the next migration in `folder` takes, zero-padded: one after the highest number
31
+ * a file there starts with, or `0001` for a missing or empty folder.
32
+ */
33
+ export async function nextMigrationNumber(root, folder) {
34
+ let entries = await wrap(() => readdir(join(root, folder)));
35
+ if (isFailure(entries)) {
36
+ let code = entries.error.code;
37
+ if (code !== "ENOENT")
38
+ return entries;
39
+ }
40
+ let names = isFailure(entries) ? [] : entries.data;
41
+ let highest = 0;
42
+ for (let name of names) {
43
+ let number = /^(\d+)[_-]/.exec(name)?.[1];
44
+ if (number !== undefined)
45
+ highest = Math.max(highest, Number.parseInt(number, 10));
46
+ }
47
+ return success(String(highest + 1).padStart(NUMBER_WIDTH, "0"));
48
+ }