@donotdev/functions 0.2.3 → 0.3.1
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/guidelines/VERCEL.md +2 -2
- package/lib/chunks/{chunk-UH445BGK.js → chunk-2N73OZFE.js} +2 -2
- package/lib/chunks/chunk-472JD6X7.js +22 -0
- package/lib/chunks/chunk-472JD6X7.js.map +7 -0
- package/lib/chunks/{chunk-QXIOO2RL.js → chunk-BTWJEJCV.js} +2 -2
- package/lib/chunks/chunk-CN6WXKYF.js +22 -0
- package/lib/chunks/chunk-CN6WXKYF.js.map +7 -0
- package/lib/chunks/{chunk-GDIUOJMD.js → chunk-DGBZDD6D.js} +2 -2
- package/lib/chunks/chunk-GBZQPOX4.js +151 -0
- package/lib/chunks/{chunk-F3WBFWPO.js.map → chunk-GBZQPOX4.js.map} +3 -3
- package/lib/chunks/chunk-ORBGTVJI.js +22 -0
- package/lib/chunks/{chunk-EZKRLLSQ.js.map → chunk-ORBGTVJI.js.map} +1 -1
- package/lib/chunks/chunk-R3I7U5QT.js +22 -0
- package/lib/chunks/chunk-R3I7U5QT.js.map +7 -0
- package/lib/chunks/{chunk-6NXIK35R.js → chunk-XWMG2FWZ.js} +2 -2
- package/lib/chunks/{chunk-6NXIK35R.js.map → chunk-XWMG2FWZ.js.map} +1 -1
- package/lib/chunks/chunk-ZCY6GTIC.js +22 -0
- package/lib/chunks/chunk-ZCY6GTIC.js.map +7 -0
- package/lib/chunks/{monitoring-LXNVBD3G.js → monitoring-KF7FRUQ6.js} +2 -2
- package/lib/chunks/{rateLimiter-GG5LPWXJ.js → rateLimiter-S7TITXOD.js} +2 -2
- package/lib/chunks/{server-NODQAE3F.js → server-SU4BVPPF.js} +2 -2
- package/lib/firebase/auth/removeCustomClaims.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/helpers/updateUserSubscription.d.ts +2 -8
- package/lib/shared/billing/index.d.ts +2 -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/index.d.ts +0 -1
- package/lib/shared/index.js +1 -1
- package/lib/shared/utils.d.ts +0 -9
- package/lib/supabase/crud/bulk.d.ts +7 -0
- package/lib/supabase/crud/create.d.ts +5 -1
- package/lib/supabase/crud/entityStore.d.ts +54 -14
- package/lib/supabase/crud/update.d.ts +7 -2
- package/lib/supabase/index.d.ts +4 -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/package.json +3 -3
- package/src/firebase/auth/removeCustomClaims.ts +31 -1
- package/src/firebase/auth/setCustomClaims.ts +3 -0
- 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 +10 -21
- package/src/firebase/crud/bulk.ts +23 -10
- package/src/firebase/crud/create.ts +19 -18
- package/src/firebase/crud/get.ts +3 -12
- package/src/firebase/crud/list.ts +5 -4
- package/src/firebase/crud/update.ts +35 -19
- package/src/firebase/registerCrudFunctions.ts +1 -0
- 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/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/helpers/updateUserSubscription.ts +10 -14
- package/src/shared/billing/index.ts +2 -0
- package/src/shared/billing/verifyOrderCheckout.ts +142 -0
- package/src/shared/crud/bulkCore.ts +110 -81
- package/src/shared/crud/index.ts +1 -0
- package/src/shared/crud/written.ts +56 -0
- package/src/shared/index.d.ts +0 -9
- package/src/shared/index.ts +0 -1
- package/src/shared/utils.ts +0 -43
- 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/removeCustomClaims.ts +7 -2
- package/src/supabase/auth/setCustomClaims.ts +4 -2
- package/src/supabase/crud/bulk.ts +47 -0
- package/src/supabase/crud/create.ts +14 -24
- package/src/supabase/crud/entityStore.ts +106 -17
- package/src/supabase/crud/get.ts +3 -12
- package/src/supabase/crud/list.ts +5 -4
- package/src/supabase/crud/update.ts +20 -18
- package/src/supabase/index.ts +7 -0
- package/src/supabase/registerCrudFunctions.ts +1 -0
- package/src/vercel/__tests__/bulk.test.ts +16 -8
- package/src/vercel/api/crud/bulk.ts +27 -4
- package/src/vercel/api/crud/create.ts +17 -19
- package/src/vercel/api/crud/get.ts +5 -6
- package/src/vercel/api/crud/list.ts +4 -5
- package/src/vercel/api/crud/update.ts +20 -18
- package/lib/chunks/chunk-EZKRLLSQ.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js +0 -22
- package/lib/chunks/chunk-F3PHE627.js.map +0 -7
- package/lib/chunks/chunk-F3WBFWPO.js +0 -151
- package/lib/chunks/chunk-G5DRV3DH.js +0 -22
- package/lib/chunks/chunk-G5DRV3DH.js.map +0 -7
- package/lib/chunks/chunk-Q2WLRFOE.js +0 -22
- package/lib/chunks/chunk-Q2WLRFOE.js.map +0 -7
- package/lib/chunks/chunk-W74UL7AY.js +0 -22
- package/lib/chunks/chunk-W74UL7AY.js.map +0 -7
- package/lib/shared/schema.d.ts +0 -56
- package/src/shared/__tests__/schema.test.ts +0 -219
- package/src/shared/schema.ts +0 -188
- /package/lib/chunks/{chunk-UH445BGK.js.map → chunk-2N73OZFE.js.map} +0 -0
- /package/lib/chunks/{chunk-QXIOO2RL.js.map → chunk-BTWJEJCV.js.map} +0 -0
- /package/lib/chunks/{chunk-GDIUOJMD.js.map → chunk-DGBZDD6D.js.map} +0 -0
- /package/lib/chunks/{monitoring-LXNVBD3G.js.map → monitoring-KF7FRUQ6.js.map} +0 -0
- /package/lib/chunks/{rateLimiter-GG5LPWXJ.js.map → rateLimiter-S7TITXOD.js.map} +0 -0
- /package/lib/chunks/{server-NODQAE3F.js.map → server-SU4BVPPF.js.map} +0 -0
|
@@ -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
|
-
|
|
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
|
|
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
|
-
/**
|
|
13
|
-
|
|
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
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
|
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', '
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
+
});
|
|
@@ -43,6 +43,7 @@ const BLOCKED_CLAIM_KEYS = new Set([
|
|
|
43
43
|
'elevated',
|
|
44
44
|
'plan',
|
|
45
45
|
'tier',
|
|
46
|
+
'subscription',
|
|
46
47
|
'provider',
|
|
47
48
|
'providers',
|
|
48
49
|
'sub',
|
|
@@ -102,10 +103,14 @@ export function createRemoveCustomClaims() {
|
|
|
102
103
|
delete existingClaims[key];
|
|
103
104
|
}
|
|
104
105
|
|
|
105
|
-
//
|
|
106
|
+
// Supabase merges app_metadata; omitted keys survive. Null deletes a key.
|
|
107
|
+
// Patch only requested keys, never replay stale subscription/role metadata.
|
|
108
|
+
const removals = Object.fromEntries(
|
|
109
|
+
data.claimsToRemove.map((key) => [key, null])
|
|
110
|
+
);
|
|
106
111
|
const { error: updateError } =
|
|
107
112
|
await ctx.supabaseAdmin.auth.admin.updateUserById(ctx.uid, {
|
|
108
|
-
app_metadata:
|
|
113
|
+
app_metadata: removals,
|
|
109
114
|
});
|
|
110
115
|
if (updateError) throw updateError;
|
|
111
116
|
|
|
@@ -42,6 +42,7 @@ const BLOCKED_CLAIM_KEYS = new Set([
|
|
|
42
42
|
'elevated',
|
|
43
43
|
'plan',
|
|
44
44
|
'tier',
|
|
45
|
+
'subscription',
|
|
45
46
|
'provider',
|
|
46
47
|
'providers',
|
|
47
48
|
'sub',
|
|
@@ -123,10 +124,11 @@ export function createSetCustomClaims(options: SetCustomClaimsOptions) {
|
|
|
123
124
|
>;
|
|
124
125
|
const updatedClaims = { ...existingClaims, ...data.customClaims };
|
|
125
126
|
|
|
126
|
-
//
|
|
127
|
+
// Supabase merges app_metadata server-side. Send only allowed changes so a
|
|
128
|
+
// stale read cannot replay subscription/role over a concurrent trusted update.
|
|
127
129
|
const { error: updateError } =
|
|
128
130
|
await ctx.supabaseAdmin.auth.admin.updateUserById(ctx.uid, {
|
|
129
|
-
app_metadata:
|
|
131
|
+
app_metadata: data.customClaims,
|
|
130
132
|
});
|
|
131
133
|
if (updateError) throw updateError;
|
|
132
134
|
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
BulkCollisionError,
|
|
24
24
|
BulkRequestSchema,
|
|
25
25
|
DoNotDevError,
|
|
26
|
+
statusOf,
|
|
26
27
|
} from '@donotdev/core/server';
|
|
27
28
|
import type {
|
|
28
29
|
BulkRequest,
|
|
@@ -42,6 +43,13 @@ import { createSupabaseHandler } from '../baseFunction.js';
|
|
|
42
43
|
|
|
43
44
|
const mapper = defaultFieldMapper;
|
|
44
45
|
|
|
46
|
+
/**
|
|
47
|
+
* SQLSTATE `crud_bulk` raises when an updated row's status is not the one read
|
|
48
|
+
* before the RPC (custom `PT409`, HTTP 409 via PostgREST, never retried): the bulk was validated against a stale
|
|
49
|
+
* status, nothing is written.
|
|
50
|
+
*/
|
|
51
|
+
const STATUS_CHANGED_SQLSTATE = 'PT409';
|
|
52
|
+
|
|
45
53
|
/** Request payload accepted by the bulk handler — mirrors {@link BulkRequestSchema}. */
|
|
46
54
|
export type BulkEntityRequest = BulkRequest;
|
|
47
55
|
|
|
@@ -103,6 +111,13 @@ function preparePatch(
|
|
|
103
111
|
* which wraps `BEGIN ... COMMIT` — any failure triggers `ROLLBACK` and the
|
|
104
112
|
* client observes a rejected promise with no partial state.
|
|
105
113
|
*
|
|
114
|
+
* The stored rows of the updated ids are read before the RPC (their status picks
|
|
115
|
+
* each patch's schema, the CRUD rules). The statuses read are passed as
|
|
116
|
+
* `p_expected_statuses`; `crud_bulk` locks each updated row (`FOR UPDATE`) and
|
|
117
|
+
* rejects the whole bulk (`unavailable`, nothing written) when a status changed in
|
|
118
|
+
* between. Requires the `crud_bulk_status_guard` migration (5-argument
|
|
119
|
+
* `crud_bulk`); against an older database the RPC call fails (function not found).
|
|
120
|
+
*
|
|
106
121
|
* The factory returns a handler that is auto-registered as `bulk_${collection}`
|
|
107
122
|
* by {@link createSupabaseCrudFunctions}.
|
|
108
123
|
*
|
|
@@ -164,6 +179,9 @@ export function createSupabaseBulkEntity(
|
|
|
164
179
|
BulkRequestSchema,
|
|
165
180
|
async (data: BulkEntityRequest, ctx): Promise<BulkResponse> => {
|
|
166
181
|
const { uid, userRole, supabaseAdmin } = ctx;
|
|
182
|
+
// Status of each updated row as read by `readStored` (id → status), re-checked
|
|
183
|
+
// by `crud_bulk` under lock before any write.
|
|
184
|
+
const expectedStatuses: Record<string, string | null> = {};
|
|
167
185
|
|
|
168
186
|
try {
|
|
169
187
|
return await executeBulk({
|
|
@@ -177,6 +195,28 @@ export function createSupabaseBulkEntity(
|
|
|
177
195
|
userRole,
|
|
178
196
|
// Supabase's `crud_bulk` RPC mints ids server-side — skip the
|
|
179
197
|
// client-side mint hook so the RPC owns the id space.
|
|
198
|
+
// Stored rows of the updated ids: their status decides each patch's
|
|
199
|
+
// schema. This read is outside the RPC transaction: the statuses read
|
|
200
|
+
// are sent to `crud_bulk`, which re-checks them under lock.
|
|
201
|
+
readStored: async (ids) => {
|
|
202
|
+
const { data: rows, error: readError } = await supabaseAdmin
|
|
203
|
+
.from(collection)
|
|
204
|
+
.select('*')
|
|
205
|
+
.in('id', [...ids]);
|
|
206
|
+
if (readError) {
|
|
207
|
+
throw new DoNotDevError(
|
|
208
|
+
`Failed to read rows for bulk: ${readError.message}`,
|
|
209
|
+
'internal'
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
const stored = new Map<string, Record<string, unknown>>();
|
|
213
|
+
for (const row of (rows ?? []) as Record<string, unknown>[]) {
|
|
214
|
+
const mapped = mapper.fromBackendRow(row) as Record<string, unknown>;
|
|
215
|
+
stored.set(String(mapped.id), mapped);
|
|
216
|
+
expectedStatuses[String(mapped.id)] = statusOf(mapped);
|
|
217
|
+
}
|
|
218
|
+
return stored;
|
|
219
|
+
},
|
|
180
220
|
stampInsertMetadata: prepareInsertRow,
|
|
181
221
|
stampUpdateMetadata: preparePatch,
|
|
182
222
|
transact: async ({ inserts, updates, deletes }) => {
|
|
@@ -186,7 +226,14 @@ export function createSupabaseBulkEntity(
|
|
|
186
226
|
p_inserts: inserts.map((i) => i.row),
|
|
187
227
|
p_updates: updates.map((u) => ({ id: u.id, patch: u.patch })),
|
|
188
228
|
p_deletes: deletes,
|
|
229
|
+
p_expected_statuses: expectedStatuses,
|
|
189
230
|
});
|
|
231
|
+
if (rpcError?.code === STATUS_CHANGED_SQLSTATE) {
|
|
232
|
+
throw new DoNotDevError(
|
|
233
|
+
`Bulk rejected, nothing written: ${rpcError.message}. Reload and retry.`,
|
|
234
|
+
'unavailable'
|
|
235
|
+
);
|
|
236
|
+
}
|
|
190
237
|
if (rpcError) {
|
|
191
238
|
throw new DoNotDevError(
|
|
192
239
|
`Failed to execute bulk: ${rpcError.message}`,
|