@donotdev/functions 0.2.2 → 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 (161) hide show
  1. package/README.md +1 -1
  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-OZX5ZG44.js.map → chunk-EZKRLLSQ.js.map} +1 -1
  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-2A4FPYNB.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-PJCJ5H2O.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-UIDJS2KA.js → monitoring-LXNVBD3G.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-GG5LPWXJ.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-NODQAE3F.js} +2 -2
  26. package/lib/firebase/crud/aggregate.d.ts +1 -1
  27. package/lib/firebase/index.js +1 -1
  28. package/lib/firebase/index.js.map +3 -3
  29. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  30. package/lib/shared/billing/createCheckout.d.ts +1 -1
  31. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  32. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  33. package/lib/shared/billing/stripePinned.d.ts +43 -0
  34. package/lib/shared/denoEnv.d.ts +25 -0
  35. package/lib/shared/github.d.ts +0 -8
  36. package/lib/shared/index.js +1 -1
  37. package/lib/shared/logger.d.ts +14 -14
  38. package/lib/shared/utils/external/subscription.d.ts +0 -8
  39. package/lib/shared/utils.d.ts +15 -3
  40. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  41. package/lib/supabase/crud/create.d.ts +0 -8
  42. package/lib/supabase/crud/entityStore.d.ts +13 -0
  43. package/lib/supabase/crud/update.d.ts +0 -8
  44. package/lib/supabase/index.d.ts +1 -0
  45. package/lib/supabase/index.js +1 -1
  46. package/lib/supabase/index.js.map +4 -4
  47. package/lib/vercel/api/index.js +1 -1
  48. package/lib/vercel/api/index.js.map +3 -3
  49. package/package.json +9 -9
  50. package/src/firebase/auth/getCustomClaims.ts +2 -0
  51. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  52. package/src/firebase/auth/removeCustomClaims.ts +2 -0
  53. package/src/firebase/auth/setCustomClaims.ts +3 -0
  54. package/src/firebase/baseFunction.ts +5 -2
  55. package/src/firebase/billing/changePlan.ts +6 -5
  56. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  57. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  58. package/src/firebase/billing/webhookHandler.ts +4 -4
  59. package/src/firebase/crud/aggregate.ts +41 -12
  60. package/src/firebase/crud/bulk.ts +7 -0
  61. package/src/firebase/crud/create.ts +21 -8
  62. package/src/firebase/crud/delete.ts +6 -1
  63. package/src/firebase/crud/get.ts +9 -2
  64. package/src/firebase/crud/list.ts +18 -8
  65. package/src/firebase/crud/update.ts +15 -7
  66. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  67. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  68. package/src/firebase/oauth/exchangeToken.ts +4 -0
  69. package/src/firebase/oauth/getConnections.ts +1 -1
  70. package/src/firebase/oauth/githubAccess.ts +3 -0
  71. package/src/firebase/oauth/refreshToken.ts +1 -0
  72. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  73. package/src/shared/ai/classifyAIError.ts +18 -10
  74. package/src/shared/ai/createAIRoute.ts +2 -1
  75. package/src/shared/ai/resolveModelTier.ts +2 -1
  76. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  77. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  78. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  79. package/src/shared/billing/checkoutValidation.ts +19 -2
  80. package/src/shared/billing/createCheckout.ts +56 -11
  81. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  82. package/src/shared/billing/orderWebhook.ts +69 -1
  83. package/src/shared/billing/stripeClient.ts +2 -1
  84. package/src/shared/billing/stripePinned.ts +71 -0
  85. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  86. package/src/shared/billing/webhookHandler.ts +5 -1
  87. package/src/shared/crud/bulkCore.ts +3 -2
  88. package/src/shared/denoEnv.ts +29 -0
  89. package/src/shared/email/createEmailRoute.ts +2 -2
  90. package/src/shared/errorHandling.ts +8 -8
  91. package/src/shared/firebase.ts +26 -9
  92. package/src/shared/github.ts +15 -5
  93. package/src/shared/logger.ts +37 -38
  94. package/src/shared/schema.ts +6 -10
  95. package/src/shared/utils/external/date.ts +4 -4
  96. package/src/shared/utils/external/subscription.ts +2 -89
  97. package/src/shared/utils/firebaseHelpers.ts +2 -0
  98. package/src/shared/utils/internal/idempotency.ts +3 -0
  99. package/src/shared/utils/internal/monitoring.ts +6 -5
  100. package/src/shared/utils/internal/validation.ts +2 -0
  101. package/src/shared/utils/schemaValidation.ts +1 -0
  102. package/src/shared/utils/validation.ts +10 -20
  103. package/src/shared/utils.ts +12 -7
  104. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  105. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  106. package/src/supabase/auth/deleteAccount.ts +72 -5
  107. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  108. package/src/supabase/crud/aggregate.ts +85 -72
  109. package/src/supabase/crud/bulk.ts +3 -0
  110. package/src/supabase/crud/create.ts +13 -9
  111. package/src/supabase/crud/delete.ts +2 -1
  112. package/src/supabase/crud/entityStore.ts +1 -1
  113. package/src/supabase/crud/get.ts +2 -1
  114. package/src/supabase/crud/list.ts +23 -17
  115. package/src/supabase/crud/update.ts +9 -6
  116. package/src/supabase/edgeFunction.ts +2 -1
  117. package/src/supabase/email/createEmailFunction.ts +2 -1
  118. package/src/supabase/index.ts +1 -0
  119. package/src/supabase/oauth/exchangeToken.ts +1 -0
  120. package/src/supabase/oauth/getConnections.ts +1 -1
  121. package/src/supabase/oauth/refreshToken.ts +1 -0
  122. package/src/supabase/utils/idempotency.ts +1 -1
  123. package/src/supabase/utils/monitoring.ts +1 -0
  124. package/src/vercel/api/billing/change-plan.ts +6 -5
  125. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  126. package/src/vercel/api/crud/bulk.ts +7 -2
  127. package/src/vercel/api/crud/create.ts +6 -3
  128. package/src/vercel/api/crud/delete.ts +5 -2
  129. package/src/vercel/api/crud/get.ts +5 -2
  130. package/src/vercel/api/crud/list.ts +6 -3
  131. package/src/vercel/api/crud/update.ts +6 -3
  132. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  133. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  134. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  135. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  136. package/src/vercel/baseFunction.ts +5 -1
  137. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  138. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  139. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  140. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  141. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  142. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  143. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  144. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  145. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  146. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  147. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  148. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  149. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  150. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  151. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  152. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  153. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  154. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  155. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  156. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  157. package/src/shared/utils/functionWrapper.ts +0 -73
  158. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-UH445BGK.js.map} +0 -0
  159. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-LXNVBD3G.js.map} +0 -0
  160. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-GG5LPWXJ.js.map} +0 -0
  161. /package/lib/chunks/{server-RYGEBS2B.js.map → server-NODQAE3F.js.map} +0 -0
