@vvedantb/server 0.18.0 → 0.19.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.19.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#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).
8
+
3
9
  ## 0.18.0
4
10
 
5
11
  ### Minor Changes
@@ -0,0 +1,54 @@
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
+ /** The app's generated `httpAction`. */
24
+ httpAction: (fn: (ctx: Ctx, request: Request) => Promise<Response>) => Handler;
25
+ /** Route prefix, for example `/api/hub`: routes are `<basePath>/homepage` and `<basePath>/query`. */
26
+ basePath: string;
27
+ /** Browser origins that may call the routes with credentials. */
28
+ allowedOrigins: readonly string[];
29
+ /** Cards for `GET <basePath>/homepage`. Runs only with an identity. */
30
+ homepage: (ctx: Ctx) => Promise<HomepageCard[]>;
31
+ /**
32
+ * Results for `POST <basePath>/query`. Runs only with an identity and a
33
+ * non-empty `query`. Return `null` to answer 401.
34
+ */
35
+ query: (ctx: Ctx, query: string) => Promise<JsonInput[] | null>;
36
+ /**
37
+ * CORS headers and an `OPTIONS` preflight on the homepage route too.
38
+ * Default true. The query route always has both.
39
+ */
40
+ homepageCors?: boolean;
41
+ };
42
+ /**
43
+ * Register the routes a hub app calls on a product backend:
44
+ * `GET <basePath>/homepage` (cards) and `POST <basePath>/query` (search),
45
+ * with origin-allowlist CORS.
46
+ */
47
+ export declare function registerHomepageRoutes<Ctx extends HomepageRoutesCtx, Handler>(http: {
48
+ route(spec: {
49
+ path: string;
50
+ method: Method;
51
+ handler: Handler;
52
+ }): void;
53
+ }, config: HomepageRoutesConfig<Ctx, Handler>): void;
54
+ 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";
@@ -0,0 +1,26 @@
1
+ /** How a product signs its emails. */
2
+ export type ProductEmailBrand = {
3
+ /** Product name, as in "Welcome to Acme!". */
4
+ name: string;
5
+ /** Sender, for example `Acme <waitlist@example.com>`. */
6
+ from: string;
7
+ /** Closing name under "Best regards,". */
8
+ signOff: string;
9
+ /** HTML placed after the sign-off: links, contact line. */
10
+ footerHtml: string;
11
+ };
12
+ /** A ready-to-send email, in the shape Resend's `emails.send` takes. */
13
+ export type ProductEmail = {
14
+ from: string;
15
+ to: string;
16
+ subject: string;
17
+ text: string;
18
+ html: string;
19
+ };
20
+ /** The email sent when someone joins a product's waitlist. */
21
+ export declare function waitlistWelcomeEmail(brand: ProductEmailBrand, to: string): ProductEmail;
22
+ /**
23
+ * An admin-written update. Each line of `message` becomes a paragraph; the
24
+ * message is HTML and is not escaped, so only admins may supply it.
25
+ */
26
+ 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
+ }
@@ -9,3 +9,4 @@ export { createAuthorizationServerMetadataProxy, createHealthHandler, createOpti
9
9
  export { registerMcpRoutes, type McpEndpointRoutes, type McpRouteMethod, type McpRouter, type McpRouteSpec, type McpRoutesConfig, } from "./routes.js";
10
10
  export { runSdkMcpRequest, type RunSdkMcpRequestOptions, type SdkServerLike, type SdkTransportLike, } from "./sdk.js";
11
11
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, type JsonSchemaConverter, type JsonSchemaObject, type JsonSchemaToolDefinition, type McpTool, type ToolAnnotations, type ToolContent, type ToolContext, type ToolListEntry, type ToolRegistry, type ToolResult, type ToolsToListOptions, type ZodLikeSchema, type ZodToolDefinition, } from "./tools.js";
12
+ export { createZodJsonSchemaConverter, type ZodJsonSchemaOptions } from "./zodJsonSchema.js";
package/dist/mcp/index.js CHANGED
@@ -9,3 +9,4 @@ export { createAuthorizationServerMetadataProxy, createHealthHandler, createOpti
9
9
  export { registerMcpRoutes, } from "./routes.js";
10
10
  export { runSdkMcpRequest, } from "./sdk.js";
11
11
  export { assertUniqueToolNames, createToolRegistry, defineTool, formatIssues, invalidArgumentsResult, runTool, toolErrorResult, toolJsonResult, toolsToList, toolTextResult, } from "./tools.js";
12
+ export { createZodJsonSchemaConverter } from "./zodJsonSchema.js";
@@ -0,0 +1,18 @@
1
+ import type { z } from "zod";
2
+ import type { JsonSchemaConverter } from "./tools.js";
3
+ export type ZodJsonSchemaOptions = {
4
+ /**
5
+ * Drop the `±Number.MAX_SAFE_INTEGER` bounds that zod 4 adds to `z.int()`,
6
+ * which zod 3 did not emit. Default false.
7
+ */
8
+ stripSafeIntegerBounds?: boolean;
9
+ };
10
+ /**
11
+ * A `JsonSchemaConverter` for zod 4 schemas that reproduces the zod 3
12
+ * (zod-to-json-schema) output: draft-07, input types, its key order, and
13
+ * `additionalProperties: false` on every object with properties.
14
+ *
15
+ * Pass `z.toJSONSchema` from the app's own zod, so the package root does not
16
+ * load zod.
17
+ */
18
+ export declare function createZodJsonSchemaConverter(toJSONSchema: typeof z.toJSONSchema, options?: ZodJsonSchemaOptions): JsonSchemaConverter;
@@ -0,0 +1,103 @@
1
+ // MCP SDK 1.30 turned an empty zod shape into a zod 4 mini object, whose
2
+ // JSON Schema puts $schema first and has no additionalProperties.
3
+ const EMPTY_INPUT_SCHEMA = {
4
+ $schema: "http://json-schema.org/draft-07/schema#",
5
+ type: "object",
6
+ properties: {},
7
+ };
8
+ function isZodType(schema) {
9
+ return "_zod" in schema;
10
+ }
11
+ function isEmptyObject(schema) {
12
+ return "shape" in schema && typeof schema.shape === "object" && schema.shape !== null && Object.keys(schema.shape).length === 0;
13
+ }
14
+ function isJsonObject(value) {
15
+ return value !== null && typeof value === "object" && !Array.isArray(value);
16
+ }
17
+ // zod-to-json-schema emitted keys in this order and set additionalProperties
18
+ // false on every object with properties. Reproducing both keeps tools/list
19
+ // output byte-identical to the zod 3 converter.
20
+ const KEY_ORDER = [
21
+ "type",
22
+ "enum",
23
+ "const",
24
+ "items",
25
+ "properties",
26
+ "required",
27
+ "additionalProperties",
28
+ "anyOf",
29
+ "allOf",
30
+ "oneOf",
31
+ "not",
32
+ "format",
33
+ "minimum",
34
+ "maximum",
35
+ "exclusiveMinimum",
36
+ "exclusiveMaximum",
37
+ "multipleOf",
38
+ "minItems",
39
+ "maxItems",
40
+ "minLength",
41
+ "maxLength",
42
+ "pattern",
43
+ "propertyNames",
44
+ "default",
45
+ ];
46
+ /**
47
+ * A `JsonSchemaConverter` for zod 4 schemas that reproduces the zod 3
48
+ * (zod-to-json-schema) output: draft-07, input types, its key order, and
49
+ * `additionalProperties: false` on every object with properties.
50
+ *
51
+ * Pass `z.toJSONSchema` from the app's own zod, so the package root does not
52
+ * load zod.
53
+ */
54
+ export function createZodJsonSchemaConverter(toJSONSchema, options = {}) {
55
+ const stripBounds = options.stripSafeIntegerBounds ?? false;
56
+ function normaliseProperties(node) {
57
+ if (node === null || typeof node !== "object" || Array.isArray(node))
58
+ return normalise(node);
59
+ const out = {};
60
+ for (const [key, value] of Object.entries(node))
61
+ out[key] = normalise(value);
62
+ return out;
63
+ }
64
+ function normalise(node) {
65
+ if (Array.isArray(node))
66
+ return node.map(normalise);
67
+ if (node === null || typeof node !== "object")
68
+ return node;
69
+ const source = { ...node };
70
+ if (stripBounds) {
71
+ if (source.maximum === Number.MAX_SAFE_INTEGER)
72
+ delete source.maximum;
73
+ if (source.minimum === -Number.MAX_SAFE_INTEGER)
74
+ delete source.minimum;
75
+ }
76
+ if (source.type === "object" && "properties" in source && !("additionalProperties" in source)) {
77
+ source.additionalProperties = false;
78
+ }
79
+ const out = {};
80
+ for (const key of KEY_ORDER) {
81
+ if (key in source)
82
+ out[key] = key === "properties" ? normaliseProperties(source[key]) : normalise(source[key]);
83
+ }
84
+ for (const [key, value] of Object.entries(source)) {
85
+ if (!KEY_ORDER.includes(key) && key !== "description" && key !== "$schema")
86
+ out[key] = normalise(value);
87
+ }
88
+ if ("description" in source)
89
+ out.description = normalise(source.description);
90
+ if ("$schema" in source)
91
+ out.$schema = normalise(source.$schema);
92
+ return out;
93
+ }
94
+ return (schema) => {
95
+ if (!isZodType(schema))
96
+ return {};
97
+ if (isEmptyObject(schema))
98
+ return EMPTY_INPUT_SCHEMA;
99
+ const raw = JSON.parse(JSON.stringify(toJSONSchema(schema, { target: "draft-7", io: "input" })));
100
+ const out = normalise(raw);
101
+ return isJsonObject(out) ? out : {};
102
+ };
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vvedantb/server",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "description": "Shared Convex backend helpers, MCP server scaffolding and Node-side MCP OAuth client helpers from one root import: query-limit errors, Clerk auth and token verification, an MCP bearer-token cache, Expo push token storage, batched send and receipts, Clerk-user lookups and ensure-user for Convex functions, V Pro plan checks and Clerk Billing webhook helpers, bearer tokens, env, CORS, JSON responses, MCP route registration, a bearer-auth MCP HTTP handler, OAuth metadata, a JSON-RPC dispatcher, explorer tools, WebCrypto primitives, Convex optimistic-update helpers, MCP OAuth client helpers (provider, sign-in, refresh, revocation, loopback redirect server) for desktop apps, a QuickJS code sandbox that bridges script tool calls to host handlers, and a pure artifacts core (Zod contract, state limits and ops, quiz and flashcards pages, a sandboxed document wrapper with CSP and a guest state bridge); and, from the `@vvedantb/server/ai` subpath, Vercel AI Gateway helpers (service tier provider options, cost from provider metadata, error classification).",
6
6
  "type": "module",