@donotdev/functions 0.2.1 → 0.2.3

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 (184) hide show
  1. package/README.md +2 -2
  2. package/lib/chunks/chunk-6NXIK35R.js +23 -0
  3. package/lib/chunks/chunk-6NXIK35R.js.map +7 -0
  4. package/lib/chunks/chunk-EZKRLLSQ.js +22 -0
  5. package/lib/chunks/chunk-EZKRLLSQ.js.map +7 -0
  6. package/lib/chunks/chunk-F3PHE627.js +22 -0
  7. package/lib/chunks/chunk-F3PHE627.js.map +7 -0
  8. package/lib/chunks/chunk-F3WBFWPO.js +151 -0
  9. package/lib/chunks/chunk-F3WBFWPO.js.map +7 -0
  10. package/lib/chunks/chunk-G5DRV3DH.js +22 -0
  11. package/lib/chunks/chunk-G5DRV3DH.js.map +7 -0
  12. package/lib/chunks/{chunk-5IPULSUX.js → chunk-GDIUOJMD.js} +2 -2
  13. package/lib/chunks/chunk-GDIUOJMD.js.map +7 -0
  14. package/lib/chunks/chunk-Q2WLRFOE.js +22 -0
  15. package/lib/chunks/chunk-Q2WLRFOE.js.map +7 -0
  16. package/lib/chunks/chunk-QXIOO2RL.js +22 -0
  17. package/lib/chunks/chunk-QXIOO2RL.js.map +7 -0
  18. package/lib/chunks/{chunk-3F4BWKQD.js → chunk-UH445BGK.js} +2 -2
  19. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  20. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  21. package/lib/chunks/chunk-W74UL7AY.js +22 -0
  22. package/lib/chunks/chunk-W74UL7AY.js.map +7 -0
  23. package/lib/chunks/{monitoring-E7JBYBHQ.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-SQISLOP5.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/server-NODQAE3F.js +22 -0
  26. package/lib/firebase/billing/index.d.ts +2 -2
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/index.d.ts +1 -1
  29. package/lib/firebase/index.js +1 -1
  30. package/lib/firebase/index.js.map +4 -4
  31. package/lib/firebase/registerCrudFunctions.d.ts +0 -5
  32. package/lib/shared/billing/checkoutPrice.d.ts +3 -6
  33. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  34. package/lib/shared/billing/createCheckout.d.ts +4 -4
  35. package/lib/shared/billing/firestoreIdempotency.d.ts +2 -2
  36. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  37. package/lib/shared/billing/idempotency.d.ts +3 -23
  38. package/lib/shared/billing/idempotencyContract.d.ts +0 -20
  39. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  40. package/lib/shared/billing/stripePinned.d.ts +43 -0
  41. package/lib/shared/denoEnv.d.ts +25 -0
  42. package/lib/shared/github.d.ts +0 -8
  43. package/lib/shared/index.js +1 -1
  44. package/lib/shared/logger.d.ts +14 -14
  45. package/lib/shared/utils/external/subscription.d.ts +0 -8
  46. package/lib/shared/utils/internal/auth.d.ts +1 -5
  47. package/lib/shared/utils.d.ts +12 -83
  48. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  49. package/lib/supabase/crud/create.d.ts +0 -8
  50. package/lib/supabase/crud/entityStore.d.ts +13 -0
  51. package/lib/supabase/crud/update.d.ts +0 -8
  52. package/lib/supabase/index.d.ts +1 -0
  53. package/lib/supabase/index.js +1 -1
  54. package/lib/supabase/index.js.map +4 -4
  55. package/lib/vercel/api/index.js +1 -1
  56. package/lib/vercel/api/index.js.map +3 -3
  57. package/package.json +9 -9
  58. package/src/firebase/auth/getCustomClaims.ts +2 -0
  59. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  60. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  61. package/src/firebase/auth/setCustomClaims.ts +3 -0
  62. package/src/firebase/baseFunction.ts +8 -4
  63. package/src/firebase/billing/changePlan.ts +6 -5
  64. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  65. package/src/firebase/billing/index.d.ts +0 -12
  66. package/src/firebase/billing/index.ts +0 -3
  67. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  68. package/src/firebase/billing/webhookHandler.ts +4 -4
  69. package/src/firebase/crud/aggregate.ts +41 -12
  70. package/src/firebase/crud/bulk.ts +7 -0
  71. package/src/firebase/crud/create.ts +21 -8
  72. package/src/firebase/crud/delete.ts +6 -1
  73. package/src/firebase/crud/get.ts +9 -2
  74. package/src/firebase/crud/list.ts +18 -8
  75. package/src/firebase/crud/update.ts +15 -7
  76. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  77. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  78. package/src/firebase/index.ts +0 -1
  79. package/src/firebase/oauth/disconnect.ts +2 -2
  80. package/src/firebase/oauth/exchangeToken.ts +6 -2
  81. package/src/firebase/oauth/getConnections.ts +3 -3
  82. package/src/firebase/oauth/githubAccess.ts +7 -4
  83. package/src/firebase/oauth/refreshToken.ts +3 -2
  84. package/src/firebase/registerCrudFunctions.ts +0 -19
  85. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  86. package/src/shared/__tests__/idempotency.test.ts +0 -32
  87. package/src/shared/__tests__/utils.test.ts +0 -25
  88. package/src/shared/ai/classifyAIError.ts +18 -10
  89. package/src/shared/ai/createAIRoute.ts +2 -1
  90. package/src/shared/ai/resolveModelTier.ts +2 -1
  91. package/src/shared/billing/__tests__/createCheckout.compat.test.ts +4 -110
  92. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  93. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  94. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  95. package/src/shared/billing/checkoutPrice.ts +7 -42
  96. package/src/shared/billing/checkoutValidation.ts +19 -2
  97. package/src/shared/billing/createCheckout.ts +59 -30
  98. package/src/shared/billing/firestoreIdempotency.ts +2 -21
  99. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  100. package/src/shared/billing/idempotency.ts +4 -54
  101. package/src/shared/billing/idempotencyContract.ts +0 -21
  102. package/src/shared/billing/orderWebhook.ts +69 -1
  103. package/src/shared/billing/stripeClient.ts +2 -1
  104. package/src/shared/billing/stripePinned.ts +71 -0
  105. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  106. package/src/shared/billing/webhookHandler.ts +5 -1
  107. package/src/shared/crud/bulkCore.ts +3 -2
  108. package/src/shared/denoEnv.ts +29 -0
  109. package/src/shared/email/createEmailRoute.ts +2 -2
  110. package/src/shared/errorHandling.ts +8 -8
  111. package/src/shared/firebase.ts +26 -9
  112. package/src/shared/github.ts +15 -5
  113. package/src/shared/logger.ts +37 -38
  114. package/src/shared/schema.ts +6 -10
  115. package/src/shared/utils/external/date.ts +4 -4
  116. package/src/shared/utils/external/subscription.ts +2 -89
  117. package/src/shared/utils/firebaseHelpers.ts +2 -0
  118. package/src/shared/utils/internal/auth.ts +1 -6
  119. package/src/shared/utils/internal/idempotency.ts +3 -0
  120. package/src/shared/utils/internal/monitoring.ts +6 -5
  121. package/src/shared/utils/internal/validation.ts +2 -0
  122. package/src/shared/utils/schemaValidation.ts +1 -0
  123. package/src/shared/utils/validation.ts +10 -20
  124. package/src/shared/utils.ts +12 -138
  125. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  126. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  127. package/src/supabase/auth/deleteAccount.ts +72 -5
  128. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  129. package/src/supabase/crud/aggregate.ts +85 -72
  130. package/src/supabase/crud/bulk.ts +3 -0
  131. package/src/supabase/crud/create.ts +13 -9
  132. package/src/supabase/crud/delete.ts +2 -1
  133. package/src/supabase/crud/entityStore.ts +1 -1
  134. package/src/supabase/crud/get.ts +2 -1
  135. package/src/supabase/crud/list.ts +23 -17
  136. package/src/supabase/crud/update.ts +9 -6
  137. package/src/supabase/edgeFunction.ts +2 -1
  138. package/src/supabase/email/createEmailFunction.ts +2 -1
  139. package/src/supabase/index.ts +1 -0
  140. package/src/supabase/oauth/exchangeToken.ts +1 -0
  141. package/src/supabase/oauth/getConnections.ts +1 -1
  142. package/src/supabase/oauth/refreshToken.ts +1 -0
  143. package/src/supabase/utils/idempotency.ts +1 -1
  144. package/src/supabase/utils/monitoring.ts +1 -0
  145. package/src/vercel/api/billing/change-plan.ts +6 -5
  146. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  147. package/src/vercel/api/crud/bulk.ts +7 -2
  148. package/src/vercel/api/crud/create.ts +6 -3
  149. package/src/vercel/api/crud/delete.ts +5 -2
  150. package/src/vercel/api/crud/get.ts +5 -2
  151. package/src/vercel/api/crud/list.ts +6 -3
  152. package/src/vercel/api/crud/update.ts +6 -3
  153. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  154. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  155. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  156. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  157. package/src/vercel/baseFunction.ts +5 -1
  158. package/lib/chunks/chunk-5IPULSUX.js.map +0 -7
  159. package/lib/chunks/chunk-6USHTJED.js +0 -22
  160. package/lib/chunks/chunk-6USHTJED.js.map +0 -7
  161. package/lib/chunks/chunk-CXBSROEW.js +0 -23
  162. package/lib/chunks/chunk-CXBSROEW.js.map +0 -7
  163. package/lib/chunks/chunk-GYTCWMXV.js +0 -22
  164. package/lib/chunks/chunk-GYTCWMXV.js.map +0 -7
  165. package/lib/chunks/chunk-LCDLG4VG.js +0 -151
  166. package/lib/chunks/chunk-LCDLG4VG.js.map +0 -7
  167. package/lib/chunks/chunk-MQANUSY3.js +0 -22
  168. package/lib/chunks/chunk-MQANUSY3.js.map +0 -7
  169. package/lib/chunks/chunk-OFQVO3FD.js +0 -22
  170. package/lib/chunks/chunk-OFQVO3FD.js.map +0 -7
  171. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  172. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  173. package/lib/chunks/chunk-US2VOP4S.js +0 -22
  174. package/lib/chunks/chunk-US2VOP4S.js.map +0 -7
  175. package/lib/chunks/chunk-YTKDNZNW.js +0 -22
  176. package/lib/chunks/chunk-YTKDNZNW.js.map +0 -7
  177. package/lib/chunks/server-IQ5JNJOM.js +0 -22
  178. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  179. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  180. package/src/shared/utils/functionWrapper.ts +0 -73
  181. /package/lib/chunks/{chunk-3F4BWKQD.js.map → chunk-UH445BGK.js.map} +0 -0
  182. /package/lib/chunks/{monitoring-E7JBYBHQ.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  183. /package/lib/chunks/{rateLimiter-SQISLOP5.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  184. /package/lib/chunks/{server-IQ5JNJOM.js.map → server-NODQAE3F.js.map} +0 -0
@@ -32,9 +32,4 @@ export type CrudFunctions = Record<string, HttpsFunction>;
32
32
  * ```
33
33
  */
34
34
  export declare function createCrudFunctions(entities: Record<string, Entity | unknown>, options?: RegisterOptions): CrudFunctions;
35
- /**
36
- * @deprecated Use createCrudFunctions() for ESM. This mutates target which doesn't work in ESM.
37
- * Auto-register CRUD functions for all entities (CJS pattern)
38
- */
39
- export declare function registerCrudFunctions(entities: Record<string, Entity | unknown>, target?: Record<string, any>, options?: RegisterOptions): CrudFunctions;
40
35
  export {};
@@ -11,16 +11,13 @@ import type Stripe from 'stripe';
11
11
  import type { CheckoutMode, CheckoutSessionParams, CreateCheckoutSessionRequest, StripePaymentBackItem, StripeSubscriptionBackItem } from '@donotdev/core/server';
12
12
  /** Price resolved for a single-price item (0.1.x rules). */
13
13
  export interface PricePlan {
14
- /** Fixed price charged; undefined for dynamic pricing */
15
- priceId?: string;
16
- /** 0.1.x dynamic pricing (client unitAmount + productName) */
17
- dynamic: boolean;
14
+ /** Price charged */
15
+ priceId: string;
18
16
  mode: CheckoutMode;
19
17
  }
20
18
  /**
21
19
  * 0.1.x pricing for StripePayment/StripeSubscription: a request priceId (must
22
- * match the config priceId when set), else 0.1.x dynamic pricing capped by
23
- * `maxUnitAmount`, else the back-config priceId.
20
+ * match the config priceId when set), else the back-config priceId.
24
21
  */
25
22
  export declare function resolvePricePlan(item: StripePaymentBackItem | StripeSubscriptionBackItem, request: CreateCheckoutSessionRequest): PricePlan;
26
23
  /** 0.1.x params → Stripe params (what the 0.1.x Firebase/Supabase providers sent). */
@@ -32,7 +32,7 @@ export declare function validateCheckoutUrl(url: string, name: string): void;
32
32
  * Sanitize client metadata: enforce string values, strip script injection.
33
33
  * Length limits are checked on the final metadata ({@link assertStripeMetadata}).
34
34
  */
35
- export declare function sanitizeMetadata(metadata: Record<string, any>): Record<string, string>;
35
+ export declare function sanitizeMetadata(metadata: Record<string, unknown>): Record<string, string>;
36
36
  /**
37
37
  * Throw a validation error when metadata exceeds Stripe's limits
38
38
  * ({@link STRIPE_METADATA_LIMITS}), instead of letting Stripe answer 400.
@@ -2,7 +2,7 @@
2
2
  * @fileoverview Create Checkout Session Algorithm
3
3
  * @description Platform-agnostic algorithm for creating Stripe checkout sessions.
4
4
  * StripePayment/StripeSubscription items keep the 0.1.x behaviour (request or
5
- * back-config priceId, 0.1.x dynamic pricing). StripeOrder items are priced on
5
+ * back-config priceId). StripeOrder items are priced on
6
6
  * the server (`resolveLineItems`) and need a {@link StripeSessionProvider}.
7
7
  *
8
8
  * @version 0.2.0
@@ -64,11 +64,11 @@ export interface AuthCheckoutProvider {
64
64
  * Create checkout session algorithm
65
65
  *
66
66
  * 1. Resolve the billing config item and verify the user
67
- * 2. Single-price items: 0.1.x pricing (request/back-config priceId, dynamic pricing)
68
- * 3. `beforeCheckout` hook (block/allow; 0.1.x dynamic-pricing overrides)
67
+ * 2. Single-price items: 0.1.x pricing (request/back-config priceId)
68
+ * 3. `beforeCheckout` hook (block/allow)
69
69
  * 4. StripeOrder: reject inclusive manual Tax Rates, `resolveLineItems` prices every line
70
70
  * and may set per-order session options (`ResolvedOrder.session`: tax rates,
71
- * payment methods, expiry, invoice footer)
71
+ * payment methods, expiry, invoice footer, existing Stripe customer)
72
72
  * 5. Validate metadata against Stripe limits, create the session through the provider
73
73
  *
74
74
  * Server-owned metadata (`userId`, `billingConfigKey`, `orderId`) is written after
@@ -1,4 +1,4 @@
1
- import type { LegacyIdempotencyStore } from './idempotencyContract.js';
1
+ import type { IdempotencyStore } from './idempotencyContract.js';
2
2
  /**
3
3
  * Firestore-backed store (transactions). Collection: `webhook_idempotency`.
4
4
  *
@@ -10,4 +10,4 @@ import type { LegacyIdempotencyStore } from './idempotencyContract.js';
10
10
  * @since 0.2.0
11
11
  * @author AMBROISE PARK Consulting
12
12
  */
13
- export declare function createFirestoreIdempotencyStore(): LegacyIdempotencyStore;
13
+ export declare function createFirestoreIdempotencyStore(): IdempotencyStore;
@@ -1,4 +1,4 @@
1
- import type { BillingAuthProvider } from '@donotdev/core/server';
1
+ import type { BillingAuthProvider, StripeBackConfig } from '@donotdev/core/server';
2
2
  /**
3
3
  * Cancel user subscription at period end
4
4
  *
@@ -17,7 +17,7 @@ export declare function cancelUserSubscription(userId: string, authProvider: Bil
17
17
  * @since 0.0.1
18
18
  * @author AMBROISE PARK Consulting
19
19
  */
20
- export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: Record<string, any>, authProvider: BillingAuthProvider): Promise<{
20
+ export declare function changeUserPlan(userId: string, newPriceId: string, billingConfigKey: string, billingConfig: StripeBackConfig, authProvider: BillingAuthProvider): Promise<{
21
21
  success: boolean;
22
22
  newTier: string;
23
23
  newPrice: number;
@@ -1,6 +1,6 @@
1
- import type { LegacyIdempotencyStore } from './idempotencyContract.js';
1
+ import type { IdempotencyStore } from './idempotencyContract.js';
2
2
  export { RESERVATION_LEASE_MS, ReservationLostError, WEBHOOK_EVENT_RETENTION_MS, } from './idempotencyContract.js';
3
- export type { IdempotencyStore, LegacyIdempotencyStore, ReservationResult, } from './idempotencyContract.js';
3
+ export type { IdempotencyStore, ReservationResult, } from './idempotencyContract.js';
4
4
  export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
5
5
  /**
6
6
  * In-memory store. Single process only: for tests, never for a deployed webhook.
@@ -9,25 +9,5 @@ export { createFirestoreIdempotencyStore } from './firestoreIdempotency.js';
9
9
  * @since 0.2.0
10
10
  * @author AMBROISE PARK Consulting
11
11
  */
12
- export declare function createInMemoryIdempotencyStore(): LegacyIdempotencyStore;
13
- /**
14
- * 0.1.x store auto-detection: Firestore when configured, else in-memory.
15
- *
16
- * @deprecated In-memory is not durable across instances. Pass an explicit store:
17
- * {@link createFirestoreIdempotencyStore} or `createSupabaseIdempotencyStore`.
18
- * Framework webhook entry points already do.
19
- * @version 0.2.0
20
- * @since 0.0.1
21
- * @author AMBROISE PARK Consulting
22
- */
23
- export declare function createIdempotencyStore(): LegacyIdempotencyStore;
24
- /**
25
- * Reset the store cached by {@link createIdempotencyStore} (tests).
26
- *
27
- * @deprecated See {@link createIdempotencyStore}.
28
- * @version 0.1.0
29
- * @since 0.0.1
30
- * @author AMBROISE PARK Consulting
31
- */
32
- export declare function resetIdempotencyStore(): void;
12
+ export declare function createInMemoryIdempotencyStore(): IdempotencyStore;
33
13
  export { WEBHOOK_EVENTS_SQL, createSupabaseIdempotencyStore, } from './supabaseIdempotency.js';
@@ -48,26 +48,6 @@ export interface IdempotencyStore {
48
48
  */
49
49
  release(eventId: string, ownerToken: string): Promise<boolean>;
50
50
  }
51
- /**
52
- * Store with the 0.1.x accessors.
53
- *
54
- * @deprecated Use {@link IdempotencyStore}: `reserve` returns three states and
55
- * an owner token; `checkAndReserve` and `isProcessed` do not.
56
- * @version 0.2.0
57
- * @since 0.2.0
58
- * @author AMBROISE PARK Consulting
59
- */
60
- export interface LegacyIdempotencyStore extends IdempotencyStore {
61
- /** 0.1.x: `true` when the event must be skipped (processed or live lease). */
62
- checkAndReserve(eventId: string): Promise<boolean>;
63
- /** Whether the event was processed (non-atomic read). */
64
- isProcessed(eventId: string): Promise<boolean>;
65
- /**
66
- * Mark processed. Without `ownerToken` (0.1.x call) the write is unconditional.
67
- * @throws {ReservationLostError} When `ownerToken` is given and no longer owns the event
68
- */
69
- markProcessed(eventId: string, ownerToken?: string): Promise<void>;
70
- }
71
51
  /**
72
52
  * Thrown by `markProcessed` when the caller no longer owns the reservation:
73
53
  * its lease expired and another delivery retook the event, or the row is gone.
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * @fileoverview StripeOrder webhook handling
3
3
  * @description Maps Checkout Session events of one-time, multi-line orders to the
4
- * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`).
4
+ * app's order hooks (`onOrderPaid`, `onOrderPaymentFailed`, `onOrderExpired`), and
5
+ * `customer.tax_id.updated` to `onTaxIdUpdated`.
5
6
  * Hook errors propagate: the webhook answers non-2xx and Stripe retries.
6
7
  *
7
8
  * @version 0.2.0
@@ -9,7 +10,7 @@
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
11
12
  import type Stripe from 'stripe';
12
- import type { CheckoutSessionSnapshot, PaidLineItem, StripeOrderBackItem } from '@donotdev/core/server';
13
+ import type { CheckoutSessionSnapshot, PaidLineItem, StripeBackConfig, StripeOrderBackItem, TaxIdSnapshot } from '@donotdev/core/server';
13
14
  /**
14
15
  * Checkout Session events that concern orders.
15
16
  *
@@ -73,3 +74,29 @@ export declare function listPaidLineItems(stripe: Stripe, sessionId: string): Pr
73
74
  * @author AMBROISE PARK Consulting
74
75
  */
75
76
  export declare function handleOrderSessionEvent(eventType: OrderSessionEventType, eventId: string, apiVersion: string | null, session: Stripe.Checkout.Session, billingConfigKey: string, orderItem: StripeOrderBackItem, stripe: Stripe): Promise<void>;
77
+ /**
78
+ * Map a Stripe TaxId to the provider-neutral snapshot given to `onTaxIdUpdated`.
79
+ *
80
+ * @param taxId - TaxId from a `customer.tax_id.updated` event
81
+ * @returns Snapshot
82
+ *
83
+ * @version 0.2.0
84
+ * @since 0.2.3
85
+ * @author AMBROISE PARK Consulting
86
+ */
87
+ export declare function toTaxIdSnapshot(taxId: Stripe.TaxId): TaxIdSnapshot;
88
+ /**
89
+ * Handle `customer.tax_id.updated`: run `onTaxIdUpdated` of every StripeOrder item
90
+ * that defines it, once per distinct function. Called by `processWebhook` after
91
+ * signature verification and idempotency reservation (same path as order events).
92
+ *
93
+ * @param eventId - Stripe event ID
94
+ * @param taxId - TaxId from the event
95
+ * @param config - App back config
96
+ * @throws When a hook throws (the webhook answers non-2xx and Stripe retries)
97
+ *
98
+ * @version 0.2.0
99
+ * @since 0.2.3
100
+ * @author AMBROISE PARK Consulting
101
+ */
102
+ export declare function handleTaxIdUpdated(eventId: string, taxId: Stripe.TaxId, config: StripeBackConfig): Promise<void>;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @fileoverview Typed access to Stripe fields of the pinned API version
3
+ * @description The Stripe SDK types follow the latest API version only, while
4
+ * requests run at `STRIPE_API_VERSION_PIN` (pre-basil). Fields that basil
5
+ * moved (subscription period, invoice subscription) are read here, through one
6
+ * documented cast, instead of `as any` at every call site. Internal: not
7
+ * re-exported from any package entry.
8
+ *
9
+ * @version 0.1.0
10
+ * @since 0.2.2
11
+ * @author AMBROISE PARK Consulting
12
+ */
13
+ import type Stripe from 'stripe';
14
+ /** Subscription fields present at `STRIPE_API_VERSION_PIN`, dropped from the latest SDK types. */
15
+ interface PinnedSubscriptionFields {
16
+ current_period_start: number;
17
+ current_period_end: number;
18
+ }
19
+ /**
20
+ * Period fields of a subscription at the pinned API version.
21
+ *
22
+ * @version 0.1.0
23
+ * @since 0.2.2
24
+ * @author AMBROISE PARK Consulting
25
+ */
26
+ export declare function pinnedSubscriptionPeriod(subscription: Stripe.Subscription): PinnedSubscriptionFields;
27
+ /**
28
+ * Subscription id of an invoice at the pinned API version.
29
+ *
30
+ * @version 0.1.0
31
+ * @since 0.2.2
32
+ * @author AMBROISE PARK Consulting
33
+ */
34
+ export declare function pinnedInvoiceSubscriptionId(invoice: Stripe.Invoice): string | null;
35
+ /**
36
+ * Narrows a value to one of a readonly list of literals.
37
+ *
38
+ * @version 0.1.0
39
+ * @since 0.2.2
40
+ * @author AMBROISE PARK Consulting
41
+ */
42
+ export declare function isOneOf<T extends string>(values: readonly T[], value: string): value is T;
43
+ export {};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @fileoverview Typed access to the Deno env from cross-runtime code
3
+ * @description Supabase Edge Functions run on Deno, Firebase/Vercel on Node.
4
+ * This package compiles against the Node lib types, which have no `Deno`
5
+ * global. Internal: not re-exported from any package entry.
6
+ *
7
+ * @version 0.1.0
8
+ * @since 0.2.2
9
+ * @author AMBROISE PARK Consulting
10
+ */
11
+ /** The part of the Deno namespace read by this package. */
12
+ interface DenoEnvNamespace {
13
+ env?: {
14
+ get(key: string): string | undefined;
15
+ };
16
+ }
17
+ /**
18
+ * Deno env accessor, when running on Deno.
19
+ *
20
+ * @version 0.1.0
21
+ * @since 0.2.2
22
+ * @author AMBROISE PARK Consulting
23
+ */
24
+ export declare function getDenoEnv(): DenoEnvNamespace['env'];
25
+ export {};
@@ -1,11 +1,3 @@
1
- /**
2
- * @fileoverview GitHub API Service for functions
3
- * @description Server-safe GitHub API utilities for repository management
4
- *
5
- * @version 0.1.0
6
- * @since 0.0.1
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  /** Configuration for authenticating with the GitHub API. */
10
2
  export interface GitHubApiConfig {
11
3
  accessToken: string;
@@ -18,5 +18,5 @@ if (typeof globalThis !== 'undefined') {
18
18
  globalThis.global = globalThis;
19
19
  }
20
20
  }
21
- import{A as E,B as F,C as G,D as O,E as P,F as Q,G as aa,H as ba,I as ca,J as Da,K as Ea,L as Fa,M as Ga,N as Ha,O as Ia,P as Ja,a as c,b as d,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y,v as z,w as A,x as B,y as C,z as D}from"../chunks/chunk-US2VOP4S.js";import{c as va,d as ya,e as za,f as Aa}from"../chunks/chunk-YTKDNZNW.js";import{a as e,b as f,c as da,d as Ba,e as Ca}from"../chunks/chunk-MQANUSY3.js";import{B as ua,C as wa,D as xa,a as b,b as H,c as I,d as J,e as K,f as L,g as M,h as N,i as ea,j as fa,k as ga,l as ha,m as ia,p as ja,q as ka,r as la,s as ma,t as na,u as oa,v as pa,w as qa,x as ra,y as sa,z as ta}from"../chunks/chunk-LCDLG4VG.js";import"../chunks/chunk-CXBSROEW.js";import{L as a}from"../chunks/chunk-GYTCWMXV.js";import{a as R,b as S,c as T,d as U,e as V}from"../chunks/chunk-5IPULSUX.js";import{a as W,b as X,c as Y,d as Z,e as _,f as $}from"../chunks/chunk-3F4BWKQD.js";import"../chunks/chunk-PWAGW4R6.js";import"../chunks/chunk-AYY7UXNI.js";export{H as AuthBackendSchema,$ as DEFAULT_RATE_LIMITS,a as DoNotDevError,c as GitHubApiService,ja as MIN_ORDER_API_VERSION,ka as ORDER_ID_METADATA_KEY,la as PRODUCT_ID_METADATA_KEY,sa as RESERVATION_LEASE_MS,ra as ReservationLostError,j as StripeValidationSchemas,wa as WEBHOOK_EVENTS_SQL,ta as WEBHOOK_EVENT_RETENTION_MS,K as assertAdmin,J as assertAuthenticated,ea as calculateCost,C as calculateSubscriptionEndDate,F as cancelUserSubscription,P as checkIdempotency,S as checkPaymentFailureRate,T as checkPaymentVolume,W as checkRateLimit,X as checkRateLimitWithFirestore,ha as classifyAIError,V as cleanupOldMetrics,pa as createCheckoutAlgorithm,x as createFirebaseCallable,v as createFirebaseFunction,y as createFirebaseFunctionExports,va as createFirestoreIdempotencyStore,d as createGitHubApiService,za as createIdempotencyStore,ya as createInMemoryIdempotencyStore,e as createMetadata,Ca as createResendProvider,xa as createSupabaseIdempotencyStore,Fa as createTimestamp,A as createVercelApiHandler,w as createVercelFunction,z as createVercelHandler,Da as exchangeTokenAlgorithm,da as executeBulk,i as filterVisibleFields,D as findReferences,U as getPaymentMetricsSummary,_ as getRateLimitStatus,E as getTierFromPriceId,G as getUserSubscription,h as getVisibleFields,Ea as grantAccessAlgorithm,fa as handleAIRequest,Ba as handleEmailRequest,b as handleError,oa as handleOrderSessionEvent,O as initializeFirebaseAdmin,g as isFieldVisible,Ha as isTimestamp,na as listPaidLineItems,ia as mapClassifiedToHTTP,I as parseAuthBackend,Ja as prepareForFirestore,ua as processWebhook,R as recordPaymentMetrics,Aa as resetIdempotencyStore,Y as resetRateLimit,Z as resetRateLimitInFirestore,ga as resolveModelForTier,aa as safeJsonParse,Q as storeIdempotencyResult,ma as toCheckoutSessionSnapshot,B as toISOString,Ga as toTimestamp,Ia as transformFirestoreData,f as updateMetadata,qa as updateUserSubscription,ba as validateCollectionName,ca as validateDocument,n as validateEmail,m as validateGitHubUsername,r as validateMetadata,l as validatePurchaseRequest,s as validateRequestData,o as validateStripePriceId,p as validateStripeSessionId,q as validateUrl,k as validateWebhookEvent,M as verifyAuthToken,N as verifyFirebaseAuthToken,L as verifyToken,t as withSchemaValidation,u as withVercelSchemaValidation};
21
+ import{A as E,B as F,C as G,D as N,E as O,F as P,G as $,H as aa,I as ba,J as Ca,K as Da,L as Ea,M as Fa,N as Ga,O as Ha,P as Ia,a as c,b as d,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y,v as z,w as A,x as B,y as C,z as D}from"../chunks/chunk-Q2WLRFOE.js";import{a as H,b as I,c as J,d as K,e as L,f as M,g as wa,h as za}from"../chunks/chunk-EZKRLLSQ.js";import{a as e,b as f,c as ca,d as Aa,e as Ba}from"../chunks/chunk-G5DRV3DH.js";import{A as ya,a as b,b as da,d as ea,e as fa,f as ga,g as ha,j as ia,k as ja,l as ka,m as la,n as ma,o as na,p as oa,q as pa,r as qa,s as ra,t as sa,u as ta,v as ua,y as va,z as xa}from"../chunks/chunk-F3WBFWPO.js";import"../chunks/chunk-6NXIK35R.js";import{N as a}from"../chunks/chunk-W74UL7AY.js";import{a as Q,b as R,c as S,d as T,e as U}from"../chunks/chunk-GDIUOJMD.js";import{a as V,b as W,c as X,d as Y,e as Z,f as _}from"../chunks/chunk-UH445BGK.js";import"../chunks/chunk-W6W4L44F.js";import"../chunks/chunk-AYY7UXNI.js";export{H as AuthBackendSchema,_ as DEFAULT_RATE_LIMITS,a as DoNotDevError,c as GitHubApiService,ia as MIN_ORDER_API_VERSION,ja as ORDER_ID_METADATA_KEY,ka as PRODUCT_ID_METADATA_KEY,ta as RESERVATION_LEASE_MS,sa as ReservationLostError,j as StripeValidationSchemas,xa as WEBHOOK_EVENTS_SQL,ua as WEBHOOK_EVENT_RETENTION_MS,K as assertAdmin,J as assertAuthenticated,da as calculateCost,C as calculateSubscriptionEndDate,F as cancelUserSubscription,O as checkIdempotency,R as checkPaymentFailureRate,S as checkPaymentVolume,V as checkRateLimit,W as checkRateLimitWithFirestore,ga as classifyAIError,U as cleanupOldMetrics,qa as createCheckoutAlgorithm,x as createFirebaseCallable,v as createFirebaseFunction,y as createFirebaseFunctionExports,wa as createFirestoreIdempotencyStore,d as createGitHubApiService,za as createInMemoryIdempotencyStore,e as createMetadata,Ba as createResendProvider,ya as createSupabaseIdempotencyStore,Ea as createTimestamp,A as createVercelApiHandler,w as createVercelFunction,z as createVercelHandler,Ca as exchangeTokenAlgorithm,ca as executeBulk,i as filterVisibleFields,D as findReferences,T as getPaymentMetricsSummary,Z as getRateLimitStatus,E as getTierFromPriceId,G as getUserSubscription,h as getVisibleFields,Da as grantAccessAlgorithm,ea as handleAIRequest,Aa as handleEmailRequest,b as handleError,na as handleOrderSessionEvent,pa as handleTaxIdUpdated,N as initializeFirebaseAdmin,g as isFieldVisible,Ga as isTimestamp,ma as listPaidLineItems,ha as mapClassifiedToHTTP,I as parseAuthBackend,Ia as prepareForFirestore,va as processWebhook,Q as recordPaymentMetrics,X as resetRateLimit,Y as resetRateLimitInFirestore,fa as resolveModelForTier,$ as safeJsonParse,P as storeIdempotencyResult,la as toCheckoutSessionSnapshot,B as toISOString,oa as toTaxIdSnapshot,Fa as toTimestamp,Ha as transformFirestoreData,f as updateMetadata,ra as updateUserSubscription,aa as validateCollectionName,ba as validateDocument,n as validateEmail,m as validateGitHubUsername,r as validateMetadata,l as validatePurchaseRequest,s as validateRequestData,o as validateStripePriceId,p as validateStripeSessionId,q as validateUrl,k as validateWebhookEvent,M as verifyAuthToken,L as verifyToken,t as withSchemaValidation,u as withVercelSchemaValidation};
22
22
  //# sourceMappingURL=index.js.map
@@ -15,9 +15,9 @@ export interface LogEntry {
15
15
  level: LogLevel;
16
16
  message: string;
17
17
  timestamp: string;
18
- context?: Record<string, any>;
18
+ context?: Record<string, unknown>;
19
19
  error?: Error;
20
- metadata?: Record<string, any>;
20
+ metadata?: Record<string, unknown>;
21
21
  }
22
22
  /**
23
23
  * Server-side logger with Sentry integration
@@ -56,7 +56,7 @@ export declare const logger: {
56
56
  * @since 0.0.1
57
57
  * @author AMBROISE PARK Consulting
58
58
  */
59
- debug(message: string, context?: Record<string, any>): void;
59
+ debug(message: string, context?: Record<string, unknown>): void;
60
60
  /**
61
61
  * Log informational messages
62
62
  * @param message - Log message
@@ -66,7 +66,7 @@ export declare const logger: {
66
66
  * @since 0.0.1
67
67
  * @author AMBROISE PARK Consulting
68
68
  */
69
- info(message: string, context?: Record<string, any>): void;
69
+ info(message: string, context?: Record<string, unknown>): void;
70
70
  /**
71
71
  * Log warning messages
72
72
  * @param message - Log message
@@ -76,7 +76,7 @@ export declare const logger: {
76
76
  * @since 0.0.1
77
77
  * @author AMBROISE PARK Consulting
78
78
  */
79
- warn(message: string, context?: Record<string, any>): void;
79
+ warn(message: string, context?: Record<string, unknown>): void;
80
80
  /**
81
81
  * Log error messages with Sentry integration
82
82
  * @param message - Log message
@@ -86,7 +86,7 @@ export declare const logger: {
86
86
  * @since 0.0.1
87
87
  * @author AMBROISE PARK Consulting
88
88
  */
89
- error(message: string, context?: Record<string, any>): Promise<void>;
89
+ error(message: string, context?: Record<string, unknown>): Promise<void>;
90
90
  /**
91
91
  * Log fatal errors with Sentry integration
92
92
  * @param message - Log message
@@ -96,7 +96,7 @@ export declare const logger: {
96
96
  * @since 0.0.1
97
97
  * @author AMBROISE PARK Consulting
98
98
  */
99
- fatal(message: string, context?: Record<string, any>): Promise<void>;
99
+ fatal(message: string, context?: Record<string, unknown>): Promise<void>;
100
100
  /**
101
101
  * Core logging method
102
102
  * @param level - Log level
@@ -109,7 +109,7 @@ export declare const logger: {
109
109
  * @since 0.0.1
110
110
  * @author AMBROISE PARK Consulting
111
111
  */
112
- log(level: LogLevel, message: string, context?: Record<string, any>): void;
112
+ log(level: LogLevel, message: string, context?: Record<string, unknown>): void;
113
113
  /**
114
114
  * Check if Sentry is enabled
115
115
  * @returns True if Sentry is available and configured
@@ -126,10 +126,10 @@ export declare const logger: {
126
126
  * @param context - Additional context to include in all logs
127
127
  * @returns Child logger instance
128
128
  */
129
- export declare function createChildLogger(context: Record<string, any>): {
130
- debug: (message: string, additionalContext?: Record<string, any>) => void;
131
- info: (message: string, additionalContext?: Record<string, any>) => void;
132
- warn: (message: string, additionalContext?: Record<string, any>) => void;
133
- error: (message: string, additionalContext?: Record<string, any>) => Promise<void>;
134
- fatal: (message: string, additionalContext?: Record<string, any>) => Promise<void>;
129
+ export declare function createChildLogger(context: Record<string, unknown>): {
130
+ debug: (message: string, additionalContext?: Record<string, unknown>) => void;
131
+ info: (message: string, additionalContext?: Record<string, unknown>) => void;
132
+ warn: (message: string, additionalContext?: Record<string, unknown>) => void;
133
+ error: (message: string, additionalContext?: Record<string, unknown>) => Promise<void>;
134
+ fatal: (message: string, additionalContext?: Record<string, unknown>) => Promise<void>;
135
135
  };
@@ -15,14 +15,6 @@ import type { SubscriptionClaims } from '@donotdev/core/server';
15
15
  * @author AMBROISE PARK Consulting
16
16
  */
17
17
  export declare function getTierFromPriceId(priceId: string): string;
18
- /**
19
- * Validates subscription status and updates Firebase custom claims
20
- *
21
- * @version 0.1.0
22
- * @since 0.0.1
23
- * @author AMBROISE PARK Consulting
24
- */
25
- export declare function updateFirebaseUserSubscription(firebaseUid: string, subscription: any): Promise<void>;
26
18
  /**
27
19
  * Cancels user subscription and resets to free tier
28
20
  *
@@ -45,7 +45,7 @@ export declare function parseAuthBackend(backend: unknown): AuthProvider;
45
45
  * @since 0.0.1
46
46
  * @author AMBROISE PARK Consulting
47
47
  */
48
- export declare function assertAuthenticated(uid: string): string;
48
+ export declare function assertAuthenticated(uid: string | undefined): string;
49
49
  /**
50
50
  * Validates that user has admin privileges.
51
51
  * Uses IServerAuthAdapter when configured, falls back to Firebase Admin SDK.
@@ -88,7 +88,3 @@ export declare function verifyToken(token: string, provider?: AuthProvider): Pro
88
88
  * @author AMBROISE PARK Consulting
89
89
  */
90
90
  export declare function verifyAuthToken(req: NextApiRequest, provider?: AuthProvider): Promise<string>;
91
- /**
92
- * @deprecated Use verifyAuthToken instead. Kept for backwards compatibility.
93
- */
94
- export declare const verifyFirebaseAuthToken: typeof verifyAuthToken;
@@ -1,21 +1,15 @@
1
- import { DoNotDevError } from '@donotdev/core/server';
2
- import type { UserRole } from '@donotdev/core/server';
3
- export { DoNotDevError };
4
1
  /**
5
- * Assert that a user is authenticated from a Firebase callable auth context.
6
- *
7
- * @deprecated Import `assertAuthenticated` from `@donotdev/functions/shared/utils/internal/auth` instead.
8
- * This wrapper extracts uid from a Firebase callable auth context and delegates
9
- * to the canonical version.
10
- *
11
- * @param auth - Firebase callable request auth context (object with `.uid`)
12
- * @returns The authenticated user's uid
2
+ * @fileoverview Shared utilities for Firebase and Vercel functions
3
+ * @description Common utilities that can be used by both Firebase and Vercel function implementations
13
4
  *
14
5
  * @version 0.1.0
15
6
  * @since 0.0.1
16
7
  * @author AMBROISE PARK Consulting
17
8
  */
18
- export declare function assertAuthenticated(auth: any): string;
9
+ import * as v from 'valibot';
10
+ import { DoNotDevError } from '@donotdev/core/server';
11
+ import type { UserRole } from '@donotdev/core/server';
12
+ export { DoNotDevError };
19
13
  /**
20
14
  * Get user role from Firebase auth context
21
15
  *
@@ -32,7 +26,10 @@ export declare function assertAuthenticated(auth: any): string;
32
26
  * @since 0.0.1
33
27
  * @author AMBROISE PARK Consulting
34
28
  */
35
- export declare function getUserRole(auth: any): UserRole;
29
+ export declare function getUserRole(auth: {
30
+ uid?: string;
31
+ token?: Record<string, unknown>;
32
+ } | null | undefined): UserRole;
36
33
  /**
37
34
  * Creates a standardized success response
38
35
  *
@@ -56,77 +53,9 @@ export declare function createErrorResponse(error: unknown): {
56
53
  error: {
57
54
  code: string;
58
55
  message: string;
59
- details?: any;
56
+ details?: Record<string, unknown>;
60
57
  };
61
58
  };
62
- /**
63
- * Updates user subscription in Firebase.
64
- *
65
- * **Architecture decision — throwing stubs for billing functions:**
66
- * These subscription functions (`updateUserSubscription`, `getUserSubscription`,
67
- * `cancelUserSubscription`, `handleSubscriptionCancellation`) are intentional
68
- * placeholder implementations. They exist so the framework compiles and
69
- * type-checks out of the box, but throw at runtime to surface missing
70
- * integration early. Consumer apps replace them with their billing provider
71
- * integration (Stripe, Paddle, LemonSqueezy, etc.) via the documented
72
- * `shared/billing/helpers/` modules.
73
- *
74
- * C10: This was a silent no-op stub. It now throws to surface the missing
75
- * implementation at startup rather than silently dropping webhook events.
76
- * Use `updateUserSubscription` from `shared/billing/helpers/updateUserSubscription.ts`
77
- * (which requires an authProvider) instead.
78
- *
79
- * @deprecated Import `updateUserSubscription` from `@donotdev/functions/shared/billing/helpers/updateUserSubscription`.
80
- * @version 0.1.0
81
- * @since 0.0.1
82
- * @author AMBROISE PARK Consulting
83
- */
84
- export declare function updateUserSubscription(_firebaseUid: string, _subscription: any): Promise<void>;
85
- /**
86
- * Gets user subscription from Firebase.
87
- *
88
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
89
- *
90
- * @deprecated Import from `@donotdev/functions/shared/billing/helpers` or implement directly using Firebase Admin SDK / Stripe API.
91
- * @version 0.1.0
92
- * @since 0.0.1
93
- * @author AMBROISE PARK Consulting
94
- */
95
- export declare function getUserSubscription(_firebaseUid: string): Promise<any>;
96
- /**
97
- * Cancels user subscription.
98
- *
99
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
100
- *
101
- * @deprecated Import `cancelUserSubscription` from `@donotdev/functions/shared/billing/helpers/subscriptionManagement`.
102
- * @version 0.1.0
103
- * @since 0.0.1
104
- * @author AMBROISE PARK Consulting
105
- */
106
- export declare function cancelUserSubscription(_firebaseUid: string, _subscription: any): Promise<void>;
107
- /**
108
- * Handles subscription cancellation.
109
- *
110
- * C10: This was a silent no-op stub. Now throws to surface the missing implementation.
111
- *
112
- * @deprecated Handle via Stripe webhook events. Use `processWebhook` from `@donotdev/functions/shared/billing/webhookHandler`.
113
- * @version 0.1.0
114
- * @since 0.0.1
115
- * @author AMBROISE PARK Consulting
116
- */
117
- export declare function handleSubscriptionCancellation(_firebaseUid: string, _subscription: any): Promise<void>;
118
- /**
119
- * Asserts that a user has admin privileges
120
- * Uses role hierarchy: super > admin > user > guest
121
- *
122
- * @deprecated Import `assertAdmin` from `@donotdev/functions/shared/utils/internal/auth` instead.
123
- * This is a thin wrapper that delegates to the canonical provider-agnostic version.
124
- *
125
- * @version 0.1.0
126
- * @since 0.0.1
127
- * @author AMBROISE PARK Consulting
128
- */
129
- export declare function assertAdmin(uid: string): Promise<string>;
130
59
  /**
131
60
  * Validates document data
132
61
  *
@@ -134,7 +63,7 @@ export declare function assertAdmin(uid: string): Promise<string>;
134
63
  * @since 0.0.1
135
64
  * @author AMBROISE PARK Consulting
136
65
  */
137
- export declare function validateDocument(data: any, schema?: any): void;
66
+ export declare function validateDocument(data: unknown, schema?: v.GenericSchema): void;
138
67
  /**
139
68
  * Validates a Firestore collection name from client-supplied schema.
140
69
  *
@@ -1,6 +1,25 @@
1
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
2
+ /**
3
+ * Options for {@link createDeleteAccount}.
4
+ *
5
+ * @version 0.2.0
6
+ * @since 0.2.3
7
+ */
8
+ export interface DeleteAccountOptions {
9
+ /**
10
+ * Runs before the auth user is deleted (close the account, anonymize data, cancel
11
+ * subscriptions...). Throwing refuses the deletion: the user is NOT deleted and the
12
+ * client receives HTTP 409 `{ error: message, code }` (`code` when the thrown error
13
+ * carries a string `code`). The message and code reach the browser unmasked, so
14
+ * throw client-safe values only — a refusal code such as `open_orders` that the
15
+ * client translates under `auth:deleteAccount.errors.<code>` (see `useDeleteAccount`).
16
+ */
17
+ beforeDelete?: (ctx: SupabaseHandlerContext) => Promise<void>;
18
+ }
1
19
  /**
2
20
  * Create a Supabase Edge Function handler for account deletion.
3
21
  *
22
+ * @param options - Optional `beforeDelete` step; without it, deletes the user directly
4
23
  * @returns `(req: Request) => Promise<Response>` handler
5
24
  *
6
25
  * @example
@@ -10,7 +29,20 @@
10
29
  * Deno.serve(createDeleteAccount());
11
30
  * ```
12
31
  *
13
- * @version 0.1.0
32
+ * @example
33
+ * ```typescript
34
+ * // Refuse while the account still has open orders (the SQL function raises 'open_orders')
35
+ * Deno.serve(
36
+ * createDeleteAccount({
37
+ * beforeDelete: async ({ supabaseAdmin, uid }) => {
38
+ * const { error } = await supabaseAdmin.rpc('close_my_account', { p_uid: uid });
39
+ * if (error) throw error; // → 409 { error: 'open_orders', code: 'P0001' }
40
+ * },
41
+ * })
42
+ * );
43
+ * ```
44
+ *
45
+ * @version 0.2.0
14
46
  * @since 0.5.0
15
47
  */
16
- export declare function createDeleteAccount(): (req: Request) => Promise<Response>;
48
+ export declare function createDeleteAccount(options?: DeleteAccountOptions): (req: Request) => Promise<Response>;
@@ -1,11 +1,3 @@
1
- /**
2
- * @fileoverview Generic handler to create an entity in Supabase.
3
- * @description Provides a reusable implementation for creating documents in PostgreSQL with validation.
4
- *
5
- * @version 0.1.0
6
- * @since 0.5.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  import * as v from 'valibot';
10
2
  import type { UserRole } from '@donotdev/core/server';
11
3
  /** Request payload for creating an entity with optional idempotency. */
@@ -48,6 +48,19 @@ export interface EntityStore<Row> {
48
48
  /** Updates the rows matching `where` (hidden rows included) and returns them as stored. */
49
49
  update(where: readonly EntityStoreCondition[], patch: EntityStoreValues<Row>): Promise<Row[]>;
50
50
  }
51
+ /** The PostgREST filter builder methods the store uses. */
52
+ export interface Filterable {
53
+ eq(column: string, value: unknown): this;
54
+ neq(column: string, value: unknown): this;
55
+ gt(column: string, value: unknown): this;
56
+ gte(column: string, value: unknown): this;
57
+ lt(column: string, value: unknown): this;
58
+ lte(column: string, value: unknown): this;
59
+ in(column: string, values: readonly unknown[]): this;
60
+ not(column: string, operator: string, value: unknown): this;
61
+ contains(column: string, value: unknown): this;
62
+ overlaps(column: string, value: unknown): this;
63
+ }
51
64
  /**
52
65
  * Creates an entity-aware CRUD store for server code.
53
66
  *
@@ -1,11 +1,3 @@
1
- /**
2
- * @fileoverview Generic handler to update an entity in Supabase.
3
- * @description Provides a reusable implementation for updating documents in PostgreSQL with validation.
4
- *
5
- * @version 0.1.0
6
- * @since 0.5.0
7
- * @author AMBROISE PARK Consulting
8
- */
9
1
  import * as v from 'valibot';
10
2
  import type { UserRole } from '@donotdev/core/server';
11
3
  /** Request payload for updating an entity by ID with optional idempotency. */