@donotdev/functions 0.1.0 → 0.1.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 (95) hide show
  1. package/guidelines/FUNCTIONS.md +9 -0
  2. package/guidelines/VERCEL.md +260 -0
  3. package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
  4. package/lib/firebase/index.js +3 -3
  5. package/lib/firebase/index.js.map +4 -4
  6. package/lib/shared/ai/classifyAIError.d.ts +35 -0
  7. package/lib/shared/ai/costTracker.d.ts +20 -0
  8. package/lib/shared/ai/createAIRoute.d.ts +20 -0
  9. package/lib/shared/ai/index.d.ts +6 -0
  10. package/lib/shared/ai/resolveModelTier.d.ts +14 -0
  11. package/lib/shared/billing/createCheckout.d.ts +8 -2
  12. package/lib/shared/email/createEmailRoute.d.ts +30 -0
  13. package/lib/shared/email/index.d.ts +3 -0
  14. package/lib/shared/email/provider.d.ts +30 -0
  15. package/lib/shared/email/resendProvider.d.ts +22 -0
  16. package/lib/shared/github.d.ts +5 -0
  17. package/lib/shared/index.d.ts +2 -0
  18. package/lib/shared/index.js +4 -3
  19. package/lib/shared/index.js.map +4 -4
  20. package/lib/shared/logger.d.ts +2 -0
  21. package/lib/shared/oauth/exchangeToken.d.ts +1 -0
  22. package/lib/shared/oauth/grantAccess.d.ts +1 -0
  23. package/lib/shared/utils/internal/idempotency.d.ts +1 -0
  24. package/lib/supabase/ai/createAIFunction.d.ts +30 -0
  25. package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
  26. package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
  27. package/lib/supabase/billing/changePlan.d.ts +1 -1
  28. package/lib/supabase/crud/aggregate.d.ts +1 -0
  29. package/lib/supabase/crud/create.d.ts +1 -0
  30. package/lib/supabase/crud/delete.d.ts +1 -0
  31. package/lib/supabase/crud/get.d.ts +1 -0
  32. package/lib/supabase/crud/list.d.ts +1 -0
  33. package/lib/supabase/crud/update.d.ts +1 -0
  34. package/lib/supabase/edgeFunction.d.ts +56 -0
  35. package/lib/supabase/email/createEmailFunction.d.ts +31 -0
  36. package/lib/supabase/index.d.ts +8 -0
  37. package/lib/supabase/index.js +3 -2
  38. package/lib/supabase/index.js.map +4 -4
  39. package/lib/vercel/api/ai/chat.d.ts +29 -0
  40. package/lib/vercel/api/ai/index.d.ts +1 -0
  41. package/lib/vercel/api/index.d.ts +1 -0
  42. package/lib/vercel/api/index.js +3 -2
  43. package/lib/vercel/api/index.js.map +4 -4
  44. package/package.json +38 -5
  45. package/src/firebase/billing/createCheckoutSession.ts +79 -187
  46. package/src/firebase/oauth/exchangeToken.ts +4 -4
  47. package/src/firebase/oauth/refreshToken.ts +4 -4
  48. package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
  49. package/src/shared/ai/classifyAIError.ts +163 -0
  50. package/src/shared/ai/costTracker.ts +51 -0
  51. package/src/shared/ai/createAIRoute.ts +397 -0
  52. package/src/shared/ai/index.ts +8 -0
  53. package/src/shared/ai/resolveModelTier.ts +58 -0
  54. package/src/shared/billing/createCheckout.ts +153 -8
  55. package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
  56. package/src/shared/billing/idempotency.ts +5 -0
  57. package/src/shared/email/createEmailRoute.ts +81 -0
  58. package/src/shared/email/index.ts +5 -0
  59. package/src/shared/email/provider.ts +31 -0
  60. package/src/shared/email/resendProvider.ts +56 -0
  61. package/src/shared/errorHandling.ts +10 -4
  62. package/src/shared/github.ts +38 -0
  63. package/src/shared/index.ts +2 -0
  64. package/src/shared/logger.ts +2 -0
  65. package/src/shared/oauth/exchangeToken.ts +1 -0
  66. package/src/shared/oauth/grantAccess.ts +1 -0
  67. package/src/shared/utils/internal/idempotency.ts +1 -0
  68. package/src/shared/utils/internal/rateLimiter.ts +6 -3
  69. package/src/shared/validation.ts +1 -1
  70. package/src/supabase/ai/createAIFunction.ts +75 -0
  71. package/src/supabase/auth/removeCustomClaims.ts +38 -2
  72. package/src/supabase/auth/setCustomClaims.ts +66 -5
  73. package/src/supabase/baseFunction.ts +26 -2
  74. package/src/supabase/billing/changePlan.ts +6 -1
  75. package/src/supabase/billing/createCheckoutSession.ts +16 -2
  76. package/src/supabase/crud/aggregate.ts +1 -0
  77. package/src/supabase/crud/create.ts +1 -0
  78. package/src/supabase/crud/delete.ts +1 -0
  79. package/src/supabase/crud/get.ts +1 -0
  80. package/src/supabase/crud/list.ts +1 -0
  81. package/src/supabase/crud/update.ts +1 -0
  82. package/src/supabase/edgeFunction.ts +195 -0
  83. package/src/supabase/email/createEmailFunction.ts +75 -0
  84. package/src/supabase/index.ts +12 -0
  85. package/src/supabase/oauth/exchangeToken.ts +38 -7
  86. package/src/supabase/oauth/refreshToken.ts +4 -5
  87. package/src/supabase/registerCrudFunctions.ts +29 -41
  88. package/src/supabase/utils/idempotency.ts +6 -2
  89. package/src/vercel/api/ai/chat.ts +77 -0
  90. package/src/vercel/api/ai/index.ts +1 -0
  91. package/src/vercel/api/billing/create-checkout-session.ts +27 -4
  92. package/src/vercel/api/billing/webhook-handler.ts +8 -1
  93. package/src/vercel/api/index.ts +1 -0
  94. package/src/vercel/api/oauth/exchange-token.ts +24 -1
  95. package/src/vercel/api/utils/cors.ts +6 -0
