@vvedantb/server 0.18.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/ai/errors.d.ts +0 -2
  3. package/dist/ai/errors.js +0 -16
  4. package/dist/ai/serviceTier.d.ts +0 -4
  5. package/dist/ai/serviceTier.js +0 -4
  6. package/dist/artifacts/document.d.ts +0 -2
  7. package/dist/artifacts/document.js +0 -1
  8. package/dist/artifacts/protocol.d.ts +0 -5
  9. package/dist/artifacts/schemas.d.ts +0 -6
  10. package/dist/artifacts/storageShim.js +0 -2
  11. package/dist/convex/authFunctions.d.ts +0 -57
  12. package/dist/convex/clerkBilling.d.ts +2 -18
  13. package/dist/convex/clerkBilling.js +0 -9
  14. package/dist/convex/clerkBillingFunctions.d.ts +0 -35
  15. package/dist/convex/clerkBillingFunctions.js +0 -8
  16. package/dist/convex/clerkBillingNodeFunctions.d.ts +0 -29
  17. package/dist/convex/clerkBillingNodeFunctions.js +0 -1
  18. package/dist/convex/clerkUserAuth.d.ts +0 -18
  19. package/dist/convex/clerkUserAuth.js +0 -14
  20. package/dist/convex/clerkWebhook.d.ts +0 -2
  21. package/dist/convex/convexAdminClient.d.ts +0 -30
  22. package/dist/convex/convexAdminClient.js +0 -34
  23. package/dist/convex/convexQueryLimits.d.ts +0 -8
  24. package/dist/convex/convexQueryLimits.js +0 -8
  25. package/dist/convex/createMcpAuthActions.d.ts +0 -31
  26. package/dist/convex/expoPush.d.ts +0 -24
  27. package/dist/convex/expoPush.js +0 -4
  28. package/dist/convex/homepageRoutes.d.ts +42 -0
  29. package/dist/convex/homepageRoutes.js +46 -0
  30. package/dist/convex/index.d.ts +2 -0
  31. package/dist/convex/index.js +2 -0
  32. package/dist/convex/mcpServerInfo.d.ts +0 -2
  33. package/dist/convex/mcpTokenCache.d.ts +0 -17
  34. package/dist/convex/mcpTokenCache.js +0 -2
  35. package/dist/convex/memoryStore.js +0 -6
  36. package/dist/convex/originAllowlistCors.d.ts +0 -8
  37. package/dist/convex/productEmails.d.ts +22 -0
  38. package/dist/convex/productEmails.js +37 -0
  39. package/dist/convex/tempId.js +0 -2
  40. package/dist/convex/vPlan.d.ts +0 -4
  41. package/dist/convex/vProModule.d.ts +0 -27
  42. package/dist/convex/vProModule.js +0 -11
  43. package/dist/convex/verifyClerkAccessToken.d.ts +3 -13
  44. package/dist/convex/verifyClerkOAuthJwt.d.ts +0 -18
  45. package/dist/convex/verifyClerkOAuthJwt.js +0 -6
  46. package/dist/crypto/aesGcm.d.ts +0 -2
  47. package/dist/crypto/aesGcm.js +0 -2
  48. package/dist/crypto/encoding.d.ts +0 -8
  49. package/dist/crypto/encoding.js +0 -3
  50. package/dist/generative-ui/catalog.d.ts +0 -17
  51. package/dist/generative-ui/catalog.js +0 -18
  52. package/dist/generative-ui/spec.d.ts +0 -8
  53. package/dist/generative-ui/spec.js +0 -12
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +1 -0
  56. package/dist/mcp/dispatcher.d.ts +0 -7
  57. package/dist/mcp/dispatcher.js +0 -1
  58. package/dist/mcp/explorer.d.ts +0 -21
  59. package/dist/mcp/http.d.ts +3 -30
  60. package/dist/mcp/http.js +14 -0
  61. package/dist/mcp/index.d.ts +2 -1
  62. package/dist/mcp/index.js +2 -1
  63. package/dist/mcp/json.d.ts +0 -1
  64. package/dist/mcp/jsonRpc.d.ts +0 -2
  65. package/dist/mcp/metadata.d.ts +0 -15
  66. package/dist/mcp/routes.d.ts +2 -12
  67. package/dist/mcp/routes.js +6 -2
  68. package/dist/mcp/sdk.d.ts +0 -12
  69. package/dist/mcp/tools.d.ts +0 -18
  70. package/dist/mcp/tools.js +0 -1
  71. package/dist/mcp/zodJsonSchema.d.ts +14 -0
  72. package/dist/mcp/zodJsonSchema.js +98 -0
  73. package/dist/mcp-oauth-client/loopback.d.ts +0 -5
  74. package/dist/mcp-oauth-client/loopback.js +0 -6
  75. package/dist/mcp-oauth-client/oauth.d.ts +0 -14
  76. package/dist/mcp-oauth-client/oauth.js +0 -16
  77. package/dist/mcp-oauth-client/state.d.ts +0 -3
  78. package/dist/sandbox/runtime.d.ts +0 -15
  79. package/dist/sandbox/runtime.js +0 -25
  80. package/dist/skills/githubSkills.d.ts +51 -0
  81. package/dist/skills/githubSkills.js +172 -0
  82. package/dist/skills/index.d.ts +2 -0
  83. package/dist/skills/index.js +2 -0
  84. package/dist/skills/skillRef.d.ts +18 -0
  85. package/dist/skills/skillRef.js +168 -0
  86. package/package.json +1 -1
