@sdxc/kit 2026.10.24 → 2026.10.26

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 (82) hide show
  1. package/README.md +28 -15
  2. package/changelog.jsonl +125 -4
  3. package/dist/architecture/graph.d.ts +16 -3
  4. package/dist/architecture/graph.js +37 -19
  5. package/dist/architecture/layers.d.ts +10 -3
  6. package/dist/architecture/layers.js +38 -9
  7. package/dist/commands/destroy.d.ts +1 -1
  8. package/dist/commands/make.d.ts +5 -5
  9. package/dist/commands/make.js +11 -8
  10. package/dist/commands/scaffold.d.ts +1 -1
  11. package/dist/contract.d.ts +3 -3
  12. package/dist/doctor/checks.d.ts +2 -2
  13. package/dist/doctor/checks.js +14 -2
  14. package/dist/doctor/constant-names.d.ts +17 -0
  15. package/dist/doctor/constant-names.js +106 -0
  16. package/dist/doctor/dependencies.d.ts +3 -3
  17. package/dist/doctor/dependencies.js +3 -3
  18. package/dist/doctor/fan-out.d.ts +3 -2
  19. package/dist/doctor/fan-out.js +4 -3
  20. package/dist/doctor/fetch-param.d.ts +15 -0
  21. package/dist/doctor/fetch-param.js +37 -0
  22. package/dist/doctor/files.d.ts +2 -0
  23. package/dist/doctor/files.js +4 -0
  24. package/dist/doctor/local-const.d.ts +15 -0
  25. package/dist/doctor/local-const.js +54 -0
  26. package/dist/doctor/logger.d.ts +15 -0
  27. package/dist/doctor/logger.js +41 -0
  28. package/dist/doctor/orphans.d.ts +3 -3
  29. package/dist/doctor/orphans.js +33 -7
  30. package/dist/doctor/process-env.d.ts +15 -0
  31. package/dist/doctor/process-env.js +39 -0
  32. package/dist/doctor/project.js +17 -13
  33. package/dist/doctor/result-throws.d.ts +5 -4
  34. package/dist/doctor/result-throws.js +6 -5
  35. package/dist/doctor/source-rule.d.ts +35 -0
  36. package/dist/doctor/source-rule.js +52 -0
  37. package/dist/doctor/stack-imports.d.ts +15 -0
  38. package/dist/doctor/stack-imports.js +60 -0
  39. package/dist/doctor/syntax.d.ts +31 -0
  40. package/dist/doctor/syntax.js +56 -0
  41. package/dist/make/binding.d.ts +13 -8
  42. package/dist/make/binding.js +96 -64
  43. package/dist/make/from-model.js +2 -7
  44. package/dist/make/index.js +2 -7
  45. package/dist/package-manager.d.ts +6 -0
  46. package/dist/package-manager.js +25 -2
  47. package/dist/scaffold/index.js +25 -19
  48. package/dist/ui/commands.js +2 -5
  49. package/dist/ui/registry.d.ts +2 -2
  50. package/dist/ui/registry.js +1 -1
  51. package/dist/upgrade/changelog.d.ts +2 -0
  52. package/dist/upgrade/changelog.js +2 -0
  53. package/dist/upgrade/project.d.ts +2 -2
  54. package/dist/upgrade/prompt.d.ts +3 -2
  55. package/dist/upgrade/prompt.js +43 -2
  56. package/package.json +5 -5
  57. package/registry/ui/youtube-embed.json +3 -3
  58. package/stubs/scaffold.test-mcp.stub +5 -1
  59. package/templates/app/AGENTS.md +3 -1
  60. package/templates/app/app/commands/db/fresh.ts +20 -13
  61. package/templates/app/app/commands/db/migrate.ts +42 -32
  62. package/templates/app/app/http/controllers/api/openapi.test.ts +29 -0
  63. package/templates/app/app/http/controllers/api/openapi.tsx +8 -2
  64. package/templates/app/app/http/controllers/health.test.ts +35 -0
  65. package/templates/app/app/http/controllers/health.ts +16 -0
  66. package/templates/app/app/http/controllers/mcp.test.ts +16 -0
  67. package/templates/app/app/http/middleware/access.ts +6 -3
  68. package/templates/app/app/http/middleware/page.ts +3 -4
  69. package/templates/app/app/http/middleware/server-timing.test.ts +1 -1
  70. package/templates/app/app/initializers/database.test.ts +6 -1
  71. package/templates/app/app/initializers/health.ts +17 -0
  72. package/templates/app/app/initializers/openapi.ts +5 -4
  73. package/templates/app/app/initializers/router.test.ts +1 -1
  74. package/templates/app/app/initializers/router.tsx +5 -6
  75. package/templates/app/app/test/cloudflare-workers.test.ts +27 -0
  76. package/templates/app/app/test/cloudflare-workers.ts +17 -4
  77. package/templates/app/app/test/database.ts +33 -0
  78. package/templates/app/app/test/mcp.ts +96 -0
  79. package/templates/app/package.json +1 -0
  80. package/templates/app/resources/layouts/document.tsx +2 -3
  81. package/templates/app/routes/api.ts +17 -7
  82. package/templates/app/app/http/controllers/api/health.tsx +0 -15
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The `stack-imports` check: the project imports the library its stack settled on for each
3
+ * concern, so validation, UI and markup each have one way to be written: `remix/data-schema`
4
+ * for schemas, `remix/component` JSX for UI and server HTML, and `css()` mixins for styles.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { sourceCheck } from "./source-rule.js";
10
+ import { isNode, lineAt, parseModule, walk } from "./syntax.js";
11
+ /** Each replaced library, matched on the import's specifier. */
12
+ const REPLACEMENTS = [
13
+ { specifier: /^zod(?:\/|$)/, use: "remix/data-schema" },
14
+ {
15
+ specifier: /^(?:react|react-dom|react-router|@remix-run\/react|preact)(?:\/|$)/,
16
+ use: "remix/component",
17
+ },
18
+ { specifier: /^(?:tailwindcss|@tailwindcss\/[^/]+)(?:\/|$)/, use: "css() mixins" },
19
+ { specifier: /^remix\/html-template(?:\/|$)/, use: "remix/component JSX rendered on the server" },
20
+ ];
21
+ /** Nodes whose `source` names the module they load. */
22
+ const LOADS = new Set([
23
+ "ImportDeclaration",
24
+ "ImportExpression",
25
+ "ExportNamedDeclaration",
26
+ "ExportAllDeclaration",
27
+ ]);
28
+ /** Every import, re-export or dynamic `import()` of a replaced library, tests included. */
29
+ export const STACK_IMPORTS_RULE = {
30
+ name: "stack-imports",
31
+ tests: true,
32
+ find: findStackImports,
33
+ passed: "Every import uses the stack's library for its concern",
34
+ noun: ["import of a replaced library", "imports of replaced libraries"],
35
+ fix: "Import the library named in each finding instead",
36
+ };
37
+ /** Warns on each import of a library the stack replaces. */
38
+ export const stackImportsCheck = sourceCheck(STACK_IMPORTS_RULE);
39
+ /** Each place `source` loads a replaced library, with the library to use instead. */
40
+ export function findStackImports(file, source) {
41
+ let parsed = parseModule(file, source);
42
+ if (parsed === null)
43
+ return [];
44
+ let findings = [];
45
+ walk(parsed.program, (node) => {
46
+ if (!LOADS.has(node.type) || !isNode(node.source))
47
+ return;
48
+ let specifier = node.source.value;
49
+ if (typeof specifier !== "string")
50
+ return;
51
+ let replacement = REPLACEMENTS.find((entry) => entry.specifier.test(specifier));
52
+ if (replacement === undefined)
53
+ return;
54
+ findings.push({
55
+ line: lineAt(source, node.start),
56
+ message: `imports ${specifier}; use ${replacement.use}`,
57
+ });
58
+ });
59
+ return findings;
60
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The parsed view of a module the source-rule checks read: its oxc AST, its comments, and a walk
3
+ * that hands every node its ancestors, so a rule decides on a node and where it sits in one pass.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Comment } from "oxc-parser";
9
+ /** An oxc AST node, read by `type` and by whichever fields a rule needs. */
10
+ export interface SyntaxNode {
11
+ type: string;
12
+ start: number;
13
+ end: number;
14
+ [field: string]: unknown;
15
+ }
16
+ /** A module's AST and comments. */
17
+ export interface ParsedModule {
18
+ program: SyntaxNode;
19
+ comments: Comment[];
20
+ }
21
+ /**
22
+ * The module oxc parses from `source`, or `null` when it cannot, so the type checker rather than
23
+ * doctor names the syntax error.
24
+ */
25
+ export declare function parseModule(file: string, source: string): ParsedModule | null;
26
+ /** Calls `enter` on every node under `root`, depth first, with its ancestors outermost first. */
27
+ export declare function walk(root: SyntaxNode, enter: (node: SyntaxNode, ancestors: readonly SyntaxNode[]) => void): void;
28
+ /** Whether `value` is an AST node rather than a scalar or a plain field object. */
29
+ export declare function isNode(value: unknown): value is SyntaxNode;
30
+ /** The 1-based line holding character `index` of `source`. */
31
+ export declare function lineAt(source: string, index: number): number;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The parsed view of a module the source-rule checks read: its oxc AST, its comments, and a walk
3
+ * that hands every node its ancestors, so a rule decides on a node and where it sits in one pass.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { parseSync } from "oxc-parser";
9
+ /**
10
+ * The module oxc parses from `source`, or `null` when it cannot, so the type checker rather than
11
+ * doctor names the syntax error.
12
+ */
13
+ export function parseModule(file, source) {
14
+ let parsed = parseSync(file, source);
15
+ if (parsed.errors.length > 0)
16
+ return null;
17
+ return { program: parsed.program, comments: parsed.comments };
18
+ }
19
+ /** Calls `enter` on every node under `root`, depth first, with its ancestors outermost first. */
20
+ export function walk(root, enter) {
21
+ let ancestors = [];
22
+ let visit = (node) => {
23
+ enter(node, ancestors);
24
+ ancestors.push(node);
25
+ for (let child of children(node))
26
+ visit(child);
27
+ ancestors.pop();
28
+ };
29
+ visit(root);
30
+ }
31
+ /** The nodes held directly by `node`'s fields, in source order. */
32
+ function children(node) {
33
+ let found = [];
34
+ for (let [key, value] of Object.entries(node)) {
35
+ if (key === "type")
36
+ continue;
37
+ for (let item of Array.isArray(value) ? value : [value]) {
38
+ if (isNode(item))
39
+ found.push(item);
40
+ }
41
+ }
42
+ return found;
43
+ }
44
+ /** Whether `value` is an AST node rather than a scalar or a plain field object. */
45
+ export function isNode(value) {
46
+ return (typeof value === "object" && value !== null && typeof Reflect.get(value, "type") === "string");
47
+ }
48
+ /** The 1-based line holding character `index` of `source`. */
49
+ export function lineAt(source, index) {
50
+ let line = 1;
51
+ for (let at = 0; at < index && at < source.length; at++) {
52
+ if (source.charCodeAt(at) === 10)
53
+ line += 1;
54
+ }
55
+ return line;
56
+ }
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * `sdxc make secret`, `make binding` and `make do`: edit `cloudflare.config.ts`, append
3
- * `.env.example` for secrets, re-export a Durable Object from `bootstrap/worker.ts`, and print
4
- * `sdxc run typegen` so agents stop hand-editing three places.
3
+ * `.env.example` for secrets, re-export a Durable Object from `bootstrap/worker.ts`, and note
4
+ * `sdxc run typegen`, answering what changed for the project's `format` like every other kind.
5
5
  *
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
9
  import type { AnyCommandContext } from "@sdxc/cli";
