@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.
- package/LICENSE.md +21 -0
- package/README.md +93 -0
- package/config.schema.json +89 -0
- package/dist/bin.d.ts +9 -0
- package/dist/bin.js +10 -0
- package/dist/cli.d.ts +33 -0
- package/dist/cli.js +58 -0
- package/dist/commands/create.d.ts +20 -0
- package/dist/commands/create.js +164 -0
- package/dist/commands/init.d.ts +16 -0
- package/dist/commands/init.js +27 -0
- package/dist/commands/make.d.ts +335 -0
- package/dist/commands/make.js +152 -0
- package/dist/commands/run.d.ts +23 -0
- package/dist/commands/run.js +51 -0
- package/dist/commands/ui/add.d.ts +23 -0
- package/dist/commands/ui/add.js +50 -0
- package/dist/commands/ui/diff.d.ts +20 -0
- package/dist/commands/ui/diff.js +28 -0
- package/dist/commands/ui/list.d.ts +24 -0
- package/dist/commands/ui/list.js +45 -0
- package/dist/commands/ui/remove.d.ts +22 -0
- package/dist/commands/ui/remove.js +48 -0
- package/dist/commands/ui/update.d.ts +23 -0
- package/dist/commands/ui/update.js +37 -0
- package/dist/commands/upgrade.d.ts +30 -0
- package/dist/commands/upgrade.js +184 -0
- package/dist/config.d.ts +81 -0
- package/dist/config.js +157 -0
- package/dist/contract.d.ts +161 -0
- package/dist/contract.js +308 -0
- package/dist/create/github.d.ts +63 -0
- package/dist/create/github.js +172 -0
- package/dist/create/target.d.ts +31 -0
- package/dist/create/target.js +56 -0
- package/dist/create/templates.d.ts +62 -0
- package/dist/create/templates.js +228 -0
- package/dist/dependencies.d.ts +34 -0
- package/dist/dependencies.js +76 -0
- package/dist/diff.d.ts +14 -0
- package/dist/diff.js +103 -0
- package/dist/format.d.ts +21 -0
- package/dist/format.js +40 -0
- package/dist/init.d.ts +38 -0
- package/dist/init.js +92 -0
- package/dist/lock.d.ts +74 -0
- package/dist/lock.js +214 -0
- package/dist/make/declare.d.ts +54 -0
- package/dist/make/declare.js +495 -0
- package/dist/make/generate.d.ts +56 -0
- package/dist/make/generate.js +139 -0
- package/dist/make/imports.d.ts +43 -0
- package/dist/make/imports.js +104 -0
- package/dist/make/index.d.ts +43 -0
- package/dist/make/index.js +136 -0
- package/dist/make/kinds.d.ts +39 -0
- package/dist/make/kinds.js +95 -0
- package/dist/make/migrations.d.ts +21 -0
- package/dist/make/migrations.js +48 -0
- package/dist/make/names.d.ts +31 -0
- package/dist/make/names.js +47 -0
- package/dist/make/stubs.d.ts +44 -0
- package/dist/make/stubs.js +89 -0
- package/dist/middleware.d.ts +44 -0
- package/dist/middleware.js +49 -0
- package/dist/package-manager.d.ts +41 -0
- package/dist/package-manager.js +80 -0
- package/dist/project.d.ts +19 -0
- package/dist/project.js +42 -0
- package/dist/releases.d.ts +40 -0
- package/dist/releases.js +110 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +126 -0
- package/dist/ui/commands.d.ts +114 -0
- package/dist/ui/commands.js +432 -0
- package/dist/ui/imports.d.ts +46 -0
- package/dist/ui/imports.js +160 -0
- package/dist/ui/layout.d.ts +48 -0
- package/dist/ui/layout.js +138 -0
- package/dist/ui/registry.d.ts +58 -0
- package/dist/ui/registry.js +82 -0
- package/dist/upgrade/changelog.d.ts +50 -0
- package/dist/upgrade/changelog.js +69 -0
- package/dist/upgrade/project.d.ts +62 -0
- package/dist/upgrade/project.js +132 -0
- package/dist/upgrade/prompt.d.ts +51 -0
- package/dist/upgrade/prompt.js +227 -0
- package/dist/upgrade/registry.d.ts +33 -0
- package/dist/upgrade/registry.js +50 -0
- package/lock.schema.json +60 -0
- package/package.json +45 -0
- package/stubs/command.stub +12 -0
- package/stubs/command.test.stub +18 -0
- package/stubs/controller.form.stub +33 -0
- package/stubs/controller.stub +17 -0
- package/stubs/controller.test.stub +15 -0
- package/stubs/email.stub +44 -0
- package/stubs/email.test.stub +16 -0
- package/stubs/factory.stub +10 -0
- package/stubs/initializer.stub +7 -0
- package/stubs/initializer.test.stub +13 -0
- package/stubs/job.cron.stub +12 -0
- package/stubs/job.stub +11 -0
- package/stubs/job.test.stub +15 -0
- package/stubs/mcp.resource.stub +12 -0
- package/stubs/mcp.stub +10 -0
- package/stubs/mcp.test.stub +15 -0
- package/stubs/middleware.stub +11 -0
- package/stubs/middleware.test.stub +13 -0
- package/stubs/migration.stub +1 -0
- package/stubs/model.stub +24 -0
- package/stubs/model.test.stub +15 -0
- package/stubs/policy.stub +13 -0
- package/stubs/policy.test.stub +17 -0
- package/stubs/service.stub +13 -0
- package/stubs/service.test.stub +14 -0
- package/stubs/validator.stub +14 -0
- package/stubs/validator.test.stub +22 -0
- package/templates/app/README.md +57 -0
- package/templates/app/app/commands/about.test.ts +29 -0
- package/templates/app/app/commands/about.ts +34 -0
- package/templates/app/app/commands/index.ts +15 -0
- package/templates/app/app/http/controllers/home.tsx +22 -0
- package/templates/app/app/http/controllers/not-found.tsx +25 -0
- package/templates/app/app/initializers/assets.ts +11 -0
- package/templates/app/app/initializers/cli.ts +35 -0
- package/templates/app/app/initializers/dispatcher.ts +18 -0
- package/templates/app/app/initializers/logger.ts +10 -0
- package/templates/app/app/initializers/mcp.ts +16 -0
- package/templates/app/app/initializers/router.tsx +65 -0
- package/templates/app/app/jobs/index.ts +10 -0
- package/templates/app/app/mcp/resources/index.ts +9 -0
- package/templates/app/app/mcp/tools/index.ts +10 -0
- package/templates/app/bootstrap/browser.ts +27 -0
- package/templates/app/bootstrap/cli.ts +9 -0
- package/templates/app/bootstrap/worker.ts +31 -0
- package/templates/app/cloudflare.config.ts +28 -0
- package/templates/app/config/router-context.d.ts +20 -0
- package/templates/app/gitignore +9 -0
- package/templates/app/package.json +38 -0
- package/templates/app/resources/layouts/document.tsx +58 -0
- package/templates/app/routes/web.ts +12 -0
- package/templates/app/tsconfig.json +40 -0
- package/templates/app/vite.config.ts +40 -0
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Declares and maps what `make job`, `make controller`, `make mcp` and `make command` generate:
|
|
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.
|
|
7
|
+
*
|
|
8
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
9
|
+
* @copyright Sergio Xalambrí 2026
|
|
10
|
+
*/
|
|
11
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
12
|
+
import { dirname, join, posix } from "node:path";
|
|
13
|
+
import { addProperty, findModuleReferences, insertAfterLast } from "@sdxc/codemod";
|
|
14
|
+
import { failure, isFailure, isSuccess, success, wrap } from "@sdxc/result";
|
|
15
|
+
import { memberAccess } from "./generate.js";
|
|
16
|
+
import { ensureImport, resolvesTo, specifierFor } from "./imports.js";
|
|
17
|
+
import { camel } from "./names.js";
|
|
18
|
+
/** The `remix/routes` helper each `--method` declares with; `form` adds a page and an action. */
|
|
19
|
+
const ROUTE_HELPERS = {
|
|
20
|
+
get: "get",
|
|
21
|
+
post: "post",
|
|
22
|
+
put: "put",
|
|
23
|
+
patch: "patch",
|
|
24
|
+
delete: "del",
|
|
25
|
+
form: "form",
|
|
26
|
+
};
|
|
27
|
+
/** The name an instance gets when the initializer that creates it cannot be read, by factory. */
|
|
28
|
+
const INSTANCE_NAMES = {
|
|
29
|
+
createRouter: "router",
|
|
30
|
+
createHandler: "mcp",
|
|
31
|
+
createCLI: "cli",
|
|
32
|
+
};
|
|
33
|
+
/** Plans the declaration and mapping for `request` in the project at `root`. */
|
|
34
|
+
export async function declare(request, root) {
|
|
35
|
+
if (request.kind === "job")
|
|
36
|
+
return declareJob(request, root);
|
|
37
|
+
if (request.kind === "controller")
|
|
38
|
+
return declareController(request, root);
|
|
39
|
+
if (request.kind === "command")
|
|
40
|
+
return declareCommand(request, root);
|
|
41
|
+
return declareMcp(request, root);
|
|
42
|
+
}
|
|
43
|
+
/** Declares a job in `app/jobs/index.ts` and maps it on the job dispatcher. */
|
|
44
|
+
async function declareJob(request, root) {
|
|
45
|
+
let declarations = "app/jobs/index.ts";
|
|
46
|
+
let module = "app/jobs/index";
|
|
47
|
+
let { name } = request;
|
|
48
|
+
let initializer = await findInitializer(root, module, "createJobDispatcher");
|
|
49
|
+
let instance = initializer === null ? "dispatcher" : instanceOf(initializer, "createJobDispatcher");
|
|
50
|
+
let local = initializer === null ? "jobs" : (defaultLocal(initializer, module) ?? "jobs");
|
|
51
|
+
let groups = initializer === null ? null : reusedGroup(initializer, instance, local, name);
|
|
52
|
+
let path = [...(groups ?? name.segments.slice(0, -1).map(camel)), name.key];
|
|
53
|
+
let value = request.variant === "cron"
|
|
54
|
+
? `job({ cron: ${JSON.stringify(request.cron ?? "")} })`
|
|
55
|
+
: "job({ input: s.object({}) })";
|
|
56
|
+
let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
|
|
57
|
+
let statement = `${instance}.map(${local}.${path.join(".")}, () => import(${JSON.stringify(handler)}));`;
|
|
58
|
+
let manual = (reason) => ({
|
|
59
|
+
kind: "manual",
|
|
60
|
+
path: path.join("."),
|
|
61
|
+
reason,
|
|
62
|
+
instructions: instructions(`${declarations}, in jobs({ … })${groupNote(path)}`, `${path.at(-1)}: ${value},`, initializer?.path ?? "the job dispatcher's initializer", statement),
|
|
63
|
+
});
|
|
64
|
+
if (initializer === null)
|
|
65
|
+
return manual("no initializer in app/initializers/ creates the job dispatcher");
|
|
66
|
+
let file = await readSource(root, declarations);
|
|
67
|
+
if (isFailure(file))
|
|
68
|
+
return manual(`${declarations} could not be read`);
|
|
69
|
+
let jobsSpecifier = file.data.references.find((reference) => reference.kind === "import" && reference.names.some((bound) => bound.imported === "jobs"))?.specifier;
|
|
70
|
+
if (jobsSpecifier === undefined)
|
|
71
|
+
return manual(`${declarations} does not import jobs()`);
|
|
72
|
+
let builder = ensureImport(declarations, file.data.source, { kind: "named", name: "job" }, (specifier) => specifier === jobsSpecifier, jobsSpecifier, "job");
|
|
73
|
+
if (isFailure(builder))
|
|
74
|
+
return manual(builder.error.message);
|
|
75
|
+
let jobLocal = builder.data.local;
|
|
76
|
+
let source = builder.data.source;
|
|
77
|
+
value = value.replace(/^job\(/, `${jobLocal}(`);
|
|
78
|
+
if (request.variant !== "cron") {
|
|
79
|
+
let schema = ensureImport(declarations, source, { kind: "namespace" }, (specifier) => specifier === "remix/data-schema", "remix/data-schema", "s");
|
|
80
|
+
if (isFailure(schema))
|
|
81
|
+
return manual(schema.error.message);
|
|
82
|
+
value = `${jobLocal}({ input: ${schema.data.local}.object({}) })`;
|
|
83
|
+
source = schema.data.source;
|
|
84
|
+
}
|
|
85
|
+
let added = addProperty(declarations, source, {
|
|
86
|
+
call: "jobs",
|
|
87
|
+
path: path.slice(0, -1),
|
|
88
|
+
key: name.key,
|
|
89
|
+
value,
|
|
90
|
+
});
|
|
91
|
+
if (isFailure(added))
|
|
92
|
+
return manual(added.error.message);
|
|
93
|
+
let mapped = mapAfter(initializer, module, local, statement, `${instance}.map`, "createJobDispatcher");
|
|
94
|
+
if (isFailure(mapped))
|
|
95
|
+
return manual(mapped.error.message);
|
|
96
|
+
return {
|
|
97
|
+
kind: "edits",
|
|
98
|
+
path: path.join("."),
|
|
99
|
+
edits: [
|
|
100
|
+
{ path: declarations, before: file.data.source, after: added.data.source },
|
|
101
|
+
{ path: initializer.path, before: initializer.source, after: mapped.data },
|
|
102
|
+
],
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** Declares a route in the contract `routes/<contract>.ts` and maps it on the router. */
|
|
106
|
+
async function declareController(request, root) {
|
|
107
|
+
let { name } = request;
|
|
108
|
+
let module = `routes/${request.routes}`;
|
|
109
|
+
let contract = await findContract(root, module);
|
|
110
|
+
let initializer = await findInitializer(root, module, null);
|
|
111
|
+
let instance = initializer === null ? "router" : instanceOf(initializer, "createRouter");
|
|
112
|
+
let local = initializer === null ? "routes" : (defaultLocal(initializer, module) ?? "routes");
|
|
113
|
+
let path = [...name.segments.slice(0, -1).map(camel), name.key];
|
|
114
|
+
let helper = ROUTE_HELPERS[request.method] ?? "get";
|
|
115
|
+
let pattern = request.pattern ?? `/${name.segments.join("/")}`;
|
|
116
|
+
let value = `${helper}(${JSON.stringify(pattern)})`;
|
|
117
|
+
let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
|
|
118
|
+
let lazyLocal = "lazy";
|
|
119
|
+
let statement = (lazy) => `${instance}.map(${local}.${path.join(".")}, ${lazy}(() => import(${JSON.stringify(handler)})));`;
|
|
120
|
+
let manual = (reason) => ({
|
|
121
|
+
kind: "manual",
|
|
122
|
+
path: path.join("."),
|
|
123
|
+
reason,
|
|
124
|
+
instructions: instructions(`${contract ?? `${module}.ts`}, in route({ … })${groupNote(path)}`, `${path.at(-1)}: ${value},`, initializer?.path ?? `the initializer that maps ${module}`, statement(lazyLocal)),
|
|
125
|
+
});
|
|
126
|
+
if (contract === null)
|
|
127
|
+
return manual(`there is no route contract ${module}.ts`);
|
|
128
|
+
if (initializer === null)
|
|
129
|
+
return manual(`no initializer in app/initializers/ imports ${module}`);
|
|
130
|
+
let file = await readSource(root, contract);
|
|
131
|
+
if (isFailure(file))
|
|
132
|
+
return manual(`${contract} could not be read`);
|
|
133
|
+
let imported = ensureImport(contract, file.data.source, { kind: "named", name: helper }, (specifier) => specifier === "remix/routes", "remix/routes", helper);
|
|
134
|
+
if (isFailure(imported))
|
|
135
|
+
return manual(imported.error.message);
|
|
136
|
+
value = `${imported.data.local}(${JSON.stringify(pattern)})`;
|
|
137
|
+
let added = addProperty(contract, imported.data.source, {
|
|
138
|
+
call: "route",
|
|
139
|
+
path: path.slice(0, -1),
|
|
140
|
+
key: name.key,
|
|
141
|
+
value,
|
|
142
|
+
});
|
|
143
|
+
if (isFailure(added))
|
|
144
|
+
return manual(added.error.message);
|
|
145
|
+
let lazy = ensureImport(initializer.path, initializer.source, { kind: "named", name: "lazy" }, (specifier) => specifier.endsWith("lazy-route"), "@sdxc/lazy-route", "lazy");
|
|
146
|
+
if (isFailure(lazy))
|
|
147
|
+
return manual(lazy.error.message);
|
|
148
|
+
lazyLocal = lazy.data.local;
|
|
149
|
+
let withLazy = { ...initializer, source: lazy.data.source };
|
|
150
|
+
let mapped = mapAfter(withLazy, module, local, statement(lazyLocal), `${instance}.map`, "createRouter");
|
|
151
|
+
if (isFailure(mapped))
|
|
152
|
+
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
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/** Declares an MCP tool or resource beside the others and maps it on the MCP handler. */
|
|
163
|
+
async function declareMcp(request, root) {
|
|
164
|
+
let resource = request.variant === "resource";
|
|
165
|
+
let group = resource ? "resources" : "tools";
|
|
166
|
+
let module = `app/mcp/${group}/index`;
|
|
167
|
+
let declarations = `${module}.ts`;
|
|
168
|
+
let { name } = request;
|
|
169
|
+
let initializer = await findInitializer(root, module, "createHandler");
|
|
170
|
+
let instance = initializer === null ? "mcp" : instanceOf(initializer, "createHandler");
|
|
171
|
+
let preferred = resource ? "resourceset" : "toolset";
|
|
172
|
+
let local = initializer === null ? preferred : (defaultLocal(initializer, module) ?? preferred);
|
|
173
|
+
let path = [...name.segments.slice(0, -1).map(camel), name.key];
|
|
174
|
+
let builder = resource ? "resource" : "tool";
|
|
175
|
+
let body = resource
|
|
176
|
+
? [`name: ${JSON.stringify(request.title)},`, 'mimeType: "text/markdown",']
|
|
177
|
+
: [`description: ${JSON.stringify(`${request.title}.`)},`, "input: s.object({}),"];
|
|
178
|
+
let first = resource ? request.uri : request.tool;
|
|
179
|
+
let valueWith = (callee, lines) => `${callee}(${JSON.stringify(first)}, {\n${lines.map((line) => `\t${line}`).join("\n")}\n})`;
|
|
180
|
+
let value = valueWith(builder, body);
|
|
181
|
+
let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
|
|
182
|
+
let statement = (lazy) => `${instance}.${group}.map(${local}.${path.join(".")}, ${lazy}(() => import(${JSON.stringify(handler)})));`;
|
|
183
|
+
let manual = (reason) => ({
|
|
184
|
+
kind: "manual",
|
|
185
|
+
path: path.join("."),
|
|
186
|
+
reason,
|
|
187
|
+
instructions: instructions(`${declarations}, in ${group}({ … })${groupNote(path)}`, `${path.at(-1)}: ${value},`, initializer?.path ?? "the MCP handler's initializer", statement("lazy")),
|
|
188
|
+
});
|
|
189
|
+
if (initializer === null)
|
|
190
|
+
return manual("no initializer in app/initializers/ creates the MCP handler");
|
|
191
|
+
let file = await readSource(root, declarations);
|
|
192
|
+
if (isFailure(file))
|
|
193
|
+
return manual(`${declarations} could not be read`);
|
|
194
|
+
let mcpSpecifier = file.data.references.find((reference) => reference.kind === "import" && reference.names.some((bound) => bound.imported === group))?.specifier;
|
|
195
|
+
if (mcpSpecifier === undefined)
|
|
196
|
+
return manual(`${declarations} does not import ${group}()`);
|
|
197
|
+
let builderImport = ensureImport(declarations, file.data.source, { kind: "named", name: builder }, (specifier) => specifier === mcpSpecifier, mcpSpecifier, builder);
|
|
198
|
+
if (isFailure(builderImport))
|
|
199
|
+
return manual(builderImport.error.message);
|
|
200
|
+
let source = builderImport.data.source;
|
|
201
|
+
if (!resource) {
|
|
202
|
+
let schemaSpecifier = mcpSpecifier.replace(/mcp$/, "json-schema");
|
|
203
|
+
let schema = ensureImport(declarations, source, { kind: "namespace" }, (specifier) => specifier === schemaSpecifier, schemaSpecifier, "s");
|
|
204
|
+
if (isFailure(schema))
|
|
205
|
+
return manual(schema.error.message);
|
|
206
|
+
source = schema.data.source;
|
|
207
|
+
body[1] = `input: ${schema.data.local}.object({}),`;
|
|
208
|
+
}
|
|
209
|
+
let added = addProperty(declarations, source, {
|
|
210
|
+
call: group,
|
|
211
|
+
path: path.slice(0, -1),
|
|
212
|
+
key: name.key,
|
|
213
|
+
value: valueWith(builderImport.data.local, body),
|
|
214
|
+
});
|
|
215
|
+
if (isFailure(added))
|
|
216
|
+
return manual(added.error.message);
|
|
217
|
+
let handlerSource = initializer.references.find((reference) => reference.kind === "import" &&
|
|
218
|
+
reference.names.some((bound) => bound.imported === "createHandler"))?.specifier;
|
|
219
|
+
if (handlerSource === undefined)
|
|
220
|
+
return manual(`${initializer.path} does not import createHandler`);
|
|
221
|
+
let lazy = ensureImport(initializer.path, initializer.source, { kind: "named", name: "lazy" }, (specifier) => specifier === handlerSource, handlerSource, "lazy");
|
|
222
|
+
if (isFailure(lazy))
|
|
223
|
+
return manual(lazy.error.message);
|
|
224
|
+
let withLazy = { ...initializer, source: lazy.data.source };
|
|
225
|
+
let mapped = mapAfter(withLazy, module, local, statement(lazy.data.local), `${instance}.${group}.map`, "createHandler");
|
|
226
|
+
if (isFailure(mapped))
|
|
227
|
+
return manual(mapped.error.message);
|
|
228
|
+
return {
|
|
229
|
+
kind: "edits",
|
|
230
|
+
path: path.join("."),
|
|
231
|
+
edits: [
|
|
232
|
+
{ path: declarations, before: file.data.source, after: added.data.source },
|
|
233
|
+
{ path: initializer.path, before: initializer.source, after: mapped.data },
|
|
234
|
+
],
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Declares a command in `app/commands/index.ts` and maps it on the command line. Each folder of
|
|
239
|
+
* the name is a `commands({ … })` group, created when missing, and the command's key is the
|
|
240
|
+
* word typed to run it, so `users/send-digest` runs as `users send-digest`.
|
|
241
|
+
*/
|
|
242
|
+
async function declareCommand(request, root) {
|
|
243
|
+
let module = "app/commands/index";
|
|
244
|
+
let declarations = `${module}.ts`;
|
|
245
|
+
let segments = request.name.segments;
|
|
246
|
+
let groups = segments.slice(0, -1);
|
|
247
|
+
let leaf = segments.at(-1) ?? "";
|
|
248
|
+
let initializer = await findInitializer(root, module, "createCLI");
|
|
249
|
+
let instance = initializer === null ? "cli" : instanceOf(initializer, "createCLI");
|
|
250
|
+
let local = initializer === null ? "commandset" : (defaultLocal(initializer, module) ?? "commandset");
|
|
251
|
+
let description = JSON.stringify(request.title);
|
|
252
|
+
let handler = initializer === null ? `~/${request.handler}` : handlerSpecifier(initializer, request.handler);
|
|
253
|
+
let statement = (lazy) => `${instance}.map(${local}${memberAccess(segments)}, ${lazy}(() => import(${JSON.stringify(handler)})));`;
|
|
254
|
+
let manual = (reason) => ({
|
|
255
|
+
kind: "manual",
|
|
256
|
+
path: segments.join("."),
|
|
257
|
+
reason,
|
|
258
|
+
instructions: instructions(`${declarations}, in commands({ … })${groups.length > 0 ? `, inside a commands({ … }) group for each of ${groups.join(", ")}` : ""}`, `${keyText(leaf)}: command({ description: ${description} }),`, initializer?.path ?? "the command line's initializer", statement("lazy")),
|
|
259
|
+
});
|
|
260
|
+
if (initializer === null)
|
|
261
|
+
return manual("no initializer in app/initializers/ creates the command line");
|
|
262
|
+
let file = await readSource(root, declarations);
|
|
263
|
+
if (isFailure(file))
|
|
264
|
+
return manual(`${declarations} could not be read`);
|
|
265
|
+
let group = file.data.references.find((reference) => reference.kind === "import" && reference.names.some((bound) => bound.imported === "commands"));
|
|
266
|
+
let groupLocal = group?.names.find((bound) => bound.imported === "commands")?.local;
|
|
267
|
+
if (group === undefined || groupLocal === undefined)
|
|
268
|
+
return manual(`${declarations} does not import commands()`);
|
|
269
|
+
let builder = ensureImport(declarations, file.data.source, { kind: "named", name: "command" }, (specifier) => specifier === group.specifier, group.specifier, "command");
|
|
270
|
+
if (isFailure(builder))
|
|
271
|
+
return manual(builder.error.message);
|
|
272
|
+
let source = builder.data.source;
|
|
273
|
+
let depth = 0;
|
|
274
|
+
for (; depth < groups.length; depth += 1) {
|
|
275
|
+
let level = groups[depth] ?? "";
|
|
276
|
+
let probe = addProperty(declarations, source, {
|
|
277
|
+
call: groupLocal,
|
|
278
|
+
path: groups.slice(0, depth),
|
|
279
|
+
key: level,
|
|
280
|
+
value: "0",
|
|
281
|
+
});
|
|
282
|
+
if (isSuccess(probe))
|
|
283
|
+
break;
|
|
284
|
+
if (probe.error.code !== "duplicate-key")
|
|
285
|
+
return manual(probe.error.message);
|
|
286
|
+
let isGroup = new RegExp(`(?:^|[\\s{,])["']?${escape(level)}["']?\\s*:\\s*${escape(groupLocal)}\\(`);
|
|
287
|
+
if (!isGroup.test(source)) {
|
|
288
|
+
return manual(`\`${groups.slice(0, depth + 1).join(".")}\` is a command, not a group`);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
let entry = `${keyText(leaf)}: ${builder.data.local}({ description: ${description} })`;
|
|
292
|
+
let added = depth === groups.length
|
|
293
|
+
? addProperty(declarations, source, {
|
|
294
|
+
call: groupLocal,
|
|
295
|
+
path: groups,
|
|
296
|
+
key: leaf,
|
|
297
|
+
value: `${builder.data.local}({ description: ${description} })`,
|
|
298
|
+
})
|
|
299
|
+
: addProperty(declarations, source, {
|
|
300
|
+
call: groupLocal,
|
|
301
|
+
path: groups.slice(0, depth),
|
|
302
|
+
key: groups[depth] ?? "",
|
|
303
|
+
value: groupValue(groupLocal, groups.slice(depth + 1), entry),
|
|
304
|
+
});
|
|
305
|
+
if (isFailure(added))
|
|
306
|
+
return manual(added.error.message);
|
|
307
|
+
let cliSource = initializer.references.find((reference) => reference.kind === "import" &&
|
|
308
|
+
reference.names.some((bound) => bound.imported === "createCLI"))?.specifier;
|
|
309
|
+
if (cliSource === undefined)
|
|
310
|
+
return manual(`${initializer.path} does not import createCLI`);
|
|
311
|
+
let lazy = ensureImport(initializer.path, initializer.source, { kind: "named", name: "lazy" }, (specifier) => specifier === cliSource, cliSource, "lazy");
|
|
312
|
+
if (isFailure(lazy))
|
|
313
|
+
return manual(lazy.error.message);
|
|
314
|
+
let withLazy = { ...initializer, source: lazy.data.source };
|
|
315
|
+
let mapped = mapAfter(withLazy, module, local, statement(lazy.data.local), `${instance}.map`, "createCLI");
|
|
316
|
+
if (isFailure(mapped))
|
|
317
|
+
return manual(mapped.error.message);
|
|
318
|
+
return {
|
|
319
|
+
kind: "edits",
|
|
320
|
+
path: segments.join("."),
|
|
321
|
+
edits: [
|
|
322
|
+
{ path: declarations, before: file.data.source, after: added.data.source },
|
|
323
|
+
{ path: initializer.path, before: initializer.source, after: mapped.data },
|
|
324
|
+
],
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* A `commands({ … })` group holding `entry`, wrapped in one more group for each of `levels`,
|
|
329
|
+
* outermost first, for the folders of a command name that have no group yet.
|
|
330
|
+
*/
|
|
331
|
+
function groupValue(call, levels, entry) {
|
|
332
|
+
let inner = entry;
|
|
333
|
+
for (let level of [...levels].reverse()) {
|
|
334
|
+
inner = `${keyText(level)}: ${call}({\n${indentTab(inner)},\n})`;
|
|
335
|
+
}
|
|
336
|
+
return `${call}({\n${indentTab(inner)},\n})`;
|
|
337
|
+
}
|
|
338
|
+
/** A command's key as an identifier when it is one, quoted otherwise. */
|
|
339
|
+
function keyText(key) {
|
|
340
|
+
return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
|
|
341
|
+
}
|
|
342
|
+
/** Every line of `text` indented by one tab. */
|
|
343
|
+
function indentTab(text) {
|
|
344
|
+
return text
|
|
345
|
+
.split("\n")
|
|
346
|
+
.map((line) => `\t${line}`)
|
|
347
|
+
.join("\n");
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* `file` with the declarations module imported as `local` (added when missing) and `statement`
|
|
351
|
+
* after the last call to `call`, or after the instance `factory` creates when there is none.
|
|
352
|
+
*/
|
|
353
|
+
function mapAfter(file, module, local, statement, call, factory) {
|
|
354
|
+
let examples = staticSpecifiers(file);
|
|
355
|
+
let imported = ensureImport(file.path, file.source, { kind: "default" }, (specifier) => resolvesTo(specifier, file.path, module), specifierFor(file.path, module, examples, file.aliased ?? false), local);
|
|
356
|
+
if (isFailure(imported))
|
|
357
|
+
return imported;
|
|
358
|
+
if (imported.data.local !== local)
|
|
359
|
+
return failure(new Error(`${file.path} imports ${module} as ${imported.data.local}`));
|
|
360
|
+
let inserted = insertAfterLast(file.path, imported.data.source, {
|
|
361
|
+
call,
|
|
362
|
+
statement,
|
|
363
|
+
fallbackAfter: factory,
|
|
364
|
+
});
|
|
365
|
+
if (isFailure(inserted))
|
|
366
|
+
return inserted;
|
|
367
|
+
return success(inserted.data.source);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
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.
|
|
372
|
+
*/
|
|
373
|
+
async function findInitializer(root, module, factory) {
|
|
374
|
+
let folder = "app/initializers";
|
|
375
|
+
let entries = await wrap(() => readdir(join(root, folder)));
|
|
376
|
+
if (isFailure(entries))
|
|
377
|
+
return null;
|
|
378
|
+
let files = [];
|
|
379
|
+
for (let entry of entries.data.sort()) {
|
|
380
|
+
if (!/\.tsx?$/.test(entry) || /\.test\.tsx?$/.test(entry) || entry.endsWith(".d.ts"))
|
|
381
|
+
continue;
|
|
382
|
+
let file = await readSource(root, `${folder}/${entry}`);
|
|
383
|
+
if (isSuccess(file))
|
|
384
|
+
files.push(file.data);
|
|
385
|
+
}
|
|
386
|
+
let tsconfig = await wrap(() => readFile(join(root, "tsconfig.json"), "utf8"));
|
|
387
|
+
let aliased = !isFailure(tsconfig) && tsconfig.data.includes('"~/app/*"');
|
|
388
|
+
for (let file of files)
|
|
389
|
+
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)
|
|
394
|
+
return null;
|
|
395
|
+
let calling = new RegExp(`\\b${factory}\\(`);
|
|
396
|
+
return files.find((file) => calling.test(file.source)) ?? null;
|
|
397
|
+
}
|
|
398
|
+
/** The route contract file for `module` (`routes/web`), `.ts` or `.tsx`, or `null`. */
|
|
399
|
+
async function findContract(root, module) {
|
|
400
|
+
for (let extension of [".ts", ".tsx"]) {
|
|
401
|
+
let path = `${module}${extension}`;
|
|
402
|
+
if (isSuccess(await wrap(() => readFile(join(root, path)))))
|
|
403
|
+
return path;
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
/** Reads a project file and scans its module references. */
|
|
408
|
+
async function readSource(root, path) {
|
|
409
|
+
let source = await wrap(() => readFile(join(root, path), "utf8"));
|
|
410
|
+
if (isFailure(source))
|
|
411
|
+
return source;
|
|
412
|
+
let references = findModuleReferences(path, source.data);
|
|
413
|
+
if (isFailure(references))
|
|
414
|
+
return references;
|
|
415
|
+
return success({ path, source: source.data, references: references.data });
|
|
416
|
+
}
|
|
417
|
+
/** The variable the instance `factory` creates is bound to, such as `dispatcher` or `router`. */
|
|
418
|
+
function instanceOf(file, factory) {
|
|
419
|
+
let match = new RegExp(`(?:const|let|var)\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*${factory}\\(`).exec(file.source);
|
|
420
|
+
return match?.[1] ?? INSTANCE_NAMES[factory] ?? "dispatcher";
|
|
421
|
+
}
|
|
422
|
+
/** The local name `file` binds the default export of `module` to, or `null`. */
|
|
423
|
+
function defaultLocal(file, module) {
|
|
424
|
+
for (let reference of file.references) {
|
|
425
|
+
if (reference.kind !== "import" || !resolvesTo(reference.specifier, file.path, module))
|
|
426
|
+
continue;
|
|
427
|
+
let bound = reference.names.find((name) => name.imported === "default");
|
|
428
|
+
if (bound !== undefined)
|
|
429
|
+
return bound.local;
|
|
430
|
+
}
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* The group keys of an existing job mapping whose handler lives in the folder `name` names,
|
|
435
|
+
* so `activitypub/send` joins the `activityPub` group its siblings are mapped under.
|
|
436
|
+
*/
|
|
437
|
+
function reusedGroup(file, instance, local, name) {
|
|
438
|
+
let folders = name.segments.slice(0, -1);
|
|
439
|
+
if (folders.length === 0)
|
|
440
|
+
return [];
|
|
441
|
+
let mapping = new RegExp(`${escape(instance)}\\.map\\(\\s*${escape(local)}\\.([\\w$.]+)\\s*,[^;]*?import\\(\\s*["']([^"']+)["']`, "g");
|
|
442
|
+
for (let match of file.source.matchAll(mapping)) {
|
|
443
|
+
let keys = (match[1] ?? "").split(".");
|
|
444
|
+
let target = projectPath(match[2] ?? "", file.path);
|
|
445
|
+
if (target === null || !target.startsWith("app/jobs/"))
|
|
446
|
+
continue;
|
|
447
|
+
let segments = target.slice("app/jobs/".length).split("/").slice(0, -1);
|
|
448
|
+
let sameFolder = segments.length === folders.length &&
|
|
449
|
+
segments.every((segment, index) => segment === folders[index]);
|
|
450
|
+
if (sameFolder && keys.length === folders.length + 1)
|
|
451
|
+
return keys.slice(0, -1);
|
|
452
|
+
}
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
/** A specifier written in `fromFile` as a project-relative path, or `null` for a package. */
|
|
456
|
+
function projectPath(specifier, fromFile) {
|
|
457
|
+
if (specifier.startsWith("~/"))
|
|
458
|
+
return specifier.slice(2);
|
|
459
|
+
if (specifier.startsWith("."))
|
|
460
|
+
return posix.join(dirname(fromFile), specifier);
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
/** How the initializer imports a new handler, following the form its existing mappings use. */
|
|
464
|
+
function handlerSpecifier(file, handler) {
|
|
465
|
+
let dynamic = file.references
|
|
466
|
+
.filter((reference) => reference.kind === "dynamic")
|
|
467
|
+
.map((reference) => reference.specifier);
|
|
468
|
+
let examples = dynamic.length > 0 ? dynamic : staticSpecifiers(file);
|
|
469
|
+
return specifierFor(file.path, handler, examples, file.aliased ?? false);
|
|
470
|
+
}
|
|
471
|
+
/** The specifiers of a file's static imports. */
|
|
472
|
+
function staticSpecifiers(file) {
|
|
473
|
+
return file.references
|
|
474
|
+
.filter((reference) => reference.kind === "import")
|
|
475
|
+
.map((reference) => reference.specifier);
|
|
476
|
+
}
|
|
477
|
+
/** Where a nested declaration goes, for the printed instructions. */
|
|
478
|
+
function groupNote(path) {
|
|
479
|
+
return path.length > 1 ? `, under ${path.slice(0, -1).join(".")}` : "";
|
|
480
|
+
}
|
|
481
|
+
/** The two edits to make by hand, as `make` prints them. */
|
|
482
|
+
function instructions(declarationsAt, declaration, initializer, mapping) {
|
|
483
|
+
return [`In ${declarationsAt}:`, indent(declaration), `In ${initializer}:`, indent(mapping)].join("\n");
|
|
484
|
+
}
|
|
485
|
+
/** Every line of `text` indented by two spaces. */
|
|
486
|
+
function indent(text) {
|
|
487
|
+
return text
|
|
488
|
+
.split("\n")
|
|
489
|
+
.map((line) => ` ${line}`)
|
|
490
|
+
.join("\n");
|
|
491
|
+
}
|
|
492
|
+
/** `text` with every regular-expression metacharacter escaped. */
|
|
493
|
+
function escape(text) {
|
|
494
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
495
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
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 type { Result } from "@sdxc/result";
|
|
10
|
+
import type { Config } from "../config.js";
|
|
11
|
+
import type { KindName } from "./kinds.js";
|
|
12
|
+
import type { Name } from "./names.js";
|
|
13
|
+
/** One `make` request, as the command line spelled it. */
|
|
14
|
+
export interface MakeRequest {
|
|
15
|
+
kind: KindName;
|
|
16
|
+
name: Name;
|
|
17
|
+
/** The stub variant a flag selects: `form`, `cron` or `resource`. */
|
|
18
|
+
variant: string | null;
|
|
19
|
+
/** Whether to write a test beside the file. */
|
|
20
|
+
tests: boolean;
|
|
21
|
+
/** The migration chain, for `make migration`. */
|
|
22
|
+
chain?: string;
|
|
23
|
+
/** The route contract a controller is declared in, a module in `routes/`. */
|
|
24
|
+
routes: string;
|
|
25
|
+
}
|
|
26
|
+
/** A file the run writes, by path relative to the project root. */
|
|
27
|
+
export interface PlannedFile {
|
|
28
|
+
path: string;
|
|
29
|
+
content: string;
|
|
30
|
+
}
|
|
31
|
+
/** What one run writes and the placeholder values its stubs were rendered with. */
|
|
32
|
+
export interface Plan {
|
|
33
|
+
files: PlannedFile[];
|
|
34
|
+
values: Record<string, string>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Plans `request` in the project at `root`. Every planned path must be free; an existing file
|
|
38
|
+
* is a failure naming it, before any stub is read.
|
|
39
|
+
*
|
|
40
|
+
* @param packageRoot - The `@sdxc/kit` package, whose `stubs/` holds the built-in stubs.
|
|
41
|
+
* @param overrides - Placeholder values a declaration decided, such as a job's reused group.
|
|
42
|
+
*/
|
|
43
|
+
export declare function plan(request: MakeRequest, root: string, config: Config, packageRoot: string, overrides?: Readonly<Record<string, string>>): Promise<Result<Plan, Error>>;
|
|
44
|
+
/** The folder a kind's files go in; a migration's comes from its chain instead. */
|
|
45
|
+
export declare function folderOf(kind: KindName, variant: string | null): string;
|
|
46
|
+
/**
|
|
47
|
+
* The property access that reaches a command's declaration from its contract: `.users.grant`,
|
|
48
|
+
* with a segment that is no identifier read by its quoted key (`["send-digest"]`), since a
|
|
49
|
+
* command's key is the word typed to run it.
|
|
50
|
+
*/
|
|
51
|
+
export declare function memberAccess(segments: readonly string[]): string;
|
|
52
|
+
/**
|
|
53
|
+
* The URI scheme an MCP resource is declared under: the project's package name without its
|
|
54
|
+
* scope, reduced to the characters a scheme allows, or `app` when nothing usable is left.
|
|
55
|
+
*/
|
|
56
|
+
export declare function resourceScheme(root: string): Promise<string>;
|