create-disposabl-app 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import { Command, CommanderError } from "commander";
9
9
  import * as p2 from "@clack/prompts";
10
10
  // package.json
11
- var version = "0.3.2";
11
+ var version = "0.3.3";
12
12
 
13
13
  // ../disposabl-kit/platforms.ts
14
14
  var platforms = [
@@ -0,0 +1,114 @@
1
+ import { watch } from "node:fs";
2
+ import { readdir, readFile, mkdir, writeFile } from "node:fs/promises";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { join } from "node:path";
5
+ import { spawnSync } from "node:child_process";
6
+ import {
7
+ createOpenApi,
8
+ createPlatforms,
9
+ } from "../disposabl-kit/server/lib/platform-spec";
10
+
11
+ const root = fileURLToPath(new URL(".", import.meta.url));
12
+ const convex = join(root, "convex");
13
+ const output = join(root, "generated");
14
+ const canonical = (value: unknown): string =>
15
+ JSON.stringify(value, (_, item) =>
16
+ item && typeof item === "object" && !Array.isArray(item)
17
+ ? Object.fromEntries(
18
+ Object.entries(item).sort(([a], [b]) => a.localeCompare(b)),
19
+ )
20
+ : item,
21
+ );
22
+
23
+ async function writeChanged(path: string, text: string) {
24
+ if ((await readFile(path, "utf8").catch(() => "")) !== text)
25
+ await writeFile(path, text);
26
+ }
27
+
28
+ /** Discover opt-in modules, validate the contract, then update both transports together. */
29
+ export async function generate(acceptBreaking = false) {
30
+ const files = await readdir(convex, { recursive: true });
31
+ const modules: Record<string, Record<string, unknown>> = {};
32
+ for (const file of files.sort()) {
33
+ if (
34
+ file.startsWith("_generated/") ||
35
+ !file.endsWith(".ts") ||
36
+ file.endsWith(".d.ts")
37
+ )
38
+ continue;
39
+ const source = await readFile(join(convex, file), "utf8");
40
+ if (!/\bplatforms\s*:\s*true\b/.test(source)) continue;
41
+ if (/^[\s;]*["']use node["']/.test(source))
42
+ throw new Error(
43
+ `${file}: platform validators must be in a default-runtime module; delegate Node work through an internal action.`,
44
+ );
45
+ modules[file.slice(0, -3)] = await import(
46
+ pathToFileURL(join(convex, file)).href
47
+ );
48
+ }
49
+ const next = createOpenApi(createPlatforms(modules).spec);
50
+ const previous = await readFile(join(output, "openapi.json"), "utf8")
51
+ .then(JSON.parse)
52
+ .catch((error) => {
53
+ if (error.code !== "ENOENT") throw error;
54
+ return null;
55
+ });
56
+ const changes = previous
57
+ ? Object.keys(previous.paths).filter(
58
+ (path) =>
59
+ canonical(previous.paths[path]) !== canonical(next.paths[path]),
60
+ )
61
+ : [];
62
+ if (changes.length && !acceptBreaking)
63
+ throw new Error(
64
+ `Contract changed or removed: ${changes.join(", ")}. Review the changes, then run bun run generate --accept-breaking to accept a major version.`,
65
+ );
66
+ if (previous) {
67
+ const [major, minor, patch] = previous.info.version.split(".").map(Number);
68
+ next.info.version = changes.length
69
+ ? `${major + 1}.0.0`
70
+ : canonical(previous.paths) !== canonical(next.paths)
71
+ ? `${major}.${minor + 1}.0`
72
+ : `${major}.${minor}.${patch}`;
73
+ }
74
+ const paths = Object.keys(modules);
75
+ const registry =
76
+ "// Generated by bun run generate. Do not edit.\n" +
77
+ paths
78
+ .map(
79
+ (path, index) =>
80
+ `import * as m${index} from ${JSON.stringify(`../convex/${path}`)};`,
81
+ )
82
+ .join("\n") +
83
+ `\nexport default {${paths.map((path, index) => `${JSON.stringify(path)}: m${index}`).join(",")}};\n`;
84
+ await mkdir(output, { recursive: true });
85
+ await writeChanged(
86
+ join(output, "openapi.json"),
87
+ JSON.stringify(next, null, 2) + "\n",
88
+ );
89
+ await writeChanged(join(output, "platforms.ts"), registry);
90
+ const formatted = spawnSync(process.execPath, ["fmt", output], {
91
+ stdio: "pipe",
92
+ });
93
+ if (formatted.status !== 0)
94
+ throw new Error("Could not format generated contract");
95
+ console.log(
96
+ `Generated ${Object.keys(next.paths).length} operations, contract ${next.info.version}.`,
97
+ );
98
+ }
99
+
100
+ if (import.meta.main) {
101
+ if (process.argv.includes("--watch")) {
102
+ const run = () =>
103
+ spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
104
+ stdio: "inherit",
105
+ });
106
+ run();
107
+ let timer: ReturnType<typeof setTimeout>;
108
+ watch(convex, { recursive: true }, (_, file) => {
109
+ if (!file?.endsWith(".ts")) return;
110
+ clearTimeout(timer);
111
+ timer = setTimeout(run, 200);
112
+ });
113
+ } else await generate(process.argv.includes("--accept-breaking"));
114
+ }
@@ -0,0 +1,190 @@
1
+ {
2
+ "openapi": "3.1.0",
3
+ "info": {
4
+ "title": "Application API",
5
+ "version": "0.1.0"
6
+ },
7
+ "security": [
8
+ {
9
+ "bearerAuth": []
10
+ }
11
+ ],
12
+ "components": {
13
+ "securitySchemes": {
14
+ "bearerAuth": {
15
+ "type": "http",
16
+ "scheme": "bearer"
17
+ }
18
+ }
19
+ },
20
+ "paths": {
21
+ "/api/todos/create": {
22
+ "post": {
23
+ "operationId": "todosCreate",
24
+ "x-convex-function": "todos/internal:create",
25
+ "requestBody": {
26
+ "required": true,
27
+ "content": {
28
+ "application/json": {
29
+ "schema": {
30
+ "type": "object",
31
+ "properties": {
32
+ "title": {
33
+ "type": "string"
34
+ }
35
+ },
36
+ "required": ["title"],
37
+ "additionalProperties": false
38
+ }
39
+ }
40
+ }
41
+ },
42
+ "responses": {
43
+ "200": {
44
+ "description": "Success",
45
+ "content": {
46
+ "application/json": {
47
+ "schema": {
48
+ "type": "string",
49
+ "description": "ID of a document in \"todos\""
50
+ }
51
+ }
52
+ }
53
+ },
54
+ "400": {
55
+ "description": "Invalid arguments"
56
+ },
57
+ "401": {
58
+ "description": "Authentication required"
59
+ },
60
+ "403": {
61
+ "description": "Insufficient scope"
62
+ },
63
+ "500": {
64
+ "description": "Internal error"
65
+ }
66
+ }
67
+ }
68
+ },
69
+ "/api/todos/get": {
70
+ "get": {
71
+ "operationId": "todosGet",
72
+ "x-convex-function": "todos/internal:get",
73
+ "parameters": [
74
+ {
75
+ "name": "id",
76
+ "in": "query",
77
+ "required": true,
78
+ "content": {
79
+ "application/json": {
80
+ "schema": {
81
+ "type": "string",
82
+ "description": "ID of a document in \"todos\""
83
+ }
84
+ }
85
+ }
86
+ }
87
+ ],
88
+ "responses": {
89
+ "200": {
90
+ "description": "Success",
91
+ "content": {
92
+ "application/json": {
93
+ "schema": {
94
+ "anyOf": [
95
+ {
96
+ "type": "object",
97
+ "properties": {
98
+ "userId": {
99
+ "type": "string"
100
+ },
101
+ "title": {
102
+ "type": "string"
103
+ },
104
+ "_id": {
105
+ "type": "string",
106
+ "description": "ID of a document in \"todos\""
107
+ },
108
+ "_creationTime": {
109
+ "type": "number"
110
+ }
111
+ },
112
+ "required": ["userId", "title", "_id", "_creationTime"],
113
+ "additionalProperties": false
114
+ },
115
+ {
116
+ "type": "null"
117
+ }
118
+ ]
119
+ }
120
+ }
121
+ }
122
+ },
123
+ "400": {
124
+ "description": "Invalid arguments"
125
+ },
126
+ "401": {
127
+ "description": "Authentication required"
128
+ },
129
+ "403": {
130
+ "description": "Insufficient scope"
131
+ },
132
+ "500": {
133
+ "description": "Internal error"
134
+ }
135
+ }
136
+ }
137
+ },
138
+ "/api/todos/list": {
139
+ "get": {
140
+ "operationId": "todosList",
141
+ "x-convex-function": "todos/internal:list",
142
+ "parameters": [],
143
+ "responses": {
144
+ "200": {
145
+ "description": "Success",
146
+ "content": {
147
+ "application/json": {
148
+ "schema": {
149
+ "type": "array",
150
+ "items": {
151
+ "type": "object",
152
+ "properties": {
153
+ "userId": {
154
+ "type": "string"
155
+ },
156
+ "title": {
157
+ "type": "string"
158
+ },
159
+ "_id": {
160
+ "type": "string",
161
+ "description": "ID of a document in \"todos\""
162
+ },
163
+ "_creationTime": {
164
+ "type": "number"
165
+ }
166
+ },
167
+ "required": ["userId", "title", "_id", "_creationTime"],
168
+ "additionalProperties": false
169
+ }
170
+ }
171
+ }
172
+ }
173
+ },
174
+ "400": {
175
+ "description": "Invalid arguments"
176
+ },
177
+ "401": {
178
+ "description": "Authentication required"
179
+ },
180
+ "403": {
181
+ "description": "Insufficient scope"
182
+ },
183
+ "500": {
184
+ "description": "Internal error"
185
+ }
186
+ }
187
+ }
188
+ }
189
+ }
190
+ }
@@ -0,0 +1,3 @@
1
+ // Generated by bun run generate. Do not edit.
2
+ import * as m0 from "../convex/todos/internal";
3
+ export default { "todos/internal": m0 };
@@ -3,7 +3,9 @@
3
3
  "private": true,
4
4
  "version": "0.0.0",
5
5
  "scripts": {
6
- "predev": "bun x --no-install --package @convex-dev/auth auth --keys-only",
6
+ "generate": "bun generate.ts",
7
+ "generate:watch": "bun generate.ts --watch",
8
+ "predev": "bun run generate && bun x --no-install --package @convex-dev/auth auth --keys-only",
7
9
  "dev": "convex dev",
8
10
  "logs": "convex logs",
9
11
  "typecheck": "tsc -p convex",
@@ -4,7 +4,8 @@ import { registerStaticRoutes } from "@convex-dev/static-hosting";
4
4
  import { httpActionGeneric, httpRouter } from "convex/server";
5
5
  import { components } from "../../backend/convex/_generated/api";
6
6
  import { env } from "../../backend/convex/_generated/server";
7
- import * as todos from "../../backend/convex/todos/internal";
7
+ import modules from "../../backend/generated/platforms";
8
+ import openapi from "../../backend/generated/openapi.json";
8
9
  import config from "../../../disposabl.json";
9
10
  import { validatePlatforms } from "../platforms";
10
11
  import { createPlatforms } from "./lib/platform-spec";
@@ -12,7 +13,7 @@ import { createPlatforms } from "./lib/platform-spec";
12
13
  export { tool } from "@convex-dev/mcp";
13
14
  export type { McpServerOptions, McpUser, ToolCtx } from "@convex-dev/mcp";
14
15
 
15
- const platforms = createPlatforms({ "todos/internal": todos });
16
+ const platforms = createPlatforms(modules);
16
17
  export const platformSpec = platforms.spec;
17
18
 
18
19
  const enabled = validatePlatforms(config.platforms);
@@ -41,15 +42,31 @@ export const {
41
42
 
42
43
  export default function createHttpRouter() {
43
44
  const http = httpRouter();
44
- if (mcp && enabled.includes("mcp")) mcp.registerRoutes(http);
45
- if (mcp && enabled.includes("api"))
45
+ if (mcp) {
46
+ const authRoutes = httpRouter();
47
+ mcp.registerRoutes(authRoutes);
48
+ for (const [path, method, handler] of authRoutes.getRoutes()) {
49
+ if (path !== "/mcp" || enabled.includes("mcp"))
50
+ http.route({ path, method, handler });
51
+ }
52
+ }
53
+ if (mcp && enabled.includes("api")) {
46
54
  http.route({
47
- pathPrefix: "/api/",
48
- method: "POST",
49
- handler: httpActionGeneric((ctx, request) =>
50
- platforms.handleApi(ctx, request, mcp.authenticate.bind(mcp)),
55
+ path: "/openapi.json",
56
+ method: "GET",
57
+ handler: httpActionGeneric(async () =>
58
+ Response.json({ ...openapi, servers: [{ url: env.CONVEX_SITE_URL }] }),
51
59
  ),
52
60
  });
61
+ for (const method of ["GET", "POST"] as const)
62
+ http.route({
63
+ pathPrefix: "/api/",
64
+ method,
65
+ handler: httpActionGeneric((ctx, request) =>
66
+ platforms.handleApi(ctx, request, mcp.authenticate.bind(mcp)),
67
+ ),
68
+ });
69
+ }
53
70
  registerStaticRoutes(http, components.staticHosting);
54
71
  return http;
55
72
  }
@@ -92,19 +92,37 @@ export function createPlatforms(
92
92
  request: Request,
93
93
  authenticate: McpServer["authenticate"],
94
94
  ) {
95
- const definition = routes.get(new URL(request.url).pathname);
95
+ const url = new URL(request.url);
96
+ const definition = routes.get(url.pathname);
96
97
  if (!definition)
97
98
  return Response.json({ error: "not_found" }, { status: 404 });
99
+ const method =
100
+ spec.find((operation) => operation.path === url.pathname)?.type ===
101
+ "query"
102
+ ? "GET"
103
+ : "POST";
104
+ if (request.method !== method)
105
+ return Response.json(
106
+ { error: "method_not_allowed" },
107
+ { status: 405, headers: { Allow: method } },
108
+ );
98
109
  try {
99
110
  const user = await authenticate(ctx, request);
100
111
  if (!user)
101
112
  return Response.json({ error: "unauthenticated" }, { status: 401 });
102
113
  if (definition.scope && !user.scopes.includes(definition.scope))
103
114
  return Response.json({ error: "forbidden" }, { status: 403 });
104
- const input = checkValue(
105
- v.object(definition.args ?? {}),
106
- await request.json(),
107
- );
115
+ const raw =
116
+ request.method === "GET"
117
+ ? Object.fromEntries(
118
+ [...url.searchParams].map(([key, value]) => {
119
+ if (url.searchParams.getAll(key).length !== 1)
120
+ throw new SyntaxError("Duplicate argument");
121
+ return [key, JSON.parse(value)];
122
+ }),
123
+ )
124
+ : await request.json();
125
+ const input = checkValue(v.object(definition.args ?? {}), raw);
108
126
  if (!input.ok)
109
127
  return Response.json({ error: input.error }, { status: 400 });
110
128
  const result = await definition.handler(
@@ -135,3 +153,74 @@ export function createPlatforms(
135
153
  },
136
154
  };
137
155
  }
156
+
157
+ /** The same validator schemas describe the HTTP transport and generated clients. */
158
+ export function createOpenApi(spec: Operation[], version = "0.1.0") {
159
+ const ids = new Set<string>();
160
+ return {
161
+ openapi: "3.1.0",
162
+ info: { title: "Application API", version },
163
+ security: [{ bearerAuth: [] }],
164
+ components: {
165
+ securitySchemes: { bearerAuth: { type: "http", scheme: "bearer" } },
166
+ },
167
+ paths: Object.fromEntries(
168
+ spec.map((operation) => {
169
+ const parts = operation.path.slice(5).split("/");
170
+ const operationId = parts
171
+ .map((part, i) =>
172
+ i ? part.charAt(0).toUpperCase() + part.slice(1) : part,
173
+ )
174
+ .join("");
175
+ if (ids.has(operationId))
176
+ throw new Error(`Duplicate operation ID: ${operationId}`);
177
+ ids.add(operationId);
178
+ const query = operation.type === "query";
179
+ const args = operation.args as {
180
+ properties?: Record<string, unknown>;
181
+ required?: string[];
182
+ };
183
+ return [
184
+ operation.path,
185
+ {
186
+ [query ? "get" : "post"]: {
187
+ operationId,
188
+ "x-convex-function": operation.name,
189
+ ...(query
190
+ ? {
191
+ parameters: Object.entries(args.properties ?? {}).map(
192
+ ([name, schema]) => ({
193
+ name,
194
+ in: "query",
195
+ required: args.required?.includes(name) ?? false,
196
+ content: { "application/json": { schema } },
197
+ }),
198
+ ),
199
+ }
200
+ : {
201
+ requestBody: {
202
+ required: true,
203
+ content: {
204
+ "application/json": { schema: operation.args },
205
+ },
206
+ },
207
+ }),
208
+ responses: {
209
+ "200": {
210
+ description: "Success",
211
+ content: {
212
+ "application/json": { schema: operation.returns },
213
+ },
214
+ },
215
+ "400": { description: "Invalid arguments" },
216
+ "401": { description: "Authentication required" },
217
+ "403": { description: "Insufficient scope" },
218
+ "500": { description: "Internal error" },
219
+ },
220
+ },
221
+ },
222
+ ];
223
+ }),
224
+ ),
225
+ };
226
+ }
@@ -43,6 +43,15 @@
43
43
  "cache": false,
44
44
  "persistent": true,
45
45
  "passThroughEnv": ["VITE_*"]
46
+ },
47
+ "@disposabl/backend#dev": {
48
+ "cache": false,
49
+ "persistent": true,
50
+ "with": ["@disposabl/backend#generate:watch"]
51
+ },
52
+ "generate:watch": {
53
+ "cache": false,
54
+ "persistent": true
46
55
  }
47
56
  },
48
57
  "globalDependencies": ["disposabl.json"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-disposabl-app",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Create a Disposabl app",
5
5
  "type": "module",
6
6
  "license": "MIT",