@@ -1,20 +1,3 @@
1
- /**
2
- * A tiny client for a Convex deployment's admin HTTP API, used by each app's
3
- * MCP "run query" tool. It takes the deployment's cloud URL and an admin (or
4
- * deploy) key as arguments and reads no environment variables, so the app owns
5
- * where those come from (its own `*_DEPLOY_KEY` env var, a bootstrap fetch, a
6
- * cache). No `convex` or `zod` import: the responses are parsed at the boundary
7
- * here, the same way `expoPush` and `clerkBilling` parse theirs.
8
- *
9
- * - `runTestFunction` POSTs a bundled query source to `/api/run_test_function`
10
- * with the admin key in the body. This is how `run_query` MCP tools execute
11
- * ad-hoc read-only queries against the deployment.
12
- * - `listTables` reads `/api/shapes2` (inferred shapes) and the
13
- * `_system/frontend/getSchemas` query (the declared schema) and merges them.
14
- *
15
- * `formatConvexQueryError` (in `convexQueryLimits`) turns a thrown resource
16
- * limit message into user-facing MCP error text.
17
- */
18
1
  function isRecord(value) {
19
2
  return typeof value === "object" && value !== null && !Array.isArray(value);
20
3
  }
@@ -71,12 +54,6 @@ export function createConvexAdminClient(config) {
71
54
  }
72
55
  return response.json();
73
56
  }
