@sdxc/kit 2026.10.20 → 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 (138) hide show
  1. package/README.md +178 -93
  2. package/changelog.jsonl +97 -0
  3. package/config.schema.json +160 -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 +77 -2
  23. package/dist/commands/make.js +53 -1
  24. package/dist/commands/run.d.ts +15 -11
  25. package/dist/commands/run.js +21 -16
  26. package/dist/commands/scaffold.d.ts +2 -1
  27. package/dist/commands/scaffold.js +1 -0
  28. package/dist/commands/setup.d.ts +26 -0
  29. package/dist/commands/setup.js +33 -0
  30. package/dist/config.d.ts +54 -0
  31. package/dist/config.js +92 -1
  32. package/dist/contract.d.ts +56 -3
  33. package/dist/contract.js +140 -7
  34. package/dist/dependencies.d.ts +2 -1
  35. package/dist/dependencies.js +11 -2
  36. package/dist/deploy/plan.d.ts +5 -0
  37. package/dist/deploy/plan.js +10 -0
  38. package/dist/destroy.d.ts +4 -4
  39. package/dist/destroy.js +24 -11
  40. package/dist/diagram.d.ts +32 -0
  41. package/dist/diagram.js +47 -0
  42. package/dist/doctor/checks.d.ts +2 -1
  43. package/dist/doctor/checks.js +26 -1
  44. package/dist/doctor/complexity.d.ts +13 -0
  45. package/dist/doctor/complexity.js +52 -0
  46. package/dist/doctor/crap.d.ts +14 -0
  47. package/dist/doctor/crap.js +67 -0
  48. package/dist/doctor/dependencies.d.ts +13 -0
  49. package/dist/doctor/dependencies.js +42 -0
  50. package/dist/doctor/duplication.d.ts +19 -0
  51. package/dist/doctor/duplication.js +106 -0
  52. package/dist/doctor/fan-out.d.ts +12 -0
  53. package/dist/doctor/fan-out.js +42 -0
  54. package/dist/doctor/feature-scatter.d.ts +15 -0
  55. package/dist/doctor/feature-scatter.js +84 -0
  56. package/dist/doctor/jsdoc.d.ts +44 -0
  57. package/dist/doctor/jsdoc.js +201 -0
  58. package/dist/doctor/module-size.d.ts +13 -0
  59. package/dist/doctor/module-size.js +50 -0
  60. package/dist/doctor/mutation.d.ts +20 -0
  61. package/dist/doctor/mutation.js +97 -0
  62. package/dist/doctor/orphans.d.ts +13 -0
  63. package/dist/doctor/orphans.js +50 -0
  64. package/dist/doctor/project.js +8 -5
  65. package/dist/doctor/result-throws.d.ts +17 -0
  66. package/dist/doctor/result-throws.js +72 -0
  67. package/dist/doctor/test-ratio.d.ts +12 -0
  68. package/dist/doctor/test-ratio.js +31 -0
  69. package/dist/fix/commands.d.ts +37 -0
  70. package/dist/fix/commands.js +63 -0
  71. package/dist/fix/emails.d.ts +21 -0
  72. package/dist/fix/emails.js +159 -0
  73. package/dist/fix/env.d.ts +29 -0
  74. package/dist/fix/env.js +58 -0
  75. package/dist/fix/index.d.ts +11 -0
  76. package/dist/fix/index.js +11 -0
  77. package/dist/fix/models.d.ts +20 -0
  78. package/dist/fix/models.js +95 -0
  79. package/dist/lock.js +12 -2
  80. package/dist/make/binding.d.ts +42 -0
  81. package/dist/make/binding.js +237 -0
  82. package/dist/make/generate.d.ts +11 -2
  83. package/dist/make/generate.js +47 -16
  84. package/dist/make/imports.js +7 -5
  85. package/dist/make/index.d.ts +4 -2
  86. package/dist/make/index.js +4 -1
  87. package/dist/make/kinds.d.ts +5 -0
  88. package/dist/make/kinds.js +14 -2
  89. package/dist/make/schema-diff.js +8 -1
  90. package/dist/make/stubs.d.ts +7 -2
  91. package/dist/make/stubs.js +8 -3
  92. package/dist/make/test.js +1 -0
  93. package/dist/models.js +7 -7
  94. package/dist/routes/modules.js +8 -5
  95. package/dist/routes/parse.js +8 -7
  96. package/dist/routes/routers.js +9 -5
  97. package/dist/scaffold/index.d.ts +2 -0
  98. package/dist/scaffold/index.js +13 -4
  99. package/dist/scaffold/render.d.ts +11 -1
  100. package/dist/scaffold/render.js +86 -1
  101. package/dist/setup/auth.d.ts +12 -0
  102. package/dist/setup/auth.js +209 -0
  103. package/dist/setup/billing.d.ts +11 -0
  104. package/dist/setup/billing.js +116 -0
  105. package/dist/setup/catalog.d.ts +25 -0
  106. package/dist/setup/catalog.js +34 -0
  107. package/dist/setup/credit.d.ts +13 -0
  108. package/dist/setup/credit.js +21 -0
  109. package/dist/setup/flags.d.ts +11 -0
  110. package/dist/setup/flags.js +62 -0
  111. package/dist/setup/index.d.ts +25 -0
  112. package/dist/setup/index.js +53 -0
  113. package/dist/setup/plan.d.ts +38 -0
  114. package/dist/setup/plan.js +62 -0
  115. package/dist/testing.js +3 -3
  116. package/dist/ui/layout.js +1 -1
  117. package/dist/ui/registry.d.ts +2 -2
  118. package/dist/upgrade/project.d.ts +2 -2
  119. package/dist/upgrade/prompt.js +7 -5
  120. package/package.json +10 -7
  121. package/registry/ui/attachment.json +2 -2
  122. package/registry/ui/sidebar.json +3 -3
  123. package/registry/ui/typeset.json +3 -3
  124. package/stubs/command.spec.stub +15 -0
  125. package/stubs/controller.api.spec.stub +15 -0
  126. package/stubs/controller.spec.stub +15 -0
  127. package/stubs/mcp.spec.stub +16 -0
  128. package/stubs/scaffold.migration.stub +2 -1
  129. package/stubs/scaffold.spec.stub +7 -0
  130. package/templates/app/AGENTS.md +21 -4
  131. package/templates/app/README.md +6 -3
  132. package/templates/app/app/commands/typegen.test.ts +20 -1
  133. package/templates/app/app/commands/typegen.ts +16 -2
  134. package/templates/app/app/initializers/cli.ts +7 -0
  135. package/templates/app/app/initializers/mail-transport.test.ts +8 -2
  136. package/templates/app/app/test/cloudflare-workers.ts +2 -0
  137. package/templates/app/package.json +1 -0
  138. package/templates/app/spec/config.jsonc +16 -0
