@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.20.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#155](https://github.com/vvedantb/v/pull/155) [`9b6a022`](https://github.com/vvedantb/v/commit/9b6a0223e7bf71d43bcf2d0eb4da25cb344098ee) Thanks [@vvedantb](https://github.com/vvedantb)! - Adds skill install helpers to the root export: `parseSkillRef` reads skills.sh and GitHub links, `discoverSkillFolders` and `skillFolderFiles` find a skill and its helper files in a repository tree, `parseSkillFrontmatter` reads the name and description, and `hashSkillText` returns the SHA-256 of normalised `SKILL.md` text.
8
+
9
+ ## 0.20.0
10
+
11
+ ### Minor Changes
12
+
13
+ - [#142](https://github.com/vvedantb/v/pull/142) [`94726a6`](https://github.com/vvedantb/v/commit/94726a6e58615dd0b4bc3601192ed61a22a65c4b) Thanks [@vvedantb](https://github.com/vvedantb)! - `createMcpHttpHandler` accepts `requireUpstreamSecret`. When it is `true` and `MCP_UPSTREAM_SECRET` is set, the handler returns 401 to any request without a matching `X-Mcp-Upstream` header, before the bearer check. The header name is exported as `UPSTREAM_SECRET_HEADER`. `registerMcpRoutes` now treats `authorizationServerMetadata` and `protectedResourceMetadata` as optional.
14
+
15
+ ## 0.19.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#118](https://github.com/vvedantb/v/pull/118) [`635d094`](https://github.com/vvedantb/v/commit/635d09467c7ea1480e159a64be2fa989d4710cd3) Thanks [@vvedantb](https://github.com/vvedantb)! - Add shared product backend helpers: `createZodJsonSchemaConverter` (zod 4 to zod-to-json-schema-shaped JSON Schema for MCP `tools/list`), `registerHomepageRoutes` (homepage card and query routes with origin-allowlist CORS), and `waitlistWelcomeEmail` / `productUpdateEmail` (branded Resend email content).
20
+
3
21
  ## 0.18.0
4
22
 
5
23
  ### Minor Changes
@@ -15,10 +15,8 @@
15
15
  export type GatewayErrorKind = "invalid_request" | "auth" | "model_not_found" | "rate_limit" | "quota" | "gateway" | "malformed_response" | "timeout" | "other";
16
16
  export type GatewayFailure = {
17
17
  kind: GatewayErrorKind;
18
- /** The error's own message, without ANSI colour codes. Never the request body; the SDK does not put the key in it. */
19
18
  message: string;
20
19
  retryable: boolean;
21
- /** HTTP status, set for every Gateway error (the SDK defaults it to 500 when the response had none). */
22
20
  statusCode?: number;
23
21
  };
24
22
  /** `error.message` for an `Error`, the string itself for a string, else `"Unknown error"`. */
package/dist/ai/errors.js CHANGED
@@ -8,14 +8,6 @@ export function errorMessageOf(error) {
8
8
  return error;
9
9
  return "Unknown error";
10
10
  }
11
- /**
12
- * The Gateway has no quota error type: an out-of-credits or spend-limit reply arrives as a rate-limit or
13
- * generic Gateway error, so the status (402) or the message is all there is to go on.
14
- *
15
- * Billing words (credits, funds, billing, payment, spend limit, budget) mean quota on any Gateway error. The bare
16
- * word "quota" is ambiguous on a rate-limit error ("requests per minute quota"), so there it stays `rate_limit`;
17
- * on any other Gateway error (for example a 403) it means quota.
18
- */
19
11
  const BILLING_MESSAGE = /\b(?:insufficient[ _-]?(?:funds|credits?|balance)|out of credits?|credits? (?:exhausted|limit|balance)|billing|payment required|spend(?:ing)? limit|budget (?:exceeded|limit))\b/i;
20
12
  const QUOTA_MESSAGE = /\bquota\b/i;
21
13
  function isQuotaError(error, message) {
@@ -23,19 +15,12 @@ function isQuotaError(error, message) {
23
15
  return true;
24
16
  return !GatewayRateLimitError.isInstance(error) && QUOTA_MESSAGE.test(message);
25
17
  }
26
- /**
27
- * `generateText`, `streamText` and the other `ai` calls replace a `GatewayAuthenticationError` before it reaches
28
- * the caller (`wrapGatewayError` in `ai` 5 to 7): outside production with a plain `Error` named
29
- * `GatewayAuthenticationError`, and in production (`NODE_ENV=production`) with an `AISDKError` named
30
- * `GatewayError` whose message starts "Unauthenticated". Neither has the Gateway markers, so match them by name.
31
- */
32
18
  function isWrappedAuthError(error) {
33
19
  if (!(error instanceof Error))
34
20
  return false;
35
21
  return (error.name === "GatewayAuthenticationError" ||
36
22
  (error.name === "GatewayError" && !GatewayError.isInstance(error) && /^Unauthenticated\b/.test(error.message)));
37
23
  }
38
- // ANSI colour codes, which the non-production wrapped auth error puts in its message.
39
24
  const ANSI = /\u001b\[[0-9;]*m/g;
40
25
  /**
41
26
  * Maps an AI SDK / AI Gateway failure to a `GatewayFailure`. A `RetryError` is unwrapped to its `lastError`.
@@ -68,7 +53,6 @@ export function classifyGatewayError(error) {
68
53
  return { kind: "rate_limit", message, retryable: true, ...statusCode };
69
54
  }
70
55
  if (GatewayError.isInstance(error)) {
71
- // GatewayTimeoutError is not exported by @ai-sdk/gateway, so match it by name.
72
56
  if (error.name === "GatewayTimeoutError") {
73
57
  return { kind: "timeout", message, retryable: true, ...statusCode };
74
58
  }
@@ -1,7 +1,3 @@
1
- /**
2
- * AI Gateway service tier provider options. Pure data: no AI SDK import, so
3
- * these run anywhere (Convex default runtime, Node, browsers).
4
- */
5
1
  /** A JSON value the AI SDK accepts in `providerOptions` (mirrors `JSONValue` from `@ai-sdk/provider`). */
6
2
  export type GatewayJsonValue = null | string | number | boolean | Readonly<GatewayJsonObject> | readonly GatewayJsonValue[];
7
3
  /** A JSON object the AI SDK accepts in `providerOptions` (mirrors `JSONObject` from `@ai-sdk/provider`). */
@@ -1,7 +1,3 @@
1
- /**
2
- * AI Gateway service tier provider options. Pure data: no AI SDK import, so
3
- * these run anywhere (Convex default runtime, Node, browsers).
4
- */
5
1
  /**
6
2
  * Provider options for a service tier: `{}` for `"default"`, else `{ gateway: { serviceTier: tier } }`.
7
3
  * Returns a new object on every call.
@@ -3,9 +3,7 @@ import type { ArtifactFormat } from "./schemas.js";
3
3
  import type { ArtifactStateMap } from "./stateOps.js";
4
4
  import { type ArtifactTemplateName } from "./templates.js";
5
5
  export type WrapArtifactDocumentOptions = ArtifactGuestOptions & {
6
- /** Heading for a built-in template when the body has no title. Default "Artifact". */
7
6
  title?: string;
8
- /** From `stateSpec.template`. Tried first for any format; `json` bodies without one try both templates. */
9
7
  template?: ArtifactTemplateName;
10
8
  };
11
9
  /** The body format for a fenced code block's language: html, svg and markdown render; anything else is code. */
@@ -17,7 +17,6 @@ function escapeText(value) {
17
17
  function plainTextDocument(body) {
18
18
  return `<!doctype html><html><head><meta charset="utf-8"/><style>body{font-family:system-ui,sans-serif;margin:16px;white-space:pre-wrap}</style></head><body><pre>${escapeText(body)}</pre></body></html>`;
19
19
  }
20
- /** A full HTML document for `body` before the guest is injected. Markdown and code show as escaped text. */
21
20
  function previewDocument(body, format, options) {
22
21
  if (options.template !== undefined || format === "json") {
23
22
  const templated = htmlFromArtifactTemplate({
@@ -26,11 +26,6 @@ export declare const ARTIFACT_ALIASES_GLOBAL = "__ARTIFACT_ALIASES__";
26
26
  */
27
27
  export declare const GUEST_BOOTSTRAP_SCRIPT: string;
28
28
  export type ArtifactGuestOptions = {
29
- /**
30
- * Extra globals for the state API: `["app"]` makes `window.app.state` the
31
- * same object as `window.artifactState`. Each must be a JavaScript
32
- * identifier and must not name a built-in global (`window`, `document`, …).
33
- */
34
29
  stateGlobalAliases?: readonly string[];
35
30
  };
36
31
  /** Throws on an alias that is not an identifier or would replace a global the page or the bootstrap needs. */
@@ -43,7 +43,6 @@ export type ArtifactListRow = {
43
43
  schemaVersion: number;
44
44
  stateSpec?: ArtifactStateSpec;
45
45
  currentVersion: number;
46
- /** Body size in bytes. */
47
46
  size: number;
48
47
  origin: ArtifactOrigin;
49
48
  createdAt: number;
@@ -69,11 +68,6 @@ export type ArtifactSchemas = {
69
68
  flashcardsBodyV1: z.ZodType<FlashcardsBodyV1>;
70
69
  listRow: z.ZodType<ArtifactListRow>;
71
70
  detailRow: z.ZodType<ArtifactDetailRow>;
72
- /**
73
- * Checks a body before it is saved: at most `ARTIFACT_BODY_MAX_CHARS`, and
74
- * for `json` a known type and schema version (default 1) whose parsed body
75
- * matches the typed schema. Returns the parsed JSON body when there is one.
76
- */
77
71
  validateArtifactBody(type: ArtifactType, format: ArtifactFormat, body: string, schemaVersion?: number): ArtifactBodyValidation;
78
72
  };
79
73
  /** The artifact schemas, built with the app's `z`. */
@@ -1,5 +1,3 @@
1
- // The guest's localStorage and sessionStorage shims keep their keys in the
2
- // artifact state under these prefixes, beside the `artifactState` keys.
3
1
  export const ARTIFACT_LOCAL_STORAGE_PREFIX = "ls:";
4
2
  export const ARTIFACT_SESSION_STORAGE_PREFIX = "ss:";
5
3
  export function prefixedStorageKey(prefix, key) {
@@ -1,41 +1,3 @@
1
- /**
2
- * Authenticated Convex function builders, built on convex-helpers
3
- * `customFunctions`. Each app wires its own generated `query`/`mutation`/
4
- * `action` builders and its user-lookup into one place, and gets back
5
- * `authQuery`/`authMutation`/`authAction` whose handlers receive `ctx.userId`
6
- * and which reject an unauthenticated caller before the handler runs.
7
- *
8
- * convex-helpers is an optional peer: this module imports only its *types*
9
- * (`import type`, erased at build), and the app passes the runtime functions
10
- * (`customQuery`, `customMutation`, `customAction`, `customCtx`) in. So, like
11
- * the rest of this package, importing `@vvedantb/server` never forces a
12
- * consumer to install convex or convex-helpers.
13
- *
14
- * Internal variants: call `createAuthFunctions` a second time with the
15
- * `internalQuery`/`internalMutation`/`internalAction` builders (and no
16
- * `beforeEach`), then rename the result:
17
- *
18
- * ```ts
19
- * export const { authQuery, authMutation, authAction } = createAuthFunctions({
20
- * customFunctions: { customQuery, customMutation, customAction, customCtx },
21
- * query, mutation, action,
22
- * resolveUserId: (ctx) => userAuth.requireCurrentUserId(ctx),
23
- * resolveActionUserId: (ctx) => resolveActionUserId(ctx),
24
- * beforeEach: () => assertNotInMaintenance(), // optional
25
- * });
26
- *
27
- * export const {
28
- * authQuery: internalAuthQuery,
29
- * authMutation: internalAuthMutation,
30
- * authAction: internalAuthAction,
31
- * } = createAuthFunctions({
32
- * customFunctions: { customQuery, customMutation, customAction, customCtx },
33
- * query: internalQuery, mutation: internalMutation, action: internalAction,
34
- * resolveUserId: (ctx) => userAuth.requireCurrentUserId(ctx),
35
- * resolveActionUserId: (ctx) => resolveActionUserId(ctx),
36
- * });
37
- * ```
38
- */
39
1
  import type { ActionBuilder, FunctionVisibility, GenericActionCtx, GenericDataModel, GenericMutationCtx, GenericQueryCtx, MutationBuilder, QueryBuilder } from "convex/server";
40
2
  import type { customAction, customCtx, customMutation, customQuery } from "convex-helpers/server/customFunctions";
41
3
  /** The four convex-helpers runtime functions the app injects. */
@@ -48,31 +10,12 @@ export type AuthCustomFunctions = {
48
10
  /** A query or mutation context — either one can resolve the current user. */
49
11
  export type AuthReadCtx<DataModel extends GenericDataModel> = GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>;
50
12
  export type CreateAuthFunctionsConfig<DataModel extends GenericDataModel, UserId, Visibility extends FunctionVisibility = "public"> = {
51
- /** The convex-helpers builders, imported and passed by the app. */
52
13
  customFunctions: AuthCustomFunctions;
53
- /** The app's generated query builder (public or internal). */
54
14
  query: QueryBuilder<DataModel, Visibility>;
55
- /** The app's generated mutation builder (public or internal). */
56
15
  mutation: MutationBuilder<DataModel, Visibility>;
57
- /** The app's generated action builder (public or internal). */
58
16
  action: ActionBuilder<DataModel, Visibility>;
59
- /**
60
- * Resolve the current user's id in a query or mutation. Throw to reject an
61
- * unauthenticated caller (for example `userAuth.requireCurrentUserId`, which
62
- * throws `"Not authenticated"`).
63
- */
64
17
  resolveUserId: (ctx: AuthReadCtx<DataModel>) => Promise<UserId>;
65
- /**
66
- * Resolve the current user's id in an action. An action has no `ctx.auth`
67
- * database access, so this usually runs a query (`ctx.runQuery(api.auth.me)`)
68
- * and throws when it returns null.
69
- */
70
18
  resolveActionUserId: (ctx: GenericActionCtx<DataModel>) => Promise<UserId>;
71
- /**
72
- * An optional gate that runs before the user is resolved, on every call.
73
- * Throw to block the call (for example a maintenance-mode check). Omit it for
74
- * internal builders that should run during maintenance.
75
- */
76
19
  beforeEach?: (ctx: AuthReadCtx<DataModel> | GenericActionCtx<DataModel>) => void | Promise<void>;
77
20
  };
78
21
  /**
@@ -1,8 +1,3 @@
1
- /**
2
- * Pure Clerk Billing helpers: which subscription items grant their plan, and
3
- * how a verified webhook event changes a user's stored plan slugs. No Convex
4
- * or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
5
- */
6
1
  /**
7
2
  * Clerk Billing item statuses that grant the item's plan. `canceled` means
8
3
  * cancel at period end, so it still grants until `ended`. Every other status
@@ -19,14 +14,7 @@ export declare const GRANTING_STATUSES_ACTIVE_ONLY: readonly string[];
19
14
  * parsing an event and when applying the change it gives.
20
15
  */
21
16
  export type ClerkBillingOptions = {
22
- /** Item statuses that grant the item's plan. Default `GRANTING_ITEM_STATUSES`. */
23
17
  readonly grantingStatuses?: readonly string[];
24
- /**
25
- * How `parseClerkBillingEvent` matches event types. `"exact"` (default)
26
- * handles the listed `subscription.*` and `subscriptionItem.*` types only.
27
- * `"prefix"` handles any type that starts with `subscription.` or
28
- * `subscriptionItem.`. Read only by `parseClerkBillingEvent`.
29
- */
30
18
  readonly eventMatch?: "exact" | "prefix";
31
19
  };
32
20
  /**
@@ -47,15 +35,11 @@ export type ClerkWebhookEventLike = {
47
35
  readonly data?: unknown;
48
36
  };
49
37
  /** How one billing event changes a user's stored plan slugs. */
50
- export type ClerkBillingChange =
51
- /** From a `subscription.*` event, which lists every item: overwrite the stored set. */
52
- {
38
+ export type ClerkBillingChange = {
53
39
  kind: "replace";
54
40
  clerkId: string;
55
41
  planSlugs: string[];
56
- }
57
- /** From a `subscriptionItem.*` event, which holds one item: merge it into the stored set. */
58
- | {
42
+ } | {
59
43
  kind: "item";
60
44
  clerkId: string;
61
45
  status: string;
@@ -1,8 +1,3 @@
1
- /**
2
- * Pure Clerk Billing helpers: which subscription items grant their plan, and
3
- * how a verified webhook event changes a user's stored plan slugs. No Convex
4
- * or Clerk import; apps own the `httpAction` and `internalMutation` wrappers.
5
- */
6
1
  /**
7
2
  * Clerk Billing item statuses that grant the item's plan. `canceled` means
8
3
  * cancel at period end, so it still grants until `ended`. Every other status
@@ -13,14 +8,12 @@ export const GRANTING_ITEM_STATUSES = ["active", "past_due", "canceled"];
13
8
  export const GRANTING_STATUSES_ACTIVE_PAST_DUE = ["active", "past_due"];
14
9
  /** Only `active` grants. Pass as `grantingStatuses`. */
15
10
  export const GRANTING_STATUSES_ACTIVE_ONLY = ["active"];
16
- /** Subscription events whose `data.items` is the full item list. */
17
11
  const SUBSCRIPTION_EVENTS = new Set([
18
12
  "subscription.created",
19
13
  "subscription.updated",
20
14
  "subscription.active",
21
15
  "subscription.pastDue",
22
16
  ]);
23
- /** Subscription item events whose `data` is one item. */
24
17
  const SUBSCRIPTION_ITEM_EVENTS = new Set([
25
18
  "subscriptionItem.updated",
26
19
  "subscriptionItem.active",
@@ -102,7 +95,6 @@ export function parseClerkBillingEvent(event, options = {}) {
102
95
  }
103
96
  function eventKind(type, match) {
104
97
  if (match === "prefix") {
105
- // "subscriptionItem.x" does not start with "subscription.", so the order does not matter.
106
98
  if (type.startsWith("subscriptionItem."))
107
99
  return "item";
108
100
  if (type.startsWith("subscription."))
@@ -115,7 +107,6 @@ function eventKind(type, match) {
115
107
  return "item";
116
108
  return null;
117
109
  }
118
- /** `[item]` when `value` has a string `status`; the plan is kept only with a non-empty slug. */
119
110
  function toPlanItem(value) {
120
111
  if (!isRecord(value) || typeof value.status !== "string")
121
112
  return [];
@@ -1,15 +1,3 @@
1
- /**
2
- * Clerk Billing Convex functions for apps that keep plan slugs on their own
3
- * users table: an `applyBillingChange` mutation, a paged `listClerkIds` query
4
- * and a `setPlanSlugs` mutation, plus `runClerkBillingWebhook` for the
5
- * `POST /clerk/webhooks` route.
6
- *
7
- * Like `createExpoPushFunctions`, the package never imports `convex` at
8
- * runtime. The app passes in `v` and its own function builders, and its bound
9
- * `createVProModule` writer (`vPro.writeBillingChange`) does the write, so
10
- * the table, index, field names and granting statuses stay with the app.
11
- * Backfill actions need Node and live in `clerkBillingNodeFunctions.ts`.
12
- */
13
1
  import type { FunctionReference, PaginationOptions, RegisteredMutation, RegisteredQuery } from "convex/server";
14
2
  import type { v as convexV, Validator } from "convex/values";
15
3
  import type { ClerkBillingChange, ClerkWebhookEventLike } from "./clerkBilling.js";
@@ -102,30 +90,16 @@ type ListDef<Style extends ClerkBillingListStyle> = {
102
90
  };
103
91
  export type ClerkBillingFunctionsConfig<MutationCtx, Style extends ClerkBillingListStyle> = {
104
92
  v: ConvexV;
105
- /** The app's `internalMutation`, narrowed to the two calls made here. */
106
93
  internalMutation: ((def: ApplyDef<MutationCtx>) => RegisteredMutation<"internal", {
107
94
  change: ClerkBillingChange;
108
95
  }, Promise<boolean>>) & ((def: SetPlanSlugsDef<MutationCtx>) => RegisteredMutation<"internal", SetPlanSlugsArgs, Promise<boolean>>);
109
96
  internalQuery: (def: ListDef<Style>) => RegisteredQuery<"internal", ClerkBillingListArgs<Style>, Promise<ClerkBillingListResult<Style>>>;
110
- /**
111
- * The app's `vPro.writeBillingChange`. Annotate the ctx with your
112
- * `MutationCtx`: `(ctx: MutationCtx, change) => vPro.writeBillingChange(ctx, change)`.
113
- */
114
97
  writeBillingChange: (ctx: MutationCtx, change: ClerkBillingChange) => Promise<boolean>;
115
- /** Argument and return shape of `listClerkIds`. */
116
98
  listStyle: Style;
117
- /** The users table. Default `"users"`. */
118
99
  table?: string;
119
- /** The field that holds the Clerk user id, for example `"clerkId"` or `"clerkUserId"`. */
120
100
  clerkIdField: string;
121
- /**
122
- * Skip rows whose id is missing or empty. Default `true`. Pass `false` when
123
- * the field is required: a non-string value then throws.
124
- */
125
101
  skipFalsyClerkId?: boolean;
126
- /** Rows per page for `"cursor"` and `"cursorNull"`. Default 100. The other styles take the size from the caller. */
127
102
  pageSize?: number;
128
- /** `paginationOptsValidator` from `convex/server`. Required for the `"paginationOpts"` style. */
129
103
  paginationOptsValidator?: Req<PaginationOptions>;
130
104
  };
131
105
  /**
@@ -154,25 +128,16 @@ export declare function createClerkBillingFunctions<MutationCtx, Style extends C
154
128
  listClerkIds: RegisteredQuery<"internal", ClerkBillingListArgs<Style>, Promise<ClerkBillingListResult<Style>>>;
155
129
  };
156
130
  export type RunClerkBillingWebhookOptions<Event> = {
157
- /** `verifyWebhook` from `@clerk/backend/webhooks`. Injected so this package does not import it. */
158
131
  verifyWebhook: (request: Request, options: {
159
132
  signingSecret: string;
160
133
  }) => Promise<Event>;
161
- /** `vPro.parseBillingEvent`. Return `null` for events that change no plan. */
162
134
  parseBillingEvent: (event: Event) => ClerkBillingChange | null;
163
- /** Writes the change, for example `(change) => ctx.runMutation(internal.billing.applyBillingChange, { change })`. */
164
135
  applyChange: (change: ClerkBillingChange) => Promise<unknown>;
165
- /** Status for a missing signing secret. Default 400, so Clerk retries. */
166
136
  missingSecretStatus?: number;
167
- /** Status for a failed signature check. Default 400. */
168
137
  invalidStatus?: number;
169
- /** Body for a failed signature check. Default `"Invalid webhook"`. */
170
138
  invalidBody?: string;
171
- /** Body for a missing secret. Default: `invalidBody`. */
172
139
  missingSecretBody?: string;
173
- /** When set, a rejection is logged with `console.error(logPrefix, reason, error)`. */
174
140
  logPrefix?: string;
175
- /** Passed to `verifyClerkWebhook`: a test `env` or `signingSecret`. */
176
141
  verifyOptions?: VerifyClerkWebhookOptions;
177
142
  };
178
143
  /**
@@ -57,18 +57,11 @@ export function createClerkBillingFunctions(config) {
57
57
  }));
58
58
  return { applyBillingChange, setPlanSlugs, listClerkIds };
59
59
  }
60
- /** Validator for `ClerkBillingChange`. */
61
60
  function changeValidator(v) {
62
- // `v.union` of objects infers a type that is structurally `ClerkBillingChange`.
63
61
  return v.union(v.object({ kind: v.literal("replace"), clerkId: v.string(), planSlugs: v.array(v.string()) }), v.object({ kind: v.literal("item"), clerkId: v.string(), status: v.string(), slug: v.string() }));
64
62
  }
65
- /**
66
- * One definition per list style. The style decides the args, the page options
67
- * and the return shape, so the table below is the whole list of differences.
68
- */
69
63
  function listDef(style, io) {
70
64
  const { v, cursor, pageSize, read } = io;
71
- // Each entry is a thunk, so only the requested style is built.
72
65
  const defs = {
73
66
  cursor: () => ({
74
67
  args: { cursor },
@@ -103,7 +96,6 @@ function listDef(style, io) {
103
96
  },
104
97
  }),
105
98
  };
106
- // `defs[style]()` is `ListDef<Style>`, but TypeScript widens the index to the union.
107
99
  return defs[style]();
108
100
  }
109
101
  function requirePaginationOptsValidator(validator) {
@@ -1,10 +1,3 @@
1
- /**
2
- * Node side of the Clerk Billing wiring: the `backfillPlanSlugs` action and
3
- * the webhook action. They need `@clerk/backend` and Node APIs, so
4
- * an app exports them from a `"use node"` file, apart from the V8 functions in
5
- * `clerkBillingFunctions.ts`. The Clerk client and `verifyWebhook` are
6
- * injected, so this package imports neither `convex` nor `@clerk/backend`.
7
- */
8
1
  import type { FunctionReference, RegisteredAction } from "convex/server";
9
2
  import type { v as convexV, Validator } from "convex/values";
10
3
  import { type ClerkBillingChange, type ClerkWebhookEventLike, type PlanItem } from "./clerkBilling.js";
@@ -73,11 +66,9 @@ type BackfillDef<Style extends ClerkBillingListStyle, Return extends ClerkBillin
73
66
  };
74
67
  type BackfillBuilder<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle> = (def: BackfillDef<Style, Return>) => RegisteredAction<"internal", ClerkBillingBackfillArgs<Return>, Promise<ClerkBillingBackfillResult<Return>>>;
75
68
  type ApplyConfig = {
76
- /** Write through `applyBillingChange` with a `replace` change. Default. */
77
69
  applyStyle?: "change";
78
70
  applyBillingChangeRef: () => ClerkBillingApplyChangeRef;
79
71
  } | {
80
- /** Write through a `setPlanSlugs({ clerkUserId, planSlugs })`. */
81
72
  applyStyle: "setPlanSlugs";
82
73
  setPlanSlugsRef: () => ClerkBillingSetPlanSlugsRef;
83
74
  };
@@ -89,32 +80,15 @@ type SelfConfig<Return extends ClerkBillingBackfillReturnStyle> = Return extends
89
80
  export type ClerkBillingNodeFunctionsConfig<Style extends ClerkBillingListStyle, Return extends ClerkBillingBackfillReturnStyle> = {
90
81
  v: ConvexV;
91
82
  internalAction: BackfillBuilder<Style, Return>;
92
- /** The list style the app gave `createClerkBillingFunctions`. It decides the page args and how the result is read. */
93
83
  listStyle: Style;
94
- /** Result shape and run mode. See `ClerkBillingBackfillReturnStyle`. */
95
84
  returnStyle: Return;
96
- /** `(): ClerkBillingListRef<"cursor"> => internal.billing.listClerkIds`. */
97
85
  listClerkIdsRef: () => ClerkBillingListRef<Style>;
98
- /** Builds the Clerk client when the action starts. */
99
86
  getClerkClient: () => ClerkBillingClerkLike;
100
- /** Rows per page for the list styles that do not take `numItems` from the caller. Default 100. */
101
87
  pageSize?: number;
102
- /** Item statuses that grant a plan. Default: the package default (`GRANTING_ITEM_STATUSES`). */
103
88
  grantingStatuses?: readonly string[];
104
- /**
105
- * A user Clerk answers 404 for (never subscribed). `"emptySlugs"` writes an
106
- * empty set; `"skip"` leaves the row alone and counts it as skipped. Default `"emptySlugs"`.
107
- */
108
89
  onNotFound?: "emptySlugs" | "skip";
109
- /**
110
- * A user whose Clerk call or write fails with something other than a 404.
111
- * `"throw"` stops the run. `"log"` calls `onUserError` and counts it as failed.
112
- * `"skip"` counts it as skipped with no log. Default `"throw"`.
113
- */
114
90
  onError?: "throw" | "log" | "skip";
115
- /** Called for each `"log"` failure. Default `console.error("[backfillPlanSlugs]", clerkId, error)`. */
116
91
  onUserError?: (clerkId: string, error: unknown) => void;
117
- /** Called with the result when a walking run ends, for a summary log. */
118
92
  onFinished?: (result: ClerkBillingBackfillResult<Return>) => void;
119
93
  } & ApplyConfig & SelfConfig<Return>;
120
94
  /**
@@ -150,13 +124,10 @@ export type ClerkBillingWebhookNodeActionConfig<Event extends ClerkWebhookEventL
150
124
  returns: Req<boolean>;
151
125
  handler: (ctx: Ctx, args: WebhookArgs) => Promise<boolean>;
152
126
  }) => RegisteredAction<"internal", WebhookArgs, Promise<boolean>>;
153
- /** `verifyWebhook` from `@clerk/backend/webhooks`. */
154
127
  verifyWebhook: (request: Request, options: {
155
128
  signingSecret: string;
156
129
  }) => Promise<Event>;
157
- /** `vPro.parseBillingEvent`. */
158
130
  parseBillingEvent: (event: Event) => ClerkBillingChange | null;
159
- /** Writes the change: `(ctx: ActionCtx, change) => ctx.runMutation(internal.clerk.billing.applyBillingChange, { change })`. */
160
131
  applyChange: (ctx: Ctx, change: ClerkBillingChange) => Promise<unknown>;
161
132
  /** The URL of the rebuilt request. Verification ignores it. Default `"https://convex.invalid/clerk/webhooks"`. */
162
133
  url?: string;
@@ -19,7 +19,6 @@ function isNotFound(error) {
19
19
  * ```
20
20
  */
21
21
  export function createClerkBillingNodeFunctions(config) {
22
- // The walk is untyped by style: `readPage` and `applyRef` below narrow it once.
23
22
  const loose = config;
24
23
  const backfillPlanSlugs = loose.internalAction({
25
24
  args: loose.returnStyle === "null" ? { cursor: loose.v.optional(loose.v.union(loose.v.string(), loose.v.null())) } : {},
@@ -1,9 +1,3 @@
1
- /**
2
- * Clerk-user lookups for Convex functions: the caller's identity `subject`
3
- * resolved to a row through one index. Typed structurally, so the package
4
- * never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
5
- * types below without a cast.
6
- */
7
1
  /** The part of a Convex table's type info this helper reads (`DataModel[table]`). */
8
2
  export type ClerkUserTableInfoLike = {
9
3
  document: {
@@ -52,28 +46,16 @@ export type ClerkUserMutationCtx<Table extends string, Index extends string, Fie
52
46
  };
53
47
  };
54
48
  export type ClerkUserAuthConfig<Table extends string, Index extends string, Field extends string, AdminField extends string> = {
55
- /** The users table, for example `"users"`. */
56
49
  table: Table;
57
- /** The index on the Clerk id field, for example `"by_clerk_id"`. */
58
50
  index: Index;
59
- /** The indexed field that holds the identity `subject`, for example `"clerkId"`. */
60
51
  field: Field;
61
- /** A boolean field; `isCurrentUserAdmin` is true only when it is `=== true`. */
62
52
  adminField?: AdminField;
63
- /** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
64
53
  lookup?: "first" | "unique";
65
- /** Thrown by `requireCurrentUserId` and `ensureUser`. Default `"Not authenticated"`. */
66
54
  unauthenticatedMessage?: string;
67
55
  };
68
56
  export type EnsureClerkUserOptions<Doc, Identity> = {
69
- /**
70
- * Fields to patch on an existing row, or `undefined` to leave it alone.
71
- * Only called when the row exists.
72
- */
73
57
  patch?: (existing: Doc, identity: Identity) => Partial<ClerkUserInsert<Doc>> | undefined;
74
- /** Thrown when there is no identity. Default: the config's `unauthenticatedMessage`. */
75
58
  unauthenticatedMessage?: string;
76
- /** Thrown when the identity has an empty `subject`. Default `"Clerk user ID is required"`. */
77
59
  missingSubjectMessage?: string;
78
60
  };
79
61
  export type EnsureClerkUserResult<Id> = {
@@ -1,9 +1,3 @@
1
- /**
2
- * Clerk-user lookups for Convex functions: the caller's identity `subject`
3
- * resolved to a row through one index. Typed structurally, so the package
4
- * never imports `convex`; a real `QueryCtx` or `MutationCtx` fits the ctx
5
- * types below without a cast.
6
- */
7
1
  const DEFAULT_UNAUTHENTICATED_MESSAGE = "Not authenticated";
8
2
  const DEFAULT_MISSING_SUBJECT_MESSAGE = "Clerk user ID is required";
9
3
  /**
@@ -28,7 +22,6 @@ export function createClerkUserAuth() {
28
22
  .withIndex(config.index, (q) => q.eq(config.field, clerkId));
29
23
  return config.lookup === "unique" ? query.unique() : query.first();
30
24
  }
31
- /** The caller's row, or `null` with no identity, an empty `subject`, or no row. */
32
25
  async function getCurrentUser(ctx) {
33
26
  const identity = await ctx.auth.getUserIdentity();
34
27
  if (!identity?.subject)
@@ -39,14 +32,12 @@ export function createClerkUserAuth() {
39
32
  const user = await getCurrentUser(ctx);
40
33
  return user?._id ?? null;
41
34
  }
42
- /** `getCurrentUserId`, throwing `new Error(message)` where that returns `null`. */
43
35
  async function requireCurrentUserId(ctx, message = unauthenticatedMessage) {
44
36
  const userId = await getCurrentUserId(ctx);
45
37
  if (userId === null)
46
38
  throw new Error(message);
47
39
  return userId;
48
40
  }
49
- /** `getCurrentUser`, throwing `new Error(message)` where that returns `null`. */
50
41
  async function requireCurrentUser(ctx, message = unauthenticatedMessage) {
51
42
  const user = await getCurrentUser(ctx);
52
43
  if (user === null)
@@ -61,11 +52,6 @@ export function createClerkUserAuth() {
61
52
  const user = await getCurrentUser(ctx);
62
53
  return user !== null && user[adminField] === true;
63
54
  }
64
- /**
65
- * The ensure-user mutation core: throws without an identity or `subject`,
66
- * patches an existing row when `options.patch` returns fields, otherwise
67
- * inserts `buildFields(identity)` (which must set the Clerk id field).
68
- */
69
55
  async function ensureUser(ctx, buildFields, options = {}) {
70
56
  const identity = await ctx.auth.getUserIdentity();
71
57
  if (!identity) {
@@ -2,9 +2,7 @@ export type ClerkWebhookEnv = {
2
2
  CLERK_WEBHOOK_SIGNING_SECRET?: string | undefined;
3
3
  };
4
4
  export type VerifyClerkWebhookOptions = {
5
- /** The Svix signing secret (`whsec_...`). Wins over `env`; an empty string counts as missing. */
6
5
  signingSecret?: string;
7
- /** Read for `CLERK_WEBHOOK_SIGNING_SECRET` when `signingSecret` is not given. Default `process.env`. */
8
6
  env?: ClerkWebhookEnv;
9
7
  };
10
8
  /** Why a webhook was rejected. Answer 400 for either, so Clerk retries. */
@@ -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
  /** A JSON value, as Convex's HTTP API returns it. */
19
2
  export type ConvexJsonValue = string | number | boolean | null | ConvexJsonValue[] | {
20
3
  [key: string]: ConvexJsonValue;
@@ -31,28 +14,15 @@ export type ConvexTableInfo = {
31
14
  inferredShape: ConvexJsonValue | null;
32
15
  };
33
16
  export type ConvexAdminClientConfig = {
34
- /** The deployment's `.convex.cloud` URL, with no trailing slash. */
35
17
  cloudUrl: string;
36
- /** The admin or deploy key. Sent in the body of `run_test_function` and as the `Convex` auth header elsewhere. */
37
18
  adminKey: string;
38
- /** The `fetch` to use. Defaults to `globalThis.fetch`. */
39
19
  fetch?: typeof globalThis.fetch;
40
20
  };
41
21
  export type RunTestFunctionOptions = {
42
- /** Args passed to the bundled function. Default `{}`. */
43
22
  args?: Record<string, ConvexJsonValue>;
44
- /**
45
- * The bundle path reported to Convex. Default `"testQuery.js"`. Only affects
46
- * stack traces in error messages.
47
- */
48
23
  path?: string;
49
24
  };
50
25
  export type ListTablesOptions = {
51
- /**
52
- * Return `true` to leave a table out of the result. Default: hide nothing.
53
- * Apps pass their own predicate (for example hiding `_`-prefixed system
54
- * tables, or an app's internal tables).
55
- */
56
26
  hideTable?: (name: string) => boolean;
57
27
  };
58
28
  /**