@donotdev/functions 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (203) hide show
  1. package/README.md +1 -1
  2. package/lib/chunks/chunk-522YXGDA.js +23 -0
  3. package/lib/chunks/chunk-522YXGDA.js.map +7 -0
  4. package/lib/chunks/chunk-7ODXXXES.js +151 -0
  5. package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
  6. package/lib/chunks/chunk-CP3NNKO5.js +22 -0
  7. package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
  8. package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
  9. package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
  10. package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
  11. package/lib/chunks/chunk-ICNQCRLV.js +22 -0
  12. package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
  13. package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
  14. package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
  15. package/lib/chunks/chunk-OKRR7ST5.js +22 -0
  16. package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
  17. package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
  18. package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
  19. package/lib/chunks/chunk-TJPJXJEK.js +22 -0
  20. package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
  21. package/lib/chunks/chunk-W6W4L44F.js +22 -0
  22. package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
  23. package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
  24. package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
  25. package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
  26. package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
  27. package/lib/firebase/crud/aggregate.d.ts +1 -1
  28. package/lib/firebase/crud/create.d.ts +22 -1
  29. package/lib/firebase/crud/update.d.ts +27 -3
  30. package/lib/firebase/index.js +1 -1
  31. package/lib/firebase/index.js.map +3 -3
  32. package/lib/shared/billing/checkoutValidation.d.ts +1 -1
  33. package/lib/shared/billing/createCheckout.d.ts +1 -1
  34. package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
  35. package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
  36. package/lib/shared/billing/index.d.ts +2 -0
  37. package/lib/shared/billing/orderWebhook.d.ts +29 -2
  38. package/lib/shared/billing/stripePinned.d.ts +43 -0
  39. package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
  40. package/lib/shared/crud/bulkCore.d.ts +38 -10
  41. package/lib/shared/crud/index.d.ts +1 -0
  42. package/lib/shared/crud/written.d.ts +21 -0
  43. package/lib/shared/denoEnv.d.ts +25 -0
  44. package/lib/shared/github.d.ts +0 -8
  45. package/lib/shared/index.d.ts +0 -1
  46. package/lib/shared/index.js +1 -1
  47. package/lib/shared/logger.d.ts +14 -14
  48. package/lib/shared/utils/external/subscription.d.ts +0 -8
  49. package/lib/shared/utils.d.ts +13 -10
  50. package/lib/supabase/auth/deleteAccount.d.ts +34 -2
  51. package/lib/supabase/crud/bulk.d.ts +7 -0
  52. package/lib/supabase/crud/create.d.ts +5 -9
  53. package/lib/supabase/crud/entityStore.d.ts +67 -14
  54. package/lib/supabase/crud/update.d.ts +7 -10
  55. package/lib/supabase/index.d.ts +5 -0
  56. package/lib/supabase/index.js +1 -1
  57. package/lib/supabase/index.js.map +4 -4
  58. package/lib/vercel/api/crud/create.d.ts +6 -1
  59. package/lib/vercel/api/crud/update.d.ts +8 -1
  60. package/lib/vercel/api/index.js +1 -1
  61. package/lib/vercel/api/index.js.map +3 -3
  62. package/package.json +9 -9
  63. package/src/firebase/auth/getCustomClaims.ts +2 -0
  64. package/src/firebase/auth/getUserAuthStatus.ts +2 -0
  65. package/src/firebase/auth/removeCustomClaims.ts +33 -1
  66. package/src/firebase/auth/setCustomClaims.ts +6 -0
  67. package/src/firebase/baseFunction.ts +5 -2
  68. package/src/firebase/billing/changePlan.ts +6 -5
  69. package/src/firebase/billing/createCustomerPortal.ts +6 -4
  70. package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
  71. package/src/firebase/billing/webhookHandler.ts +4 -4
  72. package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
  73. package/src/firebase/crud/__tests__/create.test.ts +64 -0
  74. package/src/firebase/crud/__tests__/update.test.ts +97 -0
  75. package/src/firebase/crud/aggregate.ts +37 -19
  76. package/src/firebase/crud/bulk.ts +30 -10
  77. package/src/firebase/crud/create.ts +40 -26
  78. package/src/firebase/crud/delete.ts +6 -1
  79. package/src/firebase/crud/get.ts +12 -14
  80. package/src/firebase/crud/list.ts +23 -12
  81. package/src/firebase/crud/update.ts +49 -25
  82. package/src/firebase/helpers/githubAccessHelper.ts +3 -0
  83. package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
  84. package/src/firebase/oauth/exchangeToken.ts +4 -0
  85. package/src/firebase/oauth/getConnections.ts +1 -1
  86. package/src/firebase/oauth/githubAccess.ts +3 -0
  87. package/src/firebase/oauth/refreshToken.ts +1 -0
  88. package/src/firebase/registerCrudFunctions.ts +1 -0
  89. package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
  90. package/src/shared/__tests__/bulkCore.test.ts +191 -0
  91. package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
  92. package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
  93. package/src/shared/__tests__/utils.test.ts +0 -30
  94. package/src/shared/ai/classifyAIError.ts +18 -10
  95. package/src/shared/ai/createAIRoute.ts +2 -1
  96. package/src/shared/ai/resolveModelTier.ts +2 -1
  97. package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
  98. package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
  99. package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
  100. package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
  101. package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
  102. package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
  103. package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
  104. package/src/shared/billing/checkoutValidation.ts +19 -2
  105. package/src/shared/billing/createCheckout.ts +56 -11
  106. package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
  107. package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
  108. package/src/shared/billing/index.ts +2 -0
  109. package/src/shared/billing/orderWebhook.ts +69 -1
  110. package/src/shared/billing/stripeClient.ts +2 -1
  111. package/src/shared/billing/stripePinned.ts +71 -0
  112. package/src/shared/billing/tierWebhookEvents.ts +3 -2
  113. package/src/shared/billing/verifyOrderCheckout.ts +142 -0
  114. package/src/shared/billing/webhookHandler.ts +5 -1
  115. package/src/shared/crud/bulkCore.ts +112 -82
  116. package/src/shared/crud/index.ts +1 -0
  117. package/src/shared/crud/written.ts +56 -0
  118. package/src/shared/denoEnv.ts +29 -0
  119. package/src/shared/email/createEmailRoute.ts +2 -2
  120. package/src/shared/errorHandling.ts +8 -8
  121. package/src/shared/firebase.ts +26 -9
  122. package/src/shared/github.ts +15 -5
  123. package/src/shared/index.d.ts +0 -9
  124. package/src/shared/index.ts +0 -1
  125. package/src/shared/logger.ts +37 -38
  126. package/src/shared/utils/external/date.ts +4 -4
  127. package/src/shared/utils/external/subscription.ts +2 -89
  128. package/src/shared/utils/firebaseHelpers.ts +2 -0
  129. package/src/shared/utils/internal/idempotency.ts +3 -0
  130. package/src/shared/utils/internal/monitoring.ts +6 -5
  131. package/src/shared/utils/internal/validation.ts +2 -0
  132. package/src/shared/utils/schemaValidation.ts +1 -0
  133. package/src/shared/utils/validation.ts +10 -20
  134. package/src/shared/utils.ts +4 -42
  135. package/src/supabase/__tests__/aggregate.test.ts +132 -0
  136. package/src/supabase/__tests__/bulk.test.ts +60 -2
  137. package/src/supabase/__tests__/create.test.ts +86 -0
  138. package/src/supabase/__tests__/entityStore.test.ts +91 -25
  139. package/src/supabase/__tests__/update.test.ts +107 -0
  140. package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
  141. package/src/supabase/auth/deleteAccount.ts +72 -5
  142. package/src/supabase/auth/removeCustomClaims.ts +7 -2
  143. package/src/supabase/auth/setCustomClaims.ts +4 -2
  144. package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
  145. package/src/supabase/crud/aggregate.ts +85 -72
  146. package/src/supabase/crud/bulk.ts +50 -0
  147. package/src/supabase/crud/create.ts +27 -33
  148. package/src/supabase/crud/delete.ts +2 -1
  149. package/src/supabase/crud/entityStore.ts +107 -18
  150. package/src/supabase/crud/get.ts +5 -13
  151. package/src/supabase/crud/list.ts +28 -21
  152. package/src/supabase/crud/update.ts +29 -24
  153. package/src/supabase/edgeFunction.ts +2 -1
  154. package/src/supabase/email/createEmailFunction.ts +2 -1
  155. package/src/supabase/index.ts +8 -0
  156. package/src/supabase/oauth/exchangeToken.ts +1 -0
  157. package/src/supabase/oauth/getConnections.ts +1 -1
  158. package/src/supabase/oauth/refreshToken.ts +1 -0
  159. package/src/supabase/registerCrudFunctions.ts +1 -0
  160. package/src/supabase/utils/idempotency.ts +1 -1
  161. package/src/supabase/utils/monitoring.ts +1 -0
  162. package/src/vercel/__tests__/bulk.test.ts +16 -8
  163. package/src/vercel/api/billing/change-plan.ts +6 -5
  164. package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
  165. package/src/vercel/api/crud/bulk.ts +34 -6
  166. package/src/vercel/api/crud/create.ts +22 -21
  167. package/src/vercel/api/crud/delete.ts +5 -2
  168. package/src/vercel/api/crud/get.ts +10 -8
  169. package/src/vercel/api/crud/list.ts +10 -8
  170. package/src/vercel/api/crud/update.ts +25 -20
  171. package/src/vercel/api/oauth/check-github-access.ts +1 -0
  172. package/src/vercel/api/oauth/exchange-token.ts +5 -2
  173. package/src/vercel/api/oauth/grant-github-access.ts +1 -0
  174. package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
  175. package/src/vercel/baseFunction.ts +5 -1
  176. package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
  177. package/lib/chunks/chunk-2IFFIUFV.js +0 -23
  178. package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
  179. package/lib/chunks/chunk-FQSQGOBN.js +0 -22
  180. package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
  181. package/lib/chunks/chunk-G4FO76EA.js +0 -22
  182. package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
  183. package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
  184. package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
  185. package/lib/chunks/chunk-M4JV2JCF.js +0 -22
  186. package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
  187. package/lib/chunks/chunk-OZX5ZG44.js +0 -22
  188. package/lib/chunks/chunk-PWAGW4R6.js +0 -22
  189. package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
  190. package/lib/chunks/chunk-UYI56E6Q.js +0 -151
  191. package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
  192. package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
  193. package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
  194. package/lib/shared/schema.d.ts +0 -56
  195. package/lib/shared/utils/functionWrapper.d.ts +0 -36
  196. package/src/shared/__tests__/schema.test.ts +0 -219
  197. package/src/shared/schema.ts +0 -192
  198. package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
  199. package/src/shared/utils/functionWrapper.ts +0 -73
  200. /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
  201. /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
  202. /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
  203. /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
