@vvedantb/server 0.10.0 → 0.12.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.
@@ -0,0 +1,31 @@
1
+ export type ClerkWebhookEnv = {
2
+ CLERK_WEBHOOK_SIGNING_SECRET?: string | undefined;
3
+ };
4
+ export type VerifyClerkWebhookOptions = {
5
+ /** The Svix signing secret (`whsec_...`). Wins over `env`; an empty string counts as missing. */
6
+ signingSecret?: string;
7
+ /** Read for `CLERK_WEBHOOK_SIGNING_SECRET` when `signingSecret` is not given. Default `process.env`. */
8
+ env?: ClerkWebhookEnv;
9
+ };
10
+ /** Why a webhook was rejected. Answer 400 for either, so Clerk retries. */
11
+ export type ClerkWebhookRejection = "missing-secret" | "invalid";
12
+ export type VerifyClerkWebhookResult<Event> = {
13
+ ok: true;
14
+ event: Event;
15
+ } | {
16
+ ok: false;
17
+ reason: ClerkWebhookRejection;
18
+ error: string;
19
+ };
20
+ /**
21
+ * Verify a Clerk (Svix) webhook request. `verifyWebhook` is injected so this
22
+ * package does not import `@clerk/backend`; pass the one from
23
+ * `@clerk/backend/webhooks`. The event type is inferred from it.
24
+ *
25
+ * Never throws. Returns `{ ok: false, reason: "missing-secret" }` without
26
+ * calling `verifyWebhook` when no secret is set, and
27
+ * `{ ok: false, reason: "invalid" }` when `verifyWebhook` throws or rejects.
28
+ */
29
+ export declare function verifyClerkWebhook<Event>(verifyWebhook: (request: Request, options: {
30
+ signingSecret: string;
31
+ }) => Promise<Event>, request: Request, options?: VerifyClerkWebhookOptions): Promise<VerifyClerkWebhookResult<Event>>;
@@ -0,0 +1,26 @@
1
+ import { errorMessage } from "../mcp/json.js";
2
+ /**
3
+ * Verify a Clerk (Svix) webhook request. `verifyWebhook` is injected so this
4
+ * package does not import `@clerk/backend`; pass the one from
5
+ * `@clerk/backend/webhooks`. The event type is inferred from it.
6
+ *
7
+ * Never throws. Returns `{ ok: false, reason: "missing-secret" }` without
8
+ * calling `verifyWebhook` when no secret is set, and
9
+ * `{ ok: false, reason: "invalid" }` when `verifyWebhook` throws or rejects.
10
+ */
11
+ export async function verifyClerkWebhook(verifyWebhook, request, options = {}) {
12
+ const signingSecret = options.signingSecret ?? (options.env ?? process.env).CLERK_WEBHOOK_SIGNING_SECRET;
13
+ if (!signingSecret) {
14
+ return {
15
+ ok: false,
16
+ reason: "missing-secret",
17
+ error: "CLERK_WEBHOOK_SIGNING_SECRET is not set in Convex env",
18
+ };
19
+ }
20
+ try {
21
+ return { ok: true, event: await verifyWebhook(request, { signingSecret }) };
22
+ }
23
+ catch (err) {
24
+ return { ok: false, reason: "invalid", error: errorMessage(err) };
25
+ }
26
+ }
@@ -1,7 +1,9 @@
1
1
  export { clerkAuthConfig, type ClerkAuthConfigEnv } from "./authConfig.js";
2
2
  export { extractBearerToken } from "./bearerToken.js";
3
3
  export { getClerkClient, type ClerkClientEnv } from "./clerk.js";
4
+ export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, type ClerkBillingChange, type ClerkBillingOptions, type ClerkWebhookEventLike, type PlanItem, } from "./clerkBilling.js";
4
5
  export { createClerkUserAuth, type ClerkUserAuthConfig, type ClerkUserDataModelLike, type ClerkUserDbReader, type ClerkUserIdentityLike, type ClerkUserIndexRange, type ClerkUserInsert, type ClerkUserMutationCtx, type ClerkUserQueryCtx, type ClerkUserTableInfoLike, type EnsureClerkUserOptions, type EnsureClerkUserResult, } from "./clerkUserAuth.js";