@@ -103,6 +103,8 @@ export declare const logger: {
103
103
  * @param message - Log message
104
104
  * @param context - Additional context data
105
105
  *
106
+ * @security Callers MUST NOT pass secrets (tokens, passwords, API keys) in context. Context is logged in plaintext.
107
+ *
106
108
  * @version 0.1.0
107
109
  * @since 0.0.1
108
110
  * @author AMBROISE PARK Consulting
@@ -7,6 +7,7 @@
7
7
  * @author AMBROISE PARK Consulting
8
8
  */
9
9
  import type { ExchangeTokenRequest, TokenResponse } from '@donotdev/core/server';
10
+ /** Platform-agnostic provider for exchanging OAuth authorization codes for tokens. */
10
11
  export interface OAuthProvider {
11
12
  exchangeCodeForToken(params: {
12
13
  code: string;
@@ -6,6 +6,7 @@
6
6
  * @since 0.0.1
7
7
  * @author AMBROISE PARK Consulting
8
8
  */
9
+ /** Platform-agnostic provider for granting OAuth access to a user. */
9
10
  export interface OAuthGrantProvider {
10
11
  grantAccess(params: {
11
12
  userId: string;
@@ -1,3 +1,4 @@
1
+ /** Stored result of a previously processed idempotent operation. */
1
2
  export interface IdempotencyResult<T = any> {
2
3
  result: T;
3
4
  processedAt: string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * @fileoverview AI Chat - Supabase Edge Function Factory
3
+ * @description Wraps the shared AI route handler for Supabase Edge Functions.
4
+ * Uses Vercel AI SDK via createAIRoute for streaming and non-streaming.
5
+ *
6
+ * @version 0.1.0
7
+ * @since 0.1.0
8
+ * @author AMBROISE PARK Consulting
9
+ */
10
+ import type { AIRouteConfig } from '@donotdev/core/server';
11
+ /**
12
+ * Create a Supabase Edge Function handler for AI chat.
13
+ *
14
+ * @param config - AI route configuration
15
+ * @returns `(req: Request) => Promise<Response>` handler
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // supabase/functions/ai-chat/index.ts
20
+ * import { createAIFunction } from '@donotdev/functions/supabase';
21
+ *
22
+ * const handler = createAIFunction({
23
+ * provider: 'anthropic',
24
+ * model: 'claude-sonnet-4-20250514',
25
+ * cost: { markup: 4.0, monthlyBudgetTokens: 500_000, showCostToUsers: false, displayCurrency: 'eur' },
26
+ * });
27
+ * Deno.serve(handler);
28
+ * ```
29
+ */
30
+ export declare function createAIFunction(config: AIRouteConfig): (req: Request) => Promise<Response>;
@@ -10,7 +10,7 @@
10
10
  * Deno.serve(createRemoveCustomClaims());
11
11
  * ```
12
12
  *
13
- * @version 0.1.0
13
+ * @version 0.2.0
14
14
  * @since 0.6.0
15
15
  */
16
16
  export declare function createRemoveCustomClaims(): (req: Request) => Promise<Response>;
@@ -1,18 +1,26 @@
1
+ /** Options for the set-custom-claims edge function factory. */
2
+ export interface SetCustomClaimsOptions {
3
+ /** Explicit allowlist of claim keys users may set on themselves. Required. */
4
+ allowedClaimKeys: string[];
5
+ }
1
6
  /**
2
7
  * Create a Supabase Edge Function handler for setting custom claims (app_metadata).
3
8
  *
4
- * Merges provided claims into the user's existing app_metadata.
9
+ * Consumers MUST specify which claim keys are self-assignable.
10
+ * The framework enforces a blocklist as a safety net even if the consumer
11
+ * accidentally includes a privilege key.
5
12
  *
13
+ * @param options - Configuration with allowedClaimKeys
6
14
  * @returns `(req: Request) => Promise<Response>` handler
7
15
  *
8
16
  * @example
9
17
  * ```typescript
10
18
  * // supabase/functions/set-custom-claims/index.ts
11
19
  * import { createSetCustomClaims } from '@donotdev/functions/supabase';
12
- * Deno.serve(createSetCustomClaims());
20
+ * Deno.serve(createSetCustomClaims({ allowedClaimKeys: ['theme', 'locale'] }));
13
21
  * ```
14
22
  *
15
- * @version 0.1.0
23
+ * @version 0.2.0
16
24
  * @since 0.6.0
17
25
  */
18
- export declare function createSetCustomClaims(): (req: Request) => Promise<Response>;
26
+ export declare function createSetCustomClaims(options: SetCustomClaimsOptions): (req: Request) => Promise<Response>;
@@ -1,4 +1,4 @@
1
- import type { StripeBackConfig } from '@donotdev/core/server';
1
+ import { type StripeBackConfig } from '@donotdev/core/server';
2
2
  /**
3
3
  * Create a Supabase Edge Function handler for plan changes.
4
4
  *
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import * as v from 'valibot';
10
10
  import type { UserRole } from '@donotdev/core/server';
11
+ /** Request payload for aggregate operations (COUNT, SUM, AVG, MIN, MAX) on entities. */
11
12
  export type AggregateEntityRequest = {
12
13
  where?: Array<[string, any, any]>;
13
14
  aggregate: {
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import * as v from 'valibot';
10
10
  import type { UserRole } from '@donotdev/core/server';
11
+ /** Request payload for creating an entity with optional idempotency. */
11
12
  export type CreateEntityRequest = {
12
13
  payload: Record<string, any>;
13
14
  idempotencyKey?: string;
@@ -1,4 +1,5 @@
1
1
  import type { UserRole } from '@donotdev/core/server';
2
+ /** Request payload for deleting a single entity by ID. */
2
3
  export type DeleteEntityRequest = {
3
4
  id: string;
4
5
  };
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import * as v from 'valibot';
10
10
  import type { EntityOwnershipConfig, UserRole } from '@donotdev/core/server';
11
+ /** Request payload for retrieving a single entity by ID. */
11
12
  export type GetEntityRequest = {
12
13
  id: string;
13
14
  };
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import * as v from 'valibot';
10
10
  import type { EntityOwnershipConfig, UserRole } from '@donotdev/core/server';
11
+ /** Request payload for listing entities with filtering, sorting, and pagination. */
11
12
  export interface ListEntityRequest {
12
13
  where?: Array<[string, any, any]>;
13
14
  orderBy?: Array<[string, 'asc' | 'desc']>;
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import * as v from 'valibot';
10
10
  import type { UserRole } from '@donotdev/core/server';
11
+ /** Request payload for updating an entity by ID with optional idempotency. */
11
12
  export type UpdateEntityRequest = {
12
13
  id: string;
13
14
  payload: Record<string, any>;
@@ -0,0 +1,56 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
2
+ /**
3
+ * Context passed to edge function handlers.
4
+ *
5
+ * @version 0.1.0
6
+ * @since 0.6.0
7
+ */
8
+ export interface EdgeFunctionContext {
9
+ /** Authenticated user (null if no valid JWT or requireAuth=false) */
10
+ user: {
11
+ id: string;
12
+ email?: string;
13
+ } | null;
14
+ /** Admin client (service role, bypasses RLS) - always available */
15
+ supabaseAdmin: SupabaseClient;
16
+ /** User-scoped client (RLS) - null if no valid JWT */
17
+ userClient: SupabaseClient | null;
18
+ /** JSON response with CORS headers */
19
+ json: (data: unknown, status?: number) => Response;
20
+ /** JSON error response: { error: message } with CORS headers */
21
+ error: (message: string, status?: number) => Response;
22
+ /** Raw response with CORS headers (for structured payloads) */
23
+ respond: (data: unknown, status: number) => Response;
24
+ }
25
+ /** Configuration options for edge function creation. */
26
+ export interface EdgeFunctionOptions {
27
+ /** Require JWT auth - returns 401 if missing/invalid (default: true) */
28
+ requireAuth?: boolean;
29
+ /** Extra CORS allowed headers (e.g., 'stripe-signature', 'x-build-secret') */
30
+ extraHeaders?: string[];
31
+ }
32
+ /**
33
+ * Create a Supabase Edge Function handler with CORS, optional auth, and response helpers.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * // Auth required (default)
38
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
39
+ * const body = await req.json();
40
+ * return ctx.json({ result: 'ok' });
41
+ * }));
42
+ *
43
+ * // No auth (public endpoint)
44
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
45
+ * return ctx.json({ public: true });
46
+ * }, { requireAuth: false }));
47
+ *
48
+ * // Custom auth (webhook)
49
+ * Deno.serve(createEdgeFunction(async (req, ctx) => {
50
+ * const sig = req.headers.get('stripe-signature');
51
+ * if (!sig) return ctx.error('Missing signature', 401);
52
+ * return ctx.json({ received: true });
53
+ * }, { requireAuth: false, extraHeaders: ['stripe-signature'] }));
54
+ * ```
55
+ */
56
+ export declare function createEdgeFunction(handler: (req: Request, ctx: EdgeFunctionContext) => Promise<Response>, options?: EdgeFunctionOptions): (req: Request) => Promise<Response>;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @fileoverview Email Send - Supabase Edge Function Factory
3
+ * @description Wraps the shared email handler for Supabase Edge Functions.
4
+ * Resolves Resend provider from env, adds auth context.
5
+ *
6
+ * @version 0.1.0
7
+ * @since 0.1.0
8
+ * @author AMBROISE PARK Consulting
9
+ */
10
+ import type { EmailRouteConfig } from '@donotdev/core/server';
11
+ /**
12
+ * Create a Supabase Edge Function handler for sending emails.
13
+ * Requires RESEND_API_KEY environment variable.
14
+ *
15
+ * @param config - Email route configuration (templates, defaultFrom)
16
+ * @returns `(req: Request) => Promise<Response>` handler
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * // supabase/functions/send-email/index.ts
21
+ * import { createEmailFunction } from '@donotdev/functions/supabase';
22
+ *
23
+ * const handler = createEmailFunction({
24
+ * provider: 'resend',
25
+ * defaultFrom: 'Frabled <noreply@frabled.com>',
26
+ * templates: { 'order-confirmation': orderConfirmationTemplate },
27
+ * });
28
+ * Deno.serve(handler);
29
+ * ```
30
+ */
31
+ export declare function createEmailFunction(config: EmailRouteConfig): (req: Request) => Promise<Response>;
@@ -8,9 +8,12 @@
8
8
  */
9
9
  export { createSupabaseHandler } from './baseFunction.js';
10
10
  export type { SupabaseHandlerContext } from './baseFunction.js';
11
+ export { createEdgeFunction } from './edgeFunction.js';
12
+ export type { EdgeFunctionContext, EdgeFunctionOptions } from './edgeFunction.js';
11
13
  export { createSupabaseAuthProvider } from './helpers/authProvider.js';
12
14
  export { createDeleteAccount } from './auth/deleteAccount.js';
13
15
  export { createSetCustomClaims } from './auth/setCustomClaims.js';
16
+ export type { SetCustomClaimsOptions } from './auth/setCustomClaims.js';
14
17
  export { createGetCustomClaims } from './auth/getCustomClaims.js';
15
18
  export { createRemoveCustomClaims } from './auth/removeCustomClaims.js';
16
19
  export { createGetUserAuthStatus } from './auth/getUserAuthStatus.js';
@@ -20,6 +23,11 @@ export { createChangePlan } from './billing/changePlan.js';
20
23
  export { createCustomerPortal } from './billing/createCustomerPortal.js';
21
24
  export { createRefreshSubscriptionStatus } from './billing/refreshSubscriptionStatus.js';
22
25
  export { createExchangeToken, createDisconnect, createRefreshToken, createGetConnections, } from './oauth/index.js';
26
+ export { createAIFunction } from './ai/createAIFunction.js';
27
+ export { resolveModelForTier } from '../shared/ai/resolveModelTier.js';
28
+ export { classifyAIError, mapClassifiedToHTTP } from '../shared/ai/classifyAIError.js';
29
+ export type { AIErrorCode, ClassifiedAIError } from '../shared/ai/classifyAIError.js';
30
+ export { createEmailFunction } from './email/createEmailFunction.js';
23
31
  export { createSupabaseGetEntity, createSupabaseCreateEntity, createSupabaseUpdateEntity, createSupabaseDeleteEntity, createSupabaseListEntities, createSupabaseAggregateEntities, } from './crud/index.js';
24
32
  export { createSupabaseCrudFunctions } from './registerCrudFunctions.js';
25
33
  export type { GetEntityRequest, CreateEntityRequest, UpdateEntityRequest, DeleteEntityRequest, ListEntityRequest, AggregateEntityRequest, ReferenceMetadata, } from './crud/index.js';