@@ -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> {
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type { SupabaseClient } from '@supabase/supabase-js';
12
13
  import * as v from 'valibot';
13
14
 
14
15
  import { filterVisibleFields } from '@donotdev/core/server';
@@ -24,6 +25,7 @@ const mapper = defaultFieldMapper;
24
25
 
25
26
  /** Request payload for creating an entity with optional idempotency. */
26
27
  export type CreateEntityRequest = {
28
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported signature; narrowing it is a breaking change for importers (deferred to a major, any-audit 2026-11-11)
27
29
  payload: Record<string, any>;
28
30
  idempotencyKey?: string;
29
31
  };
@@ -42,9 +44,9 @@ function normalizeValue(value: unknown): unknown {
42
44
  * Normalize unique key fields in payload to lowercase (for strings)
43
45
  */
44
46
  function normalizePayloadForUniqueKeys(
45
- payload: Record<string, any>,
47
+ payload: Record<string, unknown>,
46
48
  uniqueKeys: UniqueKeyDefinition[]
47
- ): Record<string, any> {
49
+ ): Record<string, unknown> {
48
50
  const normalized = { ...payload };
49
51
  for (const uniqueKey of uniqueKeys) {
50
52
  for (const field of uniqueKey.fields) {
@@ -61,13 +63,13 @@ function normalizePayloadForUniqueKeys(
61
63
  */
62
64
  async function checkUniqueKeys(
63
65
  collection: string,
64
- payload: Record<string, any>,
66
+ payload: Record<string, unknown>,
65
67
  uniqueKeys: UniqueKeyDefinition[],
66
68
  isDraft: boolean,
67
- supabaseAdmin: any
69
+ supabaseAdmin: SupabaseClient
68
70
  ): Promise<
69
71
  | { found: false }
70
- | { found: true; existingDoc: Record<string, any>; findOrCreate: boolean }
72
+ | { found: true; existingDoc: Record<string, unknown>; findOrCreate: boolean }
71
73
  > {
72
74
  for (const uniqueKey of uniqueKeys) {
73
75
  // Skip validation for drafts only if explicitly opted in
@@ -92,7 +94,7 @@ async function checkUniqueKeys(
92
94
  if (!error && existing && existing.length > 0) {
93
95
  const existingDoc = mapper.fromBackendRow(existing[0]) as Record<
94
96
  string,
95
- any
97
+ unknown
96
98
  >;
97
99
 
98
100
  if (uniqueKey.findOrCreate) {
@@ -127,12 +129,14 @@ async function checkUniqueKeys(
127
129
  */
128
130
  export function createSupabaseCreateEntity(
129
131
  collection: string,
132
+ // 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)
130
133
  createDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
134
+ // 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)
131
135
  draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
132
136
  requiredRole: UserRole
133
137
  ) {
134
138
  const requestSchema = v.object({
135
- payload: v.record(v.string(), v.any()),
139
+ payload: v.record(v.string(), v.unknown()),
136
140
  idempotencyKey: v.optional(v.string()),
137
141
  });
138
142
 
@@ -145,7 +149,7 @@ export function createSupabaseCreateEntity(
145
149
 
146
150
  // Idempotency check if key provided
147
151
  if (idempotencyKey) {
148
- const cachedResult = await checkIdempotency<any>(
152
+ const cachedResult = await checkIdempotency<unknown>(
149
153
  supabaseAdmin,
150
154
  idempotencyKey,
151
155
  'create'
@@ -233,7 +237,7 @@ export function createSupabaseCreateEntity(
233
237
 
234
238
  const result = mapper.fromBackendRow(
235
239
  inserted as Record<string, unknown>
236
- ) as Record<string, any>;
240
+ ) as Record<string, unknown>;
237
241
 
238
242
  // Store result for idempotency if key provided
239
243
  if (idempotencyKey) {
@@ -9,6 +9,7 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
+ import type { SupabaseClient } from '@supabase/supabase-js';
12
13
  import * as v from 'valibot';
13
14
 
14
15
  import type { UserRole } from '@donotdev/core/server';
@@ -47,7 +48,7 @@ export interface ReferenceMetadata {
47
48
  * @returns Array of reference information
48
49
  */
49
50
  async function findReferences(
50
- supabaseAdmin: any,
51
+ supabaseAdmin: SupabaseClient,
51
52
  collection: string,
52
53
  docId: string,
53
54
  referenceMetadata?: ReferenceMetadata
@@ -73,7 +73,7 @@ export interface EntityStore<Row> {
73
73
  const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
74
74
 
75
75
  /** The PostgREST filter builder methods the store uses. */
76
- interface Filterable {
76
+ export interface Filterable {
77
77
  eq(column: string, value: unknown): this;
78
78
  neq(column: string, value: unknown): this;
79
79
  gt(column: string, value: unknown): this;
@@ -40,6 +40,7 @@ export type GetEntityRequest = { id: string };
40
40
  */
41
41
  export function createSupabaseGetEntity(
42
42
  collection: string,
43
+ // 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)
43
44
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
44
45
  requiredRole: UserRole,
45
46
  ownership?: EntityOwnershipConfig
@@ -84,7 +85,7 @@ export function createSupabaseGetEntity(
84
85
  : defaultFieldMapper;
85
86
  const normalized = entityMapper.fromBackendRow(row) as Record<
86
87
  string,
87
- any
88
+ unknown
88
89
  >;
89
90
 
90
91
  const visibilityOptions =
@@ -31,6 +31,7 @@ import {
31
31
 
32
32
  import { DoNotDevError } from '../../shared/utils.js';
33
33
  import { createSupabaseHandler } from '../baseFunction.js';
34
+ import type { Filterable } from './entityStore.js';
34
35
 
35
36
  /** Field mapper: app (camelCase) ↔ backend (snake_case). Single boundary for list handler. */
36
37
  const mapper = defaultFieldMapper;
@@ -44,6 +45,7 @@ function toBackendColumn(field: unknown): string {
44
45
 
45
46
  /** Request payload for listing entities with filtering, sorting, and pagination. */
46
47
  export interface ListEntityRequest {
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- why: exported request type; consumers reading where values would get unknown (breaking)
47
49
  where?: Array<[string, any, any]>;
48
50
  orderBy?: Array<[string, 'asc' | 'desc']>;
49
51
  limit?: number;
@@ -58,7 +60,7 @@ export interface ListEntityRequest {
58
60
  /**
59
61
  * Encode cursor for keyset pagination
60
62
  */
61
- function encodeCursor(id: string, orderBy: Record<string, any>): string {
63
+ function encodeCursor(id: unknown, orderBy: Record<string, unknown>): string {
62
64
  const cursor = { id, orderBy };
63
65
  return Buffer.from(JSON.stringify(cursor)).toString('base64');
64
66
  }
@@ -68,7 +70,7 @@ function encodeCursor(id: string, orderBy: Record<string, any>): string {
68
70
  */
69
71
  function decodeCursor(cursor: string): {
70
72
  id: string;
71
- orderBy: Record<string, any>;
73
+ orderBy: Record<string, unknown>;
72
74
  } {
73
75
  try {
74
76
  const parsed = JSON.parse(Buffer.from(cursor, 'base64').toString());
@@ -95,12 +97,12 @@ function decodeCursor(cursor: string): {
95
97
  const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
96
98
 
97
99
  /** Apply operator; column must already be backend (snake_case) name. */
98
- function applyOperator(
99
- query: any,
100
+ function applyOperator<Q extends Filterable>(
101
+ query: Q,
100
102
  column: string,
101
103
  operator: string,
102
- value: any
103
- ): any {
104
+ value: unknown
105
+ ): Q {
104
106
  if (!SAFE_FIELD_NAME.test(column)) {
105
107
  throw new DoNotDevError(
106
108
  `Invalid field name: '${column}'`,
@@ -133,10 +135,10 @@ function applyOperator(
133
135
  }
134
136
  }
135
137
 
136
- function applyPublicCondition(
137
- query: any,
138
+ function applyPublicCondition<Q extends Filterable>(
139
+ query: Q,
138
140
  publicCondition: EntityOwnershipPublicCondition[]
139
- ): any {
141
+ ): Q {
140
142
  let q = query;
141
143
  for (const c of publicCondition) {
142
144
  q = applyOperator(q, toBackendColumn(c.field), c.op, c.value);
@@ -157,6 +159,7 @@ function applyPublicCondition(
157
159
  */
158
160
  export function createSupabaseListEntities(
159
161
  collection: string,
162
+ // 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)
160
163
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
161
164
  requiredRole: UserRole,
162
165
  listFields?: string[],
@@ -164,7 +167,7 @@ export function createSupabaseListEntities(
164
167
  isListCard?: boolean
165
168
  ) {
166
169
  const requestSchema = v.object({
167
- where: v.optional(v.array(v.tuple([v.string(), v.any(), v.any()]))),
170
+ where: v.optional(v.array(v.tuple([v.string(), v.unknown(), v.unknown()]))),
168
171
  orderBy: v.optional(
169
172
  v.array(
170
173
  v.tuple([
@@ -339,7 +342,8 @@ export function createSupabaseListEntities(
339
342
  );
340
343
  }
341
344
 
342
- let items = (rows || []) as Record<string, any>[];
345
+ // why: non-literal select string types rows as GenericStringError[]; rows are plain objects
346
+ let items = (rows || []) as unknown as Record<string, unknown>[];
343
347
 
344
348
  // Filter out cursor item for keyset pagination.
345
349
  // Note: items are still raw DB rows here (pre-normalization), so mapper.toBackendField
@@ -362,7 +366,9 @@ export function createSupabaseListEntities(
362
366
  }
363
367
 
364
368
  // Helper: Check if value is a Picture object
365
- const isPictureObject = (value: any): boolean => {
369
+ const isPictureObject = (
370
+ value: unknown
371
+ ): value is { thumbUrl: unknown; fullUrl: unknown } => {
366
372
  return (
367
373
  typeof value === 'object' &&
368
374
  value !== null &&
@@ -372,7 +378,7 @@ export function createSupabaseListEntities(
372
378
  };
373
379
 
374
380
  // Helper: Optimize picture fields for listCard (only return first picture's thumbUrl)
375
- const optimizePictureField = (value: any): any => {
381
+ const optimizePictureField = (value: unknown): unknown => {
376
382
  if (Array.isArray(value) && value.length > 0) {
377
383
  const firstPicture = value[0];
378
384
  if (isPictureObject(firstPicture)) {
@@ -402,7 +408,7 @@ export function createSupabaseListEntities(
402
408
  const filteredItems = items.map((row) => {
403
409
  const camelRow = entityMapper.fromBackendRow(row) as Record<
404
410
  string,
405
- any
411
+ unknown
406
412
  >;
407
413
  const visibleData = filterVisibleFields(
408
414
  camelRow,
@@ -415,7 +421,7 @@ export function createSupabaseListEntities(
415
421
 
416
422
  // If listFields specified, filter to only those fields (plus id always)
417
423
  if (safeListFields && safeListFields.length > 0) {
418
- const filtered: Record<string, any> = { id: camelRow.id };
424
+ const filtered: Record<string, unknown> = { id: camelRow.id };
419
425
  for (const field of safeListFields) {
420
426
  if (field in visibleData) {
421
427
  const value = visibleData[field];
@@ -426,7 +432,7 @@ export function createSupabaseListEntities(
426
432
  }
427
433
 
428
434
  // No listFields restriction, return all visible fields (optimize pictures)
429
- const optimizedData: Record<string, any> = { id: camelRow.id };
435
+ const optimizedData: Record<string, unknown> = { id: camelRow.id };
430
436
  for (const [key, value] of Object.entries(visibleData)) {
431
437
  optimizedData[key] = optimizePictureField(value);
432
438
  }
@@ -442,7 +448,7 @@ export function createSupabaseListEntities(
442
448
  if (useKeysetPagination && orderBy.length > 0) {
443
449
  // Create cursor from last item's orderBy field + id
444
450
  const firstOrderField = orderBy[0][0];
445
- const orderByValue: Record<string, any> = {};
451
+ const orderByValue: Record<string, unknown> = {};
446
452
  orderByValue[firstOrderField] = lastItem[firstOrderField];
447
453
  lastVisible = encodeCursor(lastItem.id, orderByValue);
448
454
  } else if (useKeysetPagination) {