@sdxc/kit 2026.10.21 → 2026.10.23

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 (104) hide show
  1. package/README.md +84 -4
  2. package/changelog.jsonl +86 -0
  3. package/config.schema.json +154 -0
  4. package/dist/architecture/complexity.d.ts +73 -0
  5. package/dist/architecture/complexity.js +185 -0
  6. package/dist/architecture/crap.d.ts +62 -0
  7. package/dist/architecture/crap.js +121 -0
  8. package/dist/architecture/graph.d.ts +55 -0
  9. package/dist/architecture/graph.js +194 -0
  10. package/dist/architecture/layers.d.ts +29 -0
  11. package/dist/architecture/layers.js +81 -0
  12. package/dist/architecture/mermaid.d.ts +20 -0
  13. package/dist/architecture/mermaid.js +51 -0
  14. package/dist/cli.js +9 -0
  15. package/dist/commands/create.js +4 -3
  16. package/dist/commands/deploy.js +10 -9
  17. package/dist/commands/destroy.d.ts +1 -1
  18. package/dist/commands/diagram.d.ts +17 -0
  19. package/dist/commands/diagram.js +45 -0
  20. package/dist/commands/fix.d.ts +69 -0
  21. package/dist/commands/fix.js +102 -0
  22. package/dist/commands/make.d.ts +71 -2
  23. package/dist/commands/make.js +46 -0
  24. package/dist/commands/run.d.ts +15 -11
  25. package/dist/commands/run.js +21 -16
  26. package/dist/commands/scaffold.d.ts +1 -1
  27. package/dist/commands/setup.d.ts +26 -0
  28. package/dist/commands/setup.js +33 -0
  29. package/dist/config.d.ts +52 -0
  30. package/dist/config.js +88 -1
  31. package/dist/contract.d.ts +52 -3
  32. package/dist/contract.js +124 -2
  33. package/dist/dependencies.js +7 -1
  34. package/dist/deploy/plan.d.ts +5 -0
  35. package/dist/deploy/plan.js +10 -0
  36. package/dist/destroy.js +13 -6
  37. package/dist/diagram.d.ts +32 -0
  38. package/dist/diagram.js +47 -0
  39. package/dist/doctor/checks.d.ts +2 -1
  40. package/dist/doctor/checks.js +24 -1
  41. package/dist/doctor/complexity.d.ts +13 -0
  42. package/dist/doctor/complexity.js +52 -0
  43. package/dist/doctor/crap.d.ts +14 -0
  44. package/dist/doctor/crap.js +67 -0
  45. package/dist/doctor/dependencies.d.ts +13 -0
  46. package/dist/doctor/dependencies.js +42 -0
  47. package/dist/doctor/duplication.d.ts +19 -0
  48. package/dist/doctor/duplication.js +106 -0
  49. package/dist/doctor/fan-out.d.ts +12 -0
  50. package/dist/doctor/fan-out.js +42 -0
  51. package/dist/doctor/feature-scatter.d.ts +15 -0
  52. package/dist/doctor/feature-scatter.js +84 -0
  53. package/dist/doctor/module-size.d.ts +13 -0
  54. package/dist/doctor/module-size.js +50 -0
  55. package/dist/doctor/mutation.d.ts +20 -0
  56. package/dist/doctor/mutation.js +97 -0
  57. package/dist/doctor/orphans.d.ts +13 -0
  58. package/dist/doctor/orphans.js +50 -0
  59. package/dist/doctor/project.js +8 -5
  60. package/dist/doctor/result-throws.d.ts +17 -0
  61. package/dist/doctor/result-throws.js +72 -0
  62. package/dist/doctor/test-ratio.d.ts +12 -0
  63. package/dist/doctor/test-ratio.js +31 -0
  64. package/dist/fix/commands.d.ts +37 -0
  65. package/dist/fix/commands.js +63 -0
  66. package/dist/fix/emails.d.ts +21 -0
  67. package/dist/fix/emails.js +159 -0
  68. package/dist/fix/env.d.ts +29 -0
  69. package/dist/fix/env.js +58 -0
  70. package/dist/fix/index.d.ts +11 -0
  71. package/dist/fix/index.js +11 -0
  72. package/dist/fix/models.d.ts +20 -0
  73. package/dist/fix/models.js +95 -0
  74. package/dist/lock.js +12 -2
  75. package/dist/make/binding.d.ts +42 -0
  76. package/dist/make/binding.js +237 -0
  77. package/dist/make/imports.js +7 -5
  78. package/dist/make/schema-diff.js +8 -1
  79. package/dist/models.js +7 -7
  80. package/dist/routes/modules.js +8 -5
  81. package/dist/routes/parse.js +8 -7
  82. package/dist/routes/routers.js +9 -5
  83. package/dist/setup/auth.d.ts +12 -0
  84. package/dist/setup/auth.js +209 -0
  85. package/dist/setup/billing.d.ts +11 -0
  86. package/dist/setup/billing.js +116 -0
  87. package/dist/setup/catalog.d.ts +25 -0
  88. package/dist/setup/catalog.js +34 -0
  89. package/dist/setup/credit.d.ts +13 -0
  90. package/dist/setup/credit.js +21 -0
  91. package/dist/setup/flags.d.ts +11 -0
  92. package/dist/setup/flags.js +62 -0
  93. package/dist/setup/index.d.ts +25 -0
  94. package/dist/setup/index.js +53 -0
  95. package/dist/setup/plan.d.ts +38 -0
  96. package/dist/setup/plan.js +62 -0
  97. package/dist/testing.js +3 -3
  98. package/dist/ui/layout.js +1 -1
  99. package/dist/ui/registry.d.ts +2 -2
  100. package/dist/upgrade/project.d.ts +2 -2
  101. package/dist/upgrade/prompt.js +7 -5
  102. package/package.json +10 -7
  103. package/registry/ui/attachment.json +2 -2
  104. package/templates/app/AGENTS.md +14 -1
