@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.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +169 -0
  3. package/dist/access/anyone.d.ts +10 -0
  4. package/dist/access/anyone.js +9 -0
  5. package/dist/access/role-gate.d.ts +22 -0
  6. package/dist/access/role-gate.js +21 -0
  7. package/dist/access/self-access.d.ts +30 -0
  8. package/dist/access/self-access.js +34 -0
  9. package/dist/db/delete-many-with-versions.d.ts +21 -0
  10. package/dist/db/delete-many-with-versions.js +34 -0
  11. package/dist/db/external-ref.d.ts +65 -0
  12. package/dist/db/external-ref.js +88 -0
  13. package/dist/db/orphan-cleanup.d.ts +32 -0
  14. package/dist/db/orphan-cleanup.js +64 -0
  15. package/dist/db/sessions.d.ts +46 -0
  16. package/dist/db/sessions.js +50 -0
  17. package/dist/db/sql-result.d.ts +19 -0
  18. package/dist/db/sql-result.js +41 -0
  19. package/dist/db/sync-lock.d.ts +36 -0
  20. package/dist/db/sync-lock.js +116 -0
  21. package/dist/db/transaction-db.d.ts +13 -0
  22. package/dist/db/transaction-db.js +14 -0
  23. package/dist/documents/collection-versions.d.ts +10 -0
  24. package/dist/documents/collection-versions.js +17 -0
  25. package/dist/documents/locale-record.d.ts +12 -0
  26. package/dist/documents/locale-record.js +24 -0
  27. package/dist/documents/published-where.d.ts +21 -0
  28. package/dist/documents/published-where.js +17 -0
  29. package/dist/documents/resolve-ref.d.ts +29 -0
  30. package/dist/documents/resolve-ref.js +38 -0
  31. package/dist/errors/field-errors.d.ts +11 -0
  32. package/dist/errors/field-errors.js +16 -0
  33. package/dist/errors/is-duplicate-error.d.ts +14 -0
  34. package/dist/errors/is-duplicate-error.js +22 -0
  35. package/dist/errors/public-error.d.ts +17 -0
  36. package/dist/errors/public-error.js +26 -0
  37. package/dist/fields/colour-options-field.d.ts +18 -0
  38. package/dist/fields/colour-options-field.js +44 -0
  39. package/dist/fields/colour-picker-field.d.ts +12 -0
  40. package/dist/fields/colour-picker-field.js +11 -0
  41. package/dist/fields/height-field.d.ts +12 -0
  42. package/dist/fields/height-field.js +11 -0
  43. package/dist/fields/hero-field.d.ts +16 -0
  44. package/dist/fields/hero-field.js +50 -0
  45. package/dist/fields/layout-fields.d.ts +7 -0
  46. package/dist/fields/layout-fields.js +47 -0
  47. package/dist/fields/link-field.d.ts +34 -0
  48. package/dist/fields/link-field.js +170 -0
  49. package/dist/fields/media-content-fields.d.ts +23 -0
  50. package/dist/fields/media-content-fields.js +103 -0
  51. package/dist/fields/owner-field.d.ts +19 -0
  52. package/dist/fields/owner-field.js +53 -0
  53. package/dist/fields/phone-field.d.ts +12 -0
  54. package/dist/fields/phone-field.js +11 -0
  55. package/dist/fields/seo-tab.d.ts +18 -0
  56. package/dist/fields/seo-tab.js +36 -0
  57. package/dist/fields/size-field.d.ts +8 -0
  58. package/dist/fields/size-field.js +19 -0
  59. package/dist/fields/social-url.d.ts +21 -0
  60. package/dist/fields/social-url.js +49 -0
  61. package/dist/fields/spacing-select-field.d.ts +17 -0
  62. package/dist/fields/spacing-select-field.js +36 -0
  63. package/dist/internal/component-field.d.ts +25 -0
  64. package/dist/internal/component-field.js +24 -0
  65. package/dist/operations/after-response.d.ts +24 -0
  66. package/dist/operations/after-response.js +40 -0
  67. package/dist/operations/publish-transition.d.ts +45 -0
  68. package/dist/operations/publish-transition.js +78 -0
  69. package/dist/operations/run-queued-jobs.d.ts +30 -0
  70. package/dist/operations/run-queued-jobs.js +87 -0
  71. package/dist/operations/suppress-context.d.ts +16 -0
  72. package/dist/operations/suppress-context.js +55 -0
  73. package/dist/operations/unique-slug.d.ts +12 -0
  74. package/dist/operations/unique-slug.js +23 -0
  75. package/dist/operations/unique-username.d.ts +40 -0
  76. package/dist/operations/unique-username.js +52 -0
  77. package/package.json +76 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QuiteCustard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # @quitecustard/payload
