@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,14 +9,16 @@
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
- import { filterVisibleFields } from '@donotdev/core/server';
15
+ import { filterVisibleFields, prepareCreate } from '@donotdev/core/server';
15
16
  import type { UserRole, UniqueKeyDefinition } from '@donotdev/core/server';
16
17
  import { defaultFieldMapper } from '@donotdev/supabase/server';
17
18
 
18
19
  import { createMetadata } from '../../shared/metadata.js';
19
- import { DoNotDevError, validateDocument } from '../../shared/utils.js';
20
+ import { writtenOf } from '../../shared/crud/written.js';
21
+ import { DoNotDevError } from '../../shared/utils.js';
20
22
  import { createSupabaseHandler } from '../baseFunction.js';
21
23
  import { checkIdempotency, storeIdempotency } from '../utils/idempotency.js';
22
24
 
@@ -24,6 +26,7 @@ const mapper = defaultFieldMapper;
24
26
 
25
27
  /** Request payload for creating an entity with optional idempotency. */
26
28
  export type CreateEntityRequest = {
29
+ // 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
30
  payload: Record<string, any>;
28
31
  idempotencyKey?: string;
29
32
  };
@@ -42,9 +45,9 @@ function normalizeValue(value: unknown): unknown {
42
45
  * Normalize unique key fields in payload to lowercase (for strings)
43
46
  */
44
47
  function normalizePayloadForUniqueKeys(
45
- payload: Record<string, any>,
48
+ payload: Record<string, unknown>,
46
49
  uniqueKeys: UniqueKeyDefinition[]
47
- ): Record<string, any> {
50
+ ): Record<string, unknown> {
48
51
  const normalized = { ...payload };
49
52
  for (const uniqueKey of uniqueKeys) {
50
53
  for (const field of uniqueKey.fields) {
@@ -61,13 +64,13 @@ function normalizePayloadForUniqueKeys(
61
64
  */
62
65
  async function checkUniqueKeys(
63
66
  collection: string,
64
- payload: Record<string, any>,
67
+ payload: Record<string, unknown>,
65
68
  uniqueKeys: UniqueKeyDefinition[],
66
69
  isDraft: boolean,
67
- supabaseAdmin: any
70
+ supabaseAdmin: SupabaseClient
68
71
  ): Promise<
69
72
  | { found: false }
70
- | { found: true; existingDoc: Record<string, any>; findOrCreate: boolean }
73
+ | { found: true; existingDoc: Record<string, unknown>; findOrCreate: boolean }
71
74
  > {
72
75
  for (const uniqueKey of uniqueKeys) {
73
76
  // Skip validation for drafts only if explicitly opted in
@@ -92,7 +95,7 @@ async function checkUniqueKeys(
92
95
  if (!error && existing && existing.length > 0) {
93
96
  const existingDoc = mapper.fromBackendRow(existing[0]) as Record<
94
97
  string,
95
- any
98
+ unknown
96
99
  >;
97
100
 
98
101
  if (uniqueKey.findOrCreate) {
@@ -120,19 +123,25 @@ async function checkUniqueKeys(
120
123
  /**
121
124
  * Create a Supabase Edge Function handler for creating an entity.
122
125
  *
126
+ * Status rule: a create without status gets `DEFAULT_STATUS_VALUE`; the CRUD rules
127
+ * picks the draft or create schema; the parse output is inserted, never the raw payload.
128
+ *
123
129
  * @param collection - The Supabase table name
124
- * @param documentSchema - The Valibot schema for document validation
130
+ * @param createDocumentSchema - The create schema (`createSchemas(entity).create`)
131
+ * @param draftDocumentSchema - The draft schema (`createSchemas(entity).draft`)
125
132
  * @param requiredRole - Minimum role required for this operation
126
133
  * @returns A `(req: Request) => Promise<Response>` handler for Deno.serve
127
134
  */
128
135
  export function createSupabaseCreateEntity(
129
136
  collection: string,
137
+ // 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
138
  createDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
139
+ // 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
140
  draftDocumentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
132
141
  requiredRole: UserRole
133
142
  ) {
134
143
  const requestSchema = v.object({
135
- payload: v.record(v.string(), v.any()),
144
+ payload: v.record(v.string(), v.unknown()),
136
145
  idempotencyKey: v.optional(v.string()),
137
146
  });
138
147
 
@@ -145,7 +154,7 @@ export function createSupabaseCreateEntity(
145
154
 
146
155
  // Idempotency check if key provided
147
156
  if (idempotencyKey) {
148
- const cachedResult = await checkIdempotency<any>(
157
+ const cachedResult = await checkIdempotency<unknown>(
149
158
  supabaseAdmin,
150
159
  idempotencyKey,
151
160
  'create'
@@ -155,9 +164,9 @@ export function createSupabaseCreateEntity(
155
164
  }
156
165
  }
157
166
 
158
- // New records start as drafts unless the caller explicitly sets a status.
159
- const status = payload.status ?? 'draft';
160
- const isDraft = status === 'draft';
167
+ // CRUD create rules (core/schemas crud/create), as on the client.
168
+ const schemas = { create: createDocumentSchema, draft: draftDocumentSchema };
169
+ const isDraft = prepareCreate(schemas, payload).schemaKey === 'draft';
161
170
 
162
171
  // Check unique keys if schema has metadata with uniqueKeys
163
172
  const schemaWithMeta = createDocumentSchema as {
@@ -190,35 +199,20 @@ export function createSupabaseCreateEntity(
190
199
  ? normalizePayloadForUniqueKeys(payload, uniqueKeys)
191
200
  : payload;
192
201
 
193
- // Validate against the appropriate schema.
194
- // Drafts must validate with `schemas.draft` so required fields become
195
- // nullish/optional (instead of failing strict `schemas.create`).
196
- const payloadForValidation = { ...normalizedPayload, status };
197
- validateDocument(
198
- payloadForValidation,
199
- isDraft ? draftDocumentSchema : createDocumentSchema
200
- );
202
+ // Insert the rules' `written` (resulting status included), never the raw payload.
203
+ const written = writtenOf(prepareCreate(schemas, normalizedPayload), collection, 'create');
201
204
 
202
205
  const metadata = createMetadata(uid);
203
206
  const snakeMetadata = mapper.toBackendKeys(
204
207
  metadata as Record<string, unknown>
205
208
  );
206
-
207
- const {
208
- createdAt,
209
- updatedAt,
210
- created_at,
211
- updated_at,
212
- ...payloadWithoutTimestamps
213
- } = normalizedPayload;
214
- const snakePayload = mapper.toBackendKeys(payloadWithoutTimestamps);
209
+ const snakePayload = mapper.toBackendKeys(written);
215
210
 
216
211
  // Insert document (DB sets created_at/updated_at via triggers)
217
212
  const { data: inserted, error } = await supabaseAdmin
218
213
  .from(collection)
219
214
  .insert({
220
215
  ...snakePayload,
221
- status,
222
216
  ...snakeMetadata,
223
217
  })
224
218
  .select()
@@ -233,7 +227,7 @@ export function createSupabaseCreateEntity(
233
227
 
234
228
  const result = mapper.fromBackendRow(
235
229
  inserted as Record<string, unknown>
236
- ) as Record<string, any>;
230
+ ) as Record<string, unknown>;
237
231
 
238
232
  // Store result for idempotency if key provided
239
233
  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
@@ -10,20 +10,39 @@
10
10
  * database policy hides them from non-admin users; the service role bypasses that
11
11
  * policy, so the store re-applies it on reads).
12
12
  *
13
- * No role or visibility masking: the caller is trusted server code. Atomic
14
- * multi-table writes stay in SQL functions (`client.rpc`).
13
+ * No role or visibility masking: the caller is trusted server code. Writes are
14
+ * still validated: each insert row / patch against the schema of its resulting
15
+ * status (the CRUD rules: `create`, `draft` or `update`; a patch reads the matched
16
+ * rows first, their stored status counts), and the parse output is what is written.
17
+ * A caller-chosen insert `id` is kept. Insert and patch types come from the descriptor (`CreateInput`,
18
+ * `DraftInput`, `UpdatePatch`: write classes `program`, `user`, `derived`).
19
+ * Atomic multi-table writes stay in SQL functions (`client.rpc`).
15
20
  *
16
- * @version 0.1.0
21
+ * @version 0.2.0
17
22
  * @since 0.5.0
18
23
  * @author AMBROISE PARK Consulting
19
24
  */
20
25
 
21
26
  import type { SupabaseClient } from '@supabase/supabase-js';
22
27
 
23
- import { HIDDEN_STATUSES } from '@donotdev/core/server';
24
- import type { AnyEntity, InferEntityRow } from '@donotdev/core/server';
28
+
29
+ import {
30
+ createSchemas,
31
+ HIDDEN_STATUSES,
32
+ prepareCreate,
33
+ prepareRemove,
34
+ prepareUpdate,
35
+ } from '@donotdev/core/server';
36
+ import type {
37
+ AnyEntity,
38
+ CreateInput,
39
+ DraftInput,
40
+ InferEntityRow,
41
+ UpdatePatch,
42
+ } from '@donotdev/core/server';
25
43
  import { createEntityAwareMapper } from '@donotdev/supabase/server';
26
44
 
45
+ import { writtenOf } from '../../shared/crud/written.js';
27
46
  import { DoNotDevError } from '../../shared/utils.js';
28
47
 
29
48
  /** Filter operators, same vocabulary as the list handler and the client CRUD. */
@@ -53,27 +72,61 @@ export interface EntityStoreQuery {
53
72
  includeHidden?: boolean;
54
73
  }
55
74
 
56
- /** Values written to a row: any subset of its fields; `null` clears a nullable column. */
75
+ /**
76
+ * Loose write values: any subset of the row's fields; `null` clears a nullable column.
77
+ * Default insert / patch type of {@link EntityStore}; `createEntityStore` narrows
78
+ * them to the descriptor types.
79
+ */
57
80
  export type EntityStoreValues<Row> = { [K in keyof Row]?: Row[K] | null };
58
81
 
59
- /** Entity-aware CRUD bound to one entity and one Supabase client. */
60
- export interface EntityStore<Row> {
82
+ /**
83
+ * Insert row of an entity store: a create, or a draft (`status: 'draft'`), with an
84
+ * optional caller-chosen `id` (write class never, but a minted id is allowed on
85
+ * insert: other rows may reference it).
86
+ */
87
+ export type EntityStoreInsert<E extends AnyEntity> = (CreateInput<E> | DraftInput<E>) & { id?: string };
88
+
89
+ /** Patch of an entity store: an update, or a draft write (`status: 'draft'`). */
90
+ export type EntityStorePatch<E extends AnyEntity> = UpdatePatch<E> | DraftInput<E>;
91
+
92
+ /**
93
+ * Entity-aware CRUD bound to one entity and one Supabase client.
94
+ *
95
+ * @template Row - Stored row
96
+ * @template Insert - Insert row type
97
+ * @template Patch - Update patch type
98
+ */
99
+ export interface EntityStore<Row, Insert = EntityStoreValues<Row>, Patch = EntityStoreValues<Row>> {
61
100
  /** Rows matching the query. */
62
101
  list(query?: EntityStoreQuery): Promise<Row[]>;
63
102
  /** The single row matching the query, or null; more than one row is an error. */
64
103
  find(query: EntityStoreQuery): Promise<Row | null>;
65
104
  /** Row by id, or null (hidden rows only with `includeHidden`). */
66
105
  get(id: string, options?: Pick<EntityStoreQuery, 'includeHidden' | 'select'>): Promise<Row | null>;
67
- /** Inserts rows and returns them as stored (database defaults and triggers applied). */
68
- insert(values: readonly EntityStoreValues<Row>[]): Promise<Row[]>;
69
- /** Updates the rows matching `where` (hidden rows included) and returns them as stored. */
70
- update(where: readonly EntityStoreCondition[], patch: EntityStoreValues<Row>): Promise<Row[]>;
106
+ /**
107
+ * Validates and inserts rows (CRUD create rules, `prepareCreate`); returns them as
108
+ * stored (database defaults and triggers applied). Unknown fields are logged, not
109
+ * written. A row's string `id` is kept (a minted id other rows reference); without
110
+ * one the database mints it.
111
+ */
112
+ insert(values: readonly Insert[]): Promise<Row[]>;
113
+ /**
114
+ * Validates the patch against each row matching `where` (hidden rows included; CRUD
115
+ * update rules, `prepareUpdate` on each stored row), then updates those rows; returns
116
+ * them as stored. Unknown fields are logged, not written.
117
+ */
118
+ update(where: readonly EntityStoreCondition[], patch: Patch): Promise<Row[]>;
119
+ /**
120
+ * Logical delete (CRUD rule 3) of the rows matching `where`: the update
121
+ * `{ status: 'deleted' }`. The hard delete is not part of the store.
122
+ */
123
+ remove(where: readonly EntityStoreCondition[]): Promise<void>;
71
124
  }
72
125
 
73
126
  const SAFE_FIELD_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
74
127
 
75
128
  /** The PostgREST filter builder methods the store uses. */
76
- interface Filterable {
129
+ export interface Filterable {
77
130
  eq(column: string, value: unknown): this;
78
131
  neq(column: string, value: unknown): this;
79
132
  gt(column: string, value: unknown): this;
@@ -145,7 +198,8 @@ function applyCondition<Q extends Filterable>(query: Q, column: string, operator
145
198
  *
146
199
  * @param client - Supabase client the store runs with (service role in Edge Functions)
147
200
  * @param entity - Entity from `defineEntity()`; its collection is the table
148
- * @returns Store whose rows use the entity field names
201
+ * @returns Store whose rows use the entity field names; writes validated per status
202
+ * @throws DoNotDevError `invalid-argument` on an unknown field or a write that fails its schema
149
203
  *
150
204
  * @example
151
205
  * ```typescript
@@ -157,11 +211,15 @@ function applyCondition<Q extends Filterable>(query: Q, column: string, operator
157
211
  * const rows = await products.list({ where: [['id', 'in', ids]], select: ['name', 'sku'] });
158
212
  * ```
159
213
  *
160
- * @version 0.1.0
214
+ * @version 0.2.0
161
215
  * @since 0.5.0
162
216
  */
163
- export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, entity: E): EntityStore<InferEntityRow<E>> {
217
+ export function createEntityStore<E extends AnyEntity>(
218
+ client: SupabaseClient,
219
+ entity: E
220
+ ): EntityStore<InferEntityRow<E>, EntityStoreInsert<E>, EntityStorePatch<E>> {
164
221
  type Row = InferEntityRow<E>;
222
+ const schemas = createSchemas(entity);
165
223
  const fieldNames = Object.keys(entity.fields);
166
224
  const known = new Set(fieldNames);
167
225
  const mapper = createEntityAwareMapper(fieldNames);
@@ -185,6 +243,17 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
185
243
  return out;
186
244
  };
187
245
 
246
+ const insertRow = (row: object): Record<string, unknown> => {
247
+ const values = row as Record<string, unknown>;
248
+ const written = writtenOf(prepareCreate(schemas, values), table, 'insert');
249
+ // The rules never write `id`: a caller-chosen id is kept.
250
+ return toColumns(typeof values.id === 'string' ? { ...written, id: values.id } : written);
251
+ };
252
+
253
+ /** The patch as written to one stored row (CRUD update rules). */
254
+ const patchFor = (patch: Record<string, unknown>, stored: Record<string, unknown>): Record<string, unknown> =>
255
+ writtenOf(prepareUpdate(schemas, { id: String(stored.id), patch, stored }), table, 'update');
256
+
188
257
  const fromRows = (data: unknown): Row[] => ((data ?? []) as Record<string, unknown>[]).map((row) => mapper.fromBackendRow(row) as Row);
189
258
 
190
259
  const fail = (operation: string, error: { message: string }): never => {
@@ -224,7 +293,7 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
224
293
  async insert(values) {
225
294
  if (values.length === 0) return [];
226
295
  const { data, error } = await from()
227
- .insert(values.map((v) => toColumns(v as Record<string, unknown>)))
296
+ .insert(values.map(insertRow))
228
297
  .select('*');
229
298
  if (error) fail('insert', error);
230
299
  return fromRows(data);
@@ -232,9 +301,29 @@ export function createEntityStore<E extends AnyEntity>(client: SupabaseClient, e
232
301
 
233
302
  async update(where, patch) {
234
303
  if (where.length === 0) throw new DoNotDevError(`${entity.name}: update without a condition`, 'invalid-argument');
235
- const { data, error } = await filtered(from().update(toColumns(patch as Record<string, unknown>)), where, true).select('*');
304
+ const values = patch as Record<string, unknown>;
305
+ // Each stored row gives the patch its status and a published draft its record.
306
+ const targets = await list({ where, includeHidden: true });
307
+ if (targets.length === 0) return [];
308
+ let written: Record<string, unknown> = {};
309
+ for (const row of targets) written = patchFor(values, row as Record<string, unknown>);
310
+ // Only the validated rows: `where` again (concurrency guards) and their ids.
311
+ const ids = targets.map((row) => (row as Record<string, unknown>).id);
312
+ const { data, error } = await filtered(from().update(toColumns(written)), [...where, ['id', 'in', ids]], true).select('*');
236
313
  if (error) fail('update', error);
237
314
  return fromRows(data);
238
315
  },
316
+
317
+ async remove(where) {
318
+ if (where.length === 0) throw new DoNotDevError(`${entity.name}: remove without a condition`, 'invalid-argument');
319
+ const targets = await list({ where, includeHidden: true, select: ['id'] });
320
+ const first = targets[0] as Record<string, unknown> | undefined;
321
+ if (!first) return;
322
+ // CRUD rule 3 (core/schemas crud/update `prepareRemove`): the same patch for every row.
323
+ const written = writtenOf(prepareRemove(schemas, String(first.id)), table, 'remove');
324
+ const ids = targets.map((row) => (row as Record<string, unknown>).id);
325
+ const { error } = await filtered(from().update(toColumns(written)), [...where, ['id', 'in', ids]], true).select('id');
326
+ if (error) fail('remove', error);
327
+ },
239
328
  };
240
329
  }
@@ -11,11 +11,7 @@
11
11
 
12
12
  import * as v from 'valibot';
13
13
 
14
- import {
15
- filterVisibleFields,
16
- hasRoleAccess,
17
- HIDDEN_STATUSES,
18
- } from '@donotdev/core/server';
14
+ import { filterVisibleFields, isReadableBy } from '@donotdev/core/server';
19
15
  import type { EntityOwnershipConfig, UserRole } from '@donotdev/core/server';
20
16
  import {
21
17
  createEntityAwareMapper,
@@ -40,6 +36,7 @@ export type GetEntityRequest = { id: string };
40
36
  */
41
37
  export function createSupabaseGetEntity(
42
38
  collection: string,
39
+ // 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
40
  documentSchema: v.BaseSchema<unknown, any, v.BaseIssue<unknown>>,
44
41
  requiredRole: UserRole,
45
42
  ownership?: EntityOwnershipConfig
@@ -66,13 +63,8 @@ export function createSupabaseGetEntity(
66
63
  throw new DoNotDevError('Entity not found', 'not-found');
67
64
  }
68
65
 
69
- const isAdmin = hasRoleAccess(userRole, 'admin');
70
-
71
- // Hide drafts/deleted from non-admin users (security: hidden statuses never reach public)
72
- if (
73
- !isAdmin &&
74
- (HIDDEN_STATUSES as readonly string[]).includes(row.status)
75
- ) {
66
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
67
+ if (!isReadableBy(row, userRole)) {
76
68
  throw new DoNotDevError('Entity not found', 'not-found');
77
69
  }
78
70
 
@@ -84,7 +76,7 @@ export function createSupabaseGetEntity(
84
76
  : defaultFieldMapper;
85
77
  const normalized = entityMapper.fromBackendRow(row) as Record<
86
78
  string,
87
- any
79
+ unknown
88
80
  >;
89
81
 
90
82
  const visibilityOptions =
@@ -16,7 +16,7 @@ import * as v from 'valibot';
16
16
  import {
17
17
  filterVisibleFields,
18
18
  hasRoleAccess,
19
- HIDDEN_STATUSES,
19
+ hiddenStatusesFor,
20
20
  } from '@donotdev/core/server';
21
21
  import type {
22
22
  EntityOwnershipConfig,
@@ -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([
@@ -214,9 +217,10 @@ export function createSupabaseListEntities(
214
217
  .from(collection)
215
218
  .select(selectFields, { count: 'exact' });
216
219
 
217
- // Filter out hidden statuses for non-admin users
218
- if (!isAdmin) {
219
- query = query.not('status', 'in', [...HIDDEN_STATUSES]);
220
+ // CRUD rule 4 (core/schemas crud/read): hidden statuses never reach non-admins
221
+ const hidden = hiddenStatusesFor(userRole);
222
+ if (hidden.length > 0) {
223
+ query = query.not('status', 'in', [...hidden]);
220
224
  }
221
225
 
222
226
  // Ownership: when set and not admin, listCard = public condition, list = mine filter
@@ -339,7 +343,8 @@ export function createSupabaseListEntities(
339
343
  );
340
344
  }
341
345
 
342
- let items = (rows || []) as Record<string, any>[];
346
+ // why: non-literal select string types rows as GenericStringError[]; rows are plain objects
347
+ let items = (rows || []) as unknown as Record<string, unknown>[];
343
348
 
344
349
  // Filter out cursor item for keyset pagination.
345
350
  // Note: items are still raw DB rows here (pre-normalization), so mapper.toBackendField
@@ -362,7 +367,9 @@ export function createSupabaseListEntities(
362
367
  }
363
368
 
364
369
  // Helper: Check if value is a Picture object
365
- const isPictureObject = (value: any): boolean => {
370
+ const isPictureObject = (
371
+ value: unknown
372
+ ): value is { thumbUrl: unknown; fullUrl: unknown } => {
366
373
  return (
367
374
  typeof value === 'object' &&
368
375
  value !== null &&
@@ -372,7 +379,7 @@ export function createSupabaseListEntities(
372
379
  };
373
380
 
374
381
  // Helper: Optimize picture fields for listCard (only return first picture's thumbUrl)
375
- const optimizePictureField = (value: any): any => {
382
+ const optimizePictureField = (value: unknown): unknown => {
376
383
  if (Array.isArray(value) && value.length > 0) {
377
384
  const firstPicture = value[0];
378
385
  if (isPictureObject(firstPicture)) {
@@ -402,7 +409,7 @@ export function createSupabaseListEntities(
402
409
  const filteredItems = items.map((row) => {
403
410
  const camelRow = entityMapper.fromBackendRow(row) as Record<
404
411
  string,
405
- any
412
+ unknown
406
413
  >;
407
414
  const visibleData = filterVisibleFields(
408
415
  camelRow,
@@ -415,7 +422,7 @@ export function createSupabaseListEntities(
415
422
 
416
423
  // If listFields specified, filter to only those fields (plus id always)
417
424
  if (safeListFields && safeListFields.length > 0) {
418
- const filtered: Record<string, any> = { id: camelRow.id };
425
+ const filtered: Record<string, unknown> = { id: camelRow.id };
419
426
  for (const field of safeListFields) {
420
427
  if (field in visibleData) {
421
428
  const value = visibleData[field];
@@ -426,7 +433,7 @@ export function createSupabaseListEntities(
426
433
  }
427
434
 
428
435
  // No listFields restriction, return all visible fields (optimize pictures)
429
- const optimizedData: Record<string, any> = { id: camelRow.id };
436
+ const optimizedData: Record<string, unknown> = { id: camelRow.id };
430
437
  for (const [key, value] of Object.entries(visibleData)) {
431
438
  optimizedData[key] = optimizePictureField(value);
432
439
  }
@@ -442,7 +449,7 @@ export function createSupabaseListEntities(
442
449
  if (useKeysetPagination && orderBy.length > 0) {
443
450
  // Create cursor from last item's orderBy field + id
444
451
  const firstOrderField = orderBy[0][0];
445
- const orderByValue: Record<string, any> = {};
452
+ const orderByValue: Record<string, unknown> = {};
446
453
  orderByValue[firstOrderField] = lastItem[firstOrderField];
447
454
  lastVisible = encodeCursor(lastItem.id, orderByValue);
448
455
  } else if (useKeysetPagination) {