@@ -9,7 +9,6 @@
9
9
  * @author AMBROISE PARK Consulting
10
10
  */
11
11
 
12
- import * as v from 'valibot';
13
12
 
14
13
  import { DoNotDevError } from '@donotdev/core/server';
15
14
  import type { OAuthPartnerId, UserRole } from '@donotdev/core/server';
@@ -33,7 +32,9 @@ export { DoNotDevError };
33
32
  * @since 0.0.1
34
33
  * @author AMBROISE PARK Consulting
35
34
  */
36
- export function getUserRole(auth: any): UserRole {
35
+ export function getUserRole(
36
+ auth: { uid?: string; token?: Record<string, unknown> } | null | undefined
37
+ ): UserRole {
37
38
  if (!auth?.uid) return 'guest';
38
39
 
39
40
  // Check role claim (standard pattern: auth.token.role = 'admin' | 'super' | etc.)
@@ -74,7 +75,7 @@ export function createErrorResponse(error: unknown): {
74
75
  error: {
75
76
  code: string;
76
77
  message: string;
77
- details?: any;
78
+ details?: Record<string, unknown>;
78
79
  };
79
80
  } {
80
81
  if (error instanceof DoNotDevError) {
@@ -107,45 +108,6 @@ export function createErrorResponse(error: unknown): {
107
108
  };
108
109
  }
109
110
 
110
- /**
111
- * Validates document data
112
- *
113
- * @version 0.1.0
114
- * @since 0.0.1
115
- * @author AMBROISE PARK Consulting
116
- */
117
- export function validateDocument(data: any, schema?: any): void {
118
- if (!data || typeof data !== 'object') {
119
- throw new Error('Invalid document data');
120
- }
121
-
122
- if (Array.isArray(data)) {
123
- throw new Error('Document data cannot be an array');
124
- }
125
-
126
- // Run Valibot schema validation when a schema is provided
127
- if (schema) {
128
- try {
129
- v.parse(schema, data);
130
- } catch (error: any) {
131
- if (error?.issues) {
132
- const messages = error.issues
133
- .map(
134
- (issue: v.BaseIssue<unknown>) =>
135
- `${issue.path?.map((p: any) => p.key).join('.') || 'root'}: ${issue.message}`
136
- )
137
- .join('; ');
138
- throw new DoNotDevError(
139
- `Validation failed: ${messages}`,
140
- 'invalid-argument',
141
- { details: { validationErrors: error.issues } }
142
- );
143
- }
144
- throw error;
145
- }
146
- }
147
- }
148
-
149
111
  /**
150
112
  * Validates a Firestore collection name from client-supplied schema.
151
113
  *
@@ -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
+ });
@@ -64,7 +64,8 @@ const access = {
64
64
  /** Build a bulk handler + a stubbed Supabase admin client. */
65
65
  function setup(opts?: {
66
66
  rpcResult?: unknown;
67
- rpcError?: { message: string } | null;
67
+ rpcError?: { message: string; code?: string } | null;
68
+ storedRows?: Record<string, Record<string, unknown>>;
68
69
  }) {
69
70
  const rpcSpy = vi.fn().mockResolvedValue({
70
71
  data: opts?.rpcResult ?? {
@@ -74,7 +75,15 @@ function setup(opts?: {
74
75
  },
75
76
  error: opts?.rpcError ?? null,
76
77
  });
77
- const supabaseAdmin = { rpc: rpcSpy } as unknown as any;
78
+ // Stored rows read before validation (status rule): every updated id exists, published.
79
+ const inSpy = vi.fn(async (_column: string, ids: string[]) => ({
80
+ data: ids.map((id) => ({ id, ...(opts?.storedRows?.[id] ?? { status: 'available' }) })),
81
+ error: null,
82
+ }));
83
+ const supabaseAdmin = {
84
+ rpc: rpcSpy,
85
+ from: vi.fn(() => ({ select: () => ({ in: inSpy }) })),
86
+ } as unknown as any;
78
87
 
79
88
  const inner = createSupabaseBulkEntity(
80
89
  'events',
@@ -87,6 +96,7 @@ function setup(opts?: {
87
96
  return {
88
97
  handler: inner,
89
98
  rpcSpy,
99
+ inSpy,
90
100
  ctx: {
91
101
  uid: 'user-1',
92
102
  userRole: 'user' as const,
@@ -129,6 +139,7 @@ describe('createSupabaseBulkEntity', () => {
129
139
  p_inserts: expect.any(Array),
130
140
  p_updates: expect.any(Array),
131
141
  p_deletes: ['d-1'],
142
+ p_expected_statuses: { 'u-1': 'available' },
132
143
  })
133
144
  );
134
145
  expect(result).toEqual(rpcResult);
@@ -329,4 +340,51 @@ describe('createSupabaseBulkEntity', () => {
329
340
  expect(args.p_updates.map((u: any) => u.id)).toEqual(['u-1', 'u-2']);
330
341
  expect(args.p_deletes).toEqual(['d-1', 'd-2']);
331
342
  });
343
+
344
+ it('keeps a client-supplied insert id in the RPC row (pre-minted ids win)', async () => {
345
+ const { handler, rpcSpy, ctx } = setup({
346
+ rpcResult: { insertedIds: ['line-1'], updatedIds: [], deletedIds: [] },
347
+ });
348
+ const IdLess = v.object({ name: v.pipe(v.string(), v.minLength(1)) });
349
+ const inner = createSupabaseBulkEntity('events', IdLess, IdLess, UpdateSchema, access) as unknown as (data: any, c: any) => Promise<any>;
350
+ await inner({ inserts: [{ id: 'line-1', name: 'A' }] }, ctx);
351
+ expect(handler).toBeDefined();
352
+ const args = rpcSpy.mock.calls[0]![1] as { p_inserts: Record<string, unknown>[] };
353
+ expect(args.p_inserts[0]).toMatchObject({ id: 'line-1', name: 'A' });
354
+ });
355
+
356
+ it('reads the stored rows of the updated ids once (status rule)', async () => {
357
+ const { handler, inSpy, ctx } = setup({
358
+ rpcResult: { insertedIds: [], updatedIds: ['u-1', 'u-2'], deletedIds: [] },
359
+ });
360
+ await handler({ updates: [{ id: 'u-1', patch: { name: 'A' } }, { id: 'u-2', patch: { name: 'B' } }] }, ctx);
361
+ expect(inSpy).toHaveBeenCalledTimes(1);
362
+ expect(inSpy).toHaveBeenCalledWith('id', ['u-1', 'u-2']);
363
+ });
364
+
365
+ it('sends the statuses read to crud_bulk, which re-checks them under lock', async () => {
366
+ const { handler, rpcSpy, ctx } = setup({
367
+ storedRows: { 'u-1': { status: 'draft' }, 'u-2': { status: 'available' } },
368
+ });
369
+ await handler(
370
+ { updates: [{ id: 'u-1', patch: { name: 'A' } }, { id: 'u-2', patch: { name: 'B' } }] },
371
+ ctx
372
+ );
373
+ expect(rpcSpy.mock.calls[0]![1].p_expected_statuses).toEqual({
374
+ 'u-1': 'draft',
375
+ 'u-2': 'available',
376
+ });
377
+ });
378
+
379
+ it('a status changed between read and write (PT409) rejects the bulk, nothing written', async () => {
380
+ const { handler, ctx } = setup({
381
+ rpcError: {
382
+ code: 'PT409',
383
+ message: 'crud_bulk: status of events id=u-1 changed since it was read (expected available, found draft)',
384
+ },
385
+ });
386
+ await expect(
387
+ handler({ updates: [{ id: 'u-1', patch: { name: 'A' } }] }, ctx)
388
+ ).rejects.toMatchObject({ code: 'unavailable', message: expect.stringContaining('changed since it was read') });
389
+ });
332
390
  });
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @fileoverview Unit tests for `createSupabaseCreateEntity`: status rule
3
+ * (`DEFAULT_STATUS_VALUE`, `writeSchemaFor`) and parse-output inserts. The base
4
+ * handler wrapper is stubbed (inner logic called directly).
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
8
+
9
+ vi.mock('../baseFunction.js', () => ({
10
+ createSupabaseHandler: vi.fn(
11
+ (_operationName: string, _schema: unknown, handler: unknown) => handler
12
+ ),
13
+ }));
14
+
15
+ vi.mock('@donotdev/supabase/server', () => ({
16
+ defaultFieldMapper: {
17
+ toBackendField: (f: string) => f,
18
+ toBackendKeys: (o: Record<string, unknown>) => o,
19
+ fromBackendRow: (r: Record<string, unknown>) => r,
20
+ },
21
+ }));
22
+
23
+ // Import after mocks so the create module picks them up.
24
+ import { createSchemas } from '@donotdev/core/server';
25
+
26
+ import { createSupabaseCreateEntity } from '../crud/create.js';
27
+ import { contactEntity } from '@dndev/test-entities';
28
+
29
+ const schemas = createSchemas(contactEntity);
30
+
31
+ /** Supabase admin stub: insert … single() returns the inserted row. */
32
+ const insertSpy = vi.fn();
33
+ const supabaseAdmin = {
34
+ from: () => {
35
+ let row: Record<string, unknown> = {};
36
+ const self: Record<string, unknown> = {
37
+ insert: (r: Record<string, unknown>) => {
38
+ insertSpy(r);
39
+ row = r;
40
+ return self;
41
+ },
42
+ select: () => self,
43
+ single: async () => ({ data: { id: 'n1', ...row }, error: null }),
44
+ };
45
+ return self;
46
+ },
47
+ };
48
+
49
+ const handler = createSupabaseCreateEntity(
50
+ 'contacts',
51
+ schemas.create as never,
52
+ schemas.draft as never,
53
+ 'user'
54
+ ) as unknown as (data: unknown, ctx: unknown) => Promise<unknown>;
55
+ const run = (payload: Record<string, unknown>) =>
56
+ handler({ payload }, { uid: 'u1', userRole: 'user', supabaseAdmin });
57
+ const inserted = (): Record<string, unknown> =>
58
+ insertSpy.mock.calls.at(-1)![0] as Record<string, unknown>;
59
+
60
+ describe('createSupabaseCreateEntity status rule and writes', () => {
61
+ beforeEach(() => {
62
+ insertSpy.mockClear();
63
+ });
64
+
65
+ it('a create without status is published (DEFAULT_STATUS_VALUE) and validated as a create', async () => {
66
+ await expect(run({ phone: '+33 6 12 34 56 78' })).rejects.toMatchObject({ code: 'invalid-argument' });
67
+ expect(insertSpy).not.toHaveBeenCalled();
68
+ await run({ name: 'Ana' });
69
+ expect(inserted().status).toBe('available');
70
+ });
71
+
72
+ it('a draft is validated with the draft schema', async () => {
73
+ await run({ status: 'draft', name: null });
74
+ expect(inserted().status).toBe('draft');
75
+ await expect(run({ status: 'draft', phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
76
+ });
77
+
78
+ it('inserts the parse output: unknown, hidden and generated keys never reach the table', async () => {
79
+ await run({ name: 'Ana', secret: 's', role: 'admin', createdById: 'evil', createdAt: 'x' });
80
+ const row = inserted();
81
+ expect(row).not.toHaveProperty('secret');
82
+ expect(row).not.toHaveProperty('role');
83
+ expect(row.createdAt).not.toBe('x');
84
+ expect(row.createdById).toBe('u1');
85
+ });
86
+ });
@@ -1,39 +1,48 @@
1
1
  /**
2
2
  * @fileoverview Unit tests for `createEntityStore`: field mapping both ways,
3
- * publication filter, unknown-field rejection, single-row `find`, writes.
3
+ * publication filter, unknown fields (queries rejected, writes logged), single-row `find`, writes.
4
4
  */
5
5
 
6
- import { describe, it, expect } from 'vitest';
6
+ import { describe, it, expect, vi } from 'vitest';
7
+
7
8
 
8
9
  import { createEntityStore } from '../crud/entityStore.js';
10
+ import { weightedProductEntity as entity } from '@dndev/test-entities';
9
11
 
10
12
  type Call = [string, ...unknown[]];
11
13
 
12
- /** Records every builder call; awaiting the query resolves to `result`. */
13
- function fakeClient(result: { data: unknown; error: { message: string } | null }) {
14
+ /**
15
+ * Records every builder call; awaiting a write query (insert / update) resolves to
16
+ * `result`, a read to `stored` when given (the rows an update reads first), else `result`.
17
+ */
18
+ function fakeClient(
19
+ result: { data: unknown; error: { message: string } | null },
20
+ stored?: Record<string, unknown>[]
21
+ ) {
14
22
  const calls: Call[] = [];
15
- const query: Record<string, unknown> = {};
16
- for (const m of ['select', 'insert', 'update', 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'not', 'contains', 'overlaps', 'order', 'limit']) {
17
- query[m] = (...args: unknown[]) => {
18
- calls.push([m, ...args]);
19
- return query;
20
- };
21
- }
22
- query.then = (resolve: (r: unknown) => unknown) => Promise.resolve(result).then(resolve);
23
+ const newQuery = () => {
24
+ const query: Record<string, unknown> = {};
25
+ let writes = false;
26
+ for (const m of ['select', 'insert', 'update', 'eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'not', 'contains', 'overlaps', 'order', 'limit']) {
27
+ query[m] = (...args: unknown[]) => {
28
+ calls.push([m, ...args]);
29
+ if (m === 'insert' || m === 'update') writes = true;
30
+ return query;
31
+ };
32
+ }
33
+ query.then = (resolve: (r: unknown) => unknown) =>
34
+ Promise.resolve(!writes && stored ? { data: stored, error: null } : result).then(resolve);
35
+ return query;
36
+ };
23
37
  const client = {
24
38
  from: (table: string) => {
25
39
  calls.push(['from', table]);
26
- return query;
40
+ return newQuery();
27
41
  },
28
42
  };
29
43
  return { client: client as never, calls };
30
44
  }
31
45
 
32
- const entity = {
33
- name: 'Product',
34
- collection: 'products',
35
- fields: { id: {}, status: {}, name: {}, weightGrams: {}, brandId: {} },
36
- } as never;
37
46
 
38
47
  describe('createEntityStore', () => {
39
48
  it('lists with entity names in, snake_case columns out, hidden statuses excluded', async () => {
@@ -45,7 +54,7 @@ describe('createEntityStore', () => {
45
54
  });
46
55
  expect(rows).toEqual([{ id: 'p1', name: 'A', weightGrams: 50 }]);
47
56
  expect(calls).toEqual([
48
- ['from', 'products'],
57
+ ['from', 'weighted_products'],
49
58
  ['select', 'id, name, weight_grams'],
50
59
  ['in', 'brand_id', ['b1']],
51
60
  ['not', 'status', 'in', '("draft","deleted")'],
@@ -59,10 +68,14 @@ describe('createEntityStore', () => {
59
68
  expect(calls.some(([m]) => m === 'not')).toBe(false);
60
69
  });
61
70
 
62
- it('rejects fields the entity does not define', async () => {
63
- const { client } = fakeClient({ data: [], error: null });
71
+ it('rejects query fields the entity does not define; writes log them, not written (CRUD rule 8)', async () => {
72
+ const { client, calls } = fakeClient({ data: [], error: null });
64
73
  await expect(createEntityStore(client, entity).list({ where: [['price', '==', 1]] })).rejects.toThrow("unknown field 'price'");
65
- await expect(createEntityStore(client, entity).insert([{ price: 1 } as never])).rejects.toThrow("unknown field 'price'");
74
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
75
+ await createEntityStore(client, entity).insert([{ name: 'A', price: 1 } as never]);
76
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('price'));
77
+ expect(calls).toContainEqual(['insert', [{ name: 'A', status: 'available' }]]);
78
+ warn.mockRestore();
66
79
  });
67
80
 
68
81
  it('find returns null, one row, or fails on several', async () => {
@@ -75,16 +88,69 @@ describe('createEntityStore', () => {
75
88
  it('insert and update map keys, skip undefined, return stored rows', async () => {
76
89
  const { client, calls } = fakeClient({ data: [{ id: 'p1', weight_grams: 10 }], error: null });
77
90
  const store = createEntityStore(client, entity);
78
- expect(await store.insert([{ weightGrams: 10, name: undefined }])).toEqual([{ id: 'p1', weightGrams: 10 }]);
91
+ expect(await store.insert([{ weightGrams: 10, name: 'A', brandId: undefined }])).toEqual([{ id: 'p1', weightGrams: 10 }]);
79
92
  await store.update([['id', '==', 'p1']], { weightGrams: 10 });
80
- expect(calls).toContainEqual(['insert', [{ weight_grams: 10 }]]);
93
+ // A row without status gets DEFAULT_STATUS_VALUE
94
+ expect(calls).toContainEqual(['insert', [{ weight_grams: 10, name: 'A', status: 'available' }]]);
81
95
  expect(calls).toContainEqual(['update', { weight_grams: 10 }]);
82
96
  expect(calls).toContainEqual(['eq', 'id', 'p1']);
83
97
  await expect(store.update([], { weightGrams: 1 })).rejects.toThrow('update without a condition');
84
98
  });
85
99
 
100
+ it('validates writes with the schema of their status and writes the parse output', async () => {
101
+ const { client, calls } = fakeClient({ data: [], error: null }, [{ id: 'p1', name: 'A', status: 'available' }]);
102
+ const store = createEntityStore(client, entity);
103
+ // create: required field missing, wrong value type
104
+ await expect(store.insert([{ weightGrams: 1 } as never])).rejects.toMatchObject({ code: 'invalid-argument' });
105
+ await expect(store.insert([{ name: 'A', weightGrams: 'x' } as never])).rejects.toMatchObject({ code: 'invalid-argument' });
106
+ // draft: required may be empty, filled values keep their format
107
+ await store.insert([{ status: 'draft', weightGrams: 2 }]);
108
+ expect(calls).toContainEqual(['insert', [{ status: 'draft', weight_grams: 2 }]]);
109
+ await expect(store.insert([{ status: 'draft', weightGrams: 'x' } as never])).rejects.toMatchObject({ code: 'invalid-argument' });
110
+ // program class (editable: false) is written by trusted code
111
+ await store.update([['id', '==', 'p1']], { paidAt: '2026-11-17T10:00:00.000Z' });
112
+ expect(calls).toContainEqual(['update', { paid_at: '2026-11-17T10:00:00.000Z' }]);
113
+ // update: a required field sent must be filled in; a draft patch uses the draft schema
114
+ await expect(store.update([['id', '==', 'p1']], { name: '' })).rejects.toMatchObject({ code: 'invalid-argument' });
115
+ await store.update([['id', '==', 'p1']], { status: 'draft', name: null });
116
+ expect(calls).toContainEqual(['update', { status: 'draft', name: null }]);
117
+ // never class (generated) is not written
118
+ await expect(store.insert([{ name: 'A', createdAt: '2026-01-01' } as never])).resolves.toEqual([]);
119
+ expect(calls).toContainEqual(['insert', [{ name: 'A', status: 'available' }]]);
120
+ });
121
+
122
+ it('keeps a caller-chosen insert id (minted ids other rows reference)', async () => {
123
+ const { client, calls } = fakeClient({ data: [], error: null });
124
+ await createEntityStore(client, entity).insert([{ id: 'line-1', name: 'A' }, { name: 'B' }]);
125
+ expect(calls).toContainEqual(['insert', [{ id: 'line-1', name: 'A', status: 'available' }, { name: 'B', status: 'available' }]]);
126
+ });
127
+
128
+ it('update: the stored status decides the schema; publishing a draft checks the whole row', async () => {
129
+ // Stored draft edited without a status: a draft write (empty required field accepted)
130
+ const draft = fakeClient({ data: [], error: null }, [{ id: 'p1', name: 'A', status: 'draft' }]);
131
+ await createEntityStore(draft.client, entity).update([['id', '==', 'p1']], { name: null });
132
+ expect(draft.calls).toContainEqual(['update', { name: null }]);
133
+ // Only the validated rows are written: `where` plus their ids
134
+ expect(draft.calls).toContainEqual(['in', 'id', ['p1']]);
135
+ // Publishing a draft whose required field is empty: rejected, nothing written
136
+ const empty = fakeClient({ data: [], error: null }, [{ id: 'p1', name: null, status: 'draft' }]);
137
+ await expect(createEntityStore(empty.client, entity).update([['id', '==', 'p1']], { status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
138
+ expect(empty.calls.some(([m]) => m === 'update')).toBe(false);
139
+ // Soft-deleting it stays relaxed
140
+ await createEntityStore(empty.client, entity).update([['id', '==', 'p1']], { status: 'deleted' });
141
+ expect(empty.calls).toContainEqual(['update', { status: 'deleted' }]);
142
+ // Filled in: published, only the patch keys written
143
+ const filled = fakeClient({ data: [], error: null }, [{ id: 'p1', name: 'A', status: 'draft' }]);
144
+ await createEntityStore(filled.client, entity).update([['id', '==', 'p1']], { status: 'available' });
145
+ expect(filled.calls).toContainEqual(['update', { status: 'available' }]);
146
+ // No matching row: nothing written
147
+ const none = fakeClient({ data: [], error: null }, []);
148
+ expect(await createEntityStore(none.client, entity).update([['id', '==', 'p9']], { name: 'B' })).toEqual([]);
149
+ expect(none.calls.some(([m]) => m === 'update')).toBe(false);
150
+ });
151
+
86
152
  it('surfaces database errors', async () => {
87
153
  const { client } = fakeClient({ data: null, error: { message: 'boom' } });
88
- await expect(createEntityStore(client, entity).list()).rejects.toThrow('list products: boom');
154
+ await expect(createEntityStore(client, entity).list()).rejects.toThrow('list weighted_products: boom');
89
155
  });
90
156
  });
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @fileoverview Unit tests for `createSupabaseUpdateEntity` validation.
3
+ * @description Same rules as the client (createSchemas): a draft is checked whole
4
+ * against the draft schema, any other update checks what it writes against the
5
+ * update schema. The base handler wrapper is stubbed (inner logic called directly).
6
+ */
7
+
8
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
9
+
10
+ vi.mock('../baseFunction.js', () => ({
11
+ createSupabaseHandler: vi.fn(
12
+ (_operationName: string, _schema: unknown, handler: unknown) => handler
13
+ ),
14
+ }));
15
+
16
+ vi.mock('@donotdev/supabase/server', () => ({
17
+ defaultFieldMapper: {
18
+ toBackendField: (f: string) => f,
19
+ toBackendKeys: (o: Record<string, unknown>) => o,
20
+ fromBackendRow: (r: Record<string, unknown>) => r,
21
+ },
22
+ }));
23
+
24
+ // Import after mocks so the update module picks them up.
25
+ import { createSchemas } from '@donotdev/core/server';
26
+
27
+ import { createSupabaseUpdateEntity } from '../crud/update.js';
28
+ import { contactEntity } from '@dndev/test-entities';
29
+
30
+ const schemas = createSchemas(contactEntity);
31
+
32
+ /** Stored row and a Supabase admin stub: select … single() reads it, update … single() writes it. */
33
+ let stored: Record<string, unknown> = {};
34
+ const updateSpy = vi.fn();
35
+ function chain(result: () => unknown) {
36
+ const self: Record<string, unknown> = {};
37
+ for (const method of ['select', 'eq', 'update']) {
38
+ self[method] = (...args: unknown[]) => {
39
+ if (method === 'update') updateSpy(args[0]);
40
+ return self;
41
+ };
42
+ }
43
+ self.single = async () => ({ data: result(), error: null });
44
+ return self;
45
+ }
46
+ const supabaseAdmin = {
47
+ from: () => chain(() => ({ id: 'c1', ...stored })),
48
+ };
49
+
50
+ const handler = createSupabaseUpdateEntity(
51
+ 'contacts',
52
+ schemas.update as never,
53
+ schemas.draft as never,
54
+ 'user'
55
+ ) as unknown as (data: unknown, ctx: unknown) => Promise<unknown>;
56
+ const run = (payload: Record<string, unknown>) =>
57
+ handler({ id: 'c1', payload }, { uid: 'u1', userRole: 'user', supabaseAdmin });
58
+
59
+ describe('createSupabaseUpdateEntity validation', () => {
60
+ beforeEach(() => {
61
+ updateSpy.mockClear();
62
+ });
63
+
64
+ it('non-draft: checks what the update writes against the update schema', async () => {
65
+ // Legacy row with a required field empty: an update of another field passes
66
+ stored = { name: null, status: 'available' };
67
+ await expect(run({ phone: '+33 6 12 34 56 78' })).resolves.toBeDefined();
68
+ for (const payload of [{ name: null }, { name: '' }, { phone: 'TOTO' }]) {
69
+ await expect(run(payload)).rejects.toMatchObject({ code: 'invalid-argument' });
70
+ }
71
+ expect(updateSpy).toHaveBeenCalledTimes(1);
72
+ });
73
+
74
+ it('draft: required fields may be empty, filled ones keep their format', async () => {
75
+ stored = { name: 'Ana', status: 'draft' };
76
+ await expect(run({ name: null })).resolves.toBeDefined();
77
+ await expect(run({ phone: 'TOTO' })).rejects.toMatchObject({ code: 'invalid-argument' });
78
+ });
79
+
80
+ it('writes the parse output of the sent keys, never the raw payload', async () => {
81
+ stored = { name: 'Ana', status: 'draft' };
82
+ await run({ phone: '+33 6 12 34 56 78', createdById: 'evil', role: 'admin' });
83
+ expect(updateSpy).toHaveBeenCalledTimes(1);
84
+ const written = updateSpy.mock.calls[0]![0] as Record<string, unknown>;
85
+ expect(written.phone).toBe('+33 6 12 34 56 78');
86
+ expect(written).not.toHaveProperty('role');
87
+ // createdById is a backend name (write class never): only the metadata value may be present
88
+ expect(written.createdById).not.toBe('evil');
89
+ expect(written).not.toHaveProperty('name');
90
+ });
91
+
92
+ it('publishing a draft through a status-only patch checks the whole merged row', async () => {
93
+ stored = { name: null, phone: null, status: 'draft' };
94
+ await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
95
+ expect(updateSpy).not.toHaveBeenCalled();
96
+ stored = { name: 'Ana', phone: null, status: 'draft' };
97
+ await expect(run({ status: 'available' })).resolves.toBeDefined();
98
+ const written = updateSpy.mock.calls[0]![0] as Record<string, unknown>;
99
+ expect(written.status).toBe('available');
100
+ expect(written).not.toHaveProperty('name');
101
+ });
102
+
103
+ it('soft-deleting a draft stays relaxed (deleted is hidden)', async () => {
104
+ stored = { name: null, status: 'draft' };
105
+ await expect(run({ status: 'deleted' })).resolves.toBeDefined();
106
+ });
107
+ });