6
+ export { verifyClerkWebhook, type ClerkWebhookEnv, type ClerkWebhookRejection, type VerifyClerkWebhookOptions, type VerifyClerkWebhookResult, } from "./clerkWebhook.js";
5
7
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, type JsonWithCorsInit, } from "./cors.js";
6
8
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
7
9
  export { jsonResponse } from "./jsonResponse.js";
@@ -15,4 +17,5 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
15
17
  export { tempId, type TempIdFormat, type TempIdOptions } from "./tempId.js";
16
18
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, type ClerkAuthLike, type ClerkLike, type ClerkRequestStateLike, type ClerkTokenType, type ClerkVerifyRejection, type VerifiedClerkToken, type VerifyClerkAccessTokenOptions, } from "./verifyClerkAccessToken.js";
17
19
  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";
18
- export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
20
+ export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, type HasVProInput, } from "./vPlan.js";
21
+ export { createVProModule, type UserHasVProOptions, type VProCreateUser, type VProCreateUserCtx, type VProModuleConfig, type VProPlanSlugsFieldOf, type VProWriterCtx, } from "./vProModule.js";
@@ -1,7 +1,9 @@
1
1
  export { clerkAuthConfig } from "./authConfig.js";
2
2
  export { extractBearerToken } from "./bearerToken.js";
3
3
  export { getClerkClient } from "./clerk.js";
4
+ export { activePlanSlugs, applyBillingChange, applyItemToPlanSlugs, GRANTING_ITEM_STATUSES, GRANTING_STATUSES_ACTIVE_ONLY, GRANTING_STATUSES_ACTIVE_PAST_DUE, itemGrantsPlan, parseClerkBillingEvent, } from "./clerkBilling.js";
4
5
  export { createClerkUserAuth, } from "./clerkUserAuth.js";
6
+ export { verifyClerkWebhook, } from "./clerkWebhook.js";
5
7
  export { corsPreflight, jsonWithCors, mcpCorsHeaders, } from "./cors.js";
6
8
  export { formatConvexQueryError, isConvexResourceLimitError, } from "./convexQueryLimits.js";
7
9
  export { jsonResponse } from "./jsonResponse.js";
@@ -15,4 +17,5 @@ export { assertMcpTools, expectMcpToolCount } from "./mcpTestHelpers.js";
15
17
  export { tempId } from "./tempId.js";
16
18
  export { consoleClerkVerifyLogger, verifyClerkAccessToken, } from "./verifyClerkAccessToken.js";
17
19
  export { authenticateClerkBearer, CLERK_JWKS_REFETCH_MIN_MS, CLERK_JWKS_TTL_MS, clearClerkJwksCache, isOAuthAccessTokenJwt, looksLikeJwt, verifyClerkOAuthJwt, } from "./verifyClerkOAuthJwt.js";