@@ -0,0 +1,237 @@
1
+ /**
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.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
10
+ import { dirname, join } from "node:path";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { addHeaderTags, headerTags, resolveAuthor } from "../author.js";
13
+ import { unifiedDiff } from "../diff.js";
14
+ import { CONFIG_FILE, ENV_EXAMPLE_FILE, declaredBindings, exampleKeys } from "../doctor/env.js";
15
+ import { parseName } from "./names.js";
16
+ /** Binding kinds `make binding` accepts; `secret` also appends `.env.example`. */
17
+ export const BINDING_KINDS = [
18
+ "secret",
19
+ "kv",
20
+ "d1",
21
+ "r2",
22
+ "queue",
23
+ "rateLimit",
24
+ "sendEmail",
25
+ "durableObject",
26
+ ];
27
+ /** Plans and optionally writes a `bindings.<kind>()` entry for `NAME`. */
28
+ export async function makeBinding(ctx, root, input) {
29
+ let key = bindingKey(input.name);
30
+ if (isFailure(key))
31
+ return key;
32
+ let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
33
+ if (isFailure(config))
34
+ return failure(new Error(`No ${CONFIG_FILE} in the project`));
35
+ let existing = declaredBindings(config.data);
36
+ if (existing.has(key.data) && !input.force) {
37
+ return failure(new Error(`${key.data} is already declared in ${CONFIG_FILE}; pass --force to replace it`));
38
+ }
39
+ let bindingLine = bindingCall(input.kind, key.data);
40
+ let afterConfig = insertEnvBinding(config.data, key.data, bindingLine);
41
+ if (isFailure(afterConfig))
42
+ return afterConfig;
43
+ let exampleEdit = null;
44
+ if (input.kind === "secret") {
45
+ let example = await wrap(() => readFile(join(root, ENV_EXAMPLE_FILE), "utf8"));
46
+ let before = isFailure(example) ? "" : example.data;
47
+ if (!exampleKeys(before).has(key.data)) {
48
+ let after;
49
+ if (before === "")
50
+ after = `${key.data}=\n`;
51
+ else if (before.endsWith("\n"))
52
+ after = `${before}${key.data}=\n`;
53
+ else
54
+ after = `${before}\n${key.data}=\n`;
55
+ exampleEdit = { before, after };
56
+ }
57
+ }
58
+ if (input.dryRun) {
59
+ ctx.stdout(unifiedDiff(CONFIG_FILE, config.data, afterConfig.data));
60
+ if (exampleEdit !== null) {
61
+ ctx.stdout(unifiedDiff(ENV_EXAMPLE_FILE, exampleEdit.before === "" ? null : exampleEdit.before, exampleEdit.after));
62
+ }
63
+ return success(undefined);
64
+ }
65
+ await writeFile(join(root, CONFIG_FILE), afterConfig.data);
66
+ ctx.stdout(`edited ${CONFIG_FILE}\n`);
67
+ if (exampleEdit !== null) {
68
+ await writeFile(join(root, ENV_EXAMPLE_FILE), exampleEdit.after);
69
+ ctx.stdout(`edited ${ENV_EXAMPLE_FILE}\n`);
70
+ }
71
+ ctx.stdout("Next: sdxc run typegen\n");
72
+ return success(undefined);
73
+ }
74
+ /** `make secret NAME` — shorthand for `make binding secret NAME`. */
75
+ export async function makeSecret(ctx, root, input) {
76
+ return makeBinding(ctx, root, { ...input, kind: "secret" });
77
+ }
78
+ /**
79
+ * 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`.
81
+ */
82
+ export async function makeDo(ctx, root, packageRoot, input) {
83
+ let parsed = parseName(input.name);
84
+ if (isFailure(parsed))
85
+ 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));
92
+ if (isFailure(binding))
93
+ return binding;
94
+ let folder = input.role === "model" ? "app/models" : "app/services";
95
+ let file = `${folder}/${parsed.data.segments.join("/")}.ts`;
96
+ let stub = addHeaderTags(durableObjectStub(className), headerTags(await resolveAuthor(join(root, dirname(file)))));
97
+ let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
98
+ if (isFailure(config))
99
+ return failure(new Error(`No ${CONFIG_FILE} in the project`));
100
+ let worker = await wrap(() => readFile(join(root, "bootstrap/worker.ts"), "utf8"));
101
+ if (isFailure(worker))
102
+ return failure(new Error("No bootstrap/worker.ts in the project"));
103
+ let existing = declaredBindings(config.data);
104
+ if (existing.has(binding.data) && !input.force) {
105
+ return failure(new Error(`${binding.data} is already declared in ${CONFIG_FILE}; pass --force`));
106
+ }
107
+ let afterConfig = insertDurableObject(config.data, binding.data, className);
108
+ if (isFailure(afterConfig))
109
+ return afterConfig;
110
+ let exportLine = `export { ${className} } from "~/${file.replace(/\.ts$/, "")}";\n`;
111
+ let afterWorker = worker.data.includes(`export { ${className} }`)
112
+ ? worker.data
113
+ : `${worker.data.trimEnd()}\n\n${exportLine}`;
114
+ if (input.dryRun) {
115
+ ctx.stdout(unifiedDiff(file, null, stub));
116
+ ctx.stdout(unifiedDiff(CONFIG_FILE, config.data, afterConfig.data));
117
+ ctx.stdout(unifiedDiff("bootstrap/worker.ts", worker.data, afterWorker));
118
+ return success(undefined);
119
+ }
120
+ await mkdir(dirname(join(root, file)), { recursive: true });
121
+ let written = await wrap(() => writeFile(join(root, file), stub, { flag: input.force ? "w" : "wx" }));
122
+ if (isFailure(written)) {
123
+ if (written.error.code === "EEXIST") {
124
+ return failure(new Error(`${file} already exists; pass --force to replace it`));
125
+ }
126
+ return written;
127
+ }
128
+ ctx.stdout(`wrote ${file}\n`);
129
+ 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);
136
+ }
137
+ /** `NAME` as an env binding key: already `SCREAMING_SNAKE` or derived from kebab/camel. */
138
+ function bindingKey(name) {
139
+ if (/^[A-Z][A-Z0-9_]*$/.test(name))
140
+ return success(name);
141
+ let parsed = parseName(name.replaceAll("_", "-"));
142
+ if (isFailure(parsed)) {
143
+ return failure(new Error(`"${name}" is not a binding name`));
144
+ }
145
+ return success(snakeUpper(parsed.data.base));
146
+ }
147
+ function snakeUpper(kebab) {
148
+ return kebab.replaceAll("-", "_").toUpperCase();
149
+ }
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" })`;
163
+ }
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
+ }
170
+ /** Inserts a binding property into the Worker's `env: { … }` object. */
171
+ function insertEnvBinding(source, key, line) {
172
+ let env = /env\s*:\s*\{/.exec(source);
173
+ if (env === null || env.index === undefined) {
174
+ return failure(new Error(`${CONFIG_FILE} has no env: { … } block to edit`));
175
+ }
176
+ 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)}`);
185
+ }
186
+ /** Declares the DO export and env binding in `cloudflare.config.ts`. */
187
+ function insertDurableObject(source, binding, className) {
188
+ let withExport = source;
189
+ if (!source.includes(`exports`) || !/exports\s*:\s*\{/.test(source)) {
190
+ let worker = /worker\s*:\s*\{/.exec(source);
191
+ if (worker === null || worker.index === undefined) {
192
+ return failure(new Error(`${CONFIG_FILE} has no worker: { … } block`));
193
+ }
194
+ let insertAt = worker.index + worker[0].length;
195
+ withExport = `${source.slice(0, insertAt)}\n\t\texports: {\n\t\t\t${className}: exports.durableObject({ storage: "sqlite" }),\n\t\t},${source.slice(insertAt)}`;
196
+ if (!/import\s*\{[^}]*\bexports\b/.test(withExport) &&
197
+ withExport.includes('from "cf/config"')) {
198
+ withExport = withExport.replace(/import\s*\{([^}]+)\}\s*from\s*"cf\/config"/, (_match, names) => {
199
+ let list = names.split(",").map((part) => part.trim());
200
+ if (!list.includes("exports"))
201
+ list.push("exports");
202
+ return `import { ${list.join(", ")} } from "cf/config"`;
203
+ });
204
+ }
205
+ }
206
+ else if (!withExport.includes(`${className}:`)) {
207
+ let exportsBlock = /exports\s*:\s*\{/.exec(withExport);
208
+ if (exportsBlock === null || exportsBlock.index === undefined) {
209
+ return failure(new Error(`${CONFIG_FILE} exports block is malformed`));
210
+ }
211
+ let at = exportsBlock.index + exportsBlock[0].length;
212
+ withExport = `${withExport.slice(0, at)}\n\t\t\t${className}: exports.durableObject({ storage: "sqlite" }),${withExport.slice(at)}`;
213
+ }
214
+ let line = `${binding}: bindings.durableObject({ worker: manifest.name, exportName: "${className}" })`;
215
+ return insertEnvBinding(withExport, binding, line);
216
+ }
217
+ /** Minimal Durable Object class stub; `@author` / `@copyright` are added by {@link makeDo}. */
218
+ function durableObjectStub(className) {
219
+ return `/**
220
+ * The ${className} Durable Object: fill in its storage and request handlers.
221
+ */
222
+
223
+ import { DurableObject } from "cloudflare:workers";
224
+
225
+ /** Durable Object class re-exported from bootstrap/worker.ts for its binding. */
226
+ 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 });
234
+ }
235
+ }
236
+ `;
237
+ }
@@ -38,11 +38,13 @@ export function ensureImport(filename, source, what, matches, specifier, preferr
38
38
  });
39
39
  }
40
40
  }
41
- let clause = what.kind === "namespace"
42
- ? `* as ${preferred}`
43
- : what.kind === "default"
44
- ? preferred
45
- : `{ ${what.name} }`;
41
+ let clause;
42
+ if (what.kind === "namespace")
43
+ clause = `* as ${preferred}`;
44
+ else if (what.kind === "default")
45
+ clause = preferred;
46
+ else
47
+ clause = `{ ${what.name} }`;
46
48
  let local = what.kind === "named" ? what.name : preferred;
47
49
  let statement = `import ${clause} from ${literal(specifier)};`;
48
50
  return success({ source: insertImport(source, references.data, statement), local });
@@ -7,6 +7,7 @@
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
9
  import { DatabaseSync } from "node:sqlite";
10
+ import { iife } from "@sdxc/iife";
10
11
  import { failure, isFailure, success, wrap } from "@sdxc/result";
11
12
  import { checksOf, columnClause, createTable, createTableStatement, defaultClause, isKey, isNotNull, quote, uniqueIndex, } from "./schema.js";
12
13
  /**
@@ -199,7 +200,13 @@ function diffTable(db, table, current) {
199
200
  * `INTEGER PRIMARY KEY` as nullable.
200
201
  */
201
202
  function columnDifference(table, name, definition, existing) {
202
- let generated = definition.computed === undefined ? 0 : definition.computed.stored ? 3 : 2;
203
+ let generated = iife(() => {
204
+ if (definition.computed === undefined)
205
+ return 0;
206
+ if (definition.computed.stored)
207
+ return 3;
208
+ return 2;
209
+ });
203
210
  let hidden = existing.hidden === 2 || existing.hidden === 3 ? existing.hidden : 0;
204
211
  if (generated !== hidden)
205
212
  return "changes how it is generated";
package/dist/models.js CHANGED
@@ -36,13 +36,13 @@ async function modelFiles(root) {
36
36
  function columnsOf(table) {
37
37
  return Object.entries(table.columns).map(([name, definition]) => {
38
38
  let reference = definition.references;
39
- let key = table.primaryKey.includes(name)
40
- ? "primary"
41
- : reference !== undefined
42
- ? `${reference.table.name}.${reference.columns.join(", ")}`
43
- : definition.unique !== undefined && definition.unique !== false
44
- ? "unique"
45
- : null;
39
+ let key = null;
40
+ if (table.primaryKey.includes(name))
41
+ key = "primary";
42
+ else if (reference !== undefined)
43
+ key = `${reference.table.name}.${reference.columns.join(", ")}`;
44
+ else if (definition.unique !== undefined && definition.unique !== false)
45
+ key = "unique";
46
46
  return {
47
47
  name,
48
48
  type: definition.type,
@@ -9,6 +9,7 @@
9
9
  import { readFile, stat } from "node:fs/promises";
10
10
  import { join, posix } from "node:path";
11
11
  import { findModuleReferences, tokenize } from "@sdxc/codemod";
12
+ import { iife } from "@sdxc/iife";
12
13
  import { isFailure, isSuccess, wrap } from "@sdxc/result";
13
14
  import { applyHelper, helperName } from "./helpers.js";
14
15
  import { Reader } from "./parse.js";
@@ -201,11 +202,13 @@ export class Project {
201
202
  let tokens = tokenize(path, source.data);
202
203
  let references = findModuleReferences(path, source.data);
203
204
  if (isFailure(tokens) || isFailure(references)) {
204
- let error = isFailure(tokens)
205
- ? tokens.error
206
- : isFailure(references)
207
- ? references.error
208
- : null;
205
+ let error = iife(() => {
206
+ if (isFailure(tokens))
207
+ return tokens.error;
208
+ if (isFailure(references))
209
+ return references.error;
210
+ return null;
211
+ });
209
212
  this.diagnostics.push(`${path}: could not be read (${error?.message ?? "unknown error"})`);
210
213
  return null;
211
214
  }
@@ -188,8 +188,9 @@ export class Reader {
188
188
  }
189
189
  }
190
190
  /** `[async] function name(…) { … }` at `index`, as a function node, or `null`. */
191
- functionDeclaration(index, limit) {
192
- let start = index;
191
+ functionDeclaration(at, limit) {
192
+ let start = at;
193
+ let index = at;
193
194
  if (this.isWord(index, "async"))
194
195
  index += 1;
195
196
  if (!this.isWord(index, "function"))
@@ -436,11 +437,11 @@ export class Reader {
436
437
  index = this.afterComma(this.skipToDelimiter(index + 1, close), close);
437
438
  continue;
438
439
  }
439
- let name = key?.type === "identifier" || key?.type === "number"
440
- ? key.value
441
- : key?.type === "string"
442
- ? cook(key.value)
443
- : null;
440
+ let name = null;
441
+ if (key?.type === "identifier" || key?.type === "number")
442
+ name = key.value;
443
+ else if (key?.type === "string")
444
+ name = cook(key.value);
444
445
  if (name === null) {
445
446
  index = this.afterComma(this.skipToDelimiter(index, close), close);
446
447
  continue;
@@ -6,6 +6,7 @@
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
+ import { iife } from "@sdxc/iife";
9
10
  /** The longest middleware expression shown whole; longer calls show as `callee(…)`. */
10
11
  const NAME_LIMIT = 40;
11
12
  /**
@@ -301,11 +302,14 @@ export async function middlewareList(project, module, node, seen = new Set()) {
301
302
  /** One middleware: its expression as written and the module its name comes from. */
302
303
  async function middlewareEntry(project, module, node) {
303
304
  let text = module.reader.text(node);
304
- let name = node.kind === "function"
305
- ? "(inline)"
306
- : text.length > NAME_LIMIT && node.kind === "call"
307
- ? `${module.reader.text(node.callee)}(…)`
308
- : text;
305
+ let name = iife(() => {
306
+ if (node.kind === "function")
307
+ return "(inline)";
308
+ if (text.length > NAME_LIMIT && node.kind === "call") {
309
+ return `${module.reader.text(node.callee)}(…)`;
310
+ }
311
+ return text;
312
+ });
309
313
  let root = node;
310
314
  while (root.kind === "call" || root.kind === "member") {
311
315
  root = root.kind === "call" ? root.callee : root.object;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `sdxc setup auth`: OIDC relying-party wiring against r3-auth (default), reduced to the
3
+ * template's session/`actor` world — initializer, middleware, controllers, routes, secrets and
4
+ * a `signIn()` test helper.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Result } from "@sdxc/result";
10
+ import type { SetupPlan } from "./plan.js";
11
+ /** Builds the auth setup plan for `provider` (currently only `r3-auth`). */
12
+ export declare function planAuth(root: string, provider: string): Promise<Result<SetupPlan, Error>>;
@@ -0,0 +1,209 @@
1
+ /**
2
+ * `sdxc setup auth`: OIDC relying-party wiring against r3-auth (default), reduced to the
3
+ * template's session/`actor` world — initializer, middleware, controllers, routes, secrets and
4
+ * a `signIn()` test helper.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { failure, isFailure, success } from "@sdxc/result";
10
+ import { CONFIG_FILE, ENV_EXAMPLE_FILE, declaredBindings, exampleKeys } from "../doctor/env.js";
11
+ import { creditSetupFiles } from "./credit.js";
12
+ import { readProjectFile } from "./plan.js";
13
+ /** Builds the auth setup plan for `provider` (currently only `r3-auth`). */
14
+ export async function planAuth(root, provider) {
15
+ if (provider !== "r3-auth") {
16
+ return failure(new Error(`Unknown auth provider "${provider}"; this release ships r3-auth only`));
17
+ }
18
+ let config = await readProjectFile(root, CONFIG_FILE);
19
+ if (isFailure(config))
20
+ return config;
21
+ let example = await readProjectFile(root, ENV_EXAMPLE_FILE);
22
+ let exampleText = isFailure(example) ? "" : example.data;
23
+ let bindings = declaredBindings(config.data);
24
+ let listed = exampleKeys(exampleText);
25
+ let secrets = ["CLIENT_ID", "CLIENT_SECRET"];
26
+ let configAfter = config.data;
27
+ let exampleAfter = exampleText;
28
+ let edits = [];
29
+ for (let key of secrets) {
30
+ if (!bindings.has(key)) {
31
+ let inserted = insertSecret(configAfter, key);
32
+ if (isFailure(inserted))
33
+ return inserted;
34
+ configAfter = inserted.data;
35
+ }
36
+ if (!listed.has(key)) {
37
+ if (exampleAfter === "")
38
+ exampleAfter = `${key}=\n`;
39
+ else if (exampleAfter.endsWith("\n"))
40
+ exampleAfter = `${exampleAfter}${key}=\n`;
41
+ else
42
+ exampleAfter = `${exampleAfter}\n${key}=\n`;
43
+ }
44
+ }
45
+ if (configAfter !== config.data) {
46
+ edits.push({ path: CONFIG_FILE, before: config.data, after: configAfter });
47
+ }
48
+ if (exampleAfter !== exampleText) {
49
+ edits.push({
50
+ path: ENV_EXAMPLE_FILE,
51
+ before: exampleText,
52
+ after: exampleAfter,
53
+ });
54
+ }
55
+ let files = await creditSetupFiles(root, [
56
+ { path: "app/initializers/issuer.ts", content: ISSUER },
57
+ { path: "app/initializers/relying-party.ts", content: RELYING_PARTY },
58
+ { path: "app/http/middleware/auth.ts", content: AUTH_MIDDLEWARE },
59
+ { path: "app/http/controllers/auth.tsx", content: AUTH_CONTROLLER },
60
+ { path: "routes/auth.ts", content: AUTH_ROUTES },
61
+ { path: "app/test/session.ts", content: SESSION_HELPER },
62
+ ]);
63
+ return success({
64
+ feature: "auth",
65
+ provider,
66
+ files,
67
+ edits,
68
+ dependencies: ["@sdxc/auth", "@sdxc/jwt"],
69
+ notes: [
70
+ "Map routes/auth.ts in the web router with lazy(() => import(…)).",
71
+ "Point app/initializers/issuer.ts at your r3-auth deployment.",
72
+ "Add CLIENT_ID / CLIENT_SECRET to the issuer's client registration.",
73
+ "Run sdxc run typegen after the secrets land.",
74
+ "Fill signIn() / mapProfile once the local account model exists.",
75
+ ],
76
+ });
77
+ }
78
+ function insertSecret(source, key) {
79
+ let env = /env\s*:\s*\{/.exec(source);
80
+ if (env === null || env.index === undefined) {
81
+ return failure(new Error(`${CONFIG_FILE} has no env: { … } block to edit`));
82
+ }
83
+ let start = env.index + env[0].length;
84
+ return success(`${source.slice(0, start)}\n\t\t\t${key}: bindings.secret(),${source.slice(start)}`);
85
+ }
86
+ const ISSUER = `/**
87
+ * The OpenID Connect issuer this app trusts — the r3-auth deployment that issues ID tokens.
88
+ */
89
+
90
+ import { Issuer } from "@sdxc/auth/issuer";
91
+
92
+ /** The issuer URL; replace with the r3-auth origin before the first login. */
93
+ const ISSUER_URL = "https://auth.example.com";
94
+
95
+ /** The issuer every relying-party login verifies tokens against. */
96
+ export function issuer(): Issuer {
97
+ return new Issuer(new URL(ISSUER_URL));
98
+ }
99
+ `;
100
+ const RELYING_PARTY = `/**
101
+ * The confidential OIDC client that signs a visitor in: authorization redirect, callback that
102
+ * verifies the ID token, provider logout, and the session scheme auth middleware resolves.
103
+ */
104
+
105
+ import { RelyingParty } from "@sdxc/auth/relying-party";
106
+ import { JWK } from "@sdxc/jwt";
107
+
108
+ import { getEnv } from "~/app/http/middleware/env";
109
+ import { issuer } from "~/app/initializers/issuer";
110
+ import routes from "~/routes/auth";
111
+
112
+ /**
113
+ * The client for the request's own origin. Replace the issuer URL with the r3-auth deployment
114
+ * this app registers against, and map verified claims onto the local session actor.
115
+ *
116
+ * @param url - The current request URL the callback is built against.
117
+ */
118
+ export function relyingParty(url: URL | string): RelyingParty<{ id: string }> {
119
+ return new RelyingParty<{ id: string }>(issuer(), {
120
+ clientId: getEnv("CLIENT_ID"),
121
+ clientSecret: getEnv("CLIENT_SECRET"),
122
+ redirectUri: new URL(routes.callback.href(), url),
123
+ clientAuth: "client_secret_basic",
124
+ algorithms: [JWK.Algorithm.ES256],
125
+ fallbackReturnTo: "/",
126
+ mapProfile(claims) {
127
+ let subject = typeof claims.sub === "string" ? claims.sub : null;
128
+ if (subject === null) throw new Error("ID token is missing sub");
129
+ return { id: subject };
130
+ },
131
+ });
132
+ }
133
+ `;
134
+ const AUTH_MIDDLEWARE = `/**
135
+ * Session helpers for the relying party: whether a visitor is signed in, and the login /
136
+ * logout actions controllers call.
137
+ */
138
+
139
+ import { getContext } from "remix/middleware/async-context";
140
+
141
+ /** Whether the current session holds an actor. */
142
+ export function isAuthenticated(): boolean {
143
+ let ctx = getContext<{ session: { get(key: string): unknown } }>();
144
+ return ctx.session.get("actor") != null;
145
+ }
146
+
147
+ /** Stores \`actor\` on the session after a successful callback. */
148
+ export function login(actor: { id: string }): void {
149
+ let ctx = getContext<{ session: { set(key: string, value: unknown): void } }>();
150
+ ctx.session.set("actor", actor);
151
+ }
152
+
153
+ /** Clears the session actor on logout. */
154
+ export function logout(): void {
155
+ let ctx = getContext<{ session: { unset(key: string): void } }>();
156
+ ctx.session.unset("actor");
157
+ }
158
+ `;
159
+ const AUTH_CONTROLLER = `/**
160
+ * Login, callback and logout controllers for the OIDC relying party. Fill the views and the
161
+ * return-path helpers for the app's own routes.
162
+ */
163
+
164
+ import { contextOf } from "@sdxc/auth/remix/context";
165
+ import { redirect } from "@sdxc/http/response";
166
+ import { createController } from "remix/router";
167
+
168
+ import { isAuthenticated, login, logout } from "~/app/http/middleware/auth";
169
+ import { relyingParty } from "~/app/initializers/relying-party";
170
+ import routes from "~/routes/auth";
171
+
172
+ /** Starts the authorization-code flow, or sends an already-signed-in visitor home. */
173
+ export default createController({
174
+ async login(ctx) {
175
+ if (isAuthenticated()) return redirect("/", { status: redirect.Status.SeeOther });
176
+ return relyingParty(ctx.url).authorize(contextOf(ctx));
177
+ },
178
+ async callback(ctx) {
179
+ let grant = await relyingParty(ctx.url).callback(contextOf(ctx));
180
+ login(grant.profile);
181
+ return redirect("/", { status: redirect.Status.SeeOther });
182
+ },
183
+ async logout(ctx) {
184
+ logout();
185
+ return relyingParty(ctx.url).logout(contextOf(ctx), { postLogoutRedirectUri: routes.login.href() });
186
+ },
187
+ });
188
+ `;
189
+ const AUTH_ROUTES = `/**
190
+ * Auth routes the relying-party controllers answer: login, callback and logout.
191
+ */
192
+
193
+ import { get, routes } from "remix/routes";
194
+
195
+ export default routes({
196
+ login: get("/login"),
197
+ callback: get("/auth/callback"),
198
+ logout: get("/logout"),
199
+ });
200
+ `;
201
+ const SESSION_HELPER = `/**
202
+ * Test helper that signs a visitor in by setting the session actor the auth middleware reads.
203
+ */
204
+
205
+ /** Puts \`actor\` on the test session the way a completed login would. */
206
+ export function signIn(session: { set(key: string, value: unknown): void }, actor = { id: "user_test" }): void {
207
+ session.set("actor", actor);
208
+ }
209
+ `;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `sdxc setup billing`: `@sdxc/billing` provider initializer, webhook route stub, checkout
3
+ * secrets and an empty product catalog.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Result } from "@sdxc/result";
9
+ import type { SetupPlan } from "./plan.js";
10
+ /** Builds the billing setup plan for `provider` (currently only `polar`). */
11
+ export declare function planBilling(root: string, provider: string): Promise<Result<SetupPlan, Error>>;