2
+
3
+ Helpers generic over any Payload v3 project. One module per file — no barrels:
4
+
5
+ ```ts
6
+ import { relId } from '@quitecustard/payload/documents/resolve-ref'
7
+ import { transactionDb } from '@quitecustard/payload/db/transaction-db'
8
+ ```
9
+
10
+ ## Install
11
+
12
+ ```
13
+ pnpm add @quitecustard/payload
14
+ ```
15
+
16
+ Every module is a subpath export, so TypeScript needs `moduleResolution` set to `bundler`,
17
+ `node16` or `nodenext` — the legacy `node` resolution can't see subpath exports at all.
18
+
19
+ Peer dependencies: `payload` (required), `@payloadcms/drizzle` + `drizzle-orm` and `next` (optional —
20
+ only some modules touch them). Payload's module augmentation means a consumer's generated types
21
+ flow through the `CollectionSlug`-generic helpers automatically.
22
+
23
+ ## Contents
24
+
25
+ Every module is one subpath: `@quitecustard/payload/<folder>/<module>`. There are no barrels, so
26
+ the list below doubles as the import paths. Each export carries JSDoc, which is what your editor
27
+ shows on hover — this page is the map, not the reference.
28
+
29
+ ### `documents/` — reading what Payload hands back
30
+
31
+ - `resolve-ref` — `relId` / `relDoc` / `relDocs` / `relIds` / `relName` / `resolveMedia`: relation
32
+ narrowing without casts, tolerant of populate depth and of numeric or uuid ids
33
+ - `locale-record` — flattens a `locale: 'all'` read into `Partial<Record<Locale, string>>`
34
+ - `published-where` — the published clause, stated once so a bypassing read and the access rule
35
+ cannot drift apart
36
+ - `collection-versions` — `draftVersions(maxPerDoc?)`: the autosave + schedulePublish shape
37
+
38
+ ### `access/`
39
+
40
+ - `anyone` — `anyone` / `anyoneFieldLevel` / `nobody`
41
+ - `role-gate` — `hasRole` / `roleGate` / `roleGateFieldLevel`: the mechanism for reading a role off
42
+ a caller. Which roles exist, and what each one may do, stays in the consuming project.
43
+ - `self-access` — `isSameUser` / `isSelfFieldLevel` / `selfOrAdminFieldLevel`, across Payload's
44
+ three field-access argument shapes; takes a `getUserId` resolver for a project with more than one
45
+ auth collection
46
+
47
+ ### `fields/` — field and admin-config factories
48
+
49
+ This package ships no UI, so every field rendered by a custom component takes that component's
50
+ import path as a **required** parameter rather than assuming one. Each is a factory, never a shared
51
+ constant: `buildConfig` sanitises field objects in place, so two collections must not receive one.
52
+
53
+ - `link-field` — polymorphic link (internal reference, custom URL, optional static route, dropdown,
54
+ phone, email); each type appears only if its collection or component was supplied
55
+ - `hero-field` — the image/video/poster banner group, parameterised on the two upload collections
56
+ - `owner-field` — a relationship auto-stamped to the creating user, refused on update by field-level
57
+ access rather than by `admin.readOnly`, which Payload never consults on a write
58
+ - `seo-tab` — over `@payloadcms/plugin-seo`'s field factories
59
+ - `social-url` — `normaliseSocialUrl` (bare host → `https://…`) plus `validateSocialUrl`
60
+ - `colour-picker-field`, `colour-options-field`, `phone-field`, `height-field`, `size-field`,
61
+ `spacing-select-field`, `layout-fields`, `media-content-fields`
62
+
63
+ ### `db/` — raw SQL, transactions and bulk operations
64
+
65
+ Postgres only, and the only folder needing the `@payloadcms/drizzle` + `drizzle-orm` peers.
66
+
67
+ - `transaction-db` — the drizzle handle bound to an open transaction, so raw SQL commits with the
68
+ local-API writes around it instead of running on a separate connection
69
+ - `sessions` — `appendUserSession`: a race-safe INSERT onto an auth collection's session array
70
+ - `sync-lock` — `createSyncLock({slug, table, staleMs})`: single-flight locking for a long job, as a
71
+ conditional UPDATE rather than a read-then-write
72
+ - `orphan-cleanup` — `findDeletableIds`, with guard rails that refuse rather than return everything
73
+ - `delete-many-with-versions` — bulk delete that also purges the version snapshots the FK leaves behind
74
+ - `sql-result` — `resultRows` / `rowCount` across driver response shapes
75
+ - `external-ref` — provenance fields plus the partial-unique index that lets an importer upsert on
76
+ `(source, id)` instead of duplicating docs on every run, and per-parent slug uniqueness for
77
+ nested trees
78
+
79
+ ### `errors/`
80
+
81
+ - `field-errors` — the one reader for Payload's per-field error messages
82
+ - `is-duplicate-error` — detects a unique-constraint violation in both shapes Payload surfaces it in
83
+ - `public-error` — a message safe to show a user, or a fallback for anything that could leak internals
84
+
85
+ ### `operations/` — write-path and job helpers
86
+
87
+ - `publish-transition` — autosave-vs-unpublish disambiguation, cheap and exact variants
88
+ - `suppress-context` — ref-counted `req.context` flags, safe under a bulk operation's shared context
89
+ - `after-response` — defer non-critical work past the response, falling back to inline outside a request
90
+ - `run-queued-jobs` — drains the Payload job queue, which nothing else does
91
+ - `unique-slug`, `unique-username` — collision-free values, each candidate checked exactly
92
+
93
+ `src/internal/` holds implementation detail and is not importable: `"./internal/*": null` sits ahead
94
+ of the wildcard in `exports`.
95
+
96
+ ## Import provenance — `external-ref`
97
+
98
+ For a collection whose docs can arrive from an external platform as well as being typed by hand: a
99
+ product catalogue synced from Stripe or Shopify, a post archive migrated from WordPress or an RSS
100
+ feed, an events listing pulled from a ticketing API, a tournament tree imported from a bracket
101
+ service.
102
+
103
+ The doc records which platform it came from and that platform's own id, so the importer upserts on
104
+ the pair — a second run corrects the docs it already created instead of creating a duplicate of
105
+ each. Hand-made docs set neither field, and no import touches them.
106
+
107
+ ```ts
108
+ import {
109
+ externalRefFields,
110
+ externalRefIndex,
111
+ slugPerParentIndex,
112
+ } from '@quitecustard/payload/db/external-ref'
113
+
114
+ export const lessons: CollectionConfig = {
115
+ slug: 'lessons',
116
+ fields: [
117
+ // …your fields
118
+ ...externalRefFields([{ label: 'Stripe', value: 'stripe' }]),
119
+ ],
120
+ }
121
+
122
+ export const lessonsImportIndex = externalRefIndex({ table: 'lessons', prefix: 'lessons' })
123
+ export const lessonsSlugIndex = slugPerParentIndex({
124
+ table: 'lessons',
125
+ parent: 'module',
126
+ prefix: 'lessons',
127
+ })
128
+ ```
129
+
130
+ ```ts
131
+ // payload.config.ts
132
+ db: postgresAdapter({ afterSchemaInit: [lessonsImportIndex, lessonsSlugIndex] })
133
+ ```
134
+
135
+ Two hooks, because they answer to different needs and a collection rarely wants both:
136
+
137
+ - `externalRefIndex` — unique `(externalSource, externalRef)`, partial to imported rows. This is
138
+ what makes the upsert safe under concurrency: without it, two overlapping import runs both find no
139
+ doc for a source id and both create one. Only for a collection carrying `externalRefFields`, since
140
+ it indexes those columns.
141
+ - `slugPerParentIndex` — unique `(parent, slug)`. Nothing to do with imports: it's for a tree whose
142
+ slugs legitimately repeat across parents — `getting-started` under every docs section, `lesson-1`
143
+ under every module — and whose lookups always AND on the parent.
144
+
145
+ Payload's `afterSchemaInit` hooks compose, each wrapping the previous config builder rather than
146
+ replacing it, so registering both on one table is safe.
147
+
148
+ ## Contracts to know
149
+
150
+ - `sync-lock` — `createSyncLock()` expects a global with `isRunning`, `startedBy` and `startedAt`
151
+ fields, defaulting to slug `sync-lock` on table `sync_lock`; pass `{ slug, table, staleMs }` for
152
+ anything else.
153
+ - `orphan-cleanup` — `findDeletableIds` reflects foreign keys from `pg_constraint`, so the caller
154
+ names the tables that count as the row's own data via `ignore`. Non-`public` schemas pass
155
+ `{ schema }`.
156
+ - `sessions` — `appendUserSession` defaults `table` to `users_sessions`, Payload's own naming for a
157
+ `users` collection; pass `table` for any other auth collection. It is a raw INSERT rather than a
158
+ `payload.update` on purpose — the module header has the FOR UPDATE / FOR KEY SHARE deadlock
159
+ reason.
160
+ - Everything under `db/` needs **a Postgres adapter built on `@payloadcms/drizzle`** —
161
+ `@payloadcms/db-postgres` and `@payloadcms/db-vercel-postgres` both qualify, since they differ
162
+ only in the connection driver. They talk to the shared drizzle layer, never to an adapter
163
+ directly. What they can't run on is SQLite or Mongo: the raw SQL uses `pg_constraint`,
164
+ `timestamptz` and data-modifying CTEs. No module outside `db/` imports drizzle at all, so the
165
+ other five folders work on any adapter.
166
+ - `fields/seo-tab` assumes `@payloadcms/plugin-seo`, and `operations/after-response` assumes `next`.
167
+ Those two are the only modules touching either peer.
168
+
169
+ MIT licensed. Source: [custard-kit](https://github.com/QuiteCustard/custard-kit).
@@ -0,0 +1,10 @@
1
+ import type { Access, FieldAccess } from 'payload';
2
+ /** Open to every caller, authenticated or not - for public reads. */
3
+ export declare const anyone: Access;
4
+ /** The field-level shape of `anyone`, for a field inside an otherwise gated collection. */
5
+ export declare const anyoneFieldLevel: FieldAccess;
6
+ /**
7
+ * Sealed: no caller of any role, including admin. For a collection the application writes to only
8
+ * through the Local API (which bypasses access), where every REST/GraphQL operation should refuse.
9
+ */
10
+ export declare const nobody: Access;
@@ -0,0 +1,9 @@
1
+ /** Open to every caller, authenticated or not - for public reads. */
2
+ export const anyone = () => true;
3
+ /** The field-level shape of `anyone`, for a field inside an otherwise gated collection. */
4
+ export const anyoneFieldLevel = () => true;
5
+ /**
6
+ * Sealed: no caller of any role, including admin. For a collection the application writes to only
7
+ * through the Local API (which bypasses access), where every REST/GraphQL operation should refuse.
8
+ */
9
+ export const nobody = () => false;
@@ -0,0 +1,22 @@
1
+ import type { Access, ClientUser, FieldAccess, TypedUser } from 'payload';
2
+ /**
3
+ * Anything a role can be read off: the user shapes Payload hands to access rules, the absent
4
+ * cases, and any other object that may carry roles (some admin-UI surfaces narrow a user to fewer
5
+ * fields than the runtime object actually has). Predicates taking a user should use this rather
6
+ * than restating a shape - the body narrows defensively, where a cast at the call site would not.
7
+ */
8
+ export type RoleCaller = TypedUser | ClientUser | Record<string, unknown> | null | undefined;
9
+ /**
10
+ * The single role-reading idiom - read this off a caller rather than indexing `.roles` directly,
11
+ * so a caller with no roles field, or one that isn't an array, reads as "no role" instead of
12
+ * throwing. Pass an array to test several roles at once - it matches if the caller holds any.
13
+ *
14
+ * ```ts
15
+ * export const admin: Access = ({ req: { user } }) => hasRole(user, 'admin')
16
+ * ```
17
+ */
18
+ export declare const hasRole: <R extends string>(caller: RoleCaller, role: R | R[]) => boolean;
19
+ /** An `Access` rule that passes when the caller holds any of `roles`. */
20
+ export declare const roleGate: <R extends string>(roles: R | R[]) => Access;
21
+ /** The field-level equivalent of `roleGate`. */
22
+ export declare const roleGateFieldLevel: <R extends string>(roles: R | R[]) => FieldAccess;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The single role-reading idiom - read this off a caller rather than indexing `.roles` directly,
3
+ * so a caller with no roles field, or one that isn't an array, reads as "no role" instead of
4
+ * throwing. Pass an array to test several roles at once - it matches if the caller holds any.
5
+ *
6
+ * ```ts
7
+ * export const admin: Access = ({ req: { user } }) => hasRole(user, 'admin')
8
+ * ```
9
+ */
10
+ export const hasRole = (caller, role) => {
11
+ if (typeof caller !== 'object' || caller === null || !('roles' in caller))
12
+ return false;
13
+ const held = caller.roles;
14
+ if (!Array.isArray(held))
15
+ return false;
16
+ return (Array.isArray(role) ? role : [role]).some((wanted) => held.includes(wanted));
17
+ };
18
+ /** An `Access` rule that passes when the caller holds any of `roles`. */
19
+ export const roleGate = (roles) => ({ req: { user } }) => hasRole(user, roles);
20
+ /** The field-level equivalent of `roleGate`. */
21
+ export const roleGateFieldLevel = (roles) => ({ req: { user } }) => hasRole(user, roles);
@@ -0,0 +1,30 @@
1
+ import type { FieldAccess, FieldAccessArgs, TypedUser } from 'payload';
2
+ /**
3
+ * THE self check - the authenticated caller is the document being addressed. `getUserId` lets a
4
+ * project with more than one auth collection (or an id namespace shared across them) resolve the
5
+ * comparable id itself; it defaults to the plain `user.id`.
6
+ *
7
+ * `String(...)` on both sides: REST carries the id through as a path string while `user.id` comes
8
+ * off the row as a number, so a bare `===` is `5 === '5'` and denies a legitimate self-edit.
9
+ */
10
+ export declare const isSameUser: (user: TypedUser | null, docId: unknown, getUserId?: (user: TypedUser | null) => unknown) => boolean;
11
+ /**
12
+ * Whether a field-level access request is for the requesting user's own document.
13
+ *
14
+ * Field access runs in three Payload code paths that each populate a DIFFERENT subset of the args
15
+ * with the document id:
16
+ * - afterRead redaction (REST/Local API reads) passes `doc` (plus `data` and `id`)
17
+ * - the docAccess permission calc passes `doc`/`data` but not `id`
18
+ * - buildFormState - which renders the admin edit/account form - passes `id` and `data` but NO `doc`
19
+ * Checking `doc.id` alone silently returns false in the form-state path, so a non-admin viewing
20
+ * their own record in the admin panel loses every self-guarded field. Resolve the id from
21
+ * whichever arg the current path provided.
22
+ *
23
+ * 🔴 `data` is deliberately NOT consulted: it is the incoming request body, so `{"id": <my own
24
+ * id>}` would satisfy the check on someone else's document. Payload leaves BOTH `doc` and `id`
25
+ * undefined on `create`, which is why this returns false there - a document that does not exist
26
+ * yet has no owner to be.
27
+ */
28
+ export declare const isSelfFieldLevel: ({ req: { user }, id, doc }: FieldAccessArgs, getUserId?: (user: TypedUser | null) => unknown) => boolean;
29
+ /** `isSelfFieldLevel`, plus any role in `adminRoles` (default `'admin'`). */
30
+ export declare const selfOrAdminFieldLevel: (adminRoles?: string | string[], getUserId?: (user: TypedUser | null) => unknown) => FieldAccess;
@@ -0,0 +1,34 @@
1
+ import { hasRole } from './role-gate.js';
2
+ const defaultUserId = (user) => user?.id ?? null;
3
+ /**
4
+ * THE self check - the authenticated caller is the document being addressed. `getUserId` lets a
5
+ * project with more than one auth collection (or an id namespace shared across them) resolve the
6
+ * comparable id itself; it defaults to the plain `user.id`.
7
+ *
8
+ * `String(...)` on both sides: REST carries the id through as a path string while `user.id` comes
9
+ * off the row as a number, so a bare `===` is `5 === '5'` and denies a legitimate self-edit.
10
+ */
11
+ export const isSameUser = (user, docId, getUserId = defaultUserId) => {
12
+ const userId = getUserId(user);
13
+ return userId != null && docId != null && String(userId) === String(docId);
14
+ };
15
+ /**
16
+ * Whether a field-level access request is for the requesting user's own document.
17
+ *
18
+ * Field access runs in three Payload code paths that each populate a DIFFERENT subset of the args
19
+ * with the document id:
20
+ * - afterRead redaction (REST/Local API reads) passes `doc` (plus `data` and `id`)
21
+ * - the docAccess permission calc passes `doc`/`data` but not `id`
22
+ * - buildFormState - which renders the admin edit/account form - passes `id` and `data` but NO `doc`
23
+ * Checking `doc.id` alone silently returns false in the form-state path, so a non-admin viewing
24
+ * their own record in the admin panel loses every self-guarded field. Resolve the id from
25
+ * whichever arg the current path provided.
26
+ *
27
+ * 🔴 `data` is deliberately NOT consulted: it is the incoming request body, so `{"id": <my own
28
+ * id>}` would satisfy the check on someone else's document. Payload leaves BOTH `doc` and `id`
29
+ * undefined on `create`, which is why this returns false there - a document that does not exist
30
+ * yet has no owner to be.
31
+ */
32
+ export const isSelfFieldLevel = ({ req: { user }, id, doc }, getUserId) => isSameUser(user, doc?.id ?? id, getUserId);
33
+ /** `isSelfFieldLevel`, plus any role in `adminRoles` (default `'admin'`). */
34
+ export const selfOrAdminFieldLevel = (adminRoles = 'admin', getUserId) => (args) => hasRole(args.req.user, adminRoles) || isSelfFieldLevel(args, getUserId);
@@ -0,0 +1,21 @@
1
+ import type { CollectionSlug, Payload, PayloadRequest } from 'payload';
2
+ /**
3
+ * Bulk-deletes rows AND their draft-version snapshots.
4
+ *
5
+ * `payload.db.deleteMany` removes a collection's own rows, plus whatever its FKs cascade, but not
6
+ * its versions: a draft-enabled collection's `_<coll>_v.parent_id -> <coll>` FK is ON DELETE SET
7
+ * NULL, so the version rows survive with a NULL parent and then surface in the admin's draft-aware
8
+ * `join` fields as phantom relations to a doc that no longer exists.
9
+ *
10
+ * Only for the raw DB path - a cascade's bulk delete, a migration or a script - where no hooks
11
+ * fire; `payload.delete` already purges a doc's versions itself. Versions go first, then the main
12
+ * rows. Passing `req` runs both inside the caller's already-open transaction; omitting it opens and
13
+ * commits (or rolls back) one of its own, on adapters that support transactions. On a version-free
14
+ * collection this is exactly `db.deleteMany`.
15
+ */
16
+ export declare const deleteManyWithVersions: ({ payload, collection, ids, req, }: {
17
+ payload: Payload;
18
+ collection: CollectionSlug;
19
+ ids: (number | string)[];
20
+ req?: PayloadRequest;
21
+ }) => Promise<void>;
@@ -0,0 +1,34 @@
1
+ import { commitTransaction, initTransaction, killTransaction } from 'payload';
2
+ /**
3
+ * Bulk-deletes rows AND their draft-version snapshots.
4
+ *
5
+ * `payload.db.deleteMany` removes a collection's own rows, plus whatever its FKs cascade, but not
6
+ * its versions: a draft-enabled collection's `_<coll>_v.parent_id -> <coll>` FK is ON DELETE SET
7
+ * NULL, so the version rows survive with a NULL parent and then surface in the admin's draft-aware
8
+ * `join` fields as phantom relations to a doc that no longer exists.
9
+ *
10
+ * Only for the raw DB path - a cascade's bulk delete, a migration or a script - where no hooks
11
+ * fire; `payload.delete` already purges a doc's versions itself. Versions go first, then the main
12
+ * rows. Passing `req` runs both inside the caller's already-open transaction; omitting it opens and
13
+ * commits (or rolls back) one of its own, on adapters that support transactions. On a version-free
14
+ * collection this is exactly `db.deleteMany`.
15
+ */
16
+ export const deleteManyWithVersions = async ({ payload, collection, ids, req, }) => {
17
+ if (ids.length === 0)
18
+ return;
19
+ const ownReq = req ?? { payload };
20
+ const ownsTransaction = req ? false : await initTransaction(ownReq);
21
+ try {
22
+ if (payload.collections[collection]?.config.versions) {
23
+ await payload.db.deleteVersions({ collection, where: { parent: { in: ids } }, req: ownReq });
24
+ }
25
+ await payload.db.deleteMany({ collection, where: { id: { in: ids } }, req: ownReq });
26
+ if (ownsTransaction)
27
+ await commitTransaction(ownReq);
28
+ }
29
+ catch (error) {
30
+ if (ownsTransaction)
31
+ await killTransaction(ownReq);
32
+ throw error;
33
+ }
34
+ };
@@ -0,0 +1,65 @@
1
+ import type { Field } from 'payload';
2
+ import type { PostgresSchemaHook } from '@payloadcms/drizzle/postgres';
3
+ /**
4
+ * Marks a doc as imported from an external platform - a product synced from Stripe, a post migrated
5
+ * from WordPress, an event pulled from a ticketing API - by recording the platform and its own id
6
+ * for the doc, which is what an importer upserts on so a re-run updates rather than duplicates.
7
+ *
8
+ * A sidebar pair, hidden until something sets them, so a hand-made doc offers no dead inputs.
9
+ * `sources` names the platforms this project imports from.
10
+ *
11
+ * ```ts
12
+ * fields: [...externalRefFields([{ label: 'Stripe', value: 'stripe' }]), ...rest]
13
+ * ```
14
+ *
15
+ * Pair them with `externalRefIndex`, which is what makes the upsert safe under concurrency. Writing
16
+ * the fields is the importer's job: attaching a source id to a doc that was made by hand is a
17
+ * repair, and belongs in a script rather than the admin form.
18
+ */
19
+ export declare const externalRefFields: (sources: {
20
+ label: string;
21
+ value: string;
22
+ }[]) => Field[];
23
+ type AfterSchemaInitHook = PostgresSchemaHook;
24
+ /**
25
+ * One imported doc per source id: a unique index on `(externalSource, externalRef)`, partial to the
26
+ * rows that have a source, which is what makes an importer's upsert safe under concurrency.
27
+ *
28
+ * ```ts
29
+ * export const productsExternalRef = externalRefIndex({ table: 'products', prefix: 'products' })
30
+ *
31
+ * postgresAdapter({ afterSchemaInit: [productsExternalRef] })
32
+ * ```
33
+ *
34
+ * For a collection carrying `externalRefFields` - it indexes those two columns.
35
+ */
36
+ export declare const externalRefIndex: ({ table, prefix, }: {
37
+ /** Physical table name - the collection's `dbName` alias where one is set, not the slug. */
38
+ table: string;
39
+ /** Index-name prefix, conventionally the table name. */
40
+ prefix: string;
41
+ }) => AfterSchemaInitHook;
42
+ /**
43
+ * Slug uniqueness scoped to a parent instead of the whole collection - for a tree whose slugs
44
+ * legitimately repeat across parents (`getting-started` under every docs section, `lesson-1` under
45
+ * every module) and whose lookups always AND on the parent.
46
+ *
47
+ * ```ts
48
+ * export const lessonsSlugPerModule = slugPerParentIndex({
49
+ * table: 'lessons',
50
+ * parent: 'module',
51
+ * prefix: 'lessons',
52
+ * })
53
+ * ```
54
+ *
55
+ * Nothing to do with imports; a collection needing both indexes registers both hooks.
56
+ */
57
+ export declare const slugPerParentIndex: ({ table, parent, prefix, }: {
58
+ /** Physical table name - the collection's `dbName` alias where one is set, not the slug. */
59
+ table: string;
60
+ /** Drizzle column prop (the camelCase field name) of the parent relationship. */
61
+ parent: string;
62
+ /** Index-name prefix, conventionally the table name. */
63
+ prefix: string;
64
+ }) => AfterSchemaInitHook;
65
+ export {};
@@ -0,0 +1,88 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { uniqueIndex } from 'drizzle-orm/pg-core';
3
+ // Import provenance: the fields an importer stamps on a doc, and the indexes its upsert leans on.
4
+ // A plain `//` header like this one is stripped from the emitted .d.ts, so anything a consumer
5
+ // needs belongs on the exports below (JSDoc emits) or in the package README (npm renders it).
6
+ /**
7
+ * Marks a doc as imported from an external platform - a product synced from Stripe, a post migrated
8
+ * from WordPress, an event pulled from a ticketing API - by recording the platform and its own id
9
+ * for the doc, which is what an importer upserts on so a re-run updates rather than duplicates.
10
+ *
11
+ * A sidebar pair, hidden until something sets them, so a hand-made doc offers no dead inputs.
12
+ * `sources` names the platforms this project imports from.
13
+ *
14
+ * ```ts
15
+ * fields: [...externalRefFields([{ label: 'Stripe', value: 'stripe' }]), ...rest]
16
+ * ```
17
+ *
18
+ * Pair them with `externalRefIndex`, which is what makes the upsert safe under concurrency. Writing
19
+ * the fields is the importer's job: attaching a source id to a doc that was made by hand is a
20
+ * repair, and belongs in a script rather than the admin form.
21
+ */
22
+ export const externalRefFields = (sources) => [
23
+ {
24
+ name: 'externalSource',
25
+ type: 'select',
26
+ options: sources,
27
+ admin: {
28
+ position: 'sidebar',
29
+ description: 'Source platform this doc was imported from.',
30
+ condition: (data) => Boolean(data?.externalSource),
31
+ },
32
+ },
33
+ {
34
+ name: 'externalRef',
35
+ label: 'External Ref',
36
+ type: 'text',
37
+ admin: {
38
+ position: 'sidebar',
39
+ description: "The source platform's own id for this doc, stored verbatim.",
40
+ condition: (data) => Boolean(data?.externalSource),
41
+ },
42
+ },
43
+ ];
44
+ // Payload's afterSchemaInit hooks compose: each extendTable call wraps the previous config builder
45
+ // rather than replacing it, so several hooks may extend one table as long as their keys differ.
46
+ const extendWith = (table, extraConfig) => {
47
+ return ({ schema, extendTable }) => {
48
+ extendTable({ table: schema.tables[table], extraConfig });
49
+ return schema;
50
+ };
51
+ };
52
+ /**
53
+ * One imported doc per source id: a unique index on `(externalSource, externalRef)`, partial to the
54
+ * rows that have a source, which is what makes an importer's upsert safe under concurrency.
55
+ *
56
+ * ```ts
57
+ * export const productsExternalRef = externalRefIndex({ table: 'products', prefix: 'products' })
58
+ *
59
+ * postgresAdapter({ afterSchemaInit: [productsExternalRef] })
60
+ * ```
61
+ *
62
+ * For a collection carrying `externalRefFields` - it indexes those two columns.
63
+ */
64
+ export const externalRefIndex = ({ table, prefix, }) => extendWith(table, (t) => ({
65
+ externalRefUnique: uniqueIndex(`${prefix}_external_ref_uq`)
66
+ .on(t.externalSource, t.externalRef)
67
+ // Interpolated rather than written out: a `dbName` on the field changes the physical column,
68
+ // and a literal `external_source` here would name a column that isn't there.
69
+ .where(sql `${t.externalSource} IS NOT NULL`),
70
+ }));
71
+ /**
72
+ * Slug uniqueness scoped to a parent instead of the whole collection - for a tree whose slugs
73
+ * legitimately repeat across parents (`getting-started` under every docs section, `lesson-1` under
74
+ * every module) and whose lookups always AND on the parent.
75
+ *
76
+ * ```ts
77
+ * export const lessonsSlugPerModule = slugPerParentIndex({
78
+ * table: 'lessons',
79
+ * parent: 'module',
80
+ * prefix: 'lessons',
81
+ * })
82
+ * ```
83
+ *
84
+ * Nothing to do with imports; a collection needing both indexes registers both hooks.
85
+ */
86
+ export const slugPerParentIndex = ({ table, parent, prefix, }) => extendWith(table, (t) => ({
87
+ slugPerParentUnique: uniqueIndex(`${prefix}_slug_per_parent_uq`).on(t[parent], t.slug),
88
+ }));
@@ -0,0 +1,32 @@
1
+ import type { BasePayload } from 'payload';
2
+ import { type SQL } from 'drizzle-orm';
3
+ /** What counts as the row's own data, and where to look for the tables. */
4
+ export type OrphanScanOptions = {
5
+ /**
6
+ * Tables that count as the row's OWN data rather than a reference to it: its array and
7
+ * relationship child tables, its search-index rows. Everything else pointing at the row keeps it.
8
+ */
9
+ ignore?: ReadonlySet<string>;
10
+ /** An extra predicate ANDed onto the scan, e.g. ``sql`AND base.archived_at IS NULL` ``. */
11
+ extra?: SQL;
12
+ /** Postgres schema holding the tables. Defaults to `public`. */
13
+ schema?: string;
14
+ };
15
+ /**
16
+ * Ids of rows in `table` that nothing outside their own data still references - what a bulk delete
17
+ * leaves dangling.
18
+ *
19
+ * ```ts
20
+ * const ids = await findDeletableIds(payload, 'authors', {
21
+ * ignore: new Set(['authors_socials', 'authors_rels']),
22
+ * })
23
+ * ```
24
+ *
25
+ * Ids come back ascending, as whatever type the column holds - integer or uuid.
26
+ *
27
+ * Two refusals stand in front of the result, because callers delete straight from it: an EMPTY
28
+ * reflection means a broken query or the wrong database rather than "nothing references this
29
+ * table", and a run that keeps NOTHING means every guard rail missed. Either would hand back the
30
+ * whole table.
31
+ */
32
+ export declare const findDeletableIds: (payload: BasePayload, table: string, { ignore, extra, schema }?: OrphanScanOptions) => Promise<(number | string)[]>;
@@ -0,0 +1,64 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { isRecord } from '@quitecustard/core/utils/is-record';
3
+ import { resultRows } from './sql-result.js';
4
+ const fkTablesReferencing = async (payload, target, schema) => {
5
+ const res = await payload.db.drizzle.execute(sql `
6
+ SELECT t.relname AS tbl, a.attname AS col
7
+ FROM pg_constraint con
8
+ JOIN pg_class ft ON ft.oid = con.confrelid
9
+ JOIN pg_class t ON t.oid = con.conrelid
10
+ JOIN pg_namespace n ON n.oid = con.connamespace
11
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = con.conkey[1]
12
+ WHERE n.nspname = ${schema} AND con.contype = 'f' AND ft.relname = ${target}`);
13
+ return resultRows(res).flatMap((row) => {
14
+ if (!isRecord(row))
15
+ return [];
16
+ return typeof row.tbl === 'string' && typeof row.col === 'string'
17
+ ? [{ tbl: row.tbl, col: row.col }]
18
+ : [];
19
+ });
20
+ };
21
+ const idsFrom = (rows) => rows.flatMap((row) => {
22
+ if (!isRecord(row))
23
+ return [];
24
+ return typeof row.id === 'number' || typeof row.id === 'string' ? [row.id] : [];
25
+ });
26
+ /**
27
+ * Ids of rows in `table` that nothing outside their own data still references - what a bulk delete
28
+ * leaves dangling.
29
+ *
30
+ * ```ts
31
+ * const ids = await findDeletableIds(payload, 'authors', {
32
+ * ignore: new Set(['authors_socials', 'authors_rels']),
33
+ * })
34
+ * ```
35
+ *
36
+ * Ids come back ascending, as whatever type the column holds - integer or uuid.
37
+ *
38
+ * Two refusals stand in front of the result, because callers delete straight from it: an EMPTY
39
+ * reflection means a broken query or the wrong database rather than "nothing references this
40
+ * table", and a run that keeps NOTHING means every guard rail missed. Either would hand back the
41
+ * whole table.
42
+ */
43
+ export const findDeletableIds = async (payload, table, { ignore, extra = sql ``, schema = 'public' } = {}) => {
44
+ const allRefs = await fkTablesReferencing(payload, table, schema);
45
+ if (allRefs.length === 0)
46
+ throw new Error(`No foreign key references "${table}" - refusing to mark any row deletable.`);
47
+ const refs = allRefs.filter((r) => !ignore?.has(r.tbl));
48
+ // Checked AFTER the ignore filter, not just before it: an `ignore` covering every referrer leaves
49
+ // no NOT EXISTS clauses at all, and the scan degrades to `WHERE 1 = 1` plus whatever `extra` says.
50
+ // The all-rows-deletable refusal below does not catch that, because a narrowing `extra` keeps the
51
+ // count under the table total.
52
+ if (refs.length === 0)
53
+ throw new Error(`Every table referencing "${table}" is in \`ignore\` - refusing, the scan has nothing left to prove a row is unreferenced.`);
54
+ const qualified = (name) => sql.raw(`"${schema}"."${name}"`);
55
+ const notExists = refs.map((r) => sql `AND NOT EXISTS (SELECT 1 FROM ${qualified(r.tbl)} x WHERE x.${sql.raw(`"${r.col}"`)} = base.id)`);
56
+ const res = await payload.db.drizzle.execute(sql `SELECT base.id FROM ${qualified(table)} base WHERE 1 = 1 ${sql.join(notExists, sql ` `)} ${extra} ORDER BY base.id`);
57
+ const ids = idsFrom(resultRows(res));
58
+ const totals = await payload.db.drizzle.execute(sql `SELECT count(*)::int AS total FROM ${qualified(table)}`);
59
+ const totalRow = resultRows(totals)[0];
60
+ const total = isRecord(totalRow) && typeof totalRow.total === 'number' ? totalRow.total : 0;
61
+ if (ids.length > 0 && ids.length === total)
62
+ throw new Error(`Every row of "${table}" (${total}) came back deletable - refusing, the guard rails matched nothing.`);
63
+ return ids;
64
+ };