@quitecustard/payload 0.1.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/LICENSE +21 -0
- package/README.md +169 -0
- package/dist/access/anyone.d.ts +10 -0
- package/dist/access/anyone.js +9 -0
- package/dist/access/role-gate.d.ts +22 -0
- package/dist/access/role-gate.js +21 -0
- package/dist/access/self-access.d.ts +30 -0
- package/dist/access/self-access.js +34 -0
- package/dist/db/delete-many-with-versions.d.ts +21 -0
- package/dist/db/delete-many-with-versions.js +34 -0
- package/dist/db/external-ref.d.ts +65 -0
- package/dist/db/external-ref.js +88 -0
- package/dist/db/orphan-cleanup.d.ts +32 -0
- package/dist/db/orphan-cleanup.js +64 -0
- package/dist/db/sessions.d.ts +46 -0
- package/dist/db/sessions.js +50 -0
- package/dist/db/sql-result.d.ts +19 -0
- package/dist/db/sql-result.js +41 -0
- package/dist/db/sync-lock.d.ts +36 -0
- package/dist/db/sync-lock.js +116 -0
- package/dist/db/transaction-db.d.ts +13 -0
- package/dist/db/transaction-db.js +14 -0
- package/dist/documents/collection-versions.d.ts +10 -0
- package/dist/documents/collection-versions.js +17 -0
- package/dist/documents/locale-record.d.ts +12 -0
- package/dist/documents/locale-record.js +24 -0
- package/dist/documents/published-where.d.ts +21 -0
- package/dist/documents/published-where.js +17 -0
- package/dist/documents/resolve-ref.d.ts +29 -0
- package/dist/documents/resolve-ref.js +38 -0
- package/dist/errors/field-errors.d.ts +11 -0
- package/dist/errors/field-errors.js +16 -0
- package/dist/errors/is-duplicate-error.d.ts +14 -0
- package/dist/errors/is-duplicate-error.js +22 -0
- package/dist/errors/public-error.d.ts +17 -0
- package/dist/errors/public-error.js +26 -0
- package/dist/fields/colour-options-field.d.ts +18 -0
- package/dist/fields/colour-options-field.js +44 -0
- package/dist/fields/colour-picker-field.d.ts +12 -0
- package/dist/fields/colour-picker-field.js +11 -0
- package/dist/fields/height-field.d.ts +12 -0
- package/dist/fields/height-field.js +11 -0
- package/dist/fields/hero-field.d.ts +16 -0
- package/dist/fields/hero-field.js +50 -0
- package/dist/fields/layout-fields.d.ts +7 -0
- package/dist/fields/layout-fields.js +47 -0
- package/dist/fields/link-field.d.ts +34 -0
- package/dist/fields/link-field.js +170 -0
- package/dist/fields/media-content-fields.d.ts +23 -0
- package/dist/fields/media-content-fields.js +103 -0
- package/dist/fields/owner-field.d.ts +19 -0
- package/dist/fields/owner-field.js +53 -0
- package/dist/fields/phone-field.d.ts +12 -0
- package/dist/fields/phone-field.js +11 -0
- package/dist/fields/seo-tab.d.ts +18 -0
- package/dist/fields/seo-tab.js +36 -0
- package/dist/fields/size-field.d.ts +8 -0
- package/dist/fields/size-field.js +19 -0
- package/dist/fields/social-url.d.ts +21 -0
- package/dist/fields/social-url.js +49 -0
- package/dist/fields/spacing-select-field.d.ts +17 -0
- package/dist/fields/spacing-select-field.js +36 -0
- package/dist/internal/component-field.d.ts +25 -0
- package/dist/internal/component-field.js +24 -0
- package/dist/operations/after-response.d.ts +24 -0
- package/dist/operations/after-response.js +40 -0
- package/dist/operations/publish-transition.d.ts +45 -0
- package/dist/operations/publish-transition.js +78 -0
- package/dist/operations/run-queued-jobs.d.ts +30 -0
- package/dist/operations/run-queued-jobs.js +87 -0
- package/dist/operations/suppress-context.d.ts +16 -0
- package/dist/operations/suppress-context.js +55 -0
- package/dist/operations/unique-slug.d.ts +12 -0
- package/dist/operations/unique-slug.js +23 -0
- package/dist/operations/unique-username.d.ts +40 -0
- package/dist/operations/unique-username.js +52 -0
- package/package.json +76 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { BasePayload, PayloadRequest } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Add a session row for `userId` on an auth collection's `sessions` array field, dropping any that
|
|
4
|
+
* have already expired on the way past.
|
|
5
|
+
*
|
|
6
|
+
* 🔴 NOT `payload.update`. Payload stores an array field as a FULL REPLACE - delete every child
|
|
7
|
+
* row, reinsert the array it was handed. Two logins in the same moment (two devices, or a
|
|
8
|
+
* double-tap) each read `[A]`, then one writes `[A, B]` while the other writes `[A, C]` from its
|
|
9
|
+
* own stale snapshot; the loser's device is left holding a JWT whose `sid` is no longer on the
|
|
10
|
+
* row. A single-row INSERT commutes with any other login's INSERT, so there is no window to lose.
|
|
11
|
+
*
|
|
12
|
+
* No lock is taken and none should be: the FK from this table to the auth collection means every
|
|
13
|
+
* INSERT here already holds KEY SHARE on the parent row, which is exactly what a `SELECT … FOR
|
|
14
|
+
* UPDATE` on that row blocks against.
|
|
15
|
+
*
|
|
16
|
+
* Going through SQL also skips the auth collection's hook chain, which `payload.update` would run
|
|
17
|
+
* on every sign-in, and leaves its `updated_at` alone.
|
|
18
|
+
*
|
|
19
|
+
* ⚠️ This closes the race on the path that calls it only. Payload's own `addSessionToUser`,
|
|
20
|
+
* `logout` and `refresh` still read-modify-write the whole array.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* await appendUserSession({ payload, userId: user.id, sid, createdAt, expiresAt, req })
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Pass `req` wherever one exists: the statement then runs on the operation's own transaction
|
|
27
|
+
* instead of the pooled root handle.
|
|
28
|
+
*/
|
|
29
|
+
export declare const appendUserSession: ({ payload, userId, sid, createdAt, expiresAt, req, table, }: {
|
|
30
|
+
payload: BasePayload;
|
|
31
|
+
/** Id of the row owning the session - a string on a uuid-id project. */
|
|
32
|
+
userId: number | string;
|
|
33
|
+
sid: string;
|
|
34
|
+
createdAt: Date;
|
|
35
|
+
expiresAt: Date;
|
|
36
|
+
/**
|
|
37
|
+
* The operation's request, when there is one. Without it the INSERT runs on the pooled root
|
|
38
|
+
* handle: inside an open transaction that is a DIFFERENT connection, so it cannot see the
|
|
39
|
+
* uncommitted parent row (foreign key violation) and can deadlock against locks the outer
|
|
40
|
+
* transaction already holds.
|
|
41
|
+
*/
|
|
42
|
+
req?: PayloadRequest;
|
|
43
|
+
/** Physical table backing the auth collection's `sessions` array field. Defaults to Payload's
|
|
44
|
+
* own naming for a `users` collection - `<collection>_sessions` for any other slug. */
|
|
45
|
+
table?: string;
|
|
46
|
+
}) => Promise<void>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { transactionDb } from './transaction-db.js';
|
|
3
|
+
/**
|
|
4
|
+
* Add a session row for `userId` on an auth collection's `sessions` array field, dropping any that
|
|
5
|
+
* have already expired on the way past.
|
|
6
|
+
*
|
|
7
|
+
* 🔴 NOT `payload.update`. Payload stores an array field as a FULL REPLACE - delete every child
|
|
8
|
+
* row, reinsert the array it was handed. Two logins in the same moment (two devices, or a
|
|
9
|
+
* double-tap) each read `[A]`, then one writes `[A, B]` while the other writes `[A, C]` from its
|
|
10
|
+
* own stale snapshot; the loser's device is left holding a JWT whose `sid` is no longer on the
|
|
11
|
+
* row. A single-row INSERT commutes with any other login's INSERT, so there is no window to lose.
|
|
12
|
+
*
|
|
13
|
+
* No lock is taken and none should be: the FK from this table to the auth collection means every
|
|
14
|
+
* INSERT here already holds KEY SHARE on the parent row, which is exactly what a `SELECT … FOR
|
|
15
|
+
* UPDATE` on that row blocks against.
|
|
16
|
+
*
|
|
17
|
+
* Going through SQL also skips the auth collection's hook chain, which `payload.update` would run
|
|
18
|
+
* on every sign-in, and leaves its `updated_at` alone.
|
|
19
|
+
*
|
|
20
|
+
* ⚠️ This closes the race on the path that calls it only. Payload's own `addSessionToUser`,
|
|
21
|
+
* `logout` and `refresh` still read-modify-write the whole array.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* await appendUserSession({ payload, userId: user.id, sid, createdAt, expiresAt, req })
|
|
25
|
+
* ```
|
|
26
|
+
*
|
|
27
|
+
* Pass `req` wherever one exists: the statement then runs on the operation's own transaction
|
|
28
|
+
* instead of the pooled root handle.
|
|
29
|
+
*/
|
|
30
|
+
export const appendUserSession = async ({ payload, userId, sid, createdAt, expiresAt, req, table = 'users_sessions', }) => {
|
|
31
|
+
const sessionsTable = sql.raw(`"${table}"`);
|
|
32
|
+
// One statement, one round trip. A data-modifying CTE always runs to completion whether or not
|
|
33
|
+
// the outer query reads it, and both halves see the same snapshot - so `max(_order)` counts the
|
|
34
|
+
// rows being pruned. `_order` is a plain index here, not a unique one.
|
|
35
|
+
// Awaited because Payload leaves `transactionID` as a promise while the transaction is still
|
|
36
|
+
// being opened.
|
|
37
|
+
const transactionID = await req?.transactionID;
|
|
38
|
+
await transactionDb(payload, transactionID).execute(sql `
|
|
39
|
+
WITH pruned AS (
|
|
40
|
+
DELETE FROM ${sessionsTable} WHERE _parent_id = ${userId} AND expires_at <= now()
|
|
41
|
+
)
|
|
42
|
+
INSERT INTO ${sessionsTable} (id, _parent_id, _order, created_at, expires_at)
|
|
43
|
+
VALUES (
|
|
44
|
+
${sid},
|
|
45
|
+
${userId},
|
|
46
|
+
COALESCE((SELECT max(_order) FROM ${sessionsTable} WHERE _parent_id = ${userId}), 0) + 1,
|
|
47
|
+
${createdAt.toISOString()}::timestamptz,
|
|
48
|
+
${expiresAt.toISOString()}::timestamptz
|
|
49
|
+
)`);
|
|
50
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rows a raw `db.execute` returned, across driver shapes: node-postgres wraps them in `rows`,
|
|
3
|
+
* other drivers hand back a plain array. Rows come out as `unknown` - narrow each one structurally
|
|
4
|
+
* rather than asserting a shape the driver never promised.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const rows = resultRows(await payload.db.drizzle.execute(sql`SELECT id FROM widgets`))
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare const resultRows: (result: unknown) => unknown[];
|
|
11
|
+
/**
|
|
12
|
+
* How many rows a raw `db.execute` AFFECTED. Use it where the count decides whether a conditional
|
|
13
|
+
* UPDATE won a race - that answer must not depend on which shape today's adapter returns.
|
|
14
|
+
*
|
|
15
|
+
* An explicit `rowCount` wins over the returned rows, so this is not `resultRows(result).length`:
|
|
16
|
+
* node-postgres answers an UPDATE or DELETE with no RETURNING as `{ rows: [], rowCount: 3 }`, and
|
|
17
|
+
* counting the empty array would report nothing changed for a write that changed three.
|
|
18
|
+
*/
|
|
19
|
+
export declare const rowCount: (result: unknown) => number;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The rows a raw `db.execute` returned, across driver shapes: node-postgres wraps them in `rows`,
|
|
3
|
+
* other drivers hand back a plain array. Rows come out as `unknown` - narrow each one structurally
|
|
4
|
+
* rather than asserting a shape the driver never promised.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const rows = resultRows(await payload.db.drizzle.execute(sql`SELECT id FROM widgets`))
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export const resultRows = (result) => {
|
|
11
|
+
if (Array.isArray(result))
|
|
12
|
+
return result;
|
|
13
|
+
if (typeof result !== 'object' || result === null)
|
|
14
|
+
return [];
|
|
15
|
+
if ('rows' in result && Array.isArray(result.rows))
|
|
16
|
+
return result.rows;
|
|
17
|
+
return [];
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* How many rows a raw `db.execute` AFFECTED. Use it where the count decides whether a conditional
|
|
21
|
+
* UPDATE won a race - that answer must not depend on which shape today's adapter returns.
|
|
22
|
+
*
|
|
23
|
+
* An explicit `rowCount` wins over the returned rows, so this is not `resultRows(result).length`:
|
|
24
|
+
* node-postgres answers an UPDATE or DELETE with no RETURNING as `{ rows: [], rowCount: 3 }`, and
|
|
25
|
+
* counting the empty array would report nothing changed for a write that changed three.
|
|
26
|
+
*/
|
|
27
|
+
export const rowCount = (result) => {
|
|
28
|
+
if (Array.isArray(result))
|
|
29
|
+
return result.length;
|
|
30
|
+
if (typeof result !== 'object' || result === null)
|
|
31
|
+
return 0;
|
|
32
|
+
// `rowCount` first, and this order is load-bearing: node-postgres answers an UPDATE or DELETE
|
|
33
|
+
// with no RETURNING as `{ rows: [], rowCount: 3 }` - the array is present and EMPTY, so reading
|
|
34
|
+
// it first reports 0 affected rows for a write that changed three. Where a driver reports both
|
|
35
|
+
// for a SELECT they agree, so nothing is lost by preferring the explicit count.
|
|
36
|
+
if ('rowCount' in result && typeof result.rowCount === 'number')
|
|
37
|
+
return result.rowCount;
|
|
38
|
+
if ('rows' in result && Array.isArray(result.rows))
|
|
39
|
+
return result.rows.length;
|
|
40
|
+
return 0;
|
|
41
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type BasePayload } from 'payload';
|
|
2
|
+
/** Where the lock lives and how long a held one stays valid. */
|
|
3
|
+
export type SyncLockOptions = {
|
|
4
|
+
/** Slug of the global holding the lock. Defaults to `sync-lock`. */
|
|
5
|
+
slug?: string;
|
|
6
|
+
/** Physical table backing that global - its `dbName` where one is set. Defaults to `sync_lock`. */
|
|
7
|
+
table?: string;
|
|
8
|
+
/** How long a held lock stays valid before another run may reclaim it. Defaults to 60 minutes. */
|
|
9
|
+
staleMs?: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A single-flight lock for a long job - an import, a sync, a rebuild - so two invocations can't run
|
|
13
|
+
* it at once. Serverless has no process memory to lock in, so the lock is a row.
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* const syncLock = createSyncLock()
|
|
17
|
+
*
|
|
18
|
+
* const held = await syncLock.acquire(payload, user.username)
|
|
19
|
+
* if (held) return conflict(`Already running, started by ${held.startedBy}`)
|
|
20
|
+
*
|
|
21
|
+
* try { await runSync() } finally { await syncLock.release(payload, user.username) }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Requires a global whose fields are `isRunning` (checkbox), `startedBy` (text) and `startedAt`
|
|
25
|
+
* (date). Point `slug` and `table` at it if you name it something other than `sync-lock`.
|
|
26
|
+
*/
|
|
27
|
+
export declare const createSyncLock: ({ slug, table, staleMs, }?: SyncLockOptions) => {
|
|
28
|
+
acquire: (payload: BasePayload, startedBy: string) => Promise<null | {
|
|
29
|
+
startedBy?: string;
|
|
30
|
+
}>;
|
|
31
|
+
release: (payload: BasePayload, startedBy: string) => Promise<void>;
|
|
32
|
+
status: (payload: BasePayload) => Promise<{
|
|
33
|
+
isRunning: boolean;
|
|
34
|
+
startedBy?: string;
|
|
35
|
+
}>;
|
|
36
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
3
|
+
import { rowCount } from './sql-result.js';
|
|
4
|
+
const defaultStaleMs = 60 * 60 * 1000;
|
|
5
|
+
// The lock lives in a Payload global, so its fields are narrowed structurally - a consumer's
|
|
6
|
+
// generated global types never reach this package.
|
|
7
|
+
const readLock = (doc) => {
|
|
8
|
+
if (!isRecord(doc))
|
|
9
|
+
return { isRunning: false };
|
|
10
|
+
return {
|
|
11
|
+
isRunning: doc.isRunning === true,
|
|
12
|
+
startedBy: typeof doc.startedBy === 'string' ? doc.startedBy : undefined,
|
|
13
|
+
startedAt: typeof doc.startedAt === 'string' ? doc.startedAt : undefined,
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* A single-flight lock for a long job - an import, a sync, a rebuild - so two invocations can't run
|
|
18
|
+
* it at once. Serverless has no process memory to lock in, so the lock is a row.
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* const syncLock = createSyncLock()
|
|
22
|
+
*
|
|
23
|
+
* const held = await syncLock.acquire(payload, user.username)
|
|
24
|
+
* if (held) return conflict(`Already running, started by ${held.startedBy}`)
|
|
25
|
+
*
|
|
26
|
+
* try { await runSync() } finally { await syncLock.release(payload, user.username) }
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Requires a global whose fields are `isRunning` (checkbox), `startedBy` (text) and `startedAt`
|
|
30
|
+
* (date). Point `slug` and `table` at it if you name it something other than `sync-lock`.
|
|
31
|
+
*/
|
|
32
|
+
export const createSyncLock = ({ slug = 'sync-lock', table = 'sync_lock', staleMs = defaultStaleMs, } = {}) => {
|
|
33
|
+
const lockTable = sql.raw(`"${table}"`);
|
|
34
|
+
// A row with no `startedAt` at all cannot be timed, so it reads as stale (reclaimable) rather
|
|
35
|
+
// than eternally held.
|
|
36
|
+
const isStale = (startedAt) => {
|
|
37
|
+
if (!startedAt)
|
|
38
|
+
return true;
|
|
39
|
+
return Date.now() - new Date(startedAt).getTime() > staleMs;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Claims the lock for `startedBy`. Returns null on success, or `{ startedBy }` naming the run
|
|
43
|
+
* that already holds it.
|
|
44
|
+
*
|
|
45
|
+
* The claim is a single conditional UPDATE, so it is atomic: only the request whose UPDATE
|
|
46
|
+
* matched the free-or-stale row gets a row back. A read-then-write cannot do this - two
|
|
47
|
+
* concurrent requests both pass the isRunning check and run overlapping jobs - and a global has
|
|
48
|
+
* no unique key to lean on, which is why this is raw SQL.
|
|
49
|
+
*
|
|
50
|
+
* A lock older than `staleMs` is reclaimable, so a run killed mid-flight cannot block every later
|
|
51
|
+
* one. So is a held lock carrying no `startedAt`: it has no age to be judged by, and treating
|
|
52
|
+
* that as fresh would hold the lock forever.
|
|
53
|
+
*/
|
|
54
|
+
const acquire = async (payload, startedBy) => {
|
|
55
|
+
const staleBefore = new Date(Date.now() - staleMs).toISOString();
|
|
56
|
+
const res = await payload.db.drizzle.execute(sql `
|
|
57
|
+
UPDATE ${lockTable}
|
|
58
|
+
SET is_running = true, started_by = ${startedBy}, started_at = now(), updated_at = now()
|
|
59
|
+
WHERE is_running IS NOT TRUE OR started_at IS NULL OR started_at < ${staleBefore}
|
|
60
|
+
RETURNING id`);
|
|
61
|
+
if (rowCount(res) > 0)
|
|
62
|
+
return null;
|
|
63
|
+
// Nothing matched, which means one of two things: another run holds a fresh lock (the ordinary
|
|
64
|
+
// contended case), or the global's row doesn't exist yet - Payload creates it lazily on first
|
|
65
|
+
// write, so before the first-ever run there is nothing for the UPDATE to hit.
|
|
66
|
+
//
|
|
67
|
+
// Only the second needs seeding, and seeding is a read-then-write (updateGlobal) that two
|
|
68
|
+
// concurrent first-ever callers could both pass through undetected. The two cases are
|
|
69
|
+
// indistinguishable from here without reading, so the advisory lock is taken for both and the
|
|
70
|
+
// UPDATE retried inside it: whoever lost the race to seed finds the row on the retry. Losing the
|
|
71
|
+
// lock therefore costs two extra statements - the advisory lock and the retry - plus a read of
|
|
72
|
+
// the global, against the one statement an uncontended claim returns on.
|
|
73
|
+
return await payload.db.drizzle.transaction(async (tx) => {
|
|
74
|
+
await tx.execute(sql `SELECT pg_advisory_xact_lock(hashtext(${slug}))`);
|
|
75
|
+
const retry = await tx.execute(sql `
|
|
76
|
+
UPDATE ${lockTable}
|
|
77
|
+
SET is_running = true, started_by = ${startedBy}, started_at = now(), updated_at = now()
|
|
78
|
+
WHERE is_running IS NOT TRUE OR started_at IS NULL OR started_at < ${staleBefore}
|
|
79
|
+
RETURNING id`);
|
|
80
|
+
if (rowCount(retry) > 0)
|
|
81
|
+
return null;
|
|
82
|
+
const lock = readLock(await payload.findGlobal({ slug }));
|
|
83
|
+
if (lock.isRunning && !isStale(lock.startedAt))
|
|
84
|
+
return { startedBy: lock.startedBy };
|
|
85
|
+
await payload.updateGlobal({
|
|
86
|
+
slug,
|
|
87
|
+
data: { isRunning: true, startedBy, startedAt: new Date().toISOString() },
|
|
88
|
+
});
|
|
89
|
+
return null;
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Releases the lock, matching on `startedBy` so a caller can only release its own.
|
|
94
|
+
*
|
|
95
|
+
* A run that outlives `staleMs` can have its lock reclaimed by another; an unconditional release
|
|
96
|
+
* in that first run's `finally` would then free the second run's lock from under it. Two
|
|
97
|
+
* overlapping runs started by the SAME name would have to straddle the threshold first.
|
|
98
|
+
*/
|
|
99
|
+
const release = async (payload, startedBy) => {
|
|
100
|
+
await payload.db.drizzle.execute(sql `
|
|
101
|
+
UPDATE ${lockTable}
|
|
102
|
+
SET is_running = false, updated_at = now()
|
|
103
|
+
WHERE started_by = ${startedBy}`);
|
|
104
|
+
};
|
|
105
|
+
/**
|
|
106
|
+
* Whether a run currently holds the lock, and who started it - for a status endpoint or a
|
|
107
|
+
* disabled "run now" button. A lock older than `staleMs` reads as free.
|
|
108
|
+
*/
|
|
109
|
+
const status = async (payload) => {
|
|
110
|
+
const lock = readLock(await payload.findGlobal({ slug }));
|
|
111
|
+
if (lock.isRunning && !isStale(lock.startedAt))
|
|
112
|
+
return { isRunning: true, startedBy: lock.startedBy };
|
|
113
|
+
return { isRunning: false };
|
|
114
|
+
};
|
|
115
|
+
return { acquire, release, status };
|
|
116
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { BasePayload } from 'payload';
|
|
2
|
+
import type { BasePostgresAdapter } from '@payloadcms/drizzle/postgres';
|
|
3
|
+
/** The drizzle handle bound to one open transaction session. */
|
|
4
|
+
export type SessionDb = BasePostgresAdapter['sessions'][string]['db'];
|
|
5
|
+
/**
|
|
6
|
+
* The raw-SQL handle for an open Payload transaction, so a statement commits or rolls back with the
|
|
7
|
+
* local-API writes on the same `transactionID`. Without one, the pooled root handle - a statement
|
|
8
|
+
* there runs in autocommit.
|
|
9
|
+
*
|
|
10
|
+
* Payload core erases `sessions[id].db` to `unknown` (it doesn't know the ORM); the adapter's own
|
|
11
|
+
* declaration is the real type, so the assertion is to that rather than a hand-rolled shape.
|
|
12
|
+
*/
|
|
13
|
+
export declare const transactionDb: (payload: BasePayload, transactionID?: number | string | null) => SessionDb | BasePayload["db"]["drizzle"];
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The raw-SQL handle for an open Payload transaction, so a statement commits or rolls back with the
|
|
3
|
+
* local-API writes on the same `transactionID`. Without one, the pooled root handle - a statement
|
|
4
|
+
* there runs in autocommit.
|
|
5
|
+
*
|
|
6
|
+
* Payload core erases `sessions[id].db` to `unknown` (it doesn't know the ORM); the adapter's own
|
|
7
|
+
* declaration is the real type, so the assertion is to that rather than a hand-rolled shape.
|
|
8
|
+
*/
|
|
9
|
+
export const transactionDb = (payload, transactionID) => {
|
|
10
|
+
const session = typeof transactionID === 'string' || typeof transactionID === 'number'
|
|
11
|
+
? payload.db.sessions?.[transactionID]
|
|
12
|
+
: undefined;
|
|
13
|
+
return session ? session.db : payload.db.drizzle;
|
|
14
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CollectionConfig } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* A collection's `versions` config for the common draft-and-publish shape: autosave every second,
|
|
4
|
+
* schedulable publish, keeping the last `maxPerDoc` versions per document.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* versions: draftVersions(10)
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare const draftVersions: (maxPerDoc?: number) => CollectionConfig["versions"];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A collection's `versions` config for the common draft-and-publish shape: autosave every second,
|
|
3
|
+
* schedulable publish, keeping the last `maxPerDoc` versions per document.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* versions: draftVersions(10)
|
|
7
|
+
* ```
|
|
8
|
+
*/
|
|
9
|
+
export const draftVersions = (maxPerDoc = 10) => ({
|
|
10
|
+
drafts: {
|
|
11
|
+
autosave: {
|
|
12
|
+
interval: 1000,
|
|
13
|
+
},
|
|
14
|
+
schedulePublish: true,
|
|
15
|
+
},
|
|
16
|
+
maxPerDoc,
|
|
17
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Flattens a `locale: 'all'` read of a localised field - which arrives as a record keyed by locale
|
|
3
|
+
* even though Payload's generated types still describe it in its single-locale shape - into
|
|
4
|
+
* `Partial<Record<L, string>>`. Unknown keys and non-string values are dropped, and an empty
|
|
5
|
+
* string is treated as absent: Payload stores `''` for a cleared field, and a caller asking "which
|
|
6
|
+
* locales have text" wants that to read as no.
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* localeRecord(doc.title, ['en', 'fr', 'es'] as const)
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare const localeRecord: <L extends string>(value: unknown, knownLocales: readonly L[]) => Partial<Record<L, string>>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
2
|
+
import { oneOf } from '@quitecustard/core/utils/one-of';
|
|
3
|
+
/**
|
|
4
|
+
* Flattens a `locale: 'all'` read of a localised field - which arrives as a record keyed by locale
|
|
5
|
+
* even though Payload's generated types still describe it in its single-locale shape - into
|
|
6
|
+
* `Partial<Record<L, string>>`. Unknown keys and non-string values are dropped, and an empty
|
|
7
|
+
* string is treated as absent: Payload stores `''` for a cleared field, and a caller asking "which
|
|
8
|
+
* locales have text" wants that to read as no.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* localeRecord(doc.title, ['en', 'fr', 'es'] as const)
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export const localeRecord = (value, knownLocales) => {
|
|
15
|
+
if (!isRecord(value))
|
|
16
|
+
return {};
|
|
17
|
+
const isKnownLocale = oneOf(knownLocales);
|
|
18
|
+
const record = {};
|
|
19
|
+
for (const [key, text] of Object.entries(value)) {
|
|
20
|
+
if (isKnownLocale(key) && typeof text === 'string' && text !== '')
|
|
21
|
+
record[key] = text;
|
|
22
|
+
}
|
|
23
|
+
return record;
|
|
24
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public row set for a draft-enabled collection. Spread it into a `where` alongside other keys,
|
|
3
|
+
* or drop it into an `and` array:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* where: { ...publishedWhere, slug: { equals } }
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* State it explicitly on every read that bypasses access control - a cached or unauthenticated read
|
|
10
|
+
* has no user, and a collection that gates anonymous reads to nothing returns ZERO rows under an
|
|
11
|
+
* enforced read. One definition keeps the access rule and the bypassing read from drifting apart.
|
|
12
|
+
* Guard it with `!draft`: previewing the unpublished version is what the draft branch is for.
|
|
13
|
+
*
|
|
14
|
+
* NOT for a query that merely happens to filter on `_status`. A hook asking "which of these are
|
|
15
|
+
* currently published" is expressing its own logic, not this policy, and should say so in full.
|
|
16
|
+
*/
|
|
17
|
+
export declare const publishedWhere: {
|
|
18
|
+
_status: {
|
|
19
|
+
equals: string;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public row set for a draft-enabled collection. Spread it into a `where` alongside other keys,
|
|
3
|
+
* or drop it into an `and` array:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* where: { ...publishedWhere, slug: { equals } }
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* State it explicitly on every read that bypasses access control - a cached or unauthenticated read
|
|
10
|
+
* has no user, and a collection that gates anonymous reads to nothing returns ZERO rows under an
|
|
11
|
+
* enforced read. One definition keeps the access rule and the bypassing read from drifting apart.
|
|
12
|
+
* Guard it with `!draft`: previewing the unpublished version is what the draft branch is for.
|
|
13
|
+
*
|
|
14
|
+
* NOT for a query that merely happens to filter on `_status`. A hook asking "which of these are
|
|
15
|
+
* currently published" is expressing its own logic, not this policy, and should say so in full.
|
|
16
|
+
*/
|
|
17
|
+
export const publishedWhere = { _status: { equals: 'published' } };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A relationship field as Payload hands it over: an id at depth 0, the doc once populated, or empty.
|
|
3
|
+
*/
|
|
4
|
+
export type Relation<T> = number | string | T | null | undefined;
|
|
5
|
+
/** Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for
|
|
6
|
+
* both numeric (Postgres serial) and string (UUID) primary keys. */
|
|
7
|
+
export declare const relId: (rel: unknown) => number | string | null;
|
|
8
|
+
/** Narrow a relation to its populated doc (object), or null when it's still an unresolved id. */
|
|
9
|
+
export declare const relDoc: <T extends {
|
|
10
|
+
id: number | string;
|
|
11
|
+
}>(rel: Relation<T>) => T | null;
|
|
12
|
+
/** The populated docs of a relationship list; rows still held as ids (depth 0) drop out. */
|
|
13
|
+
export declare const relDocs: <T extends {
|
|
14
|
+
id: number | string;
|
|
15
|
+
}>(refs: readonly Relation<T>[] | null | undefined) => T[];
|
|
16
|
+
/** A list of relationship values as plain ids, tolerant of populate depth; misses drop out. */
|
|
17
|
+
export declare const relIds: (refs: readonly unknown[] | null | undefined) => (number | string)[];
|
|
18
|
+
/**
|
|
19
|
+
* A populated doc's display name, or null - for a bare id (depth 0), a missing relation, or a doc
|
|
20
|
+
* with no name there is no name to give. `unknown` on purpose: this is THE narrowing for "name off
|
|
21
|
+
* a maybe-populated ref", so callers never hand-roll the object/cast dance; the fallback ('TBD',
|
|
22
|
+
* '-', …) stays at the call site where the surface decides it.
|
|
23
|
+
*/
|
|
24
|
+
export declare const relName: (rel: unknown) => string | null;
|
|
25
|
+
/** An upload relation as `{ id, url }`, or null when it is unpopulated or has no url yet. */
|
|
26
|
+
export declare const resolveMedia: (val: unknown) => {
|
|
27
|
+
id: number | string;
|
|
28
|
+
url: string;
|
|
29
|
+
} | null;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
2
|
+
/** The value at `key` on a maybe-populated ref, as unknown; undefined for ids and misses. */
|
|
3
|
+
const refField = (rel, key) => (isRecord(rel) ? rel[key] : undefined);
|
|
4
|
+
/** Pluck the id from a relationship value: an id, a populated doc, or null/undefined. Works for
|
|
5
|
+
* both numeric (Postgres serial) and string (UUID) primary keys. */
|
|
6
|
+
export const relId = (rel) => {
|
|
7
|
+
if (typeof rel === 'number' || typeof rel === 'string')
|
|
8
|
+
return rel;
|
|
9
|
+
const id = refField(rel, 'id');
|
|
10
|
+
return typeof id === 'number' || typeof id === 'string' ? id : null;
|
|
11
|
+
};
|
|
12
|
+
/** Narrow a relation to its populated doc (object), or null when it's still an unresolved id. */
|
|
13
|
+
export const relDoc = (rel) => isRecord(rel) ? rel : null;
|
|
14
|
+
/** The populated docs of a relationship list; rows still held as ids (depth 0) drop out. */
|
|
15
|
+
export const relDocs = (refs) => (refs ?? []).flatMap((ref) => relDoc(ref) ?? []);
|
|
16
|
+
/** A list of relationship values as plain ids, tolerant of populate depth; misses drop out. */
|
|
17
|
+
export const relIds = (refs) => (refs ?? []).flatMap((ref) => {
|
|
18
|
+
const id = relId(ref);
|
|
19
|
+
return id != null ? [id] : [];
|
|
20
|
+
});
|
|
21
|
+
/**
|
|
22
|
+
* A populated doc's display name, or null - for a bare id (depth 0), a missing relation, or a doc
|
|
23
|
+
* with no name there is no name to give. `unknown` on purpose: this is THE narrowing for "name off
|
|
24
|
+
* a maybe-populated ref", so callers never hand-roll the object/cast dance; the fallback ('TBD',
|
|
25
|
+
* '-', …) stays at the call site where the surface decides it.
|
|
26
|
+
*/
|
|
27
|
+
export const relName = (rel) => {
|
|
28
|
+
const name = refField(rel, 'name');
|
|
29
|
+
return typeof name === 'string' ? name : null;
|
|
30
|
+
};
|
|
31
|
+
/** An upload relation as `{ id, url }`, or null when it is unpopulated or has no url yet. */
|
|
32
|
+
export const resolveMedia = (val) => {
|
|
33
|
+
const id = refField(val, 'id');
|
|
34
|
+
const url = refField(val, 'url');
|
|
35
|
+
return (typeof id === 'number' || typeof id === 'string') && typeof url === 'string' && url !== ''
|
|
36
|
+
? { id, url }
|
|
37
|
+
: null;
|
|
38
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-field messages inside a Payload `ValidationError`, or an empty array for any other error.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* const detail = fieldErrorMessages(err).join(' ')
|
|
6
|
+
* ```
|
|
7
|
+
*
|
|
8
|
+
* Read structurally rather than by instanceof: the same shape arrives wrapped by the local API, by
|
|
9
|
+
* a REST response and by a driver error Payload re-threw, and only the payload is dependable.
|
|
10
|
+
*/
|
|
11
|
+
export declare const fieldErrorMessages: (err: unknown) => string[];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
2
|
+
/**
|
|
3
|
+
* The per-field messages inside a Payload `ValidationError`, or an empty array for any other error.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* const detail = fieldErrorMessages(err).join(' ')
|
|
7
|
+
* ```
|
|
8
|
+
*
|
|
9
|
+
* Read structurally rather than by instanceof: the same shape arrives wrapped by the local API, by
|
|
10
|
+
* a REST response and by a driver error Payload re-threw, and only the payload is dependable.
|
|
11
|
+
*/
|
|
12
|
+
export const fieldErrorMessages = (err) => {
|
|
13
|
+
if (!isRecord(err) || !isRecord(err.data) || !Array.isArray(err.data.errors))
|
|
14
|
+
return [];
|
|
15
|
+
return err.data.errors.flatMap((entry) => isRecord(entry) && typeof entry.message === 'string' && entry.message ? [entry.message] : []);
|
|
16
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detects Postgres unique constraint violations (code 23505) caused by concurrent writes.
|
|
3
|
+
* Only these warrant a recovery lookup - other errors (network, permissions, etc.) should fail fast.
|
|
4
|
+
*
|
|
5
|
+
* Payload surfaces the violation in two shapes: the raw driver error during a concurrent INSERT
|
|
6
|
+
* race, or a wrapped `ValidationError` whose field error reads "Value must be unique" when its
|
|
7
|
+
* pre-insert check catches an already-committed row. The ValidationError is detected structurally
|
|
8
|
+
* so every unique field is covered, not only one hardcoded field name.
|
|
9
|
+
*
|
|
10
|
+
* `ValidationError`'s top-level message ("The following field is invalid: <field>") names whichever
|
|
11
|
+
* field failed for ANY reason, not only uniqueness - matching on it here would misclassify an
|
|
12
|
+
* unrelated failure (a required field left blank, say) as a duplicate.
|
|
13
|
+
*/
|
|
14
|
+
export declare const isDuplicateError: (e: unknown) => boolean;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { fieldErrorMessages } from './field-errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Detects Postgres unique constraint violations (code 23505) caused by concurrent writes.
|
|
4
|
+
* Only these warrant a recovery lookup - other errors (network, permissions, etc.) should fail fast.
|
|
5
|
+
*
|
|
6
|
+
* Payload surfaces the violation in two shapes: the raw driver error during a concurrent INSERT
|
|
7
|
+
* race, or a wrapped `ValidationError` whose field error reads "Value must be unique" when its
|
|
8
|
+
* pre-insert check catches an already-committed row. The ValidationError is detected structurally
|
|
9
|
+
* so every unique field is covered, not only one hardcoded field name.
|
|
10
|
+
*
|
|
11
|
+
* `ValidationError`'s top-level message ("The following field is invalid: <field>") names whichever
|
|
12
|
+
* field failed for ANY reason, not only uniqueness - matching on it here would misclassify an
|
|
13
|
+
* unrelated failure (a required field left blank, say) as a duplicate.
|
|
14
|
+
*/
|
|
15
|
+
export const isDuplicateError = (e) => {
|
|
16
|
+
if (fieldErrorMessages(e).some((message) => message.toLowerCase().includes('unique')))
|
|
17
|
+
return true;
|
|
18
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
19
|
+
return (message.includes('duplicate key') ||
|
|
20
|
+
message.includes('unique constraint') ||
|
|
21
|
+
message.includes('23505'));
|
|
22
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A message safe to show a user after a failed write, or `fallback` when the error isn't one of
|
|
3
|
+
* Payload's own.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* catch (err) {
|
|
7
|
+
* return { error: publicErrorMessage(err, 'Could not save your changes') }
|
|
8
|
+
* }
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* Payload's errors are safe to surface: a ValidationError's per-field messages are authored by the
|
|
12
|
+
* project's own hooks for the user, and an APIError carries a message written for API consumers.
|
|
13
|
+
* The field detail is preferred over a ValidationError's top-level message, which is only "The
|
|
14
|
+
* following field is invalid: …". Anything else - a DB driver or network failure - can leak
|
|
15
|
+
* internals like SQL fragments and constraint names, so it collapses to the fallback.
|
|
16
|
+
*/
|
|
17
|
+
export declare const publicErrorMessage: (err: unknown, fallback: string) => string;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { fieldErrorMessages } from './field-errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* A message safe to show a user after a failed write, or `fallback` when the error isn't one of
|
|
5
|
+
* Payload's own.
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* catch (err) {
|
|
9
|
+
* return { error: publicErrorMessage(err, 'Could not save your changes') }
|
|
10
|
+
* }
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* Payload's errors are safe to surface: a ValidationError's per-field messages are authored by the
|
|
14
|
+
* project's own hooks for the user, and an APIError carries a message written for API consumers.
|
|
15
|
+
* The field detail is preferred over a ValidationError's top-level message, which is only "The
|
|
16
|
+
* following field is invalid: …". Anything else - a DB driver or network failure - can leak
|
|
17
|
+
* internals like SQL fragments and constraint names, so it collapses to the fallback.
|
|
18
|
+
*/
|
|
19
|
+
export const publicErrorMessage = (err, fallback) => {
|
|
20
|
+
const detail = fieldErrorMessages(err);
|
|
21
|
+
if (detail.length > 0)
|
|
22
|
+
return detail.join(' ');
|
|
23
|
+
if (err instanceof APIError)
|
|
24
|
+
return err.message;
|
|
25
|
+
return fallback;
|
|
26
|
+
};
|