@@ -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;
@@ -23,6 +23,8 @@ export interface ScaffoldInput {
23
23
  api?: boolean;
24
24
  /** Whether to write tests; `undefined` takes `make.tests`. */
25
25
  test: boolean | undefined;
26
+ /** Whether to write one feature `.spec`; `undefined` takes `make.specs`. */
27
+ spec?: boolean | undefined;
26
28
  dryRun: boolean;
27
29
  /** The pieces to leave out, each one the project already has or does without. */
28
30
  skip?: readonly ScaffoldPiece[];
@@ -46,11 +46,12 @@ export async function scaffold(ctx, project, packageRoot, input) {
46
46
  if (isFailure(resource))
47
47
  return resource;
48
48
  let tests = input.test ?? config.make.tests;
49
+ let specs = input.spec ?? config.make.specs;
49
50
  let skip = new Set(input.skip ?? []);
50
51
  let missing = await skippedButNeeded(root, resource.data, input, skip, tests);
51
52
  if (isFailure(missing))
52
53
  return missing;
53
- let pieces = piecesOf(resource.data, input, tests, skip);
54
+ let pieces = piecesOf(resource.data, input, tests, specs, skip);
54
55
  let folder = chainFolder(config.make.migrations, undefined);
55
56
  if (isFailure(folder))
56
57
  return folder;
@@ -65,7 +66,12 @@ export async function scaffold(ctx, project, packageRoot, input) {
65
66
  }
66
67
  let planned = [];
67
68
  let header = headerTags(await resolveAuthor(root));
68
- let values = placeholders(resource.data, header);
69
+ let values = placeholders(resource.data, header, {
70
+ pages: !skip.has("pages") && input.api !== true,
71
+ api: !skip.has("pages") && input.api === true,
72
+ mcp: input.mcp,
73
+ command: input.command,
74
+ });
69
75
  for (let piece of pieces) {
70
76
  let exists = isSuccess(await wrap(() => stat(join(root, piece.path))));
71
77
  if (exists && piece.shared === true)
@@ -219,9 +225,9 @@ async function skippedButNeeded(root, resource, input, skip, tests) {
219
225
  }
220
226
  /**
221
227
  * Every file the scaffold writes but its migration, each test right after the file it covers,
222
- * leaving out the pieces in `skip`.
228
+ * and one feature `.spec` when specs are on, leaving out the pieces in `skip`.
223
229
  */
224
- function piecesOf(resource, input, tests, skip) {
230
+ function piecesOf(resource, input, tests, specs, skip) {
225
231
  let { singular, plural } = resource;
226
232
  let name = singular.base;
227
233
  let pieces = [];
@@ -273,6 +279,9 @@ function piecesOf(resource, input, tests, skip) {
273
279
  pieces.push({ stub: "scaffold.test-mcp.stub", path: "app/test/mcp.ts", shared: true });
274
280
  }
275
281
  }
282
+ if (specs && (!skip.has("pages") || input.mcp || input.command)) {
283
+ pieces.push({ stub: "scaffold.spec.stub", path: `spec/${plural.base}.spec` });
284
+ }
276
285
  return pieces;
277
286
  }
278
287
  /**
@@ -16,11 +16,21 @@ export interface Resource {
16
16
  plural: Name;
17
17
  fields: Field[];
18
18
  }
19
+ /** Which surfaces a scaffold feature `.spec` exercises. */
20
+ export interface SpecSurfaces {
21
+ /** HTML pages under `routes/web`. */
22
+ pages: boolean;
23
+ /** JSON endpoints under `routes/api`. */
24
+ api: boolean;
25
+ mcp: boolean;
26
+ command: boolean;
27
+ }
19
28
  /**
20
29
  * Every placeholder the scaffold's stubs may use. `header` is the module JSDoc's author tags;
21
30
  * the rest derive from `resource`, the copy keys from its plural key (`posts.index.title`).
31
+ * `surfaces` fills `uses` and `cases` for the feature `.spec`.
22
32
  */
23
- export declare function placeholders(resource: Resource, header: string): Record<string, string>;
33
+ export declare function placeholders(resource: Resource, header: string, surfaces?: SpecSurfaces): Record<string, string>;
24
34
  /** The local names `routes/api.ts` imports what the operations are written with under. */
25
35
  export interface OperationLocals {
26
36
  /** `@sdxc/json-schema`'s namespace. */
@@ -12,8 +12,9 @@ import { columnSource, factorySource, fieldIndexes, FIELD_TYPES, fieldsTable } f
12
12
  /**
13
13
  * Every placeholder the scaffold's stubs may use. `header` is the module JSDoc's author tags;
14
14
  * the rest derive from `resource`, the copy keys from its plural key (`posts.index.title`).
15
+ * `surfaces` fills `uses` and `cases` for the feature `.spec`.
15
16
  */
16
- export function placeholders(resource, header) {
17
+ export function placeholders(resource, header, surfaces = { pages: true, api: false, mcp: false, command: false }) {
17
18
  let { singular, plural, fields } = resource;
18
19
  let copy = plural.key;
19
20
  let types = new Set(fields.map((field) => field.type));
@@ -22,6 +23,8 @@ export function placeholders(resource, header) {
22
23
  let labelled = types.has("text") || types.has("timestamp");
23
24
  return {
24
25
  header,
26
+ uses: specUses(surfaces),
27
+ cases: specCases(resource, surfaces),
25
28
  CONSTANT: singular.snake.toUpperCase(),
26
29
  PLURAL_CONSTANT: plural.snake.toUpperCase(),
27
30
  name: singular.base,
@@ -103,6 +106,88 @@ export function placeholders(resource, header) {
103
106
  .join(", "),
104
107
  };
105
108
  }
109
+ /** The `use` lines a feature `.spec` needs for the surfaces it exercises. */
110
+ function specUses(surfaces) {
111
+ let lines = [];
112
+ if (surfaces.pages)
113
+ lines.push("use browser");
114
+ if (surfaces.api)
115
+ lines.push("use http");
116
+ if (surfaces.command)
117
+ lines.push("use cli");
118
+ if (surfaces.mcp)
119
+ lines.push("use mcp");
120
+ return lines.join("\n");
121
+ }
122
+ /**
123
+ * One black-box case per surface the scaffold wrote: a page visit, an HTTP list, a CLI list,
124
+ * or an MCP list call — enough for the suite to compile and for an author to extend.
125
+ */
126
+ function specCases(resource, surfaces) {
127
+ let { singular, plural } = resource;
128
+ let words = singular.title.toLowerCase();
129
+ let pluralWords = plural.title.toLowerCase();
130
+ let cases = [];
131
+ if (surfaces.pages) {
132
+ cases.push([
133
+ `test "the ${pluralWords} index page loads" {`,
134
+ "\twhen {",
135
+ `\t\tbrowser.open "/${plural.base}"`,
136
+ "\t}",
137
+ "\tthen {",
138
+ `\t\texpect browser.heading "${plural.title}"`,
139
+ "\t}",
140
+ "}",
141
+ ].join("\n"));
142
+ }
143
+ if (surfaces.api) {
144
+ cases.push([
145
+ `test "GET /api/${plural.base} answers" {`,
146
+ "\twhen {",
147
+ `\t\tlet result = http.get "/api/${plural.base}" on "web"`,
148
+ "\t}",
149
+ "\tthen {",
150
+ "\t\texpect result.status 200",
151
+ "\t}",
152
+ "}",
153
+ ].join("\n"));
154
+ }
155
+ if (surfaces.command) {
156
+ cases.push([
157
+ `test "${plural.base} list runs" {`,
158
+ "\twhen {",
159
+ `\t\tlet result = cli.run "bun" "run" "cli" "${plural.base}" "list" in "."`,
160
+ "\t}",
161
+ "\tthen {",
162
+ "\t\texpect result.exit_code 0",
163
+ "\t}",
164
+ "}",
165
+ ].join("\n"));
166
+ }
167
+ if (surfaces.mcp) {
168
+ cases.push([
169
+ `test "list_${plural.snake} answers over /mcp" {`,
170
+ "\twhen {",
171
+ `\t\tlet result = mcp.call "/mcp" "list_${plural.snake}" {} on "web"`,
172
+ "\t}",
173
+ "\tthen {",
174
+ "\t\texpect result.ok true",
175
+ "\t\texpect result.is_error false",
176
+ "\t}",
177
+ "}",
178
+ ].join("\n"));
179
+ }
180
+ if (cases.length === 0) {
181
+ cases.push([
182
+ `test "the ${words} feature is reachable" {`,
183
+ "\tthen {",
184
+ '\t\texpect "todo" "todo"',
185
+ "\t}",
186
+ "}",
187
+ ].join("\n"));
188
+ }
189
+ return cases.join("\n\n");
190
+ }
106
191
  /**
107
192
  * The OpenAPI operations `scaffold --api` appends to `routes/api.ts`: the schema of a row as the
108
193
  * API answers it, then one operation per endpoint, typing each body the endpoint parses and
@@ -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>>;
@@ -0,0 +1,116 @@
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 { failure, isFailure, success } from "@sdxc/result";
9
+ import { CONFIG_FILE, ENV_EXAMPLE_FILE, declaredBindings, exampleKeys } from "../doctor/env.js";
10
+ import { creditSetupFiles } from "./credit.js";
11
+ import { readProjectFile } from "./plan.js";
12
+ /** Builds the billing setup plan for `provider` (currently only `polar`). */
13
+ export async function planBilling(root, provider) {
14
+ if (provider !== "polar") {
15
+ return failure(new Error(`Unknown billing provider "${provider}"; this release ships polar only`));
16
+ }
17
+ let config = await readProjectFile(root, CONFIG_FILE);
18
+ if (isFailure(config))
19
+ return config;
20
+ let example = await readProjectFile(root, ENV_EXAMPLE_FILE);
21
+ let exampleText = isFailure(example) ? "" : example.data;
22
+ let bindings = declaredBindings(config.data);
23
+ let listed = exampleKeys(exampleText);
24
+ let secrets = ["POLAR_ACCESS_TOKEN", "POLAR_WEBHOOK_SECRET"];
25
+ let configAfter = config.data;
26
+ let exampleAfter = exampleText;
27
+ let edits = [];
28
+ for (let key of secrets) {
29
+ if (!bindings.has(key)) {
30
+ let env = /env\s*:\s*\{/.exec(configAfter);
31
+ if (env === null || env.index === undefined) {
32
+ return failure(new Error(`${CONFIG_FILE} has no env: { … } block to edit`));
33
+ }
34
+ let start = env.index + env[0].length;
35
+ configAfter = `${configAfter.slice(0, start)}\n\t\t\t${key}: bindings.secret(),${configAfter.slice(start)}`;
36
+ }
37
+ if (!listed.has(key)) {
38
+ if (exampleAfter === "")
39
+ exampleAfter = `${key}=\n`;
40
+ else if (exampleAfter.endsWith("\n"))
41
+ exampleAfter = `${exampleAfter}${key}=\n`;
42
+ else
43
+ exampleAfter = `${exampleAfter}\n${key}=\n`;
44
+ }
45
+ }
46
+ if (configAfter !== config.data) {
47
+ edits.push({ path: CONFIG_FILE, before: config.data, after: configAfter });
48
+ }
49
+ if (exampleAfter !== exampleText) {
50
+ edits.push({ path: ENV_EXAMPLE_FILE, before: exampleText, after: exampleAfter });
51
+ }
52
+ let files = await creditSetupFiles(root, [
53
+ { path: "app/initializers/billing.ts", content: BILLING_INITIALIZER },
54
+ { path: "config/products.ts", content: PRODUCTS },
55
+ { path: "app/http/controllers/billing-webhook.ts", content: WEBHOOK },
56
+ ]);
57
+ return success({
58
+ feature: "billing",
59
+ provider,
60
+ files,
61
+ edits,
62
+ dependencies: ["@sdxc/billing"],
63
+ notes: [
64
+ "Map the webhook route and pass polar into the handlers that need it.",
65
+ "Replace the placeholder product ids in config/products.ts with Polar's.",
66
+ "Run sdxc run typegen after the secrets land.",
67
+ ],
68
+ });
69
+ }
70
+ const BILLING_INITIALIZER = `/**
71
+ * The billing platform this app sells through, configured once. Call sites name a product by
72
+ * our own slug; vendor ids live only here and in config/products.ts.
73
+ */
74
+
75
+ import { PolarBilling } from "@sdxc/billing/providers/polar";
76
+ import { env } from "cloudflare:workers";
77
+
78
+ import { PRODUCTS } from "~/config/products";
79
+
80
+ /** The billing platform, reached through the vendor-neutral contract. */
81
+ export const polar = new PolarBilling({
82
+ accessToken: () => env.POLAR_ACCESS_TOKEN,
83
+ webhookSecret: () => env.POLAR_WEBHOOK_SECRET,
84
+ products: PRODUCTS,
85
+ meters: {},
86
+ });
87
+ `;
88
+ const PRODUCTS = `/**
89
+ * Product slugs this app sells, mapped to the vendor's product ids. Fill the ids before the
90
+ * first checkout; call sites import the slug constants, never the vendor ids.
91
+ */
92
+
93
+ /** Our own name for the subscription sold, and the only product until more are added. */
94
+ export const DEFAULT_PRODUCT = "default";
95
+
96
+ /** Slug → Polar product id. Replace the placeholder before going live. */
97
+ export const PRODUCTS: Record<string, string> = {
98
+ [DEFAULT_PRODUCT]: "00000000-0000-4000-8000-000000000000",
99
+ };
100
+ `;
101
+ const WEBHOOK = `/**
102
+ * Polar webhook endpoint: verify the signature and hand the event to @sdxc/billing.
103
+ */
104
+
105
+ import { createController } from "remix/router";
106
+
107
+ import { polar } from "~/app/initializers/billing";
108
+
109
+ /** Accepts Polar webhook deliveries. */
110
+ export default createController({
111
+ async post(ctx) {
112
+ await polar.webhooks.handle(ctx.request);
113
+ return new Response(null, { status: 204 });
114
+ },
115
+ });
116
+ `;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Features `sdxc setup` can install: each row names what the plan wires, so agents discover
3
+ * the catalog the same way they discover `make` kinds.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ /** One feature this kit release knows how to set up. */
9
+ export interface SetupFeature {
10
+ /** The verb after `sdxc setup`, such as `auth`. */
11
+ name: string;
12
+ /** One sentence of what it wires. */
13
+ description: string;
14
+ /** Provider flag values this feature accepts; empty when it has none. */
15
+ providers: readonly string[];
16
+ /** Default `--provider` when the feature has providers. */
17
+ defaultProvider?: string;
18
+ }
19
+ /**
20
+ * Features shipped in this kit release. Further rows land only when their planner has a
21
+ * deterministic file list a test can assert.
22
+ */
23
+ export declare const SETUP_FEATURES: readonly SetupFeature[];
24
+ /** Looks up a feature by name, or `null` when this release does not ship it. */
25
+ export declare function setupFeature(name: string): SetupFeature | null;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Features `sdxc setup` can install: each row names what the plan wires, so agents discover
3
+ * the catalog the same way they discover `make` kinds.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ /**
9
+ * Features shipped in this kit release. Further rows land only when their planner has a
10
+ * deterministic file list a test can assert.
11
+ */
12
+ export const SETUP_FEATURES = [
13
+ {
14
+ name: "auth",
15
+ description: "OIDC relying party, login/callback/logout, client secrets, CSP formAction, signIn() helper",
16
+ providers: ["r3-auth"],
17
+ defaultProvider: "r3-auth",
18
+ },
19
+ {
20
+ name: "billing",
21
+ description: "@sdxc/billing provider, webhook route stub, portal/checkout secrets, empty product catalog",
22
+ providers: ["polar"],
23
+ defaultProvider: "polar",
24
+ },
25
+ {
26
+ name: "flags",
27
+ description: "@sdxc/flags + engine store, empty catalog, wide-event hook ready for router middleware",
28
+ providers: [],
29
+ },
30
+ ];
31
+ /** Looks up a feature by name, or `null` when this release does not ship it. */
32
+ export function setupFeature(name) {
33
+ return SETUP_FEATURES.find((feature) => feature.name === name) ?? null;
34
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Credits setup-written files the way `make` stubs do: `@author` / `@copyright` from the
3
+ * project's package.json `author` or git `user.name`, never a kit maintainer hardcoded in.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { SetupFile } from "./plan.js";
9
+ /**
10
+ * Returns `files` with each module JSDoc closed by the project's author tags. A project with
11
+ * no resolvable author leaves the sources unchanged.
12
+ */
13
+ export declare function creditSetupFiles(root: string, files: readonly SetupFile[]): Promise<SetupFile[]>;