74
- /**
75
- * Run a bundled query source through `/api/run_test_function`. `source` is a
76
- * complete Convex module whose default export is a query (the MCP tools wrap
77
- * the user's code in such a module). Returns the query's value and log lines;
78
- * throws `Error(errorMessage)` when the query errors.
79
- */
80
57
  async function runTestFunction(source, options = {}) {
81
58
  const json = await post(`${base}/api/run_test_function`, { "Content-Type": "application/json" }, {
82
59
  adminKey: config.adminKey,
@@ -86,15 +63,10 @@ export function createConvexAdminClient(config) {
86
63
  });
87
64
  return parseConvexApiResponse(json);
88
65
  }
89
- /**
90
- * Run one deployment function through `/api/query` with the admin auth
91
- * header. Used for `_system` queries like `getSchemas`; returns the value.
92
- */
93
66
  async function runSystemQuery(path, args = {}) {
94
67
  const json = await post(`${base}/api/query`, convexAuthHeaders(), { path, args, format: "json" });
95
68
  return parseConvexApiResponse(json).value;
96
69
  }
97
- /** The inferred shapes map from `/api/shapes2`, keyed by table name. */
98
70
  async function getShapes() {
99
71
  const response = await doFetch(`${base}/api/shapes2`, { headers: convexAuthHeaders() });
100
72
  if (!response.ok) {
@@ -129,12 +101,6 @@ export function createConvexAdminClient(config) {
129
101
  }
130
102
  return byTable;
131
103
  }
132
- /**
133
- * Merge the inferred shapes (`/api/shapes2`) and the declared schema
134
- * (`_system/frontend/getSchemas`) into one sorted list of tables. Each table
135
- * carries both, either of which may be `null`. Pass `hideTable` to drop
136
- * tables (system tables, app internals).
137
- */
138
104
  async function listTables(options = {}) {
139
105
  const shapes = await getShapes();
140
106
  const schemas = await runSystemQuery("_system/frontend/getSchemas");
@@ -1,11 +1,3 @@
1
- /**
2
- * Convex query resource-limit detection for MCP test queries.
3
- *
4
- * `run_test_function` failures like "Too many bytes read in a single function
5
- * execution (limit: 16777216 bytes)" used to throw out of `runTestQuery` as
6
- * an uncaught Server Error. Callers map the formatted message to an MCP
7
- * `isError` result instead.
8
- */
9
1
  export declare function isConvexResourceLimitError(message: string): boolean;
10
2
  /** User-facing MCP error text for a failed test query. */
11
3
  export declare function formatConvexQueryError(message: string): string;
@@ -1,11 +1,3 @@
1
- /**
2
- * Convex query resource-limit detection for MCP test queries.
3
- *
4
- * `run_test_function` failures like "Too many bytes read in a single function
5
- * execution (limit: 16777216 bytes)" used to throw out of `runTestQuery` as
6
- * an uncaught Server Error. Callers map the formatted message to an MCP
7
- * `isError` result instead.
8
- */
9
1
  const CONVEX_RESOURCE_LIMIT_HINT = "Use smaller limits, paginate, or query with a selective index range.";
10
2
  const CONVEX_RESOURCE_LIMIT_MARKERS = [
11
3
  "too many bytes read",
@@ -1,11 +1,3 @@
1
- /**
2
- * The `verifyAccessToken` internal action every Clerk-backed MCP app exposes:
3
- * `verifyClerkAccessToken` plus the few things that differ per app (which
4
- * Clerk instance, which token types, what to log, what to return).
5
- *
6
- * The package never imports `convex` at runtime, so the app passes in `v` and
7
- * its `internalAction` builder.
8
- */
9
1
  import type { RegisteredAction } from "convex/server";
10
2
  import type { v as convexV, Validator } from "convex/values";
11
3
  import { type ClerkAuthLike, type ClerkLike, type ClerkTokenType, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions } from "./verifyClerkAccessToken.js";
@@ -41,49 +33,26 @@ export type McpAuthMapArgs<Ctx> = {
41
33
  token: string;
42
34
  ctx: Ctx;
43
35
  userId: string;
44
- /** The Clerk result; `null` when `tryBeforeClerk` accepted the token. */
45
36
  verified: VerifiedClerkToken<ClerkAuthLike> | null;
46
37
  };
47
38
  type ClerkSource = {
48
- /** One Clerk client, or a function that builds it. */
49
39
  getClerk: McpAuthClerk;
50
40
  getClerks?: undefined;
51
41
  } | {
52
42
  getClerk?: undefined;
53
- /** Several Clerk instances, tried in order. The first success wins. */
54
43
  getClerks: McpAuthClerk[];
55
44
  };
56
45
  type CommonConfig<Ctx> = {
57
46
  v: ConvexV;
58
- /** Forwarded to `verifyClerkAccessToken`. Default `["oauth_token", "session_token"]`. */
59
47
  acceptsToken?: ClerkTokenType[];
60
- /**
61
- * `onReject` and `onError` for each Clerk attempt. Default: silent.
62
- * `onError` also gets anything the two hooks throw, but only when
63
- * `swallowHookErrors` is `true`.
64
- */
65
48
  logger?: Pick<VerifyClerkAccessTokenOptions, "onReject" | "onError">;
66
- /**
67
- * Runs before Clerk. Return a user to skip Clerk, `null` to reject the
68
- * token, or `undefined` to continue with Clerk.
69
- */
70
49
  tryBeforeClerk?: (args: McpAuthEarlyArgs<Ctx>) => Promise<McpAuthEarlyUser | null | undefined>;
71
- /**
72
- * What to do when `tryBeforeClerk` or `mapPrincipal` throws. Default
73
- * `false`: the error propagates, so the action fails and the caller can
74
- * retry. A transient fault then does not look like a rejected token. Set
75
- * `true` to call `logger.onError` and return `null` instead. Use `true` only
76
- * when the handler this action replaces caught every throw and returned
77
- * `null`. Clerk failures return `null` in both modes.
78
- */
79
50
  swallowHookErrors?: boolean;
80
51
  };
81
52
  /** Default result: `{ clerkUserId }`. */
82
53
  export type CreateMcpAuthActionsConfig<Ctx, Principal = McpAuthPrincipal> = CommonConfig<Ctx> & ClerkSource & {
83
54
  internalAction: McpAuthActionBuilder<Ctx, Principal>;
84
- /** After a user is accepted, build the result. Return `null` to reject. Default `{ clerkUserId: userId }`. */
85
55
  mapPrincipal?: (args: McpAuthMapArgs<Ctx>) => Promise<Principal | null>;
86
- /** Convex validator for the result. Default `v.union(v.object({ clerkUserId: v.string() }), v.null())`. */
87
56
  returns?: Validator<Principal | null, "required", string>;
88
57
  };
89
58
  type CustomConfig<Ctx, Principal> = CommonConfig<Ctx> & ClerkSource & {
@@ -1,14 +1,3 @@
1
- /**
2
- * Expo push notifications for Convex apps: a device-token table, `register`
3
- * and `unregister` mutations, a batched send through the Expo Push API, and
4
- * push receipts that drop dead tokens.
5
- *
6
- * The package cannot own a Convex table and never imports `convex` at
7
- * runtime, so the app defines the table in its own schema and passes in `v`,
8
- * its function builders and `requireCurrentUserId`. The HTTP side
9
- * (`sendExpoPushMessages`, `fetchExpoPushReceipts` and the token-cleanup
10
- * helpers) is plain TypeScript that runs in Node and tests with no Convex.
11
- */
12
1
  import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredAction, RegisteredMutation, RegisteredQuery } from "convex/server";
13
2
  import type { v as convexV, GenericId, Validator } from "convex/values";
14
3
  /** The default table name. */
@@ -111,9 +100,7 @@ export type ExpoPushReceiptRef = {
111
100
  token: string;
112
101
  };
113
102
  export type ExpoPushHttpOptions = {
114
- /** Default: the global `fetch`, read at call time. */
115
103
  fetch?: typeof fetch;
116
- /** Expo access token, when the project enforces enhanced push security. */
117
104
  accessToken?: string;
118
105
  };
119
106
  export type SendExpoPushMessagesOptions = ExpoPushHttpOptions & {
@@ -286,30 +273,19 @@ type CheckReceiptsDef<Ctx> = {
286
273
  };
287
274
  export type ExpoPushFunctionsConfig<Table extends string, UserId, Id, Range, MutationCtx extends PushMutationCtx<Table, UserId, Id, Range>, ActionCtx extends ActionRunCtx<UserId>> = {
288
275
  v: ConvexV;
289
- /** The validator for user ids, for example `v.id("users")`. It sets `UserId`. */
290
276
  userId: Req<UserId>;
291
- /** The app's public `mutation`, narrowed to the two calls made here. */
292
277
  mutation: ((def: RegisterDef<MutationCtx>) => RegisteredMutation<"public", RegisterArgs, Promise<null>>) & ((def: UnregisterDef<MutationCtx>) => RegisteredMutation<"public", UnregisterArgs, Promise<null>>);
293
278
  internalQuery: (def: ListTokensDef<PushQueryCtx<NoInfer<Table>, UserId, Id, Range>, UserId>) => RegisteredQuery<"internal", ListTokensArgs<UserId>, Promise<string[]>>;
294
279
  internalMutation: (def: RemoveTokensDef<PushMutationCtx<NoInfer<Table>, UserId, Id, Range>>) => RegisteredMutation<"internal", RemoveTokensArgs, Promise<null>>;
295
280
  internalAction: ((def: SendDef<ActionCtx, UserId>) => RegisteredAction<"internal", PushSendParams<UserId>, Promise<null>>) & ((def: CheckReceiptsDef<ActionCtx>) => RegisteredAction<"internal", CheckReceiptsArgs, Promise<null>>);
296
- /**
297
- * The signed-in user's id, throwing when there is none. Annotate the ctx
298
- * with your `MutationCtx`: `(ctx: MutationCtx) => userAuth.requireCurrentUserId(ctx)`.
299
- */
300
281
  requireCurrentUserId: (ctx: MutationCtx) => Promise<UserId>;
301
- /** `(): ExpoPushListTokensRef<Id<"users">> => internal.push.listTokensForUser`. */
302
282
  listTokensRef: () => ExpoPushListTokensRef<UserId>;
303
283
  removeTokensRef: () => ExpoPushRemoveTokensRef;
304
284
  sendRef: () => ExpoPushSendRef<UserId>;
305
285
  checkReceiptsRef: () => ExpoPushCheckReceiptsRef;
306
- /** The tokens table. Default `"pushTokens"`; it needs both indexes. */
307
286
  tableName?: Table;
308
- /** Wait before receipts are checked. Default `EXPO_RECEIPT_DELAY_MS` (15 minutes). */
309
287
  receiptDelayMs?: number;
310
- /** For `fetch` in tests. Default: the global `fetch`. */
311
288
  fetch?: typeof fetch;
312
- /** Read at send time, so it can come from `process.env`. Sent as a bearer token. */
313
289
  accessToken?: () => string | undefined;
314
290
  };
315
291
  /**
@@ -141,7 +141,6 @@ export async function sendExpoPushMessages(options) {
141
141
  const tickets = parseExpoTickets(await postJson(EXPO_PUSH_SEND_URL, messages, options), batch.length);
142
142
  if (tickets === null)
143
143
  continue;
144
- // Tickets come back in request order.
145
144
  tickets.forEach((ticket, index) => results.push({ token: batch[index], ticket }));
146
145
  }
147
146
  return results;
@@ -230,7 +229,6 @@ export async function schedulePush(ctx, params, options) {
230
229
  */
231
230
  export function createExpoPushFunctions(config) {
232
231
  const built = buildExpoPushFunctions(config);
233
- // The builders only check `Table` here; `schedulePush` takes the app's real ctx, so type it with `Table`.
234
232
  return {
235
233
  ...built,
236
234
  schedulePush: built.schedulePush,
@@ -254,7 +252,6 @@ function buildExpoPushFunctions(config) {
254
252
  .first();
255
253
  const fields = { userId: currentUserId, platform: args.platform, updatedAt: Date.now() };
256
254
  if (existing) {
257
- // A token moves with the device, so a new sign-in takes it over.
258
255
  await ctx.db.patch(existing._id, fields);
259
256
  }
260
257
  else {
@@ -320,7 +317,6 @@ function buildExpoPushFunctions(config) {
320
317
  const dead = tokensToRemoveFromTickets(results);
321
318
  if (dead.length > 0)
322
319
  await ctx.runMutation(config.removeTokensRef(), { tokens: dead });
323
- // Dead tokens are gone already; only check receipts for the rest.
324
320
  const receipts = receiptRefsFromTickets(results).filter((ref) => !dead.includes(ref.token));
325
321
  if (receipts.length > 0) {
326
322
  await ctx.scheduler.runAfter(config.receiptDelayMs ?? EXPO_RECEIPT_DELAY_MS, config.checkReceiptsRef(), {
@@ -0,0 +1,42 @@
1
+ import type { JsonInput } from "../mcp/json.js";
2
+ /** One line on a homepage card. */
3
+ export type HomepageCardDetail = {
4
+ title: string;
5
+ value: string;
6
+ subValue: string;
7
+ };
8
+ /** A card a product shows on a hub app's homepage. */
9
+ export type HomepageCard = {
10
+ id: number;
11
+ type: string;
12
+ category: string;
13
+ details: HomepageCardDetail[];
14
+ };
15
+ /** The part of a Convex action ctx these routes use. */
16
+ export type HomepageRoutesCtx = {
17
+ auth: {
18
+ getUserIdentity(): Promise<object | null>;
19
+ };
20
+ };
21
+ type Method = "GET" | "POST" | "OPTIONS";
22
+ export type HomepageRoutesConfig<Ctx extends HomepageRoutesCtx, Handler> = {
23
+ httpAction: (fn: (ctx: Ctx, request: Request) => Promise<Response>) => Handler;
24
+ basePath: string;
25
+ allowedOrigins: readonly string[];
26
+ homepage: (ctx: Ctx) => Promise<HomepageCard[]>;
27
+ query: (ctx: Ctx, query: string) => Promise<JsonInput[] | null>;
28
+ homepageCors?: boolean;
29
+ };
30
+ /**
31
+ * Register the routes a hub app calls on a product backend:
32
+ * `GET <basePath>/homepage` (cards) and `POST <basePath>/query` (search),
33
+ * with origin-allowlist CORS.
34
+ */
35
+ export declare function registerHomepageRoutes<Ctx extends HomepageRoutesCtx, Handler>(http: {
36
+ route(spec: {
37
+ path: string;
38
+ method: Method;
39
+ handler: Handler;
40
+ }): void;
41
+ }, config: HomepageRoutesConfig<Ctx, Handler>): void;
42
+ export {};
@@ -0,0 +1,46 @@
1
+ import { jsonResponse } from "./jsonResponse.js";
2
+ import { createOriginAllowlistCors } from "./originAllowlistCors.js";
3
+ /**
4
+ * Register the routes a hub app calls on a product backend:
5
+ * `GET <basePath>/homepage` (cards) and `POST <basePath>/query` (search),
6
+ * with origin-allowlist CORS.
7
+ */
8
+ export function registerHomepageRoutes(http, config) {
9
+ const cors = createOriginAllowlistCors(config.allowedOrigins);
10
+ const homepageCors = config.homepageCors ?? true;
11
+ const homepagePath = `${config.basePath}/homepage`;
12
+ const queryPath = `${config.basePath}/query`;
13
+ const originOf = (request) => request.headers.get("origin") ?? "";
14
+ const preflight = () => config.httpAction(async (_ctx, request) => new Response(null, { status: 200, headers: cors.preflightHeaders(originOf(request)) }));
15
+ if (homepageCors)
16
+ http.route({ path: homepagePath, method: "OPTIONS", handler: preflight() });
17
+ http.route({
18
+ path: homepagePath,
19
+ method: "GET",
20
+ handler: config.httpAction(async (ctx, request) => {
21
+ const headers = homepageCors ? cors.headers(originOf(request)) : undefined;
22
+ if (!(await ctx.auth.getUserIdentity())) {
23
+ return jsonResponse({ error: "Authentication required" }, 401, headers);
24
+ }
25
+ return jsonResponse(await config.homepage(ctx), 200, headers);
26
+ }),
27
+ });
28
+ http.route({ path: queryPath, method: "OPTIONS", handler: preflight() });
29
+ http.route({
30
+ path: queryPath,
31
+ method: "POST",
32
+ handler: config.httpAction(async (ctx, request) => {
33
+ const headers = cors.headers(originOf(request));
34
+ const body = await request.json();
35
+ const query = typeof body.query === "string" ? body.query : "";
36
+ if (!query)
37
+ return jsonResponse({ error: "No query provided" }, 400, headers);
38
+ if (!(await ctx.auth.getUserIdentity()))
39
+ return jsonResponse({ error: "Unauthorized" }, 401, headers);
40
+ const results = await config.query(ctx, query);
41
+ if (results === null)
42
+ return jsonResponse({ error: "Unauthorized" }, 401, headers);
43
+ return jsonResponse({ results }, 200, headers);
44
+ }),
45
+ });
46
+ }
@@ -25,3 +25,5 @@ export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, t
25
25
  export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, type AuthenticateClerkBearerOptions, type ClerkOAuthJwtRejection, type VerifiedClerkOAuthJwt, type VerifyClerkOAuthJwtOptions, } from "./verifyClerkOAuthJwt.js";
26
26
  export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, type HasVProInput, } from "./vPlan.js";
27
27
  export { createVProModule, type UserHasVProOptions, type VProCreateUser, type VProCreateUserCtx, type VProModuleConfig, type VProPlanSlugsFieldOf, type VProWriterCtx, } from "./vProModule.js";
28
+ export { registerHomepageRoutes, type HomepageCard, type HomepageCardDetail, type HomepageRoutesConfig, type HomepageRoutesCtx, } from "./homepageRoutes.js";
29
+ export { productUpdateEmail, waitlistWelcomeEmail, type ProductEmail, type ProductEmailBrand } from "./productEmails.js";
@@ -25,3 +25,5 @@ export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerk
25
25
  export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
26
26
  export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_CLERK_PLAN_ID, V_PRO_CLERK_PLAN_ID_STAGING, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, vProClerkPlanId, } from "./vPlan.js";
27
27
  export { createVProModule, } from "./vProModule.js";
28
+ export { registerHomepageRoutes, } from "./homepageRoutes.js";
29
+ export { productUpdateEmail, waitlistWelcomeEmail } from "./productEmails.js";
@@ -1,9 +1,7 @@
1
1
  /** An icon in MCP `serverInfo.icons` (MCP 2025-11-25 `Implementation.icons`). */
2
2
  export type McpServerIcon = {
3
- /** Icon URL, for example an absolute https URL to the app's public icon. */
4
3
  src: string;
5
4
  mimeType?: string;
6
- /** For example `["48x48"]` or `["any"]`. */
7
5
  sizes?: string[];
8
6
  theme?: "light" | "dark";
9
7
  };
@@ -1,14 +1,3 @@
1
- /**
2
- * A cache of verified MCP bearer tokens, so most requests skip the verify
3
- * step (for Clerk: a network call, often from a cold Node action). Rows hold
4
- * the SHA-256 of the token, never the token. Only successful verifications
5
- * are cached; a revoked token keeps working until its row expires (at most
6
- * `MCP_TOKEN_CACHE_TTL_MS`).
7
- *
8
- * The package cannot own a Convex table and never imports `convex` at
9
- * runtime, so the app defines the table in its own schema and passes in `v`
10
- * and its function builders.
11
- */
12
1
  import type { defineTable as convexDefineTable, FunctionReference, IndexRange, RegisteredMutation, RegisteredQuery } from "convex/server";
13
2
  import type { v as convexV, GenericId, Validator } from "convex/values";
14
3
  export declare const MCP_TOKEN_CACHE_TTL_MS: number;
@@ -70,13 +59,9 @@ export declare function mcpTokenCacheTable(defineTable: typeof convexDefineTable
70
59
  }, {}, {}>;
71
60
  export type AuthenticateWithTokenCacheOptions<Principal extends McpTokenCachePrincipal> = {
72
61
  token: string;
73
- /** For example `(tokenHash) => ctx.runQuery(internal.mcp.tokenCache.getInternal, { tokenHash })`. */
74
62
  get: (tokenHash: string) => Promise<McpTokenCacheEntry | null>;
75
- /** For example `(row) => ctx.runMutation(internal.mcp.tokenCache.putInternal, row)`. */
76
63
  put: (row: McpTokenCacheRow) => Promise<unknown>;
77
- /** The real verification, run on a miss. */
78
64
  verify: (token: string) => Promise<Principal | null>;
79
- /** Clock in ms. Default `Date.now`. */
80
65
  now?: () => number;
81
66
  };
82
67
  /**
@@ -165,9 +150,7 @@ export type McpTokenCacheFunctionsConfig<Table extends string, Id = GenericId<Ta
165
150
  v: ConvexV;
166
151
  internalQuery: McpTokenCacheQueryBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
167
152
  internalMutation: McpTokenCacheMutationBuilder<NoInfer<Table>, NoInfer<Id>, NoInfer<Range>>;
168
- /** The cache table. Default `"mcpTokenCache"`. */
169
153
  tableName?: Table;
170
- /** This module's `purgeExpired`: `(): McpTokenCachePurgeRef => internal.mcp.tokenCache.purgeExpired`. */
171
154
  purgeSelf: () => McpTokenCachePurgeRef;
172
155
  };
173
156
  /**
@@ -114,14 +114,12 @@ function logAuth(cached, authMs) {
114
114
  export function createMcpTokenCacheFunctions(config) {
115
115
  return buildMcpTokenCacheFunctions(config);
116
116
  }
117
- // Typed for any table name, so the default name needs no cast; `Table` only checks the app's builders.
118
117
  function buildMcpTokenCacheFunctions(config) {
119
118
  const { v, internalQuery, internalMutation, purgeSelf } = config;
120
119
  const table = config.tableName ?? MCP_TOKEN_CACHE_TABLE;
121
120
  const getInternal = internalQuery({
122
121
  args: { tokenHash: v.string() },
123
122
  returns: v.union(v.object({ clerkUserId: v.string(), expiresAt: v.number() }), v.null()),
124
- // expiry is checked by the caller, so this query stays cacheable
125
123
  handler: async (ctx, { tokenHash }) => {
126
124
  const row = await ctx.db
127
125
  .query(table)
@@ -33,11 +33,6 @@ export function createMemoryOptimisticStore() {
33
33
  },
34
34
  };
35
35
  }
36
- // `getFunctionName` from `convex/server` (as of 1.47), copied so this package
37
- // never imports `convex` at runtime: the root is also loaded where `convex` is
38
- // not installed. For the references Convex creates (`api`/`internal` refs,
39
- // name strings, function handles, component refs) it returns the same name or
40
- // throws the same message; tests compare it with Convex's.
41
36
  const functionName = Symbol.for("functionName");
42
37
  const toReferencePath = Symbol.for("toReferencePath");
43
38
  function getFunctionName(reference) {
@@ -47,7 +42,6 @@ function getFunctionName(reference) {
47
42
  }
48
43
  return reference;
49
44
  }
50
- // Read, not `in`: `api` references are proxies that answer property reads only.
51
45
  const symbols = reference;
52
46
  const name = symbols[functionName];
53
47
  if (name)
@@ -1,13 +1,5 @@
1
1
  export type OriginAllowlistCors = {
2
- /**
3
- * Headers for a normal response. `Access-Control-Allow-Origin` is the
4
- * origin when allowed and `""` otherwise.
5
- */
6
2
  headers(origin: string): Record<string, string>;
7
- /**
8
- * Headers for an `OPTIONS` preflight: adds `Access-Control-Max-Age: 86400`
9
- * and omits `Access-Control-Allow-Origin` unless the origin is allowed.
10
- */
11
3
  preflightHeaders(origin: string): Record<string, string>;
12
4
  };
13
5
  /**
@@ -0,0 +1,22 @@
1
+ /** How a product signs its emails. */
2
+ export type ProductEmailBrand = {
3
+ name: string;
4
+ from: string;
5
+ signOff: string;
6
+ footerHtml: string;
7
+ };
8
+ /** A ready-to-send email, in the shape Resend's `emails.send` takes. */
9
+ export type ProductEmail = {
10
+ from: string;
11
+ to: string;
12
+ subject: string;
13
+ text: string;
14
+ html: string;
15
+ };
16
+ /** The email sent when someone joins a product's waitlist. */
17
+ export declare function waitlistWelcomeEmail(brand: ProductEmailBrand, to: string): ProductEmail;
18
+ /**
19
+ * An admin-written update. Each line of `message` becomes a paragraph; the
20
+ * message is HTML and is not escaped, so only admins may supply it.
21
+ */
22
+ export declare function productUpdateEmail(brand: ProductEmailBrand, to: string, message: string): ProductEmail;
@@ -0,0 +1,37 @@
1
+ const wrap = (body) => `<div style="font-family: sans-serif; max-width: 600px; margin: 0 auto;">${body}</div>`;
2
+ /** The email sent when someone joins a product's waitlist. */
3
+ export function waitlistWelcomeEmail(brand, to) {
4
+ return {
5
+ from: brand.from,
6
+ to,
7
+ subject: `Welcome to ${brand.name}! 🎉`,
8
+ text: `Congratulations! You're now on the ${brand.name} waitlist!
9
+
10
+ We'll notify you as soon as we launch. Thank you for your interest!
11
+
12
+ Best regards,
13
+ ${brand.signOff}`,
14
+ html: wrap(`<h2 style="color: #1a1a1a;">Congratulations! 🎉</h2>` +
15
+ `<p>You're now on the ${brand.name} waitlist.</p>` +
16
+ `<p>We'll notify you as soon as we launch. Thank you for your interest!</p>` +
17
+ `<br/><p>Best regards,<br/>${brand.signOff}</p>` +
18
+ brand.footerHtml),
19
+ };
20
+ }
21
+ /**
22
+ * An admin-written update. Each line of `message` becomes a paragraph; the
23
+ * message is HTML and is not escaped, so only admins may supply it.
24
+ */
25
+ export function productUpdateEmail(brand, to, message) {
26
+ const paragraphs = message
27
+ .split("\n")
28
+ .map((line) => `<p>${line}</p>`)
29
+ .join("");
30
+ return {
31
+ from: brand.from,
32
+ to,
33
+ subject: `Update from ${brand.name}`,
34
+ text: message,
35
+ html: wrap(`<p>Dear user,</p><br/>${paragraphs}<br/><p>Best regards,<br/>${brand.signOff}</p>` + brand.footerHtml),
36
+ };
37
+ }
@@ -12,8 +12,6 @@ export function tempId(table, options = {}) {
12
12
  }
13
13
  return value;
14
14
  }
15
- // GenericId is a branded string with no constructor; this guard is the one
16
- // place a placeholder string is accepted as one.
17
15
  function isPlaceholderId(value) {
18
16
  return value.length > 0;
19
17
  }
@@ -17,13 +17,9 @@ export declare const V_PRO_PLAN_KEYS: readonly string[];
17
17
  export declare function hasVPlan(claimsOrIdentity: unknown): boolean;
18
18
  /** What `hasVPro` reads. Every field is optional. */
19
19
  export type HasVProInput = {
20
- /** A Convex `ctx.auth.getUserIdentity()` result or raw JWT claims, read by `hasVPlan`. */
21
20
  identity?: unknown;
22
- /** Plan slugs stored on the user row, for example from the Clerk Billing webhook. */
23
21
  planSlugs?: readonly string[] | null;
24
- /** Clerk user ids that get V Pro without a paid plan. See `parseVProCompUserIds`. */
25
22
  compIds?: readonly string[] | null;
26
- /** The Clerk user id to match against `compIds`. Default: `identity.subject`. */
27
23
  clerkId?: string | null;
28
24
  };
29
25
  /**
@@ -1,10 +1,5 @@
1
1
  import { type ClerkBillingChange, type ClerkWebhookEventLike } from "./clerkBilling.js";
2
2
  import { type ClerkUserDataModelLike, type ClerkUserDbReader, type ClerkUserInsert } from "./clerkUserAuth.js";
3
- /**
4
- * V Pro helpers bound to one users table and its field names, so an app keeps
5
- * its stored field (`planSlugs`, `billingPlanSlugs`, ...) with no data
6
- * migration. Typed structurally like `createClerkUserAuth`: no `convex` import.
7
- */
8
3
  /** Document fields that can hold a `string[]` (optional ones too). */
9
4
  export type VProPlanSlugsFieldOf<Doc> = {
10
5
  [K in keyof Doc & string]-?: string[] extends Doc[K] ? K : never;
@@ -31,13 +26,10 @@ export type VProCreateUser<Table extends string, Doc extends {
31
26
  export type VProMissingUserConfig<Table extends string, Doc extends {
32
27
  _id: string;
33
28
  }> = {
34
- /** Default `"noop"`: no write, `writeBillingChange` returns `false`. */
35
29
  onMissingUser?: "noop";
36
30
  createUser?: undefined;
37
31
  } | {
38
- /** `"create"` (implied by `createUser`): call `createUser`, then return `true`. */
39
32
  onMissingUser?: "create";
40
- /** Inserts the missing row with the given slugs. Required for `"create"`. */
41
33
  createUser: VProCreateUser<Table, Doc>;
42
34
  };
43
35
  export type VProModuleConfig<Table extends string, Index extends string, ClerkIdField extends string, PlanSlugsField extends string, Doc extends {
@@ -45,29 +37,13 @@ export type VProModuleConfig<Table extends string, Index extends string, ClerkId
45
37
  } = {
46
38
  _id: string;
47
39
  }> = VProMissingUserConfig<Table, Doc> & {
48
- /** The users table, for example `"users"`. */
49
40
  table: Table;
50
- /** The index on the Clerk id field, for example `"by_clerk_id"`. */
51
41
  index: Index;
52
- /** The indexed field that holds the Clerk user id, for example `"clerkId"`. */
53
42
  clerkIdField: ClerkIdField;
54
- /** The `string[]` field that stores granting plan slugs, for example `"planSlugs"`. */
55
43
  planSlugsField: PlanSlugsField;
56
- /** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
57
44
  lookup?: "first" | "unique";
58
- /**
59
- * Item statuses that grant their plan, for `nextPlanSlugs`,
60
- * `writeBillingChange` and `parseBillingEvent`. Default
61
- * `GRANTING_ITEM_STATUSES` (`active`, `past_due`, `canceled`).
62
- */
63
45
  grantingStatuses?: readonly string[];
64
- /** Event type matching for `parseBillingEvent`. Default `"exact"`. See `ClerkBillingOptions`. */
65
46
  eventMatch?: "exact" | "prefix";
66
- /**
67
- * Extra fields for the `writeBillingChange` patch of an existing row, for
68
- * example `{ billingPlansUpdatedAt: Date.now() }`. The slugs field always
69
- * wins. Not used by `planSlugsPatch` or `createUser`.
70
- */
71
47
  extraPatch?: (planSlugs: string[]) => Partial<ClerkUserInsert<Doc>>;
72
48
  };
73
49
  /** `ctx.db` for `writeBillingChange`: one index lookup and a patch. A Convex `MutationCtx` fits. */
@@ -76,14 +52,11 @@ export type VProWriterCtx<Table extends string, Index extends string, ClerkIdFie
76
52
  }, Range> = {
77
53
  db: ClerkUserDbReader<Table, Index, ClerkIdField, Doc, Range> & {
78
54
  patch(id: Doc["_id"], value: Partial<ClerkUserInsert<Doc>>): Promise<void>;
79
- /** Needed only with `createUser`; a `MutationCtx` has it. */
80
55
  insert?(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
81
56
  };
82
57
  };
83
58
  export type UserHasVProOptions = {
84
- /** The caller's identity, for the session `pla` claim. */
85
59
  identity?: unknown;
86
- /** Clerk user ids that get V Pro without a paid plan. */
87
60
  compIds?: readonly string[] | null;
88
61
  };
89
62
  /**
@@ -30,25 +30,20 @@ export function createVProModule() {
30
30
  field: config.clerkIdField,
31
31
  lookup: config.lookup,
32
32
  });
33
- /** The stored slugs; `[]` for no user, a missing field or a non-array value. */
34
33
  function planSlugsOf(user) {
35
34
  const value = user?.[config.planSlugsField];
36
35
  return Array.isArray(value) ? value.filter((slug) => typeof slug === "string") : [];
37
36
  }
38
- /** The slugs to store after `change`. */
39
37
  function nextPlanSlugs(user, change) {
40
38
  return applyBillingChange(planSlugsOf(user), change, billingOptions);
41
39
  }
42
- /** `parseClerkBillingEvent` with this module's `grantingStatuses` and `eventMatch`. */
43
40
  function parseBillingEvent(event) {
44
41
  return parseClerkBillingEvent(event, billingOptions);
45
42
  }
46
- /** `{ [planSlugsField]: planSlugs }`, for `ctx.db.patch`. */
47
43
  function planSlugsPatch(planSlugs) {
48
44
  const patch = { [config.planSlugsField]: [...planSlugs] };
49
45
  return patch;
50
46
  }
51
- /** `hasVPro` over the row's stored slugs and Clerk id, plus the given identity and comp ids. */
52
47
  function userHasVPro(user, options = {}) {
53
48
  const clerkId = user?.[config.clerkIdField];
54
49
  return hasVPro({
@@ -58,12 +53,6 @@ export function createVProModule() {
58
53
  clerkId: typeof clerkId === "string" ? clerkId : undefined,
59
54
  });
60
55
  }
61
- /**
62
- * The webhook writer's body: find the row by `change.clerkId` and patch
63
- * the new slugs (plus `extraPatch`). With no row: returns `false` with no
64
- * write (the next event or a backfill fills it in), or, with
65
- * `createUser`, calls it with the slugs and returns `true`.
66
- */
67
56
  async function writeBillingChange(ctx, change) {
68
57
  const user = await userAuth.getUserByClerkId(ctx, change.clerkId);
69
58
  if (!user) {