18
- export { hasVPlan, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
20
+ export { hasVPlan, hasVPro, parseVProCompUserIds, V_PRO_PLAN_KEY, V_PRO_PLAN_KEYS, } from "./vPlan.js";
21
+ export { createVProModule, } from "./vProModule.js";
@@ -9,3 +9,25 @@ export declare const V_PRO_PLAN_KEYS: readonly string[];
9
9
  * also matches. Anything else, including `null`, returns `false`; it never throws.
10
10
  */
11
11
  export declare function hasVPlan(claimsOrIdentity: unknown): boolean;
12
+ /** What `hasVPro` reads. Every field is optional. */
13
+ export type HasVProInput = {
14
+ /** A Convex `ctx.auth.getUserIdentity()` result or raw JWT claims, read by `hasVPlan`. */
15
+ identity?: unknown;
16
+ /** Plan slugs stored on the user row, for example from the Clerk Billing webhook. */
17
+ planSlugs?: readonly string[] | null;
18
+ /** Clerk user ids that get V Pro without a paid plan. See `parseVProCompUserIds`. */
19
+ compIds?: readonly string[] | null;
20
+ /** The Clerk user id to match against `compIds`. Default: `identity.subject`. */
21
+ clerkId?: string | null;
22
+ };
23
+ /**
24
+ * Comma-separated Clerk user ids (for example the `V_PRO_COMP_USER_IDS` env
25
+ * var) as a list. Trims each id and drops empty ones; unset means nobody.
26
+ */
27
+ export declare function parseVProCompUserIds(value: string | null | undefined): string[];
28
+ /**
29
+ * True when any source grants V Pro: the session's `pla` claim (`hasVPlan`), a
30
+ * stored plan slug in `V_PRO_PLAN_KEYS`, or a Clerk id in `compIds`. Missing
31
+ * or malformed fields count as no plan; it never throws.
32
+ */
33
+ export declare function hasVPro(input: HasVProInput | null | undefined): boolean;
@@ -21,3 +21,36 @@ export function hasVPlan(claimsOrIdentity) {
21
21
  return false;
22
22
  return V_PRO_PLAN_KEYS.includes(plan);
23
23
  }
24
+ /**
25
+ * Comma-separated Clerk user ids (for example the `V_PRO_COMP_USER_IDS` env
26
+ * var) as a list. Trims each id and drops empty ones; unset means nobody.
27
+ */
28
+ export function parseVProCompUserIds(value) {
29
+ return (value ?? "")
30
+ .split(",")
31
+ .map((id) => id.trim())
32
+ .filter((id) => id.length > 0);
33
+ }
34
+ /**
35
+ * True when any source grants V Pro: the session's `pla` claim (`hasVPlan`), a
36
+ * stored plan slug in `V_PRO_PLAN_KEYS`, or a Clerk id in `compIds`. Missing
37
+ * or malformed fields count as no plan; it never throws.
38
+ */
39
+ export function hasVPro(input) {
40
+ if (typeof input !== "object" || input === null)
41
+ return false;
42
+ const { identity, planSlugs, compIds, clerkId } = input;
43
+ if (hasVPlan(identity))
44
+ return true;
45
+ if (Array.isArray(planSlugs) && planSlugs.some((slug) => V_PRO_PLAN_KEYS.includes(slug))) {
46
+ return true;
47
+ }
48
+ const id = clerkId || identitySubject(identity);
49
+ return id !== undefined && Array.isArray(compIds) && compIds.includes(id);
50
+ }
51
+ function identitySubject(identity) {
52
+ if (typeof identity !== "object" || identity === null)
53
+ return undefined;
54
+ const subject = identity.subject;
55
+ return typeof subject === "string" && subject.length > 0 ? subject : undefined;
56
+ }
@@ -0,0 +1,109 @@
1
+ import { type ClerkBillingChange, type ClerkWebhookEventLike } from "./clerkBilling.js";
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
+ /** Document fields that can hold a `string[]` (optional ones too). */
9
+ export type VProPlanSlugsFieldOf<Doc> = {
10
+ [K in keyof Doc & string]-?: string[] extends Doc[K] ? K : never;
11
+ }[keyof Doc & string];
12
+ /** `ctx.db` for `createUser`: one insert. A Convex `MutationCtx` fits. */
13
+ export type VProCreateUserCtx<Table extends string, Doc extends {
14
+ _id: string;
15
+ }> = {
16
+ db: {
17
+ insert(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
18
+ };
19
+ };
20
+ /**
21
+ * Inserts the users row when a billing event arrives before the row exists.
22
+ * The app owns the other fields (for example `createdAt`, `lastSeenAt`).
23
+ */
24
+ export type VProCreateUser<Table extends string, Doc extends {
25
+ _id: string;
26
+ }> = (ctx: VProCreateUserCtx<Table, Doc>, args: {
27
+ clerkId: string;
28
+ planSlugs: string[];
29
+ }) => Promise<unknown>;
30
+ /** What `writeBillingChange` does when there is no row: skip it, or call `createUser`. */
31
+ export type VProMissingUserConfig<Table extends string, Doc extends {
32
+ _id: string;
33
+ }> = {
34
+ /** Default `"noop"`: no write, `writeBillingChange` returns `false`. */
35
+ onMissingUser?: "noop";
36
+ createUser?: undefined;
37
+ } | {
38
+ /** `"create"` (implied by `createUser`): call `createUser`, then return `true`. */
39
+ onMissingUser?: "create";
40
+ /** Inserts the missing row with the given slugs. Required for `"create"`. */
41
+ createUser: VProCreateUser<Table, Doc>;
42
+ };
43
+ export type VProModuleConfig<Table extends string, Index extends string, ClerkIdField extends string, PlanSlugsField extends string, Doc extends {
44
+ _id: string;
45
+ } = {
46
+ _id: string;
47
+ }> = VProMissingUserConfig<Table, Doc> & {
48
+ /** The users table, for example `"users"`. */
49
+ table: Table;
50
+ /** The index on the Clerk id field, for example `"by_clerk_id"`. */
51
+ index: Index;
52
+ /** The indexed field that holds the Clerk user id, for example `"clerkId"`. */
53
+ clerkIdField: ClerkIdField;
54
+ /** The `string[]` field that stores granting plan slugs, for example `"planSlugs"`. */
55
+ planSlugsField: PlanSlugsField;
56
+ /** How the index lookup ends. Default `"first"`; `"unique"` throws on duplicate rows. */
57
+ 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
+ grantingStatuses?: readonly string[];
64
+ /** Event type matching for `parseBillingEvent`. Default `"exact"`. See `ClerkBillingOptions`. */
65
+ 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
+ extraPatch?: (planSlugs: string[]) => Partial<ClerkUserInsert<Doc>>;
72
+ };
73
+ /** `ctx.db` for `writeBillingChange`: one index lookup and a patch. A Convex `MutationCtx` fits. */
74
+ export type VProWriterCtx<Table extends string, Index extends string, ClerkIdField extends string, Doc extends {
75
+ _id: string;
76
+ }, Range> = {
77
+ db: ClerkUserDbReader<Table, Index, ClerkIdField, Doc, Range> & {
78
+ patch(id: Doc["_id"], value: Partial<ClerkUserInsert<Doc>>): Promise<void>;
79
+ /** Needed only with `createUser`; a `MutationCtx` has it. */
80
+ insert?(table: Table, value: ClerkUserInsert<Doc>): Promise<Doc["_id"]>;
81
+ };
82
+ };
83
+ export type UserHasVProOptions = {
84
+ /** The caller's identity, for the session `pla` claim. */
85
+ identity?: unknown;
86
+ /** Clerk user ids that get V Pro without a paid plan. */
87
+ compIds?: readonly string[] | null;
88
+ };
89
+ /**
90
+ * Build V Pro helpers for one users table. Curried so `DataModel` can be given
91
+ * while the config keys are inferred (and checked against it):
92
+ *
93
+ * ```ts
94
+ * const vPro = createVProModule<DataModel>()({
95
+ * table: "users",
96
+ * index: "by_clerk_id",
97
+ * clerkIdField: "clerkId",
98
+ * planSlugsField: "planSlugs",
99
+ * });
100
+ * ```
101
+ */
102
+ export declare function createVProModule<DataModel extends ClerkUserDataModelLike>(): <const Table extends keyof DataModel & string, const Index extends keyof DataModel[Table]["indexes"] & string, const ClerkIdField extends DataModel[Table]["indexes"][Index][0], const PlanSlugsField extends VProPlanSlugsFieldOf<DataModel[Table]["document"]>>(config: VProModuleConfig<Table, Index, ClerkIdField, PlanSlugsField, DataModel[Table]["document"]>) => {
103
+ planSlugsOf: (user: Pick<DataModel[Table]["document"], PlanSlugsField> | null | undefined) => string[];
104
+ nextPlanSlugs: (user: Pick<DataModel[Table]["document"], PlanSlugsField> | null | undefined, change: ClerkBillingChange) => string[];
105
+ planSlugsPatch: (planSlugs: readonly string[]) => Record<PlanSlugsField, string[]> & Partial<ClerkUserInsert<DataModel[Table]["document"]>>;
106
+ parseBillingEvent: (event: ClerkWebhookEventLike | null | undefined) => ClerkBillingChange | null;
107
+ userHasVPro: (user: (Pick<DataModel[Table]["document"], PlanSlugsField> & Partial<Record<ClerkIdField, unknown>>) | null | undefined, options?: UserHasVProOptions) => boolean;
108
+ writeBillingChange: <Range>(ctx: VProWriterCtx<Table, Index, ClerkIdField, DataModel[Table]["document"], Range>, change: ClerkBillingChange) => Promise<boolean>;
109
+ };
@@ -0,0 +1,87 @@
1
+ import { applyBillingChange, parseClerkBillingEvent, } from "./clerkBilling.js";
2
+ import { createClerkUserAuth, } from "./clerkUserAuth.js";
3
+ import { hasVPro } from "./vPlan.js";
4
+ /**
5
+ * Build V Pro helpers for one users table. Curried so `DataModel` can be given
6
+ * while the config keys are inferred (and checked against it):
7
+ *
8
+ * ```ts
9
+ * const vPro = createVProModule<DataModel>()({
10
+ * table: "users",
11
+ * index: "by_clerk_id",
12
+ * clerkIdField: "clerkId",
13
+ * planSlugsField: "planSlugs",
14
+ * });
15
+ * ```
16
+ */
17
+ export function createVProModule() {
18
+ return function configure(config) {
19
+ const { createUser } = config;
20
+ if (config.onMissingUser === "create" && !createUser) {
21
+ throw new Error('createVProModule: onMissingUser "create" needs a createUser callback');
22
+ }
23
+ const billingOptions = {
24
+ grantingStatuses: config.grantingStatuses,
25
+ eventMatch: config.eventMatch,
26
+ };
27
+ const userAuth = createClerkUserAuth()({
28
+ table: config.table,
29
+ index: config.index,
30
+ field: config.clerkIdField,
31
+ lookup: config.lookup,
32
+ });
33
+ /** The stored slugs; `[]` for no user, a missing field or a non-array value. */
34
+ function planSlugsOf(user) {
35
+ const value = user?.[config.planSlugsField];
36
+ return Array.isArray(value) ? value.filter((slug) => typeof slug === "string") : [];
37
+ }
38
+ /** The slugs to store after `change`. */
39
+ function nextPlanSlugs(user, change) {
40
+ return applyBillingChange(planSlugsOf(user), change, billingOptions);
41
+ }
42
+ /** `parseClerkBillingEvent` with this module's `grantingStatuses` and `eventMatch`. */
43
+ function parseBillingEvent(event) {
44
+ return parseClerkBillingEvent(event, billingOptions);
45
+ }
46
+ /** `{ [planSlugsField]: planSlugs }`, for `ctx.db.patch`. */
47
+ function planSlugsPatch(planSlugs) {
48
+ const patch = { [config.planSlugsField]: [...planSlugs] };
49
+ return patch;
50
+ }
51
+ /** `hasVPro` over the row's stored slugs and Clerk id, plus the given identity and comp ids. */
52
+ function userHasVPro(user, options = {}) {
53
+ const clerkId = user?.[config.clerkIdField];
54
+ return hasVPro({
55
+ identity: options.identity,
56
+ planSlugs: planSlugsOf(user),
57
+ compIds: options.compIds,
58
+ clerkId: typeof clerkId === "string" ? clerkId : undefined,
59
+ });
60
+ }
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
+ async function writeBillingChange(ctx, change) {
68
+ const user = await userAuth.getUserByClerkId(ctx, change.clerkId);
69
+ if (!user) {
70
+ if (!createUser)
71
+ return false;
72
+ const { insert } = ctx.db;
73
+ if (!insert)
74
+ throw new Error("writeBillingChange: createUser needs ctx.db.insert (a MutationCtx)");
75
+ await createUser({ db: { insert: insert.bind(ctx.db) } }, { clerkId: change.clerkId, planSlugs: nextPlanSlugs(null, change) });
76
+ return true;
77
+ }
78
+ const planSlugs = nextPlanSlugs(user, change);
79
+ const patch = config.extraPatch
80
+ ? { ...config.extraPatch([...planSlugs]), ...planSlugsPatch(planSlugs) }
81
+ : planSlugsPatch(planSlugs);
82
+ await ctx.db.patch(user._id, patch);
83
+ return true;
84
+ }
85
+ return { planSlugsOf, nextPlanSlugs, planSlugsPatch, parseBillingEvent, userHasVPro, writeBillingChange };
86
+ };
87
+ }
package/docs/ai.md ADDED
@@ -0,0 +1,135 @@
1
+ # AI Gateway helpers (`@vvedantb/server/ai`)
2
+
3
+ Small helpers for apps that call models through the [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) with the AI SDK: service tier provider options, the Gateway cost from provider metadata, and one mapping from SDK and Gateway errors to something a caller can act on.
4
+
5
+ They are on their own subpath, not the root:
6
+
7
+ ```ts
8
+ import {
9
+ classifyGatewayError,
10
+ FLEX_GATEWAY_PROVIDER_OPTIONS,
11
+ gatewayServiceTier,
12
+ readGatewayCost,
13
+ withFlexGatewayOptions,
14
+ } from "@vvedantb/server/ai";
15
+ ```
16
+
17
+ The root (`@vvedantb/server`) does not re-export them, so a root import never loads the AI SDK.
18
+
19
+ ## Runtime and peers
20
+
21
+ - Works in the Convex default runtime (no `"use node"`), Node and browsers. No Node built-ins. `tests-node/bundle.mjs` bundles a Convex action that uses it the way `convex deploy` does.
22
+ - `ai` (`>=5`) and `@ai-sdk/gateway` (`>=1`) are optional peers, but `classifyGatewayError` imports their error classes statically, so importing `@vvedantb/server/ai` needs both installed. Any app that calls the Gateway through the AI SDK already has them.
23
+ - The service tier and cost helpers import nothing from the SDK. Their types are structural and fit the SDK's `providerOptions` and `ProviderMetadata`.
24
+ - No model IDs, prompts or `generateText` wrappers. Those stay in each app.
25
+
26
+ ## Service tier
27
+
28
+ ```ts
29
+ const { text } = await generateText({
30
+ model: TITLE_MODEL, // the app's own constant
31
+ prompt,
32
+ providerOptions: FLEX_GATEWAY_PROVIDER_OPTIONS,
33
+ });
34
+
35
+ // Per-call tier
36
+ providerOptions: gatewayServiceTier(background ? "flex" : "default");
37
+
38
+ // Flex plus other options
39
+ providerOptions: withFlexGatewayOptions({ alibaba: { enableThinking: false } });
40
+ ```
41
+
42
+ | Export | What it does |
43
+ | --- | --- |
44
+ | `GatewayServiceTier` | `"flex" \| "default" \| "ultrafast"`. |
45
+ | `gatewayServiceTier(tier)` | `{}` for `"default"` (no `serviceTier` sent), else `{ gateway: { serviceTier: tier } }`. A new object each call. Alias: `gatewayTier`. |
46
+ | `FLEX_GATEWAY_PROVIDER_OPTIONS` | `{ gateway: { serviceTier: "flex" } }`, frozen. Alias: `FLEX_PROVIDER_OPTIONS`. |
47
+ | `withFlexGatewayOptions(extra?)` | A new object: flex, with the caller's options on top. Other providers' keys are added as they are. Caller `gateway` keys are merged over `{ serviceTier: "flex" }`, so `{ gateway: { order: [...] } }` keeps flex, and a caller `serviceTier` replaces it. Nothing is mutated. |
48
+ | `GatewayProviderOptions`, `GatewayJsonObject`, `GatewayJsonValue` | Structural copies of the SDK's provider options and JSON types. |
49
+
50
+ Notes:
51
+
52
+ - Flex is cheaper and may queue. Use it for background work, not for calls a user waits on.
53
+ - A tier the provider or model does not support is a no-op on the Gateway side.
54
+ - `"ultrafast"` is kept because one app defines it, but no app has confirmed it works. The `@ai-sdk/gateway` 4.x types list `serviceTier` as `"flex" | "priority"`. Check `providerMetadata.gateway.serviceTier` to see what the Gateway applied before you rely on it.
55
+ - The local `buildChatProviderOptions(extra)` it replaces was `{ ...FLEX, ...extra }`, where a caller `gateway` key dropped flex. `withFlexGatewayOptions` merges `gateway` instead. For the options passed to it today (a thinking-off option for another provider), the output is the same.
56
+
57
+ ## Cost
58
+
59
+ ```ts
60
+ const result = await generateText({ model, prompt, providerOptions: FLEX_GATEWAY_PROVIDER_OPTIONS });
61
+ const costUsd = readGatewayCost(result.providerMetadata);
62
+ ```
63
+
64
+ `readGatewayCost(metadata)` returns `gateway.cost` (what was billed) or, if that is missing or unusable, `gateway.marketCost` (list price), so budget guards still see a value. Each may be a number or a numeric string. It returns `undefined` when neither is a finite number. A cost of `0` is returned as `0`, not skipped.
65
+
66
+ ## Errors
67
+
68
+ ```ts
69
+ try {
70
+ return await generateText({ model, prompt, maxRetries: 2 });
71
+ } catch (error) {
72
+ const failure = classifyGatewayError(error);
73
+ // { kind, message, retryable, statusCode? }
74
+ if (failure.kind === "quota") notifyBilling();
75
+ throw new AppError(appCodeFor(failure.kind), failure.message);
76
+ }
77
+ ```
78
+
79
+ `classifyGatewayError(error)` never throws. It unwraps `RetryError` to its last error, then checks in this order:
80
+
81
+ | `kind` | Matches | `retryable` |
82
+ | --- | --- | --- |
83
+ | `invalid_request` | `InvalidArgumentError`, `GatewayInvalidRequestError` | `false` |
84
+ | `auth` | `GatewayAuthenticationError`, and the error `ai` puts in its place (see below) | `false` |
85
+ | `model_not_found` | `NoSuchModelError`, `GatewayModelNotFoundError` | `false` |
86
+ | `quota` | A Gateway error with status 402, or a billing message (credits, funds, billing, payment required, spend limit, budget), or the word "quota" on a Gateway error that is not a rate limit | `false` |
87
+ | `rate_limit` | `GatewayRateLimitError` | `true` |
88
+ | `timeout` | The Gateway's `GatewayTimeoutError` (matched by name, as the package does not export it) | `true` |
89
+ | `gateway` | Any other Gateway error | the SDK's `isRetryable` |
90
+ | `malformed_response` | `InvalidResponseDataError` | `true` |
91
+ | `timeout` | An `Error` named `TimeoutError` or `AbortError` | `true` |
92
+ | `other` | Anything else | `false` |
93
+
94
+ - `statusCode` is set for every Gateway error. The SDK sets it to 500 when the response had none.
95
+ - `message` is the error's own message with ANSI colour codes and outer whitespace removed. The SDK keeps the Gateway's generation ID suffix (`"... [gen_…]"`). Request bodies and keys are not in it.
96
+ - Checks use the SDK's `isInstance`, which matches a marker symbol, so errors from another copy of `ai` or `@ai-sdk/gateway` in the bundle still match.
97
+ - `errorMessageOf(error)`: `error.message` for an `Error`, the string for a string, else `"Unknown error"`.
98
+
99
+ ### Auth errors from `generateText`
100
+
101
+ `generateText`, `streamText` and the other `ai` calls replace a `GatewayAuthenticationError` before the caller sees it (`wrapGatewayError` in `ai` 5 to 7). Outside production it becomes a plain `Error` named `GatewayAuthenticationError`. With `NODE_ENV=production` it becomes an `AISDKError` named `GatewayError` whose message starts "Unauthenticated". Neither has the Gateway markers or a status code, so the local copy this came from classified both as `other`. `classifyGatewayError` matches them by name and returns `auth` with no `statusCode`.
102
+
103
+ ### Quota and rate limits
104
+
105
+ The Gateway has no quota error type. An out-of-credits or spend-limit reply arrives as a rate-limit error or a generic Gateway error (an unknown error type becomes `GatewayInternalServerError` with the response status). So the classifier uses the status and the message:
106
+
107
+ - Status 402, or a billing word, means `quota` on any Gateway error.
108
+ - The bare word "quota" is ambiguous on a rate-limit error ("requests per minute quota"). There it stays `rate_limit`, as before. On any other Gateway error (for example a 403) it means `quota`.
109
+ - Errors that are not Gateway errors are never `quota`.
110
+
111
+ Callers that had only `rate_limit` should handle `quota` too. Treat it as not retryable until someone tops up or the period resets.
112
+
113
+ ### Changes from the local `gatewayErrors.ts`
114
+
115
+ - New kind `quota`, checked before `rate_limit`.
116
+ - `auth` also matches the error `ai` puts in place of `GatewayAuthenticationError`.
117
+ - The Gateway's own timeout is `timeout`, not `gateway`.
118
+ - `statusCode` is set for every Gateway error, not only the `gateway` kind.
119
+ - `message` has ANSI colour codes and outer whitespace removed.
120
+ - No `"use node"`.
121
+
122
+ ## Adopting it in the apps
123
+
124
+ Each app can delete its local copy once it imports from `@vvedantb/server/ai` (0.11.0 or later). Keep model IDs, prompts and app wrappers local. Paths are as found in each app.
125
+
126
+ | Local file | Replace with | Keep local |
127
+ | --- | --- | --- |
128
+ | `src/core/gateway.ts`: `GatewayTier`, `gatewayTier`, `FLEX_PROVIDER_OPTIONS` | `GatewayServiceTier`, `gatewayTier`, `FLEX_PROVIDER_OPTIONS` (same names) | Model IDs, the provider routing and Anthropic option helpers, the gateway factory and its type |
129
+ | `packages/backend/engine/llm/aiGateway.ts`: `FLEX_GATEWAY_PROVIDER_OPTIONS`, `buildChatProviderOptions`, `readGatewayCost`, `parseCost` | `FLEX_GATEWAY_PROVIDER_OPTIONS`, `withFlexGatewayOptions`, `readGatewayCost` | Model IDs, the thinking-off option, the text and embedding wrappers, result types |
130
+ | `systemOneClient.ts` (same app): `classifyError` | Call `classifyGatewayError`, then map `kind` to the app's own errors | The app's error types, key redaction, detail trimming |
131
+ | `packages/backend/convex/_ai/gatewayErrors.ts` (whole file) | `classifyGatewayError`, `errorMessageOf`, `GatewayErrorKind`, `GatewayFailure` | Each caller's own codes and copy; add a case for `quota` |
132
+ | `packages/backend/convex/textGen.ts` (same app): inline `{ gateway: { serviceTier: "flex" } }` | `FLEX_GATEWAY_PROVIDER_OPTIONS` | Prompts and the model constant |
133
+ | Other apps' local Gateway tier, cost and error helpers (not reviewed: those repos were not readable when this was written) | The same exports | App wrappers and model IDs |
134
+
135
+ Since the shared module has no `"use node"`, callers of the old `gatewayErrors.ts` can import it from the default runtime too.