10
10
  import type { Result } from "@sdxc/result";
11
+ import type { Made } from "./index.js";
11
12
  /** Binding kinds `make binding` accepts; `secret` also appends `.env.example`. */
12
13
  export declare const BINDING_KINDS: readonly ["secret", "kv", "d1", "r2", "queue", "rateLimit", "sendEmail", "durableObject"];
13
14
  /** One of {@link BINDING_KINDS}. */
@@ -16,27 +17,31 @@ export type BindingKind = (typeof BINDING_KINDS)[number];
16
17
  export type DoRole = "model" | "service";
17
18
  /** Context these makers need to print. */
18
19
  export type BindingContext = Pick<AnyCommandContext, "stdout">;
19
- /** Plans and optionally writes a `bindings.<kind>()` entry for `NAME`. */
20
+ /**
21
+ * Plans and optionally writes a `bindings.<kind>()` entry for `NAME`; `--force` replaces an
22
+ * existing declaration of `NAME` where it stands.
23
+ */
20
24
  export declare function makeBinding(ctx: BindingContext, root: string, input: {
21
25
  kind: BindingKind;
22
26
  name: string;
23
27
  dryRun: boolean;
24
28
  force: boolean;
25
- }): Promise<Result<void, Error>>;
29
+ }): Promise<Result<Made, Error>>;
26
30
  /** `make secret NAME` — shorthand for `make binding secret NAME`. */
