@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.
- package/README.md +1 -1
- package/lib/chunks/chunk-522YXGDA.js +23 -0
- package/lib/chunks/chunk-522YXGDA.js.map +7 -0
- package/lib/chunks/chunk-7ODXXXES.js +151 -0
- package/lib/chunks/chunk-7ODXXXES.js.map +7 -0
- package/lib/chunks/chunk-CP3NNKO5.js +22 -0
- package/lib/chunks/chunk-CP3NNKO5.js.map +7 -0
- package/lib/chunks/{chunk-2A4FPYNB.js → chunk-CVYSXC27.js} +2 -2
- package/lib/chunks/chunk-CVYSXC27.js.map +7 -0
- package/lib/chunks/{chunk-PJCJ5H2O.js → chunk-HZM5X5A7.js} +2 -2
- package/lib/chunks/chunk-ICNQCRLV.js +22 -0
- package/lib/chunks/chunk-ICNQCRLV.js.map +7 -0
- package/lib/chunks/chunk-OAZ2JYSD.js +22 -0
- package/lib/chunks/chunk-OAZ2JYSD.js.map +7 -0
- package/lib/chunks/chunk-OKRR7ST5.js +22 -0
- package/lib/chunks/chunk-OKRR7ST5.js.map +7 -0
- package/lib/chunks/chunk-PDBNKSBQ.js +22 -0
- package/lib/chunks/chunk-PDBNKSBQ.js.map +7 -0
- package/lib/chunks/chunk-TJPJXJEK.js +22 -0
- package/lib/chunks/{chunk-OZX5ZG44.js.map → chunk-TJPJXJEK.js.map} +1 -1
- package/lib/chunks/chunk-W6W4L44F.js +22 -0
- package/lib/chunks/chunk-W6W4L44F.js.map +7 -0
- package/lib/chunks/{monitoring-UIDJS2KA.js → monitoring-UCBNPPW2.js} +2 -2
- package/lib/chunks/{rateLimiter-WNWHI3B4.js → rateLimiter-XKECWM33.js} +2 -2
- package/lib/chunks/{server-RYGEBS2B.js → server-24XGDDO3.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/firebase/crud/aggregate.d.ts +1 -1
- package/lib/firebase/crud/create.d.ts +22 -1
- package/lib/firebase/crud/update.d.ts +27 -3
- package/lib/firebase/index.js +1 -1
- package/lib/firebase/index.js.map +3 -3
- package/lib/shared/billing/checkoutValidation.d.ts +1 -1
- package/lib/shared/billing/createCheckout.d.ts +1 -1
- package/lib/shared/billing/helpers/subscriptionManagement.d.ts +2 -2
- package/lib/shared/billing/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -0
- package/lib/shared/billing/orderWebhook.d.ts +29 -2
- package/lib/shared/billing/stripePinned.d.ts +43 -0
- package/lib/shared/billing/verifyOrderCheckout.d.ts +53 -0
- package/lib/shared/crud/bulkCore.d.ts +38 -10
- package/lib/shared/crud/index.d.ts +1 -0
- package/lib/shared/crud/written.d.ts +21 -0
- package/lib/shared/denoEnv.d.ts +25 -0
- package/lib/shared/github.d.ts +0 -8
- package/lib/shared/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/logger.d.ts +14 -14
- package/lib/shared/utils/external/subscription.d.ts +0 -8
- package/lib/shared/utils.d.ts +13 -10
- package/lib/supabase/auth/deleteAccount.d.ts +34 -2
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -9
- package/lib/supabase/crud/entityStore.d.ts +67 -14
- package/lib/supabase/crud/update.d.ts +7 -10
- package/lib/supabase/index.d.ts +5 -0
- package/lib/supabase/index.js +1 -1
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/crud/create.d.ts +6 -1
- package/lib/vercel/api/crud/update.d.ts +8 -1
- package/lib/vercel/api/index.js +1 -1
- package/lib/vercel/api/index.js.map +3 -3
- package/package.json +9 -9
- package/src/firebase/auth/getCustomClaims.ts +2 -0
- package/src/firebase/auth/getUserAuthStatus.ts +2 -0
- package/src/firebase/auth/removeCustomClaims.ts +33 -1
- package/src/firebase/auth/setCustomClaims.ts +6 -0
- package/src/firebase/baseFunction.ts +5 -2
- package/src/firebase/billing/changePlan.ts +6 -5
- package/src/firebase/billing/createCustomerPortal.ts +6 -4
- package/src/firebase/billing/refreshSubscriptionStatus.ts +7 -5
- package/src/firebase/billing/webhookHandler.ts +4 -4
- package/src/firebase/crud/__tests__/bulk.test.ts +50 -1
- package/src/firebase/crud/__tests__/create.test.ts +64 -0
- package/src/firebase/crud/__tests__/update.test.ts +97 -0
- package/src/firebase/crud/aggregate.ts +37 -19
- package/src/firebase/crud/bulk.ts +30 -10
- package/src/firebase/crud/create.ts +40 -26
- package/src/firebase/crud/delete.ts +6 -1
- package/src/firebase/crud/get.ts +12 -14
- package/src/firebase/crud/list.ts +23 -12
- package/src/firebase/crud/update.ts +49 -25
- package/src/firebase/helpers/githubAccessHelper.ts +3 -0
- package/src/firebase/helpers/githubTeamAccessHelper.ts +1 -0
- package/src/firebase/oauth/exchangeToken.ts +4 -0
- package/src/firebase/oauth/getConnections.ts +1 -1
- package/src/firebase/oauth/githubAccess.ts +3 -0
- package/src/firebase/oauth/refreshToken.ts +1 -0
- package/src/firebase/registerCrudFunctions.ts +1 -0
- package/src/firebase/scheduled/checkExpiredSubscriptions.ts +4 -1
- package/src/shared/__tests__/bulkCore.test.ts +191 -0
- package/src/shared/__tests__/removeCustomClaims.test.ts +117 -0
- package/src/shared/__tests__/setCustomClaims.test.ts +103 -0
- package/src/shared/__tests__/utils.test.ts +0 -30
- package/src/shared/ai/classifyAIError.ts +18 -10
- package/src/shared/ai/createAIRoute.ts +2 -1
- package/src/shared/ai/resolveModelTier.ts +2 -1
- package/src/shared/billing/__tests__/createCheckout.test.ts +94 -0
- package/src/shared/billing/__tests__/firestoreIdempotency.emulator.test.ts +1 -1
- package/src/shared/billing/__tests__/updateUserSubscription.test.ts +139 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.exports.test.ts +47 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.supabase.integration.test.ts +107 -0
- package/src/shared/billing/__tests__/verifyOrderCheckout.test.ts +233 -0
- package/src/shared/billing/__tests__/webhookHandler.test.ts +108 -0
- package/src/shared/billing/checkoutValidation.ts +19 -2
- package/src/shared/billing/createCheckout.ts +56 -11
- package/src/shared/billing/helpers/subscriptionManagement.ts +14 -10
- package/src/shared/billing/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/orderWebhook.ts +69 -1
- package/src/shared/billing/stripeClient.ts +2 -1
- package/src/shared/billing/stripePinned.ts +71 -0
- package/src/shared/billing/tierWebhookEvents.ts +3 -2
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/billing/webhookHandler.ts +5 -1
- package/src/shared/crud/bulkCore.ts +112 -82
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/denoEnv.ts +29 -0
- package/src/shared/email/createEmailRoute.ts +2 -2
- package/src/shared/errorHandling.ts +8 -8
- package/src/shared/firebase.ts +26 -9
- package/src/shared/github.ts +15 -5
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/logger.ts +37 -38
- package/src/shared/utils/external/date.ts +4 -4
- package/src/shared/utils/external/subscription.ts +2 -89
- package/src/shared/utils/firebaseHelpers.ts +2 -0
- package/src/shared/utils/internal/idempotency.ts +3 -0
- package/src/shared/utils/internal/monitoring.ts +6 -5
- package/src/shared/utils/internal/validation.ts +2 -0
- package/src/shared/utils/schemaValidation.ts +1 -0
- package/src/shared/utils/validation.ts +10 -20
- package/src/shared/utils.ts +4 -42
- package/src/supabase/__tests__/aggregate.test.ts +132 -0
- package/src/supabase/__tests__/bulk.test.ts +60 -2
- package/src/supabase/__tests__/create.test.ts +86 -0
- package/src/supabase/__tests__/entityStore.test.ts +91 -25
- package/src/supabase/__tests__/update.test.ts +107 -0
- package/src/supabase/auth/__tests__/deleteAccount.test.ts +102 -0
- package/src/supabase/auth/deleteAccount.ts +72 -5
- package/src/supabase/auth/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/billing/refreshSubscriptionStatus.ts +6 -5
- package/src/supabase/crud/aggregate.ts +85 -72
- package/src/supabase/crud/bulk.ts +50 -0
- package/src/supabase/crud/create.ts +27 -33
- package/src/supabase/crud/delete.ts +2 -1
- package/src/supabase/crud/entityStore.ts +107 -18
- package/src/supabase/crud/get.ts +5 -13
- package/src/supabase/crud/list.ts +28 -21
- package/src/supabase/crud/update.ts +29 -24
- package/src/supabase/edgeFunction.ts +2 -1
- package/src/supabase/email/createEmailFunction.ts +2 -1
- package/src/supabase/index.ts +8 -0
- package/src/supabase/oauth/exchangeToken.ts +1 -0
- package/src/supabase/oauth/getConnections.ts +1 -1
- package/src/supabase/oauth/refreshToken.ts +1 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/supabase/utils/idempotency.ts +1 -1
- package/src/supabase/utils/monitoring.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/billing/change-plan.ts +6 -5
- package/src/vercel/api/billing/refresh-subscription-status.ts +3 -1
- package/src/vercel/api/crud/bulk.ts +34 -6
- package/src/vercel/api/crud/create.ts +22 -21
- package/src/vercel/api/crud/delete.ts +5 -2
- package/src/vercel/api/crud/get.ts +10 -8
- package/src/vercel/api/crud/list.ts +10 -8
- package/src/vercel/api/crud/update.ts +25 -20
- package/src/vercel/api/oauth/check-github-access.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +5 -2
- package/src/vercel/api/oauth/grant-github-access.ts +1 -0
- package/src/vercel/api/oauth/revoke-github-access.ts +1 -0
- package/src/vercel/baseFunction.ts +5 -1
- package/lib/chunks/chunk-2A4FPYNB.js.map +0 -7
- package/lib/chunks/chunk-2IFFIUFV.js +0 -23
- package/lib/chunks/chunk-2IFFIUFV.js.map +0 -7
- package/lib/chunks/chunk-FQSQGOBN.js +0 -22
- package/lib/chunks/chunk-FQSQGOBN.js.map +0 -7
- package/lib/chunks/chunk-G4FO76EA.js +0 -22
- package/lib/chunks/chunk-G4FO76EA.js.map +0 -7
- package/lib/chunks/chunk-LSM5Y2E5.js +0 -22
- package/lib/chunks/chunk-LSM5Y2E5.js.map +0 -7
- package/lib/chunks/chunk-M4JV2JCF.js +0 -22
- package/lib/chunks/chunk-M4JV2JCF.js.map +0 -7
- package/lib/chunks/chunk-OZX5ZG44.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js +0 -22
- package/lib/chunks/chunk-PWAGW4R6.js.map +0 -7
- package/lib/chunks/chunk-UYI56E6Q.js +0 -151
- package/lib/chunks/chunk-UYI56E6Q.js.map +0 -7
- package/lib/chunks/chunk-ZVHC2CAV.js +0 -22
- package/lib/chunks/chunk-ZVHC2CAV.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/lib/shared/utils/functionWrapper.d.ts +0 -36
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -192
- package/src/shared/utils/__tests__/functionWrapper.test.ts +0 -122
- package/src/shared/utils/functionWrapper.ts +0 -73
- /package/lib/chunks/{chunk-PJCJ5H2O.js.map → chunk-HZM5X5A7.js.map} +0 -0
- /package/lib/chunks/{monitoring-UIDJS2KA.js.map → monitoring-UCBNPPW2.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-WNWHI3B4.js.map → rateLimiter-XKECWM33.js.map} +0 -0
- /package/lib/chunks/{server-RYGEBS2B.js.map → server-24XGDDO3.js.map} +0 -0
|
@@ -15,8 +15,10 @@ import { describe, it, expect, vi } from 'vitest';
|
|
|
15
15
|
import { BulkCollisionError } from '@donotdev/core/server';
|
|
16
16
|
import { DoNotDevError } from '@donotdev/core/server';
|
|
17
17
|
import { DEFAULT_STATUS_VALUE } from '@donotdev/core/server';
|
|
18
|
+
import { createSchemas } from '@donotdev/core/server';
|
|
18
19
|
|
|
19
20
|
import { executeBulk } from '../crud/bulkCore.js';
|
|
21
|
+
import { contactEntity } from '@dndev/test-entities';
|
|
20
22
|
|
|
21
23
|
// ---------------------------------------------------------------------------
|
|
22
24
|
// Fixtures
|
|
@@ -32,6 +34,11 @@ const ACCESS = {
|
|
|
32
34
|
delete: 'user' as const,
|
|
33
35
|
};
|
|
34
36
|
|
|
37
|
+
/** Stored rows of the mock store: every updated id exists, published, unless listed. */
|
|
38
|
+
let storedRows: Record<string, Record<string, unknown>> = {};
|
|
39
|
+
const readStored = async (ids: readonly string[]) =>
|
|
40
|
+
new Map(ids.map((id) => [id, storedRows[id] ?? { status: 'available' }]));
|
|
41
|
+
|
|
35
42
|
/** Default response-shape returned by the mock transact. */
|
|
36
43
|
function okResponse(prepared: {
|
|
37
44
|
inserts: Array<{ id: string; row: Record<string, unknown> }>;
|
|
@@ -60,6 +67,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
60
67
|
createSchema,
|
|
61
68
|
updateSchema,
|
|
62
69
|
access: ACCESS,
|
|
70
|
+
readStored,
|
|
63
71
|
uid: 'u1',
|
|
64
72
|
userRole: 'user',
|
|
65
73
|
transact,
|
|
@@ -85,6 +93,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
85
93
|
createSchema,
|
|
86
94
|
updateSchema,
|
|
87
95
|
access: ACCESS,
|
|
96
|
+
readStored,
|
|
88
97
|
uid: 'u1',
|
|
89
98
|
userRole: 'user',
|
|
90
99
|
transact,
|
|
@@ -114,6 +123,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
114
123
|
createSchema,
|
|
115
124
|
updateSchema,
|
|
116
125
|
access: ACCESS,
|
|
126
|
+
readStored,
|
|
117
127
|
uid: 'u1',
|
|
118
128
|
userRole: 'user',
|
|
119
129
|
transact,
|
|
@@ -138,6 +148,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
138
148
|
createSchema,
|
|
139
149
|
updateSchema,
|
|
140
150
|
access: ACCESS,
|
|
151
|
+
readStored,
|
|
141
152
|
uid: 'u1',
|
|
142
153
|
userRole: 'user',
|
|
143
154
|
transact,
|
|
@@ -159,6 +170,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
159
170
|
createSchema,
|
|
160
171
|
updateSchema,
|
|
161
172
|
access: { ...ACCESS, delete: 'admin' },
|
|
173
|
+
readStored,
|
|
162
174
|
uid: 'u1',
|
|
163
175
|
userRole: 'user',
|
|
164
176
|
transact,
|
|
@@ -181,6 +193,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
181
193
|
createSchema,
|
|
182
194
|
updateSchema,
|
|
183
195
|
access: { read: 'user' }, // no create role configured
|
|
196
|
+
readStored,
|
|
184
197
|
uid: 'u1',
|
|
185
198
|
userRole: 'user',
|
|
186
199
|
transact,
|
|
@@ -204,6 +217,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
204
217
|
createSchema,
|
|
205
218
|
updateSchema,
|
|
206
219
|
access: { update: 'user' }, // no create/delete roles configured — fine
|
|
220
|
+
readStored,
|
|
207
221
|
uid: 'u1',
|
|
208
222
|
userRole: 'user',
|
|
209
223
|
transact,
|
|
@@ -225,6 +239,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
225
239
|
createSchema,
|
|
226
240
|
updateSchema,
|
|
227
241
|
access: ACCESS,
|
|
242
|
+
readStored,
|
|
228
243
|
uid: 'u1',
|
|
229
244
|
userRole: 'user',
|
|
230
245
|
transact,
|
|
@@ -249,6 +264,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
249
264
|
createSchema,
|
|
250
265
|
updateSchema,
|
|
251
266
|
access: ACCESS,
|
|
267
|
+
readStored,
|
|
252
268
|
uid: 'u1',
|
|
253
269
|
userRole: 'user',
|
|
254
270
|
transact,
|
|
@@ -261,6 +277,173 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
261
277
|
expect(transact).not.toHaveBeenCalled();
|
|
262
278
|
});
|
|
263
279
|
|
|
280
|
+
it('validates updates with the entity schemas: draft patch → draft schema, other → update schema (with the id)', async () => {
|
|
281
|
+
const schemas = createSchemas(contactEntity);
|
|
282
|
+
const run = (patch: Record<string, unknown>) =>
|
|
283
|
+
executeBulk({
|
|
284
|
+
collection: 'contacts',
|
|
285
|
+
ops: { updates: [{ id: 'c1', patch }] },
|
|
286
|
+
createSchema: schemas.create,
|
|
287
|
+
draftCreateSchema: schemas.draft,
|
|
288
|
+
updateSchema: schemas.update,
|
|
289
|
+
access: ACCESS,
|
|
290
|
+
readStored,
|
|
291
|
+
uid: 'u1',
|
|
292
|
+
userRole: 'user',
|
|
293
|
+
transact: async (prepared) => okResponse(prepared),
|
|
294
|
+
});
|
|
295
|
+
await expect(run({ name: 'Ana' })).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
296
|
+
await expect(run({ status: 'draft', name: null })).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
297
|
+
for (const patch of [{ name: null }, { name: '' }, { status: 'draft', phone: 'TOTO' }]) {
|
|
298
|
+
await expect(run(patch)).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it('stores the parse output: unknown keys dropped from inserts and patches', async () => {
|
|
303
|
+
const transact = vi.fn(okResponse);
|
|
304
|
+
await executeBulk({
|
|
305
|
+
collection: 'events',
|
|
306
|
+
ops: {
|
|
307
|
+
inserts: [{ name: 'Alice', role: 'admin' }],
|
|
308
|
+
updates: [{ id: 'u1', patch: { name: 'Bob', createdById: 'evil' } }],
|
|
309
|
+
},
|
|
310
|
+
createSchema,
|
|
311
|
+
updateSchema,
|
|
312
|
+
access: ACCESS,
|
|
313
|
+
readStored,
|
|
314
|
+
uid: 'u1',
|
|
315
|
+
userRole: 'user',
|
|
316
|
+
transact,
|
|
317
|
+
});
|
|
318
|
+
const prepared = transact.mock.calls[0]![0];
|
|
319
|
+
expect(prepared.inserts[0]!.row).toEqual({ name: 'Alice', status: DEFAULT_STATUS_VALUE });
|
|
320
|
+
expect(prepared.updates[0]!.patch).toEqual({ name: 'Bob' });
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it('keeps a client-supplied insert id (pre-minted, referenced by other rows) when the target mints', async () => {
|
|
324
|
+
const schemas = createSchemas(contactEntity);
|
|
325
|
+
const transact = vi.fn(okResponse);
|
|
326
|
+
await executeBulk({
|
|
327
|
+
collection: 'lines',
|
|
328
|
+
ops: { inserts: [{ id: 'line-1', name: 'A' }, { name: 'B' }] },
|
|
329
|
+
createSchema: schemas.create,
|
|
330
|
+
updateSchema: schemas.update,
|
|
331
|
+
access: ACCESS,
|
|
332
|
+
readStored,
|
|
333
|
+
uid: 'u1',
|
|
334
|
+
userRole: 'user',
|
|
335
|
+
transact,
|
|
336
|
+
});
|
|
337
|
+
const prepared = transact.mock.calls[0]![0];
|
|
338
|
+
expect(prepared.inserts[0]).toMatchObject({ id: 'line-1', row: { id: 'line-1', name: 'A' } });
|
|
339
|
+
expect(prepared.inserts[1]!.id).toBe('');
|
|
340
|
+
expect(prepared.inserts[1]!.row).not.toHaveProperty('id');
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it('with mintInsertId the minted id wins over a client id', async () => {
|
|
344
|
+
const transact = vi.fn(okResponse);
|
|
345
|
+
await executeBulk({
|
|
346
|
+
collection: 'events',
|
|
347
|
+
ops: { inserts: [{ id: 'client-1', name: 'A' }] },
|
|
348
|
+
createSchema,
|
|
349
|
+
updateSchema,
|
|
350
|
+
access: ACCESS,
|
|
351
|
+
readStored,
|
|
352
|
+
uid: 'u1',
|
|
353
|
+
userRole: 'user',
|
|
354
|
+
mintInsertId: () => 'minted-1',
|
|
355
|
+
transact,
|
|
356
|
+
});
|
|
357
|
+
const prepared = transact.mock.calls[0]![0];
|
|
358
|
+
expect(prepared.inserts[0]!.id).toBe('minted-1');
|
|
359
|
+
expect(prepared.inserts[0]!.row).not.toHaveProperty('id');
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('update schema from the resulting status (patch ?? stored): a stored draft edit stays a draft write', async () => {
|
|
363
|
+
const schemas = createSchemas(contactEntity);
|
|
364
|
+
const transact = vi.fn(okResponse);
|
|
365
|
+
const run = (patch: Record<string, unknown>) =>
|
|
366
|
+
executeBulk({
|
|
367
|
+
collection: 'contacts',
|
|
368
|
+
ops: { updates: [{ id: 'c1', patch }] },
|
|
369
|
+
createSchema: schemas.create,
|
|
370
|
+
draftCreateSchema: schemas.draft,
|
|
371
|
+
updateSchema: schemas.update,
|
|
372
|
+
access: ACCESS,
|
|
373
|
+
readStored,
|
|
374
|
+
uid: 'u1',
|
|
375
|
+
userRole: 'user',
|
|
376
|
+
transact,
|
|
377
|
+
});
|
|
378
|
+
// Client form edit of a stored draft by a viewer who cannot edit status
|
|
379
|
+
storedRows = { c1: { id: 'c1', name: 'Ana', status: 'draft' } };
|
|
380
|
+
await expect(run({ name: null })).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
381
|
+
// Publishing through a status-only patch: the whole stored row is checked
|
|
382
|
+
storedRows = { c1: { id: 'c1', name: null, status: 'draft' } };
|
|
383
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument', message: expect.stringContaining('updates[0]') });
|
|
384
|
+
storedRows = { c1: { id: 'c1', status: 'draft' } };
|
|
385
|
+
await expect(run({ status: 'available' })).rejects.toMatchObject({ code: 'invalid-argument' });
|
|
386
|
+
// Soft-deleting a draft stays relaxed
|
|
387
|
+
storedRows = { c1: { id: 'c1', name: null, status: 'draft' } };
|
|
388
|
+
await expect(run({ status: 'deleted' })).resolves.toMatchObject({ updatedIds: ['c1'] });
|
|
389
|
+
// Filled in: published, only the sent keys written
|
|
390
|
+
transact.mockClear();
|
|
391
|
+
storedRows = { c1: { id: 'c1', name: 'Ana', status: 'draft' } };
|
|
392
|
+
await run({ status: 'available' });
|
|
393
|
+
expect(transact.mock.calls[0]![0].updates[0]!.patch).toEqual({ status: 'available' });
|
|
394
|
+
storedRows = {};
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it('updates without readStored are rejected (internal), no transact', async () => {
|
|
398
|
+
const transact = vi.fn(okResponse);
|
|
399
|
+
await expect(
|
|
400
|
+
executeBulk({
|
|
401
|
+
collection: 'events',
|
|
402
|
+
ops: { updates: [{ id: 'e1', patch: { name: 'x' } }] },
|
|
403
|
+
createSchema,
|
|
404
|
+
updateSchema,
|
|
405
|
+
access: ACCESS,
|
|
406
|
+
uid: 'u1',
|
|
407
|
+
userRole: 'user',
|
|
408
|
+
transact,
|
|
409
|
+
})
|
|
410
|
+
).rejects.toMatchObject({ code: 'internal', message: expect.stringContaining('readStored') });
|
|
411
|
+
expect(transact).not.toHaveBeenCalled();
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it('inserts and deletes need no readStored', async () => {
|
|
415
|
+
await expect(
|
|
416
|
+
executeBulk({
|
|
417
|
+
collection: 'events',
|
|
418
|
+
ops: { inserts: [{ name: 'a' }], deletes: ['e9'] },
|
|
419
|
+
createSchema,
|
|
420
|
+
updateSchema,
|
|
421
|
+
access: ACCESS,
|
|
422
|
+
uid: 'u1',
|
|
423
|
+
userRole: 'user',
|
|
424
|
+
transact: async (prepared) => okResponse(prepared),
|
|
425
|
+
})
|
|
426
|
+
).resolves.toMatchObject({ deletedIds: ['e9'] });
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it('an updated id with no stored row is rejected (not-found), no transact', async () => {
|
|
430
|
+
const transact = vi.fn(okResponse);
|
|
431
|
+
await expect(
|
|
432
|
+
executeBulk({
|
|
433
|
+
collection: 'events',
|
|
434
|
+
ops: { updates: [{ id: 'gone', patch: { name: 'x' } }] },
|
|
435
|
+
createSchema,
|
|
436
|
+
updateSchema,
|
|
437
|
+
access: ACCESS,
|
|
438
|
+
readStored: async () => new Map(),
|
|
439
|
+
uid: 'u1',
|
|
440
|
+
userRole: 'user',
|
|
441
|
+
transact,
|
|
442
|
+
})
|
|
443
|
+
).rejects.toMatchObject({ code: 'not-found', message: expect.stringContaining('updates[0]') });
|
|
444
|
+
expect(transact).not.toHaveBeenCalled();
|
|
445
|
+
});
|
|
446
|
+
|
|
264
447
|
it('wire-schema failure throws invalid-argument without calling transact', async () => {
|
|
265
448
|
const transact = vi.fn();
|
|
266
449
|
|
|
@@ -272,6 +455,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
272
455
|
createSchema,
|
|
273
456
|
updateSchema,
|
|
274
457
|
access: ACCESS,
|
|
458
|
+
readStored,
|
|
275
459
|
uid: 'u1',
|
|
276
460
|
userRole: 'user',
|
|
277
461
|
transact,
|
|
@@ -299,6 +483,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
299
483
|
createSchema,
|
|
300
484
|
updateSchema,
|
|
301
485
|
access: ACCESS,
|
|
486
|
+
readStored,
|
|
302
487
|
uid: 'user-1',
|
|
303
488
|
userRole: 'user',
|
|
304
489
|
mintInsertId: () => `mint-${++mintCounter}`,
|
|
@@ -364,6 +549,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
364
549
|
createSchema,
|
|
365
550
|
updateSchema,
|
|
366
551
|
access: ACCESS,
|
|
552
|
+
readStored,
|
|
367
553
|
uid: 'user-1',
|
|
368
554
|
userRole: 'user',
|
|
369
555
|
transact,
|
|
@@ -391,6 +577,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
391
577
|
createSchema,
|
|
392
578
|
updateSchema,
|
|
393
579
|
access: ACCESS,
|
|
580
|
+
readStored,
|
|
394
581
|
uid: 'u1',
|
|
395
582
|
userRole: 'user',
|
|
396
583
|
transact,
|
|
@@ -415,6 +602,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
415
602
|
createSchema,
|
|
416
603
|
updateSchema,
|
|
417
604
|
access: ACCESS,
|
|
605
|
+
readStored,
|
|
418
606
|
uid: 'u1',
|
|
419
607
|
userRole: 'user',
|
|
420
608
|
transact,
|
|
@@ -440,6 +628,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
440
628
|
createSchema,
|
|
441
629
|
updateSchema,
|
|
442
630
|
access: ACCESS,
|
|
631
|
+
readStored,
|
|
443
632
|
uid: 'u1',
|
|
444
633
|
userRole: 'user',
|
|
445
634
|
transact,
|
|
@@ -461,6 +650,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
461
650
|
createSchema,
|
|
462
651
|
updateSchema,
|
|
463
652
|
access: ACCESS,
|
|
653
|
+
readStored,
|
|
464
654
|
uid: 'u1',
|
|
465
655
|
userRole: 'user',
|
|
466
656
|
transact,
|
|
@@ -479,6 +669,7 @@ describe('executeBulk (shared CRUD core)', () => {
|
|
|
479
669
|
createSchema,
|
|
480
670
|
updateSchema,
|
|
481
671
|
access: ACCESS,
|
|
672
|
+
readStored,
|
|
482
673
|
uid: 'u1',
|
|
483
674
|
userRole: 'user',
|
|
484
675
|
transact,
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const { getUser, setCustomUserClaims, getUserById, updateUserById } = vi.hoisted(() => ({
|
|
4
|
+
getUser: vi.fn(),
|
|
5
|
+
setCustomUserClaims: vi.fn(),
|
|
6
|
+
getUserById: vi.fn(),
|
|
7
|
+
updateUserById: vi.fn(),
|
|
8
|
+
}));
|
|
9
|
+
|
|
10
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
11
|
+
getFirebaseAdminAuth: () => ({ getUser, setCustomUserClaims }),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('../../firebase/baseFunction.js', () => ({
|
|
14
|
+
createBaseFunction: (_config: unknown, _schema: unknown, _name: string, handler: unknown) => handler,
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('../../supabase/baseFunction.js', () => ({
|
|
17
|
+
createSupabaseHandler: (_name: string, _schema: unknown, handler: unknown) => handler,
|
|
18
|
+
}));
|
|
19
|
+
|
|
20
|
+
import { removeCustomClaims } from '../../firebase/auth/removeCustomClaims.js';
|
|
21
|
+
import { createRemoveCustomClaims } from '../../supabase/auth/removeCustomClaims.js';
|
|
22
|
+
|
|
23
|
+
// Base wrappers are mocked to expose only the authenticated business logic.
|
|
24
|
+
type Handler = (data: { claimsToRemove: string[] }, context: unknown) => Promise<unknown>;
|
|
25
|
+
|
|
26
|
+
const subscription = {
|
|
27
|
+
tier: 'member',
|
|
28
|
+
status: 'active',
|
|
29
|
+
subscriptionEnd: null,
|
|
30
|
+
updatedAt: '2026-06-01T00:00:00.000Z',
|
|
31
|
+
};
|
|
32
|
+
const paidSubscription = {
|
|
33
|
+
...subscription,
|
|
34
|
+
tier: 'premium',
|
|
35
|
+
subscriptionId: 'sub_paid',
|
|
36
|
+
customerId: 'cus_paid',
|
|
37
|
+
cancelAtPeriodEnd: false,
|
|
38
|
+
};
|
|
39
|
+
const existingClaims = { subscription, role: 'user', locale: 'en', theme: 'dark' };
|
|
40
|
+
const protectedKeys = [
|
|
41
|
+
'admin', 'isAdmin', 'isSuper', 'isSuperAdmin', 'role', 'roles',
|
|
42
|
+
'permissions', 'superuser', 'moderator', 'staff', 'elevated',
|
|
43
|
+
'plan', 'tier', 'subscription', 'provider', 'providers', 'sub', 'iss', 'aud',
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
beforeEach(() => {
|
|
47
|
+
vi.clearAllMocks();
|
|
48
|
+
getUser.mockResolvedValue({ customClaims: existingClaims });
|
|
49
|
+
setCustomUserClaims.mockResolvedValue(undefined);
|
|
50
|
+
getUserById.mockResolvedValue({ data: { user: { app_metadata: existingClaims } }, error: null });
|
|
51
|
+
updateUserById.mockResolvedValue({ error: null });
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
for (const provider of ['firebase', 'supabase'] as const) {
|
|
55
|
+
describe(`${provider} self-service claim removal`, () => {
|
|
56
|
+
const create = () => (provider === 'firebase'
|
|
57
|
+
? removeCustomClaims()
|
|
58
|
+
: createRemoveCustomClaims()) as unknown as Handler;
|
|
59
|
+
const context = {
|
|
60
|
+
uid: 'user-1',
|
|
61
|
+
supabaseAdmin: { auth: { admin: { getUserById, updateUserById } } },
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
it.each(protectedKeys)('rejects protected %s removal before accessing the provider', async (key) => {
|
|
65
|
+
await expect(create()({ claimsToRemove: ['locale', key] }, context))
|
|
66
|
+
.rejects.toThrow(`Protected claims cannot be removed: ${key}`);
|
|
67
|
+
expect(getUser).not.toHaveBeenCalled();
|
|
68
|
+
expect(getUserById).not.toHaveBeenCalled();
|
|
69
|
+
expect(setCustomUserClaims).not.toHaveBeenCalled();
|
|
70
|
+
expect(updateUserById).not.toHaveBeenCalled();
|
|
71
|
+
expect(existingClaims.locale).toBe('en');
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it.each([subscription, paidSubscription])(
|
|
75
|
+
'preserves canonical subscription and unrelated metadata when removing safe keys',
|
|
76
|
+
async (canonicalSubscription) => {
|
|
77
|
+
const claims = { ...existingClaims, subscription: canonicalSubscription };
|
|
78
|
+
getUser.mockResolvedValue({ customClaims: claims });
|
|
79
|
+
getUserById.mockResolvedValue({ data: { user: { app_metadata: claims } }, error: null });
|
|
80
|
+
const updatedClaims = { subscription: canonicalSubscription, role: 'user' };
|
|
81
|
+
|
|
82
|
+
await expect(create()({ claimsToRemove: ['locale', 'theme', 'missing'] }, context))
|
|
83
|
+
.resolves.toEqual({ success: true, customClaims: updatedClaims });
|
|
84
|
+
if (provider === 'firebase') {
|
|
85
|
+
expect(setCustomUserClaims).toHaveBeenCalledExactlyOnceWith('user-1', updatedClaims);
|
|
86
|
+
} else {
|
|
87
|
+
expect(updateUserById).toHaveBeenCalledExactlyOnceWith('user-1', {
|
|
88
|
+
app_metadata: { locale: null, theme: null, missing: null },
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
expect(claims).toEqual({ ...existingClaims, subscription: canonicalSubscription });
|
|
92
|
+
}
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
it.runIf(provider === 'supabase')('actually deletes safe keys without replaying a stale subscription', async () => {
|
|
96
|
+
const revoked = { ...subscription, tier: 'free', status: 'canceled' };
|
|
97
|
+
const stored: Record<string, unknown> = { ...existingClaims, subscription: revoked };
|
|
98
|
+
// Mirror Supabase Auth UpdateAppMetaData: merge values, delete null keys.
|
|
99
|
+
updateUserById.mockImplementation(async (_uid, { app_metadata }) => {
|
|
100
|
+
for (const [key, value] of Object.entries(app_metadata)) {
|
|
101
|
+
if (value === null) delete stored[key];
|
|
102
|
+
else stored[key] = value;
|
|
103
|
+
}
|
|
104
|
+
return { error: null };
|
|
105
|
+
});
|
|
106
|
+
await create()({ claimsToRemove: ['locale', 'theme'] }, context);
|
|
107
|
+
expect(stored).toEqual({ subscription: revoked, role: 'user' });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('keeps safe removal working when the user has no claims', async () => {
|
|
111
|
+
getUser.mockResolvedValue({});
|
|
112
|
+
getUserById.mockResolvedValue({ data: { user: {} }, error: null });
|
|
113
|
+
await expect(create()({ claimsToRemove: ['locale'] }, context))
|
|
114
|
+
.resolves.toEqual({ success: true, customClaims: {} });
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const { getUser, setCustomUserClaims, getUserById, updateUserById } = vi.hoisted(() => ({
|
|
4
|
+
getUser: vi.fn(),
|
|
5
|
+
setCustomUserClaims: vi.fn(),
|
|
6
|
+
getUserById: vi.fn(),
|
|
7
|
+
updateUserById: vi.fn(),
|
|
8
|
+
}));
|
|
9
|
+
|
|
10
|
+
vi.mock('@donotdev/firebase/server', () => ({
|
|
11
|
+
getFirebaseAdminAuth: () => ({ getUser, setCustomUserClaims }),
|
|
12
|
+
getFirebaseAdminFirestore: vi.fn(),
|
|
13
|
+
}));
|
|
14
|
+
vi.mock('../../firebase/baseFunction.js', () => ({
|
|
15
|
+
createBaseFunction: (_config: unknown, _schema: unknown, _name: string, handler: unknown) => handler,
|
|
16
|
+
}));
|
|
17
|
+
vi.mock('../../supabase/baseFunction.js', () => ({
|
|
18
|
+
createSupabaseHandler: (_name: string, _schema: unknown, handler: unknown) => handler,
|
|
19
|
+
}));
|
|
20
|
+
|
|
21
|
+
import { setCustomClaims } from '../../firebase/auth/setCustomClaims.js';
|
|
22
|
+
import { createSetCustomClaims } from '../../supabase/auth/setCustomClaims.js';
|
|
23
|
+
|
|
24
|
+
// Base wrappers are mocked above to expose only the authenticated business logic.
|
|
25
|
+
type Handler = (data: { customClaims: Record<string, unknown> }, context: unknown) => Promise<unknown>;
|
|
26
|
+
|
|
27
|
+
const subscription = {
|
|
28
|
+
tier: 'member',
|
|
29
|
+
status: 'active',
|
|
30
|
+
subscriptionEnd: null,
|
|
31
|
+
updatedAt: '2026-06-01T00:00:00.000Z',
|
|
32
|
+
};
|
|
33
|
+
const existingClaims = { subscription, role: 'user', locale: 'en' };
|
|
34
|
+
|
|
35
|
+
beforeEach(() => {
|
|
36
|
+
vi.clearAllMocks();
|
|
37
|
+
getUser.mockResolvedValue({ customClaims: existingClaims });
|
|
38
|
+
setCustomUserClaims.mockResolvedValue(undefined);
|
|
39
|
+
getUserById.mockResolvedValue({ data: { user: { app_metadata: existingClaims } }, error: null });
|
|
40
|
+
updateUserById.mockResolvedValue({ error: null });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
for (const provider of ['firebase', 'supabase'] as const) {
|
|
44
|
+
describe(`${provider} self-service custom claims`, () => {
|
|
45
|
+
const create = (allowedClaimKeys: string[]) => provider === 'firebase'
|
|
46
|
+
? setCustomClaims({ allowedClaimKeys })
|
|
47
|
+
: createSetCustomClaims({ allowedClaimKeys });
|
|
48
|
+
const context = {
|
|
49
|
+
uid: 'user-1',
|
|
50
|
+
supabaseAdmin: { auth: { admin: { getUserById, updateUserById } } },
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
it.each(['subscription', 'role', 'tier', 'plan'])(
|
|
54
|
+
'rejects mistakenly allowlisted %s at factory creation',
|
|
55
|
+
(key) => {
|
|
56
|
+
expect(() => create(['locale', key])).toThrow(`Claim key "${key}" is blocked`);
|
|
57
|
+
expect(getUser).not.toHaveBeenCalled();
|
|
58
|
+
expect(getUserById).not.toHaveBeenCalled();
|
|
59
|
+
expect(setCustomUserClaims).not.toHaveBeenCalled();
|
|
60
|
+
expect(updateUserById).not.toHaveBeenCalled();
|
|
61
|
+
}
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
it.each([subscription, { ...subscription, tier: 'premium', subscriptionId: 'sub_paid', customerId: 'cus_paid', cancelAtPeriodEnd: false }, null])(
|
|
65
|
+
'rejects subscription assignment or replacement through the request',
|
|
66
|
+
async (value) => {
|
|
67
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
68
|
+
await expect(handler({ customClaims: { subscription: value } }, context))
|
|
69
|
+
.rejects.toThrow('Claim keys not allowed: subscription');
|
|
70
|
+
expect(getUser).not.toHaveBeenCalled();
|
|
71
|
+
expect(getUserById).not.toHaveBeenCalled();
|
|
72
|
+
expect(setCustomUserClaims).not.toHaveBeenCalled();
|
|
73
|
+
expect(updateUserById).not.toHaveBeenCalled();
|
|
74
|
+
}
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
it.runIf(provider === 'supabase')('does not replay stale access claims over a concurrent trusted revoke', async () => {
|
|
78
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
79
|
+
const revoked = { ...subscription, tier: 'free', status: 'canceled' };
|
|
80
|
+
const stored = { ...existingClaims, subscription: revoked };
|
|
81
|
+
// getUserById returns the earlier snapshot; the server has since revoked access.
|
|
82
|
+
updateUserById.mockImplementation(async (_uid, { app_metadata }) => {
|
|
83
|
+
Object.assign(stored, app_metadata);
|
|
84
|
+
return { error: null };
|
|
85
|
+
});
|
|
86
|
+
await handler({ customClaims: { locale: 'fr' } }, context);
|
|
87
|
+
expect(stored).toEqual({ ...existingClaims, subscription: revoked, locale: 'fr' });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('preserves canonical subscription and unrelated claims when updating an allowed key', async () => {
|
|
91
|
+
const handler = create(['locale']) as unknown as Handler;
|
|
92
|
+
const updatedClaims = { ...existingClaims, locale: 'fr' };
|
|
93
|
+
await expect(handler({ customClaims: { locale: 'fr' } }, context))
|
|
94
|
+
.resolves.toEqual({ success: true, customClaims: updatedClaims });
|
|
95
|
+
if (provider === 'firebase') {
|
|
96
|
+
expect(setCustomUserClaims).toHaveBeenCalledWith('user-1', updatedClaims);
|
|
97
|
+
} else {
|
|
98
|
+
expect(updateUserById).toHaveBeenCalledWith('user-1', { app_metadata: { locale: 'fr' } });
|
|
99
|
+
}
|
|
100
|
+
expect(existingClaims.subscription).toEqual(subscription);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -44,7 +44,6 @@ import {
|
|
|
44
44
|
getUserRole,
|
|
45
45
|
createSuccessResponse,
|
|
46
46
|
createErrorResponse,
|
|
47
|
-
validateDocument,
|
|
48
47
|
validateCollectionName,
|
|
49
48
|
} from '../utils';
|
|
50
49
|
import { validateStripeEnvironment } from '../billing/stripeClient';
|
|
@@ -166,35 +165,6 @@ describe('createErrorResponse', () => {
|
|
|
166
165
|
});
|
|
167
166
|
});
|
|
168
167
|
|
|
169
|
-
// ---------------------------------------------------------------------------
|
|
170
|
-
// validateDocument
|
|
171
|
-
// ---------------------------------------------------------------------------
|
|
172
|
-
|
|
173
|
-
describe('validateDocument', () => {
|
|
174
|
-
it('accepts valid object data', () => {
|
|
175
|
-
expect(() => validateDocument({ name: 'test' })).not.toThrow();
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
it('rejects null', () => {
|
|
179
|
-
expect(() => validateDocument(null)).toThrow('Invalid document data');
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
it('rejects undefined', () => {
|
|
183
|
-
expect(() => validateDocument(undefined)).toThrow('Invalid document data');
|
|
184
|
-
});
|
|
185
|
-
|
|
186
|
-
it('rejects non-object', () => {
|
|
187
|
-
expect(() => validateDocument('string')).toThrow('Invalid document data');
|
|
188
|
-
expect(() => validateDocument(123)).toThrow('Invalid document data');
|
|
189
|
-
});
|
|
190
|
-
|
|
191
|
-
it('rejects arrays', () => {
|
|
192
|
-
expect(() => validateDocument([1, 2])).toThrow(
|
|
193
|
-
'Document data cannot be an array'
|
|
194
|
-
);
|
|
195
|
-
});
|
|
196
|
-
});
|
|
197
|
-
|
|
198
168
|
// ---------------------------------------------------------------------------
|
|
199
169
|
// validateCollectionName
|
|
200
170
|
// ---------------------------------------------------------------------------
|
|
@@ -139,12 +139,18 @@ export function mapClassifiedToHTTP(code: AIErrorCode): number {
|
|
|
139
139
|
function extractStatus(err: unknown): number | undefined {
|
|
140
140
|
if (err && typeof err === 'object') {
|
|
141
141
|
// Anthropic SDK errors have .status
|
|
142
|
-
if ('status' in err && typeof
|
|
143
|
-
return
|
|
142
|
+
if ('status' in err && typeof err.status === 'number') {
|
|
143
|
+
return err.status;
|
|
144
144
|
}
|
|
145
145
|
// Some errors nest status in .error
|
|
146
|
-
if (
|
|
147
|
-
|
|
146
|
+
if (
|
|
147
|
+
'error' in err &&
|
|
148
|
+
typeof err.error === 'object' &&
|
|
149
|
+
err.error !== null &&
|
|
150
|
+
'status' in err.error &&
|
|
151
|
+
typeof err.error.status === 'number'
|
|
152
|
+
) {
|
|
153
|
+
return err.error.status;
|
|
148
154
|
}
|
|
149
155
|
}
|
|
150
156
|
return undefined;
|
|
@@ -154,7 +160,7 @@ function extractMessage(err: unknown): string {
|
|
|
154
160
|
if (err instanceof Error) return err.message.toLowerCase();
|
|
155
161
|
if (typeof err === 'string') return err.toLowerCase();
|
|
156
162
|
if (err && typeof err === 'object' && 'message' in err) {
|
|
157
|
-
return String(
|
|
163
|
+
return String(err.message).toLowerCase();
|
|
158
164
|
}
|
|
159
165
|
return '';
|
|
160
166
|
}
|
|
@@ -162,12 +168,14 @@ function extractMessage(err: unknown): string {
|
|
|
162
168
|
function extractRetryAfter(err: unknown): number | undefined {
|
|
163
169
|
if (err && typeof err === 'object') {
|
|
164
170
|
// Anthropic SDK puts headers on the error
|
|
165
|
-
const headers =
|
|
166
|
-
if (headers) {
|
|
167
|
-
const retryAfter =
|
|
168
|
-
typeof headers.get === 'function'
|
|
171
|
+
const headers: unknown = 'headers' in err ? err.headers : undefined;
|
|
172
|
+
if (headers && typeof headers === 'object') {
|
|
173
|
+
const retryAfter: unknown =
|
|
174
|
+
'get' in headers && typeof headers.get === 'function'
|
|
169
175
|
? headers.get('retry-after')
|
|
170
|
-
:
|
|
176
|
+
: 'retry-after' in headers
|
|
177
|
+
? headers['retry-after']
|
|
178
|
+
: undefined;
|
|
171
179
|
if (retryAfter) {
|
|
172
180
|
const seconds = Number(retryAfter);
|
|
173
181
|
if (!Number.isNaN(seconds)) return seconds * 1000;
|
|
@@ -28,6 +28,7 @@ import type {
|
|
|
28
28
|
import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
|
|
29
29
|
|
|
30
30
|
import { calculateCost } from './costTracker.js';
|
|
31
|
+
import { getDenoEnv } from '../denoEnv.js';
|
|
31
32
|
|
|
32
33
|
// =============================================================================
|
|
33
34
|
// Types
|
|
@@ -395,7 +396,7 @@ function jsonError(message: string, status: number): Response {
|
|
|
395
396
|
|
|
396
397
|
function getEnv(name: string): string | undefined {
|
|
397
398
|
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
398
|
-
return (
|
|
399
|
+
return getDenoEnv()?.get(name);
|
|
399
400
|
}
|
|
400
401
|
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
401
402
|
}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
import { AI_TIERS } from '@donotdev/core/server';
|
|
15
15
|
import type { AITierId } from '@donotdev/core/server';
|
|
16
|
+
import { getDenoEnv } from '../denoEnv.js';
|
|
16
17
|
|
|
17
18
|
// =============================================================================
|
|
18
19
|
// Env helper (Deno + Node cross-runtime)
|
|
@@ -20,7 +21,7 @@ import type { AITierId } from '@donotdev/core/server';
|
|
|
20
21
|
|
|
21
22
|
function getEnv(name: string): string | undefined {
|
|
22
23
|
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
23
|
-
return (
|
|
24
|
+
return getDenoEnv()?.get(name);
|
|
24
25
|
}
|
|
25
26
|
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
26
27
|
}
|