@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
@@ -0,0 +1,132 @@
1
+ /**
2
+ * @fileoverview Unit tests for `createSupabaseAggregateEntities`.
3
+ * @description Regression: filters were applied on `from()` (no filter methods) and
4
+ * grouping called a non-existent `.group()`, so any `where` or `groupBy` threw.
5
+ */
6
+
7
+ import * as v from 'valibot';
8
+ import { describe, it, expect, vi } from 'vitest';
9
+
10
+ vi.mock('../baseFunction.js', () => ({
11
+ createSupabaseHandler: vi.fn(
12
+ (_operationName: string, _schema: unknown, handler: any) => handler
13
+ ),
14
+ }));
15
+
16
+ vi.mock('@donotdev/supabase/server', () => ({
17
+ defaultFieldMapper: {
18
+ toBackendField: (f: string) =>
19
+ f.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`),
20
+ },
21
+ }));
22
+
23
+ import { createSupabaseAggregateEntities } from '../crud/aggregate.js';
24
+
25
+ type Result = { data: unknown[] | null; error: null; count: number | null };
26
+
27
+ /** Minimal PostgREST stub: from() has only select(); filters live on the builder. */
28
+ function setup(result: Result) {
29
+ const calls: Array<[string, ...unknown[]]> = [];
30
+ const builder: Record<string, unknown> = {
31
+ then: (resolve: (r: Result) => unknown) => resolve(result),
32
+ };
33
+ for (const op of [
34
+ 'eq',
35
+ 'neq',
36
+ 'gt',
37
+ 'gte',
38
+ 'lt',
39
+ 'lte',
40
+ 'in',
41
+ 'not',
42
+ 'contains',
43
+ ]) {
44
+ builder[op] = (...args: unknown[]) => {
45
+ calls.push([op, ...args]);
46
+ return builder;
47
+ };
48
+ }
49
+ const select = vi.fn((...args: unknown[]) => {
50
+ calls.push(['select', ...args]);
51
+ return builder;
52
+ });
53
+ const supabaseAdmin = { from: vi.fn(() => ({ select })) };
54
+ const handler = createSupabaseAggregateEntities(
55
+ 'orders',
56
+ v.object({}),
57
+ 'user'
58
+ ) as unknown as (data: unknown, ctx: unknown) => Promise<{ value: unknown }>;
59
+ return {
60
+ calls,
61
+ run: (data: unknown) => handler(data, { supabaseAdmin }),
62
+ };
63
+ }
64
+
65
+ describe('createSupabaseAggregateEntities', () => {
66
+ it('applies where filters after select', async () => {
67
+ const { calls, run } = setup({ data: null, error: null, count: 3 });
68
+ const res = await run({
69
+ where: [['status', '==', 'paid']],
70
+ aggregate: { field: 'id', operation: 'count' },
71
+ });
72
+ expect(res.value).toBe(3);
73
+ expect(calls).toEqual([
74
+ ['select', '*', { count: 'exact', head: true }],
75
+ ['eq', 'status', 'paid'],
76
+ ]);
77
+ });
78
+
79
+ it('sums a column over filtered rows', async () => {
80
+ const { calls, run } = setup({
81
+ data: [
82
+ { total_amount: 10 },
83
+ { total_amount: '5' },
84
+ { total_amount: null },
85
+ ],
86
+ error: null,
87
+ count: null,
88
+ });
89
+ const res = await run({
90
+ where: [['amount', '>', 0]],
91
+ aggregate: { field: 'totalAmount', operation: 'sum' },
92
+ });
93
+ expect(res.value).toBe(15);
94
+ expect(calls[0]).toEqual(['select', 'total_amount']);
95
+ });
96
+
97
+ it('groups rows in JS for every operation', async () => {
98
+ const rows = [
99
+ { customer_id: 'a', status: 'paid', total: 10 },
100
+ { customer_id: 'a', status: 'paid', total: 30 },
101
+ { customer_id: 'b', status: 'paid', total: 5 },
102
+ { customer_id: 'b', status: 'open', total: 7 },
103
+ ];
104
+ const { calls, run } = setup({ data: rows, error: null, count: null });
105
+
106
+ const avg = await run({
107
+ where: [['total', '>=', 0]],
108
+ aggregate: { field: 'total', operation: 'avg' },
109
+ groupBy: ['customerId', 'status'],
110
+ });
111
+ expect(avg.value).toEqual({ 'a|paid': 20, 'b|paid': 5, 'b|open': 7 });
112
+ expect(calls[0]).toEqual(['select', 'customer_id, status, total']);
113
+ expect(calls[1]).toEqual(['gte', 'total', 0]);
114
+
115
+ const count = await run({
116
+ aggregate: { field: 'id', operation: 'count' },
117
+ groupBy: ['customerId'],
118
+ });
119
+ expect(count.value).toEqual({ a: 2, b: 2 });
120
+ });
121
+
122
+ it('throws on a query error', async () => {
123
+ const { run } = setup({
124
+ data: null,
125
+ error: { message: 'boom' } as never,
126
+ count: null,
127
+ });
128
+ await expect(
129
+ run({ aggregate: { field: 'id', operation: 'count' } })
130
+ ).rejects.toThrow(/boom/);
131
+ });
132
+ });
@@ -0,0 +1,102 @@
1
+ /**
2
+ * @fileoverview Unit tests for `createDeleteAccount`.
3
+ * @description `beforeDelete` runs first; a throw refuses the deletion with a 409
4
+ * carrying the error's message and code, and the auth user is kept.
5
+ */
6
+
7
+ import { describe, it, expect, vi } from 'vitest';
8
+
9
+ vi.mock('../../baseFunction.js', () => ({
10
+ createSupabaseHandler: vi.fn(
11
+ (_operationName: string, _schema: unknown, handler: any) => handler
12
+ ),
13
+ }));
14
+
15
+ import { createDeleteAccount } from '../deleteAccount.js';
16
+
17
+ type Handler = (data: unknown, ctx: unknown) => Promise<unknown>;
18
+
19
+ function setup(deleteError: unknown = null) {
20
+ const order: string[] = [];
21
+ const deleteUser = vi.fn(async () => {
22
+ order.push('deleteUser');
23
+ return { error: deleteError };
24
+ });
25
+ const ctx = {
26
+ uid: 'user-1',
27
+ userRole: 'user',
28
+ supabaseAdmin: { auth: { admin: { deleteUser } } },
29
+ };
30
+ return { ctx, deleteUser, order };
31
+ }
32
+
33
+ describe('createDeleteAccount', () => {
34
+ it('deletes the caller without options (unchanged behaviour)', async () => {
35
+ const { ctx, deleteUser } = setup();
36
+ const handler = createDeleteAccount() as unknown as Handler;
37
+ await expect(handler({}, ctx)).resolves.toEqual({ success: true });
38
+ expect(deleteUser).toHaveBeenCalledWith('user-1');
39
+ });
40
+
41
+ it('runs beforeDelete with the context before deleting the user', async () => {
42
+ const { ctx, deleteUser, order } = setup();
43
+ const beforeDelete = vi.fn(async (c: unknown) => {
44
+ expect(c).toBe(ctx);
45
+ order.push('beforeDelete');
46
+ });
47
+ const handler = createDeleteAccount({ beforeDelete }) as unknown as Handler;
48
+ await expect(handler({}, ctx)).resolves.toEqual({ success: true });
49
+ expect(order).toEqual(['beforeDelete', 'deleteUser']);
50
+ expect(deleteUser).toHaveBeenCalledTimes(1);
51
+ });
52
+
53
+ it('refuses with 409 { error, code } and keeps the user when beforeDelete throws', async () => {
54
+ const { ctx, deleteUser } = setup();
55
+ const refusal = Object.assign(new Error('open_orders'), { code: 'P0001' });
56
+ const handler = createDeleteAccount({
57
+ beforeDelete: async () => {
58
+ throw refusal;
59
+ },
60
+ }) as unknown as Handler;
61
+ const res = (await handler({}, ctx)) as Response;
62
+ expect(res).toBeInstanceOf(Response);
63
+ expect(res.status).toBe(409);
64
+ expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
65
+ expect(deleteUser).not.toHaveBeenCalled();
66
+ });
67
+
68
+ it('refuses an error without a code with its message only', async () => {
69
+ const { ctx, deleteUser } = setup();
70
+ const handler = createDeleteAccount({
71
+ beforeDelete: async () => {
72
+ throw new Error('unpaid_terms');
73
+ },
74
+ }) as unknown as Handler;
75
+ const res = (await handler({}, ctx)) as Response;
76
+ expect(res.status).toBe(409);
77
+ expect(await res.json()).toEqual({ error: 'unpaid_terms' });
78
+ expect(deleteUser).not.toHaveBeenCalled();
79
+ });
80
+
81
+ it('refuses a plain-object rejection (PostgREST { message, code } shape)', async () => {
82
+ const { ctx, deleteUser } = setup();
83
+ const handler = createDeleteAccount({
84
+ beforeDelete: async () => {
85
+ // eslint-disable-next-line @typescript-eslint/only-throw-error -- why: PostgREST rejects with plain objects
86
+ throw { message: 'open_orders', code: 'P0001', details: null };
87
+ },
88
+ }) as unknown as Handler;
89
+ const res = (await handler({}, ctx)) as Response;
90
+ expect(await res.json()).toEqual({ error: 'open_orders', code: 'P0001' });
91
+ expect(deleteUser).not.toHaveBeenCalled();
92
+ });
93
+
94
+ it('throws when Supabase fails to delete the user', async () => {
95
+ const failure = new Error('db down');
96
+ const { ctx } = setup(failure);
97
+ const handler = createDeleteAccount({
98
+ beforeDelete: async () => {},
99
+ }) as unknown as Handler;
100
+ await expect(handler({}, ctx)).rejects.toBe(failure);
101
+ });
102
+ });
@@ -2,9 +2,10 @@
2
2
 
3
3
  /**
4
4
  * @fileoverview Delete Account Supabase Edge Function
5
- * @description Deletes the authenticated user's account via Supabase Admin.
5
+ * @description Deletes the authenticated user's account via Supabase Admin, after an
6
+ * optional consumer `beforeDelete` step that can refuse the deletion.
6
7
  *
7
- * @version 0.1.0
8
+ * @version 0.2.0
8
9
  * @since 0.5.0
9
10
  * @author AMBROISE PARK Consulting
10
11
  */
@@ -12,6 +13,7 @@
12
13
  import * as v from 'valibot';
13
14
 
14
15
  import { createSupabaseHandler } from '../baseFunction.js';
16
+ import type { SupabaseHandlerContext } from '../baseFunction.js';
15
17
 
16
18
  // =============================================================================
17
19
  // Schema
@@ -19,13 +21,55 @@ import { createSupabaseHandler } from '../baseFunction.js';
19
21
 
20
22
  const deleteAccountSchema = v.object({});
21
23
 
24
+ // =============================================================================
25
+ // Types
26
+ // =============================================================================
27
+
28
+ /**
29
+ * Options for {@link createDeleteAccount}.
30
+ *
31
+ * @version 0.2.0
32
+ * @since 0.2.3
33
+ */
34
+ export interface DeleteAccountOptions {
35
+ /**
36
+ * Runs before the auth user is deleted (close the account, anonymize data, cancel
37
+ * subscriptions...). Throwing refuses the deletion: the user is NOT deleted and the
38
+ * client receives HTTP 409 `{ error: message, code }` (`code` when the thrown error
39
+ * carries a string `code`). The message and code reach the browser unmasked, so
40
+ * throw client-safe values only — a refusal code such as `open_orders` that the
41
+ * client translates under `auth:deleteAccount.errors.<code>` (see `useDeleteAccount`).
42
+ */
43
+ beforeDelete?: (ctx: SupabaseHandlerContext) => Promise<void>;
44
+ }
45
+
46
+ /** HTTP status of a refusal raised by `beforeDelete`. */
47
+ const REFUSAL_STATUS = 409;
48
+
22
49
  // =============================================================================
23
50
  // Handler
24
51
  // =============================================================================
25
52
 
53
+ /** The 409 response carrying a `beforeDelete` refusal to the client. */
54
+ function refusalResponse(error: unknown): Response {
55
+ // why: PostgREST/Supabase errors may arrive as plain { message, code } objects
56
+ const record =
57
+ typeof error === 'object' && error !== null
58
+ ? (error as { message?: unknown; code?: unknown })
59
+ : {};
60
+ const message =
61
+ typeof record.message === 'string' ? record.message : String(error);
62
+ const code = typeof record.code === 'string' ? record.code : undefined;
63
+ return new Response(JSON.stringify({ error: message, code }), {
64
+ status: REFUSAL_STATUS,
65
+ headers: { 'Content-Type': 'application/json' },
66
+ });
67
+ }
68
+
26
69
  /**
27
70
  * Create a Supabase Edge Function handler for account deletion.
28
71
  *
72
+ * @param options - Optional `beforeDelete` step; without it, deletes the user directly
29
73
  * @returns `(req: Request) => Promise<Response>` handler
30
74
  *
31
75
  * @example
@@ -35,14 +79,37 @@ const deleteAccountSchema = v.object({});
35
79
  * Deno.serve(createDeleteAccount());
36
80
  * ```
37
81
  *
38
- * @version 0.1.0
82
+ * @example
83
+ * ```typescript
84
+ * // Refuse while the account still has open orders (the SQL function raises 'open_orders')
85
+ * Deno.serve(
86
+ * createDeleteAccount({
87
+ * beforeDelete: async ({ supabaseAdmin, uid }) => {
88
+ * const { error } = await supabaseAdmin.rpc('close_my_account', { p_uid: uid });
89
+ * if (error) throw error; // → 409 { error: 'open_orders', code: 'P0001' }
90
+ * },
91
+ * })
92
+ * );
93
+ * ```
94
+ *
95
+ * @version 0.2.0
39
96
  * @since 0.5.0
40
97
  */
41
- export function createDeleteAccount() {
98
+ export function createDeleteAccount(options: DeleteAccountOptions = {}) {
99
+ const { beforeDelete } = options;
42
100
  return createSupabaseHandler(
43
101
  'delete-account',
44
102
  deleteAccountSchema,
45
- async (_data, ctx) => {
103
+ async (_data, ctx): Promise<{ success: true } | Response> => {
104
+ if (beforeDelete) {
105
+ try {
106
+ await beforeDelete(ctx);
107
+ } catch (error) {
108
+ console.error('[delete-account] beforeDelete refused:', error);
109
+ return refusalResponse(error);
110
+ }
111
+ }
112
+
46
113
  const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(ctx.uid);
47
114
  if (error) throw error;
48
115
 
@@ -15,6 +15,7 @@ import * as v from 'valibot';
15
15
  import { initStripe, stripe, validateStripeEnvironment } from '../../shared/billing/stripeClient.js';
16
16
  import { createSupabaseHandler } from '../baseFunction.js';
17
17
  import { createSupabaseAuthProvider } from '../helpers/authProvider.js';
18
+ import { pinnedSubscriptionPeriod } from '../../shared/billing/stripePinned.js';
18
19
 
19
20
  // =============================================================================
20
21
  // Schema
@@ -66,12 +67,12 @@ export function createRefreshSubscriptionStatus() {
66
67
  ...(currentClaims.subscription as Record<string, unknown>),
67
68
  status: subscription.status,
68
69
  currentPeriodStart: new Date(
69
- (subscription as any).current_period_start * 1000
70
+ pinnedSubscriptionPeriod(subscription).current_period_start * 1000
70
71
  ).toISOString(),
71
72
  currentPeriodEnd: new Date(
72
- (subscription as any).current_period_end * 1000
73
+ pinnedSubscriptionPeriod(subscription).current_period_end * 1000
73
74
  ).toISOString(),
74
- cancelAtPeriodEnd: (subscription as any).cancel_at_period_end,
75
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
75
76
  },
76
77
  };
77
78
 
@@ -82,9 +83,9 @@ export function createRefreshSubscriptionStatus() {
82
83
  userId: data.userId,
83
84
  status: subscription.status,
84
85
  currentPeriodEnd: new Date(
85
- (subscription as any).current_period_end * 1000
86
+ pinnedSubscriptionPeriod(subscription).current_period_end * 1000
86
87
  ).toISOString(),
87
- cancelAtPeriodEnd: (subscription as any).cancel_at_period_end,
88
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
88
89
  };
89
90
  }
90
91
  );
@@ -16,11 +16,13 @@ import { defaultFieldMapper } from '@donotdev/supabase/server';
16
16
 
17
17
  import { DoNotDevError } from '../../shared/utils.js';
18
18
  import { createSupabaseHandler } from '../baseFunction.js';
19
+ import type { Filterable } from './entityStore.js';
19
20
 
20
21
  const mapper = defaultFieldMapper;
21
22
 
22
23
  /** Request payload for aggregate operations (COUNT, SUM, AVG, MIN, MAX) on entities. */
23
24
  export type AggregateEntityRequest = {
25
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported request type; consumers reading where values would get unknown (breaking)
24
26
  where?: Array<[string, any, any]>;
25
27
  aggregate: {
26
28
  field: string;
@@ -29,12 +31,12 @@ export type AggregateEntityRequest = {
29
31
  groupBy?: string[];
30
32
  };
31
33
 
32
- function applyOperator(
33
- query: any,
34
+ function applyOperator<Q extends Filterable>(
35
+ query: Q,
34
36
  column: string,
35
37
  operator: string,
36
- value: any
37
- ): any {
38
+ value: unknown
39
+ ): Q {
38
40
  switch (operator) {
39
41
  case '==':
40
42
  return query.eq(column, value);
@@ -59,6 +61,35 @@ function applyOperator(
59
61
  }
60
62
  }
61
63
 
64
+ /**
65
+ * Aggregate one column over rows. `count` counts rows; the numeric operations
66
+ * ignore null and non-numeric values and return 0 when none remain.
67
+ */
68
+ function reduceRows(
69
+ rows: Record<string, unknown>[],
70
+ operation: AggregateEntityRequest['aggregate']['operation'],
71
+ column: string
72
+ ): number {
73
+ if (operation === 'count') return rows.length;
74
+
75
+ const values = rows
76
+ .map((row) => row[column])
77
+ .filter((value) => value != null && !isNaN(Number(value)))
78
+ .map(Number);
79
+ if (values.length === 0) return 0;
80
+
81
+ switch (operation) {
82
+ case 'sum':
83
+ return values.reduce((a, b) => a + b, 0);
84
+ case 'avg':
85
+ return values.reduce((a, b) => a + b, 0) / values.length;
86
+ case 'min':
87
+ return Math.min(...values);
88
+ case 'max':
89
+ return Math.max(...values);
90
+ }
91
+ }
92
+
62
93
  /**
63
94
  * Create a Supabase Edge Function handler for aggregating entities.
64
95
  *
@@ -69,11 +100,12 @@ function applyOperator(
69
100
  */
70
101
  export function createSupabaseAggregateEntities(
71
102
  collection: string,
103
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
72
104
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
73
105
  requiredRole: UserRole
74
106
  ) {
75
107
  const requestSchema = v.object({
76
- where: v.optional(v.array(v.tuple([v.string(), v.any(), v.any()]))),
108
+ where: v.optional(v.array(v.tuple([v.string(), v.unknown(), v.unknown()]))),
77
109
  aggregate: v.object({
78
110
  field: v.string(),
79
111
  operation: v.picklist(['count', 'sum', 'avg', 'min', 'max']),
@@ -89,8 +121,26 @@ export function createSupabaseAggregateEntities(
89
121
  const { supabaseAdmin } = ctx;
90
122
 
91
123
  const aggregateColumn = mapper.toBackendField(aggregate.field);
92
-
93
- let query: any = supabaseAdmin.from(collection);
124
+ const groupColumns = (groupBy ?? []).map((f) => mapper.toBackendField(f));
125
+ const isGrouped = groupColumns.length > 0;
126
+ const isUngroupedCount = !isGrouped && aggregate.operation === 'count';
127
+
128
+ // select() first: filters exist on the filter builder it returns, not on from().
129
+ // Ungrouped count needs no rows (head request); otherwise fetch only the
130
+ // group and aggregate columns and aggregate in JS (PostgREST has no GROUP BY).
131
+ const selectColumns = isUngroupedCount
132
+ ? '*'
133
+ : [
134
+ ...new Set([
135
+ ...groupColumns,
136
+ ...(aggregate.operation === 'count' ? [] : [aggregateColumn]),
137
+ ]),
138
+ ].join(', ');
139
+ let query = isUngroupedCount
140
+ ? supabaseAdmin
141
+ .from(collection)
142
+ .select(selectColumns, { count: 'exact', head: true })
143
+ : supabaseAdmin.from(collection).select(selectColumns);
94
144
 
95
145
  for (const [field, operator, value] of where) {
96
146
  query = applyOperator(
@@ -101,24 +151,6 @@ export function createSupabaseAggregateEntities(
101
151
  );
102
152
  }
103
153
 
104
- if (groupBy && groupBy.length > 0) {
105
- const groupByColumns = groupBy
106
- .map((f) => mapper.toBackendField(f))
107
- .join(', ');
108
- const selectFields = `${groupByColumns}, ${aggregate.operation}(${aggregateColumn})`;
109
- query = query.select(selectFields);
110
- for (const field of groupBy) {
111
- query = query.group(mapper.toBackendField(field));
112
- }
113
- } else {
114
- if (aggregate.operation === 'count') {
115
- query = query.select('*', { count: 'exact', head: true });
116
- } else {
117
- query = query.select(aggregateColumn);
118
- }
119
- }
120
-
121
- // Execute query
122
154
  const { data: rows, error, count } = await query;
123
155
 
124
156
  if (error) {
@@ -128,54 +160,35 @@ export function createSupabaseAggregateEntities(
128
160
  );
129
161
  }
130
162
 
131
- // Process results
132
- if (groupBy && groupBy.length > 0) {
133
- const grouped: Record<string, number> = {};
134
- for (const row of (rows || []) as any[]) {
135
- const groupKey = groupBy
136
- .map((f) => row[mapper.toBackendField(f)])
137
- .join('|');
138
- grouped[groupKey] = row[`${aggregate.operation}`] || 0;
139
- }
140
- return { value: grouped };
141
- } else {
142
- // Single aggregate value
143
- if (aggregate.operation === 'count') {
144
- return { value: count ?? 0 };
145
- } else {
146
- // Calculate aggregate from rows
147
- const values = (rows || ([] as any[]))
148
- .map((row: any) => row[aggregateColumn])
149
- .filter((v: any) => v != null && !isNaN(Number(v)))
150
- .map((v: any) => Number(v));
151
-
152
- if (values.length === 0) {
153
- return { value: 0 };
154
- }
155
-
156
- let result: number;
157
- switch (aggregate.operation) {
158
- case 'sum':
159
- result = values.reduce((a: number, b: number) => a + b, 0);
160
- break;
161
- case 'avg':
162
- result =
163
- values.reduce((a: number, b: number) => a + b, 0) /
164
- values.length;
165
- break;
166
- case 'min':
167
- result = Math.min(...values);
168
- break;
169
- case 'max':
170
- result = Math.max(...values);
171
- break;
172
- default:
173
- result = 0;
174
- }
175
-
176
- return { value: result };
177
- }
163
+ if (isUngroupedCount) {
164
+ return { value: count ?? 0 };
165
+ }
166
+
167
+ // why: select() with a runtime column string types rows as a parser-error type
168
+ const typedRows = (rows ?? []) as unknown as Record<string, unknown>[];
169
+
170
+ if (!isGrouped) {
171
+ return {
172
+ value: reduceRows(typedRows, aggregate.operation, aggregateColumn),
173
+ };
174
+ }
175
+
176
+ const groups = new Map<string, Record<string, unknown>[]>();
177
+ for (const row of typedRows) {
178
+ const groupKey = groupColumns.map((c) => String(row[c])).join('|');
179
+ const groupRows = groups.get(groupKey);
180
+ if (groupRows) groupRows.push(row);
181
+ else groups.set(groupKey, [row]);
182
+ }
183
+ const grouped: Record<string, number> = {};
184
+ for (const [groupKey, groupRows] of groups) {
185
+ grouped[groupKey] = reduceRows(
186
+ groupRows,
187
+ aggregate.operation,
188
+ aggregateColumn
189
+ );
178
190
  }
191
+ return { value: grouped };
179
192
  },
180
193
  requiredRole
181
194
  );
@@ -138,8 +138,11 @@ function preparePatch(
138
138
  */
139
139
  export function createSupabaseBulkEntity(
140
140
  collection: string,
141
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
141
142
  createSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
142
144
  draftCreateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
145
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: accepts schemas of any output type; v.GenericSchema would make InferOutput unknown for callers (breaking)
143
146
  updateSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
144
147
  access: EntityAccessConfig
145
148
  ): (req: Request) => Promise<Response> {