27
31
  export declare function makeSecret(ctx: BindingContext, root: string, input: {
28
32
  name: string;
29
33
  dryRun: boolean;
30
34
  force: boolean;
31
- }): Promise<Result<void, Error>>;
35
+ }): Promise<Result<Made, Error>>;
32
36
  /**
33
37
  * Writes a Durable Object class stub, re-exports it from `bootstrap/worker.ts`, and declares
34
- * the binding plus `exports.durableObject` in `cloudflare.config.ts`.
38
+ * the binding plus `exports.durableObject` in `cloudflare.config.ts`. A name ending in `do`,
39
+ * in any case, gets the `DO` suffix once: `feed-do` and `FeedDO` both write `FeedDO`.
35
40
  */
36
- export declare function makeDo(ctx: BindingContext, root: string, packageRoot: string, input: {
41
+ export declare function makeDo(ctx: BindingContext, root: string, input: {
37
42
  name: string;
38
43
  role: DoRole;
39
44
  binding?: string;
40
45
  dryRun: boolean;
41
46
  force: boolean;
42
- }): Promise<Result<void, Error>>;
47
+ }): Promise<Result<Made, Error>>;
@@ -1,12 +1,12 @@
1
1
  /**
2
2
  * `sdxc make secret`, `make binding` and `make do`: edit `cloudflare.config.ts`, append
3
- * `.env.example` for secrets, re-export a Durable Object from `bootstrap/worker.ts`, and print
4
- * `sdxc run typegen` so agents stop hand-editing three places.
3
+ * `.env.example` for secrets, re-export a Durable Object from `bootstrap/worker.ts`, and note
4
+ * `sdxc run typegen`, answering what changed for the project's `format` like every other kind.
5
5
  *
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
- import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
10
10
  import { dirname, join } from "node:path";
11
11
  import { failure, isFailure, success, wrap } from "@sdxc/result";
12
12
  import { addHeaderTags, headerTags, resolveAuthor } from "../author.js";
@@ -24,7 +24,16 @@ export const BINDING_KINDS = [
24
24
  "sendEmail",
25
25
  "durableObject",
26
26
  ];
27
- /** Plans and optionally writes a `bindings.<kind>()` entry for `NAME`. */
27
+ /** The entry point a Durable Object class is re-exported from, where Cloudflare finds it. */
28
+ const WORKER_FILE = "bootstrap/worker.ts";
29
+ /** The note every maker here ends with, since `env` is typed from the config it edited. */
30
+ const TYPEGEN_NOTE = "Next: sdxc run typegen\n";
31
+ /** What a dry run answers: nothing changed and nothing left to note. */
32
+ const NOTHING_MADE = { changed: [], notes: [] };
33
+ /**
34
+ * Plans and optionally writes a `bindings.<kind>()` entry for `NAME`; `--force` replaces an
35
+ * existing declaration of `NAME` where it stands.
36
+ */
28
37
  export async function makeBinding(ctx, root, input) {
29
38
  let key = bindingKey(input.name);
30
39
  if (isFailure(key))
@@ -36,7 +45,7 @@ export async function makeBinding(ctx, root, input) {
36
45
  if (existing.has(key.data) && !input.force) {
37
46
  return failure(new Error(`${key.data} is already declared in ${CONFIG_FILE}; pass --force to replace it`));
38
47
  }
39
- let bindingLine = bindingCall(input.kind, key.data);
48
+ let bindingLine = bindingCall(input.kind, key.data, config.data);
40
49
  let afterConfig = insertEnvBinding(config.data, key.data, bindingLine);
41
50
  if (isFailure(afterConfig))
42
51
  return afterConfig;
@@ -60,16 +69,17 @@ export async function makeBinding(ctx, root, input) {
60
69
  if (exampleEdit !== null) {
61
70
  ctx.stdout(unifiedDiff(ENV_EXAMPLE_FILE, exampleEdit.before === "" ? null : exampleEdit.before, exampleEdit.after));
62
71
  }
63
- return success(undefined);
72
+ return success(NOTHING_MADE);
64
73
  }
65
74
  await writeFile(join(root, CONFIG_FILE), afterConfig.data);
66
- ctx.stdout(`edited ${CONFIG_FILE}\n`);
75
+ ctx.stdout(`Edited ${CONFIG_FILE}\n`);
76
+ let changed = [CONFIG_FILE];
67
77
  if (exampleEdit !== null) {
68
78
  await writeFile(join(root, ENV_EXAMPLE_FILE), exampleEdit.after);
69
- ctx.stdout(`edited ${ENV_EXAMPLE_FILE}\n`);
79
+ ctx.stdout(`Edited ${ENV_EXAMPLE_FILE}\n`);
80
+ changed.push(ENV_EXAMPLE_FILE);
70
81
  }
71
- ctx.stdout("Next: sdxc run typegen\n");
72
- return success(undefined);
82
+ return success({ changed, notes: [TYPEGEN_NOTE] });
73
83
  }
74
84
  /** `make secret NAME` — shorthand for `make binding secret NAME`. */
75
85
  export async function makeSecret(ctx, root, input) {
@@ -77,18 +87,18 @@ export async function makeSecret(ctx, root, input) {
77
87
  }
78
88
  /**
79
89
  * Writes a Durable Object class stub, re-exports it from `bootstrap/worker.ts`, and declares
80
- * the binding plus `exports.durableObject` in `cloudflare.config.ts`.
90
+ * the binding plus `exports.durableObject` in `cloudflare.config.ts`. A name ending in `do`,
91
+ * in any case, gets the `DO` suffix once: `feed-do` and `FeedDO` both write `FeedDO`.
81
92
  */
82
- export async function makeDo(ctx, root, packageRoot, input) {
93
+ export async function makeDo(ctx, root, input) {
83
94
  let parsed = parseName(input.name);
84
95
  if (isFailure(parsed))
85
96
  return parsed;
86
- let className = parsed.data.pascal.endsWith("DO")
87
- ? parsed.data.pascal
88
- : `${parsed.data.pascal}DO`;
89
- let binding = input.binding !== undefined
90
- ? bindingKey(input.binding)
91
- : success(snakeUpper(parsed.data.base.replace(/-?do$/, "") || parsed.data.base));
97
+ let stem = parseName(parsed.data.base.replace(/(.)-do$/, "$1"));
98
+ if (isFailure(stem))
99
+ return stem;
100
+ let className = `${stem.data.pascal}DO`;
101
+ let binding = input.binding !== undefined ? bindingKey(input.binding) : success(snakeUpper(stem.data.base));
92
102
  if (isFailure(binding))
93
103
  return binding;
94
104
  let folder = input.role === "model" ? "app/models" : "app/services";
@@ -97,7 +107,7 @@ export async function makeDo(ctx, root, packageRoot, input) {
97
107
  let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
98
108
  if (isFailure(config))
99
109
  return failure(new Error(`No ${CONFIG_FILE} in the project`));
100
- let worker = await wrap(() => readFile(join(root, "bootstrap/worker.ts"), "utf8"));
110
+ let worker = await wrap(() => readFile(join(root, WORKER_FILE), "utf8"));
101
111
  if (isFailure(worker))
102
112
  return failure(new Error("No bootstrap/worker.ts in the project"));
103
113
  let existing = declaredBindings(config.data);
@@ -114,9 +124,10 @@ export async function makeDo(ctx, root, packageRoot, input) {
114
124
  if (input.dryRun) {
115
125
  ctx.stdout(unifiedDiff(file, null, stub));
116
126
  ctx.stdout(unifiedDiff(CONFIG_FILE, config.data, afterConfig.data));
117
- ctx.stdout(unifiedDiff("bootstrap/worker.ts", worker.data, afterWorker));
118
- return success(undefined);
127
+ ctx.stdout(unifiedDiff(WORKER_FILE, worker.data, afterWorker));
128
+ return success(NOTHING_MADE);
119
129
  }
130
+ let replaced = input.force && (await exists(join(root, file)));
120
131
  await mkdir(dirname(join(root, file)), { recursive: true });
121
132
  let written = await wrap(() => writeFile(join(root, file), stub, { flag: input.force ? "w" : "wx" }));
122
133
  if (isFailure(written)) {
@@ -125,14 +136,20 @@ export async function makeDo(ctx, root, packageRoot, input) {
125
136
  }
126
137
  return written;
127
138
  }
128
- ctx.stdout(`wrote ${file}\n`);
139
+ ctx.stdout(`${replaced ? "Replaced" : "Wrote"} ${file}\n`);
129
140
  await writeFile(join(root, CONFIG_FILE), afterConfig.data);
130
- ctx.stdout(`edited ${CONFIG_FILE}\n`);
131
- await writeFile(join(root, "bootstrap/worker.ts"), afterWorker);
132
- ctx.stdout("edited bootstrap/worker.ts\n");
133
- ctx.stdout("Next: sdxc run typegen\n");
134
- void packageRoot;
135
- return success(undefined);
141
+ ctx.stdout(`Edited ${CONFIG_FILE}\n`);
142
+ let changed = [file, CONFIG_FILE];
143
+ if (afterWorker !== worker.data) {
144
+ await writeFile(join(root, WORKER_FILE), afterWorker);
145
+ ctx.stdout(`Edited ${WORKER_FILE}\n`);
146
+ changed.push(WORKER_FILE);
147
+ }
148
+ return success({ changed, notes: [TYPEGEN_NOTE] });
149
+ }
150
+ /** Whether `path` exists. */
151
+ async function exists(path) {
152
+ return !isFailure(await wrap(() => stat(path)));
136
153
  }
137
154
  /** `NAME` as an env binding key: already `SCREAMING_SNAKE` or derived from kebab/camel. */
138
155
  function bindingKey(name) {
@@ -147,41 +164,60 @@ function bindingKey(name) {
147
164
  function snakeUpper(kebab) {
148
165
  return kebab.replaceAll("-", "_").toUpperCase();
149
166
  }
150
- function bindingCall(kind, key) {
151
- if (kind === "secret")
152
- return `${key}: bindings.secret()`;
153
- if (kind === "sendEmail")
154
- return `${key}: bindings.sendEmail()`;
155
- if (kind === "rateLimit") {
156
- return `${key}: bindings.rateLimit({ namespace: "1001", simple: { limit: 100, period: 60 } })`;
157
- }
158
- if (kind === "kv") {
159
- return `${key}: bindings.kv({ id: "00000000000000000000000000000000" })`;
160
- }
161
- if (kind === "d1") {
162
- return `${key}: bindings.d1({ name: manifest.name, id: "00000000-0000-4000-8000-000000000000" })`;
167
+ /**
168
+ * The declaration `make binding` writes for `kind`. Named resources take the key in kebab case,
169
+ * after the Worker for a database or a queue, so a new binding never shares the template's; a
170
+ * rate limit takes the next namespace number `config` leaves free.
171
+ */
172
+ function bindingCall(kind, key, config) {
173
+ let kebab = key.toLowerCase().replaceAll("_", "-");
174
+ switch (kind) {
175
+ case "secret":
176
+ case "sendEmail":
177
+ return `${key}: bindings.${kind}()`;
178
+ case "rateLimit":
179
+ return `${key}: bindings.rateLimit({ namespace: "${freeNamespace(config)}", simple: { limit: 100, period: 60 } })`;
180
+ case "kv":
181
+ return `${key}: bindings.kv({ id: "00000000000000000000000000000000" })`;
182
+ case "d1":
183
+ return `${key}: bindings.d1({ name: \`\${manifest.name}-${kebab}\`, id: "00000000-0000-4000-8000-000000000000" })`;
184
+ case "r2":
185
+ return `${key}: bindings.r2({ name: "${kebab}" })`;
186
+ case "queue":
187
+ return `${key}: bindings.queue({ name: \`\${manifest.name}-${kebab}\` })`;
188
+ default:
189
+ return `${key}: bindings.durableObject({ worker: manifest.name, exportName: "${pascalOf(kebab)}DO" })`;
163
190
  }
164
- if (kind === "r2")
165
- return `${key}: bindings.r2({ name: "${key.toLowerCase()}" })`;
166
- if (kind === "queue")
167
- return `${key}: bindings.queue({ name: manifest.name })`;
168
- return `${key}: bindings.durableObject({ worker: /* self */, exportName: "TODO" })`;
169
191
  }
170
- /** Inserts a binding property into the Worker's `env: { … }` object. */
192
+ /** One above the highest rate-limit namespace `config` declares, and `1001` when it declares none. */
193
+ function freeNamespace(config) {
194
+ let taken = [...config.matchAll(/namespace\s*:\s*"(\d+)"/g)].map((match) => Number(match[1]));
195
+ return Math.max(1000, ...taken) + 1;
196
+ }
197
+ /** `user-uploads` as `UserUploads`. */
198
+ function pascalOf(kebab) {
199
+ return kebab
200
+ .split("-")
201
+ .map((part) => `${part.charAt(0).toUpperCase()}${part.slice(1)}`)
202
+ .join("");
203
+ }
204
+ /**
205
+ * Puts `line` into the Worker's `env: { … }` object: in place of an existing declaration of
206
+ * `key`, keeping its comment and position, or as the object's first entry.
207
+ */
171
208
  function insertEnvBinding(source, key, line) {
209
+ let declared = new RegExp(`^([ \\t]*)${key}\\s*:\\s*bindings\\.\\w+\\s*\\([^)]*\\)\\s*,?`, "m");
210
+ let existing = declared.exec(source);
211
+ if (existing !== null) {
212
+ let indent = existing[1] ?? "";
213
+ return success(`${source.slice(0, existing.index)}${indent}${line},${source.slice(existing.index + existing[0].length)}`);
214
+ }
172
215
  let env = /env\s*:\s*\{/.exec(source);
173
- if (env === null || env.index === undefined) {
216
+ if (env === null) {
174
217
  return failure(new Error(`${CONFIG_FILE} has no env: { … } block to edit`));
175
218
  }
176
219
  let start = env.index + env[0].length;
177
- let stripped = source.replace(new RegExp(`(?:^|\\n)(\\s*)${key}\\s*:\\s*bindings\\.\\w+\\s*\\([^)]*\\)\\s*,?`, "m"), "\n");
178
- let envAgain = /env\s*:\s*\{/.exec(stripped);
179
- if (envAgain === null || envAgain.index === undefined) {
180
- return failure(new Error(`${CONFIG_FILE} env block could not be re-found after cleanup`));
181
- }
182
- start = envAgain.index + envAgain[0].length;
183
- let indent = "\t\t\t";
184
- return success(`${stripped.slice(0, start)}\n${indent}${line},${stripped.slice(start)}`);
220
+ return success(`${source.slice(0, start)}\n\t\t\t${line},${source.slice(start)}`);
185
221
  }
186
222
  /** Declares the DO export and env binding in `cloudflare.config.ts`. */
187
223
  function insertDurableObject(source, binding, className) {
@@ -217,20 +253,16 @@ function insertDurableObject(source, binding, className) {
217
253
  /** Minimal Durable Object class stub; `@author` / `@copyright` are added by {@link makeDo}. */
218
254
  function durableObjectStub(className) {
219
255
  return `/**
220
- * The ${className} Durable Object: fill in its storage and request handlers.
256
+ * The ${className} Durable Object: one instance per name, with storage of its own.
221
257
  */
222
258
 
223
259
  import { DurableObject } from "cloudflare:workers";
224
260
 
225
261
  /** Durable Object class re-exported from bootstrap/worker.ts for its binding. */
226
262
  export class ${className} extends DurableObject<Cloudflare.Env> {
227
- /**
228
- * Handles a fetch against this object.
229
- *
230
- * @param request - The inbound request.
231
- */
232
- async fetch(request: Request): Promise<Response> {
233
- return new Response("${className}", { status: 200 });
263
+ /** Answers every request a stub forwards with the class name, until the object serves its own. */
264
+ override fetch(): Response {
265
+ return new Response("${className}");
234
266
  }
235
267
  }
236
268
  `;
@@ -10,8 +10,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
  import { pathToFileURL } from "node:url";
12
12
  import { failure, isFailure, success, wrap } from "@sdxc/result";
13
- import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
14
- import { readManifest } from "../upgrade/project.js";
13
+ import { projectPackageManager } from "../package-manager.js";
15
14
  import { KINDS } from "./kinds.js";
16
15
  import { chainFolder } from "./migrations.js";
17
16
  import { parseName } from "./names.js";
@@ -138,11 +137,7 @@ function isTableShape(value) {
138
137
  }
139
138
  /** `bun` for a project on Bun and `node` otherwise, as `sdxc run` decides. */
140
139
  async function projectRuntime(root) {
141
- let manifest = await readManifest(root);
142
- let manager = await packageManager({
143
- declared: isFailure(manifest) ? undefined : manifest.data.manifest.packageManager,
144
- findLockFile: lockFileAtOrAbove(root),
145
- });
140
+ let manager = await projectPackageManager(root);
146
141
  return manager.name === "bun" ? "bun" : "node";
147
142
  }
148
143
  /** Every numbered SQL file of the chain at `folder`; a chain with no folder yet is empty. */
@@ -15,9 +15,8 @@ import { failure, isFailure, success, wrap } from "@sdxc/result";
15
15
  import { missingDependencies } from "../dependencies.js";
16
16
  import { unifiedDiff } from "../diff.js";
17
17
  import { formatFiles } from "../format.js";
18
- import { lockFileAtOrAbove, packageManager } from "../package-manager.js";
18
+ import { projectPackageManager } from "../package-manager.js";
19
19
  import { columnSource, factorySource, parseFields, pluralize, resolveReferences, } from "../scaffold/fields.js";
20
- import { readManifest } from "../upgrade/project.js";
21
20
  import { declare, declaresAbilities, findRow } from "./declare.js";
22
21
  import { planEmail } from "./email.js";
23
22
  import { fieldMigration } from "./from-fields.js";
@@ -268,11 +267,7 @@ export async function makeUnformatted(ctx, project, packageRoot, input) {
268
267
  ctx.stdout(`Edited ${edit.path}\n`);
269
268
  }
270
269
  if (dependencies.data !== null) {
271
- let read = await readManifest(root);
272
- let manager = await packageManager({
273
- declared: isFailure(read) ? undefined : read.data.manifest.packageManager,
274
- findLockFile: lockFileAtOrAbove(root),
275
- });
270
+ let manager = await projectPackageManager(root);
276
271
  let added = dependencies.data.added.map(({ name, version }) => `${name}@${version}`);
277
272
  ctx.stdout(`Added ${added.join(", ")} to package.json; run ${manager.install.join(" ")}\n`);
278
273
  }
@@ -29,6 +29,12 @@ export interface PackageManagerSources {
29
29
  * lookup order, then the user agent, and npm when none of them names one it knows.
30
30
  */
31
31
  export declare function packageManager(sources: PackageManagerSources): Promise<PackageManager>;
32
+ /**
33
+ * The package manager of the project at `root`: its `package.json` `packageManager` field, then
34
+ * the nearest lock file at or above it. Every command that prints an install reads it here, so
35
+ * they agree on the same project.
36
+ */
37
+ export declare function projectPackageManager(root: string): Promise<PackageManager>;
32
38
  /**
33
39
  * Finds lock files in `root`, then in each directory above it, so a package inside a workspace
34
40
  * takes the workspace's lock file and the nearest directory holding one decides.
@@ -6,9 +6,9 @@
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
- import { stat } from "node:fs/promises";
9
+ import { readFile, stat } from "node:fs/promises";
10
10
  import { dirname, join } from "node:path";
11
- import { isSuccess, wrap } from "@sdxc/result";
11
+ import { isFailure, isSuccess, wrap } from "@sdxc/result";
12
12
  /** The package managers by name, with the commands each one spells. */
13
13
  const PACKAGE_MANAGERS = {
14
14
  bun: { name: "bun", install: ["bun", "install"], dlx: ["bunx"], run: ["bun", "run"] },
@@ -48,6 +48,29 @@ export async function packageManager(sources) {
48
48
  return PACKAGE_MANAGERS[locked[1]];
49
49
  return PACKAGE_MANAGERS[known(sources.userAgent?.split("/")[0]) ?? "npm"];
50
50
  }
51
+ /**
52
+ * The package manager of the project at `root`: its `package.json` `packageManager` field, then
53
+ * the nearest lock file at or above it. Every command that prints an install reads it here, so
54
+ * they agree on the same project.
55
+ */
56
+ export async function projectPackageManager(root) {
57
+ return packageManager({
58
+ declared: await declaredPackageManager(root),
59
+ findLockFile: lockFileAtOrAbove(root),
60
+ });
61
+ }
62
+ /** The `packageManager` field of the `package.json` at `root`, when it holds a string. */
63
+ async function declaredPackageManager(root) {
64
+ let text = await wrap(() => readFile(join(root, "package.json"), "utf8"));
65
+ if (isFailure(text))
66
+ return undefined;
67
+ let manifest = wrap(() => JSON.parse(text.data));
68
+ if (isFailure(manifest) || typeof manifest.data !== "object" || manifest.data === null) {
69
+ return undefined;
70
+ }
71
+ let declared = Reflect.get(manifest.data, "packageManager");
72
+ return typeof declared === "string" ? declared : undefined;
73
+ }
51
74
  /**
52
75
  * Finds lock files in `root`, then in each directory above it, so a package inside a workspace
53
76
  * takes the workspace's lock file and the nearest directory holding one decides.