@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,18 @@
|
|
|
1
|
+
import type { CollectionSlug, Tab } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* A ready-made "SEO" tab over `@payloadcms/plugin-seo`'s field factories - the title/description/
|
|
4
|
+
* image/preview quartet every collection using the plugin wants, wired to a `meta` group.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* tabs: [contentTab, seoTab({ imageCollection: 'images' })]
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare const seoTab: ({ imageCollection, localized, }: {
|
|
11
|
+
/** Upload collection the meta image field relates to. */
|
|
12
|
+
imageCollection: CollectionSlug;
|
|
13
|
+
/**
|
|
14
|
+
* Whether the three fields that store a value - title, image, description - are localized.
|
|
15
|
+
* Defaults to false. Overview and Preview are UI-only and carry nothing to localize.
|
|
16
|
+
*/
|
|
17
|
+
localized?: boolean;
|
|
18
|
+
}) => Tab;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { OverviewField, MetaTitleField, MetaDescriptionField, MetaImageField, PreviewField, } from '@payloadcms/plugin-seo/fields';
|
|
2
|
+
/**
|
|
3
|
+
* A ready-made "SEO" tab over `@payloadcms/plugin-seo`'s field factories - the title/description/
|
|
4
|
+
* image/preview quartet every collection using the plugin wants, wired to a `meta` group.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* tabs: [contentTab, seoTab({ imageCollection: 'images' })]
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export const seoTab = ({ imageCollection, localized = false, }) => ({
|
|
11
|
+
name: 'meta',
|
|
12
|
+
label: 'SEO',
|
|
13
|
+
fields: [
|
|
14
|
+
OverviewField({
|
|
15
|
+
titlePath: 'meta.title',
|
|
16
|
+
descriptionPath: 'meta.description',
|
|
17
|
+
imagePath: 'meta.image',
|
|
18
|
+
}),
|
|
19
|
+
MetaTitleField({
|
|
20
|
+
hasGenerateFn: true,
|
|
21
|
+
overrides: { localized },
|
|
22
|
+
}),
|
|
23
|
+
MetaImageField({
|
|
24
|
+
relationTo: imageCollection,
|
|
25
|
+
overrides: { localized },
|
|
26
|
+
}),
|
|
27
|
+
MetaDescriptionField({
|
|
28
|
+
overrides: { localized },
|
|
29
|
+
}),
|
|
30
|
+
PreviewField({
|
|
31
|
+
hasGenerateFn: true,
|
|
32
|
+
titlePath: 'meta.title',
|
|
33
|
+
descriptionPath: 'meta.description',
|
|
34
|
+
}),
|
|
35
|
+
],
|
|
36
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { SelectField } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* A fractional-column-width select: quarter/one-third/half/two-thirds/full, default one-third.
|
|
4
|
+
*
|
|
5
|
+
* A factory rather than a constant because `buildConfig` sanitises fields in place - see the note
|
|
6
|
+
* in `layout-fields`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const sizeField: () => SelectField;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A fractional-column-width select: quarter/one-third/half/two-thirds/full, default one-third.
|
|
3
|
+
*
|
|
4
|
+
* A factory rather than a constant because `buildConfig` sanitises fields in place - see the note
|
|
5
|
+
* in `layout-fields`.
|
|
6
|
+
*/
|
|
7
|
+
export const sizeField = () => ({
|
|
8
|
+
name: 'size',
|
|
9
|
+
type: 'select',
|
|
10
|
+
defaultValue: 'one-third',
|
|
11
|
+
required: true,
|
|
12
|
+
options: [
|
|
13
|
+
{ label: 'One Quarter', value: 'quarter' },
|
|
14
|
+
{ label: 'One Third', value: 'one-third' },
|
|
15
|
+
{ label: 'Half', value: 'half' },
|
|
16
|
+
{ label: 'Two Thirds', value: 'two-thirds' },
|
|
17
|
+
{ label: 'Full', value: 'full' },
|
|
18
|
+
],
|
|
19
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FieldHook } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Normalises a free-text URL field before it is stored: a bare host like `x.com/handle` becomes
|
|
4
|
+
* `https://x.com/handle`, since Next's `<Link>` would otherwise treat it as a relative path.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* { name: 'twitter', type: 'text', hooks: { beforeChange: [normaliseSocialUrl] } }
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* A value that already carries a scheme is left alone, whatever the scheme - pair the field with
|
|
11
|
+
* `validateSocialUrl`, which is what refuses the ones that aren't http(s).
|
|
12
|
+
*/
|
|
13
|
+
export declare const normaliseSocialUrl: FieldHook;
|
|
14
|
+
/**
|
|
15
|
+
* Validator for the same field: accepts what `normaliseSocialUrl` would turn into an http(s) URL.
|
|
16
|
+
*
|
|
17
|
+
* It trims first, exactly as the hook does. `validate` runs BEFORE `beforeChange`, so without this
|
|
18
|
+
* a pasted value with a leading space is rejected as invalid even though the hook would have
|
|
19
|
+
* stored it cleanly.
|
|
20
|
+
*/
|
|
21
|
+
export declare const validateSocialUrl: (value: string | undefined | null) => true | string;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// A value is already absolute only if its scheme is followed by `//`. Testing for a bare colon
|
|
2
|
+
// would read the port in `x.test:8080/abc` as one and leave a legitimate host unprefixed.
|
|
3
|
+
const absoluteRe = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
4
|
+
const httpRe = /^https?:\/\//i;
|
|
5
|
+
const withScheme = (trimmed) => absoluteRe.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
6
|
+
/**
|
|
7
|
+
* Normalises a free-text URL field before it is stored: a bare host like `x.com/handle` becomes
|
|
8
|
+
* `https://x.com/handle`, since Next's `<Link>` would otherwise treat it as a relative path.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* { name: 'twitter', type: 'text', hooks: { beforeChange: [normaliseSocialUrl] } }
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* A value that already carries a scheme is left alone, whatever the scheme - pair the field with
|
|
15
|
+
* `validateSocialUrl`, which is what refuses the ones that aren't http(s).
|
|
16
|
+
*/
|
|
17
|
+
export const normaliseSocialUrl = ({ value }) => {
|
|
18
|
+
if (typeof value !== 'string')
|
|
19
|
+
return value;
|
|
20
|
+
const trimmed = value.trim();
|
|
21
|
+
if (!trimmed)
|
|
22
|
+
return trimmed;
|
|
23
|
+
return withScheme(trimmed);
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Validator for the same field: accepts what `normaliseSocialUrl` would turn into an http(s) URL.
|
|
27
|
+
*
|
|
28
|
+
* It trims first, exactly as the hook does. `validate` runs BEFORE `beforeChange`, so without this
|
|
29
|
+
* a pasted value with a leading space is rejected as invalid even though the hook would have
|
|
30
|
+
* stored it cleanly.
|
|
31
|
+
*/
|
|
32
|
+
export const validateSocialUrl = (value) => {
|
|
33
|
+
const trimmed = value?.trim();
|
|
34
|
+
if (!trimmed)
|
|
35
|
+
return true;
|
|
36
|
+
// Checked before prefixing, not after. `https://` + `ftp://x.test` parses as a perfectly good
|
|
37
|
+
// https URL whose HOST is `ftp`, so a scheme-bearing value has to be judged on its own scheme.
|
|
38
|
+
if (absoluteRe.test(trimmed) && !httpRe.test(trimmed))
|
|
39
|
+
return 'Must be an http(s) URL';
|
|
40
|
+
try {
|
|
41
|
+
const { protocol } = new URL(withScheme(trimmed));
|
|
42
|
+
if (protocol !== 'http:' && protocol !== 'https:')
|
|
43
|
+
return 'Must be an http(s) URL';
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return 'Must be a valid URL';
|
|
48
|
+
}
|
|
49
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Option, SelectField } from 'payload';
|
|
2
|
+
/** Tailwind's default numeric spacing scale, 2xs (0.5rem) through 7xl (12rem), as select options. */
|
|
3
|
+
export declare const defaultSpacingOptions: Option[];
|
|
4
|
+
/**
|
|
5
|
+
* A labelled spacing select - the margin/padding-per-side pattern a block-options panel repeats
|
|
6
|
+
* four times (top/bottom margin, top/bottom padding).
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* spacingSelectField({ name: 'mt', label: 'Margin Top' })
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare const spacingSelectField: ({ name, label, defaultValue, options, }: {
|
|
13
|
+
name: string;
|
|
14
|
+
label: string;
|
|
15
|
+
defaultValue?: string;
|
|
16
|
+
options?: Option[];
|
|
17
|
+
}) => SelectField;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// `Option` is either a bare string or a `{ label, value }` pair.
|
|
2
|
+
const optionValue = (option) => typeof option === 'string' ? option : String(option.value);
|
|
3
|
+
/** Tailwind's default numeric spacing scale, 2xs (0.5rem) through 7xl (12rem), as select options. */
|
|
4
|
+
export const defaultSpacingOptions = [
|
|
5
|
+
{ label: '2xs', value: '2' },
|
|
6
|
+
{ label: 'xs', value: '4' },
|
|
7
|
+
{ label: 'sm', value: '6' },
|
|
8
|
+
{ label: 'md', value: '8' },
|
|
9
|
+
{ label: 'lg', value: '10' },
|
|
10
|
+
{ label: 'xl', value: '12' },
|
|
11
|
+
{ label: '2xl', value: '16' },
|
|
12
|
+
{ label: '3xl', value: '20' },
|
|
13
|
+
{ label: '4xl', value: '24' },
|
|
14
|
+
{ label: '5xl', value: '32' },
|
|
15
|
+
{ label: '6xl', value: '40' },
|
|
16
|
+
{ label: '7xl', value: '48' },
|
|
17
|
+
];
|
|
18
|
+
/**
|
|
19
|
+
* A labelled spacing select - the margin/padding-per-side pattern a block-options panel repeats
|
|
20
|
+
* four times (top/bottom margin, top/bottom padding).
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* spacingSelectField({ name: 'mt', label: 'Margin Top' })
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export const spacingSelectField = ({ name, label, defaultValue = '4', options = defaultSpacingOptions, }) => ({
|
|
27
|
+
name,
|
|
28
|
+
label,
|
|
29
|
+
type: 'select',
|
|
30
|
+
// A default that isn't among `options` saves an invalid selection, so a custom scale falls back
|
|
31
|
+
// to its own first entry rather than to this function's idea of a sensible spacing.
|
|
32
|
+
defaultValue: options.some((option) => optionValue(option) === defaultValue)
|
|
33
|
+
? defaultValue
|
|
34
|
+
: options[0] && optionValue(options[0]),
|
|
35
|
+
options,
|
|
36
|
+
});
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Field } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Overrides for a field built by `componentField`: like `Omit<F, 'type'>`, but `name` and `label`
|
|
4
|
+
* stay optional since the factory defaults both - matching the type to what the runtime already
|
|
5
|
+
* accepts.
|
|
6
|
+
*/
|
|
7
|
+
export type ComponentFieldOverrides<F extends Field & {
|
|
8
|
+
name: string;
|
|
9
|
+
label?: unknown;
|
|
10
|
+
}> = Omit<F, 'type' | 'name' | 'label'> & {
|
|
11
|
+
name?: F['name'];
|
|
12
|
+
label?: F['label'];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Shared body for the field factories that wire a single custom admin component onto an otherwise
|
|
16
|
+
* bare field - `colourPickerField`, `phoneField`, `heightField`. Each keeps its own field type and
|
|
17
|
+
* defaults.
|
|
18
|
+
*/
|
|
19
|
+
export declare const componentField: <F extends Field & {
|
|
20
|
+
name: string;
|
|
21
|
+
label?: unknown;
|
|
22
|
+
}>(type: F["type"], component: string, defaults: {
|
|
23
|
+
name: string;
|
|
24
|
+
label: string;
|
|
25
|
+
}, overrides?: ComponentFieldOverrides<F>) => F;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared body for the field factories that wire a single custom admin component onto an otherwise
|
|
3
|
+
* bare field - `colourPickerField`, `phoneField`, `heightField`. Each keeps its own field type and
|
|
4
|
+
* defaults.
|
|
5
|
+
*/
|
|
6
|
+
export const componentField = (type, component, defaults, overrides) => {
|
|
7
|
+
const { name = defaults.name, label = defaults.label, admin, ...rest } = overrides ?? {};
|
|
8
|
+
return {
|
|
9
|
+
type,
|
|
10
|
+
name,
|
|
11
|
+
label,
|
|
12
|
+
admin: {
|
|
13
|
+
...admin,
|
|
14
|
+
components: {
|
|
15
|
+
...admin?.components,
|
|
16
|
+
Field: component,
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
...rest,
|
|
20
|
+
// Spreading `overrides` over a field literal widens it past the branch of Payload's field
|
|
21
|
+
// union it belongs to, so the cast reshapes a literal this function authored - it is not
|
|
22
|
+
// narrowing unknown data.
|
|
23
|
+
};
|
|
24
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { BasePayload } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Run non-critical follow-up work *after* the HTTP response has been sent, via
|
|
4
|
+
* Next.js `after` (backed by Vercel's `waitUntil`, so the serverless invocation
|
|
5
|
+
* stays alive until the work settles). Keeps heavy, self-correcting reconciliation
|
|
6
|
+
* - recomputing derived aggregates, posting webhooks - off the save's critical path
|
|
7
|
+
* so the editor's save returns immediately instead of blocking on a fan-out of DB
|
|
8
|
+
* queries (which in production could exceed the function timeout).
|
|
9
|
+
*
|
|
10
|
+
* `after` is only available inside a request scope (route handlers, server
|
|
11
|
+
* actions); outside one - e.g. local-API scripts or seeding - it throws, so the work is awaited
|
|
12
|
+
* inline instead, preserving correctness everywhere.
|
|
13
|
+
*
|
|
14
|
+
* `work` receives whether it was genuinely DEFERRED. That distinction is load-bearing for anything
|
|
15
|
+
* reconciling against a DELETE:
|
|
16
|
+
* - deferred (`true`): runs post-commit, so it must NOT reuse the triggering `req` - that
|
|
17
|
+
* transaction is closed. Pass `payload` and let each nested operation open its own, which reads
|
|
18
|
+
* the just-committed data and so sees this operation's changes.
|
|
19
|
+
* - inline (`false`): the caller's transaction is still OPEN, so work without `req` runs on a
|
|
20
|
+
* separate connection and is MVCC-isolated from it - a recompute would read the rows as though
|
|
21
|
+
* the delete never happened and persist pre-delete totals. Callers that care must thread `req`
|
|
22
|
+
* here so the work sees the uncommitted state it is reconciling against.
|
|
23
|
+
*/
|
|
24
|
+
export declare const runAfterResponse: (payload: BasePayload, work: (deferred: boolean) => Promise<void>) => Promise<void>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { after } from 'next/server';
|
|
2
|
+
/**
|
|
3
|
+
* Run non-critical follow-up work *after* the HTTP response has been sent, via
|
|
4
|
+
* Next.js `after` (backed by Vercel's `waitUntil`, so the serverless invocation
|
|
5
|
+
* stays alive until the work settles). Keeps heavy, self-correcting reconciliation
|
|
6
|
+
* - recomputing derived aggregates, posting webhooks - off the save's critical path
|
|
7
|
+
* so the editor's save returns immediately instead of blocking on a fan-out of DB
|
|
8
|
+
* queries (which in production could exceed the function timeout).
|
|
9
|
+
*
|
|
10
|
+
* `after` is only available inside a request scope (route handlers, server
|
|
11
|
+
* actions); outside one - e.g. local-API scripts or seeding - it throws, so the work is awaited
|
|
12
|
+
* inline instead, preserving correctness everywhere.
|
|
13
|
+
*
|
|
14
|
+
* `work` receives whether it was genuinely DEFERRED. That distinction is load-bearing for anything
|
|
15
|
+
* reconciling against a DELETE:
|
|
16
|
+
* - deferred (`true`): runs post-commit, so it must NOT reuse the triggering `req` - that
|
|
17
|
+
* transaction is closed. Pass `payload` and let each nested operation open its own, which reads
|
|
18
|
+
* the just-committed data and so sees this operation's changes.
|
|
19
|
+
* - inline (`false`): the caller's transaction is still OPEN, so work without `req` runs on a
|
|
20
|
+
* separate connection and is MVCC-isolated from it - a recompute would read the rows as though
|
|
21
|
+
* the delete never happened and persist pre-delete totals. Callers that care must thread `req`
|
|
22
|
+
* here so the work sees the uncommitted state it is reconciling against.
|
|
23
|
+
*/
|
|
24
|
+
export const runAfterResponse = async (payload, work) => {
|
|
25
|
+
const guarded = async (deferred) => {
|
|
26
|
+
try {
|
|
27
|
+
await work(deferred);
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
payload.logger.error({ err }, 'Deferred after-response work failed');
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
try {
|
|
34
|
+
after(() => guarded(true));
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// Not inside a Next.js request (scripts/seeding): run it inline instead.
|
|
38
|
+
await guarded(false);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { BasePayload, CollectionSlug, PayloadRequest } from 'payload';
|
|
2
|
+
type StatusDoc = {
|
|
3
|
+
id: number | string;
|
|
4
|
+
_status?: string | null;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Payload's afterChange `previousDoc` is the LATEST VERSION, not the published one
|
|
8
|
+
* (`updateByID` -> `getLatestCollectionVersion` queries `latest: true`), and a draft save forces
|
|
9
|
+
* `data._status = 'draft'` (`collections/operations/utilities/update.ts`, `isSavingDraft`). So the FIRST
|
|
10
|
+
* autosave tick on an already-published document reaches every afterChange hook as
|
|
11
|
+
* `previousDoc._status === 'published'` + `doc._status === 'draft'` - byte-identical to an
|
|
12
|
+
* unpublish. Ticks 2+ are draft->draft and look inert, so nothing self-heals.
|
|
13
|
+
*
|
|
14
|
+
* The unguarded test comes from Payload's own website template, where the only consequence is a
|
|
15
|
+
* redundant `revalidatePath`. It is a bug wherever the transition drives a state MUTATION - a
|
|
16
|
+
* cascade that hides a whole subtree, or one that unpublishes every child of the doc being saved.
|
|
17
|
+
*
|
|
18
|
+
* The admin PATCHes `?autosave=true&draft=true` (@payloadcms/ui Autosave). `createLocalReq` never
|
|
19
|
+
* sets either flag - it seeds `req.query` from whatever it was handed and adds only `depth` - so
|
|
20
|
+
* those flags, which are all this helper tests, are absent on a Local API call and a Local API
|
|
21
|
+
* draft save always reads as a real transition here.
|
|
22
|
+
*/
|
|
23
|
+
export declare const looksLikeAutosaveTick: (req: PayloadRequest, doc: StatusDoc) => boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Whether the doc is published RIGHT NOW, read from the published row rather than the draft-latest
|
|
26
|
+
* one. The same asymmetry `looksLikeAutosaveTick` above turns on: a draft save writes to `_versions` and
|
|
27
|
+
* leaves the published row intact, so a find with `draft: true` reports `_status: 'draft'` for a
|
|
28
|
+
* doc that is live - and where the collection autosaves, merely having the doc open in the admin is
|
|
29
|
+
* enough to produce that.
|
|
30
|
+
*
|
|
31
|
+
* Use this wherever publish state decides what a write DOES (whether generated rows are visible,
|
|
32
|
+
* whether a save goes live) rather than merely what it looks like. Reading it off a doc the caller
|
|
33
|
+
* already fetched with `draft: true` is the bug this exists to prevent.
|
|
34
|
+
*/
|
|
35
|
+
export declare const isCurrentlyPublished: (payload: BasePayload, collection: CollectionSlug, id: number | string) => Promise<boolean>;
|
|
36
|
+
/**
|
|
37
|
+
* Exact, caller-agnostic version of {@link looksLikeAutosaveTick}: a draft save writes to
|
|
38
|
+
* `_versions` only and leaves the published row intact, while a real unpublish flips it. Costs one
|
|
39
|
+
* indexed read, and only on the ambiguous (draft-direction) branch.
|
|
40
|
+
*
|
|
41
|
+
* Use this wherever the answer drives a STATE MUTATION or an outbound side effect. The cheap sync
|
|
42
|
+
* check above is proportionate only where a false negative merely costs a redundant cache purge.
|
|
43
|
+
*/
|
|
44
|
+
export declare const isDraftSaveNotUnpublish: (collection: CollectionSlug, doc: StatusDoc, req: PayloadRequest) => Promise<boolean>;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
2
|
+
const flagged = (value) => value === true || value === 'true';
|
|
3
|
+
/**
|
|
4
|
+
* Payload's afterChange `previousDoc` is the LATEST VERSION, not the published one
|
|
5
|
+
* (`updateByID` -> `getLatestCollectionVersion` queries `latest: true`), and a draft save forces
|
|
6
|
+
* `data._status = 'draft'` (`collections/operations/utilities/update.ts`, `isSavingDraft`). So the FIRST
|
|
7
|
+
* autosave tick on an already-published document reaches every afterChange hook as
|
|
8
|
+
* `previousDoc._status === 'published'` + `doc._status === 'draft'` - byte-identical to an
|
|
9
|
+
* unpublish. Ticks 2+ are draft->draft and look inert, so nothing self-heals.
|
|
10
|
+
*
|
|
11
|
+
* The unguarded test comes from Payload's own website template, where the only consequence is a
|
|
12
|
+
* redundant `revalidatePath`. It is a bug wherever the transition drives a state MUTATION - a
|
|
13
|
+
* cascade that hides a whole subtree, or one that unpublishes every child of the doc being saved.
|
|
14
|
+
*
|
|
15
|
+
* The admin PATCHes `?autosave=true&draft=true` (@payloadcms/ui Autosave). `createLocalReq` never
|
|
16
|
+
* sets either flag - it seeds `req.query` from whatever it was handed and adds only `depth` - so
|
|
17
|
+
* those flags, which are all this helper tests, are absent on a Local API call and a Local API
|
|
18
|
+
* draft save always reads as a real transition here.
|
|
19
|
+
*/
|
|
20
|
+
export const looksLikeAutosaveTick = (req, doc) => {
|
|
21
|
+
if (doc._status === 'published')
|
|
22
|
+
return false;
|
|
23
|
+
const query = isRecord(req?.query) ? req.query : {};
|
|
24
|
+
return flagged(query.autosave) || flagged(query.draft);
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Whether the doc is published RIGHT NOW, read from the published row rather than the draft-latest
|
|
28
|
+
* one. The same asymmetry `looksLikeAutosaveTick` above turns on: a draft save writes to `_versions` and
|
|
29
|
+
* leaves the published row intact, so a find with `draft: true` reports `_status: 'draft'` for a
|
|
30
|
+
* doc that is live - and where the collection autosaves, merely having the doc open in the admin is
|
|
31
|
+
* enough to produce that.
|
|
32
|
+
*
|
|
33
|
+
* Use this wherever publish state decides what a write DOES (whether generated rows are visible,
|
|
34
|
+
* whether a save goes live) rather than merely what it looks like. Reading it off a doc the caller
|
|
35
|
+
* already fetched with `draft: true` is the bug this exists to prevent.
|
|
36
|
+
*/
|
|
37
|
+
export const isCurrentlyPublished = async (payload, collection, id) => {
|
|
38
|
+
try {
|
|
39
|
+
const published = await payload.findByID({ collection, id, depth: 0 });
|
|
40
|
+
return isRecord(published) && published._status === 'published';
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Undeterminable - treat as unpublished, which keeps generated rows hidden rather than exposing
|
|
44
|
+
// a subtree the public shouldn't see yet.
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Exact, caller-agnostic version of {@link looksLikeAutosaveTick}: a draft save writes to
|
|
50
|
+
* `_versions` only and leaves the published row intact, while a real unpublish flips it. Costs one
|
|
51
|
+
* indexed read, and only on the ambiguous (draft-direction) branch.
|
|
52
|
+
*
|
|
53
|
+
* Use this wherever the answer drives a STATE MUTATION or an outbound side effect. The cheap sync
|
|
54
|
+
* check above is proportionate only where a false negative merely costs a redundant cache purge.
|
|
55
|
+
*/
|
|
56
|
+
export const isDraftSaveNotUnpublish = async (collection, doc, req) => {
|
|
57
|
+
// Publishing is always a genuine transition; only the draft direction is ambiguous.
|
|
58
|
+
if (doc._status === 'published')
|
|
59
|
+
return false;
|
|
60
|
+
if (looksLikeAutosaveTick(req, doc))
|
|
61
|
+
return true;
|
|
62
|
+
try {
|
|
63
|
+
// Threading `req` keeps this on the operation's own transaction (a req-less nested call would
|
|
64
|
+
// open a second one and deadlock against it) and shows the row as this write left it.
|
|
65
|
+
const persisted = await req.payload.findByID({
|
|
66
|
+
collection,
|
|
67
|
+
id: doc.id,
|
|
68
|
+
depth: 0,
|
|
69
|
+
req,
|
|
70
|
+
});
|
|
71
|
+
return isRecord(persisted) && persisted._status === 'published';
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Undeterminable (doc gone mid-transaction, no request context) - fall back to the historical
|
|
75
|
+
// behaviour and let the caller treat it as a real transition.
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/** What one drain did, for a cron route to return. */
|
|
3
|
+
export interface JobDrainReport {
|
|
4
|
+
/** Jobs this run picked up and executed. */
|
|
5
|
+
jobsRun: number;
|
|
6
|
+
/** Of those, the ones that ended in an error status rather than succeeding. */
|
|
7
|
+
jobsFailed: number;
|
|
8
|
+
/** Runnable jobs left over once this run hit `jobLimit`. A dry run reports the whole runnable set. */
|
|
9
|
+
jobsRemaining: number;
|
|
10
|
+
/** The reason the drain could not run at all, or null when it ran. */
|
|
11
|
+
jobsSkipped: string | null;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Runs whatever is waiting in the Payload job queue.
|
|
15
|
+
*
|
|
16
|
+
* 🔴 Nothing else does. `draftVersions()` sets `schedulePublish: true`, so Payload injects a
|
|
17
|
+
* `schedulePublish` task and flips `jobs.enabled` - but there is no `autoRun`, no worker and no
|
|
18
|
+
* second cron, so without this a scheduled publish is enqueued with its `waitUntil` and then sits
|
|
19
|
+
* there forever while the admin UI goes on reporting it as scheduled.
|
|
20
|
+
*
|
|
21
|
+
* `allQueues` because the queue name is a per-job argument: anything queued onto a non-default queue
|
|
22
|
+
* would otherwise be invisible here and strand exactly as it did before.
|
|
23
|
+
*
|
|
24
|
+
* Failures are returned, not thrown: cron monitoring keys on the response status, so one bad job
|
|
25
|
+
* must not report an otherwise healthy run as failed. `[cron] job drain failed` is the log line to
|
|
26
|
+
* alert on.
|
|
27
|
+
*/
|
|
28
|
+
export declare const runQueuedJobs: (payload: Payload, { dryRun }: {
|
|
29
|
+
dryRun: boolean;
|
|
30
|
+
}) => Promise<JobDrainReport>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// One invocation's ceiling, so a pathological backlog cannot eat the whole function budget.
|
|
2
|
+
// Anything left over is reported as `jobsRemaining` for the next run to pick up.
|
|
3
|
+
const jobLimit = 25;
|
|
4
|
+
/** The `concurrencyKey`s currently `processing`, so a dry run can exclude jobs `runJobs` would skip. */
|
|
5
|
+
const runningConcurrencyKeys = async (payload) => {
|
|
6
|
+
const running = await payload.db.find({
|
|
7
|
+
collection: 'payload-jobs',
|
|
8
|
+
limit: 0,
|
|
9
|
+
pagination: false,
|
|
10
|
+
select: { concurrencyKey: true },
|
|
11
|
+
where: { and: [{ processing: { equals: true } }, { concurrencyKey: { exists: true } }] },
|
|
12
|
+
});
|
|
13
|
+
return new Set(running.docs.flatMap((doc) => (doc.concurrencyKey ? [doc.concurrencyKey] : [])));
|
|
14
|
+
};
|
|
15
|
+
// Mirrors the clause `runJobs` builds internally (queues/operations/runJobs/index.js), so the dry-run
|
|
16
|
+
// count reports the set an applied run would actually pick up. A job that has exhausted its retries
|
|
17
|
+
// carries `hasError`, and one mid-flight carries `processing` - counting either would report a
|
|
18
|
+
// backlog that no run will ever clear. When concurrency control is on, `runJobs` also excludes jobs
|
|
19
|
+
// whose `concurrencyKey` matches one already processing - mirrored here via the same subquery, or a
|
|
20
|
+
// dry run would count a job that an applied run would skip.
|
|
21
|
+
const runnableJobsWhere = async (payload) => {
|
|
22
|
+
const and = [
|
|
23
|
+
{ completedAt: { exists: false } },
|
|
24
|
+
{ hasError: { not_equals: true } },
|
|
25
|
+
{ processing: { equals: false } },
|
|
26
|
+
{
|
|
27
|
+
or: [
|
|
28
|
+
{ waitUntil: { exists: false } },
|
|
29
|
+
{ waitUntil: { less_than: new Date().toISOString() } },
|
|
30
|
+
],
|
|
31
|
+
},
|
|
32
|
+
];
|
|
33
|
+
if (payload.config.jobs?.enableConcurrencyControl) {
|
|
34
|
+
const runningKeys = await runningConcurrencyKeys(payload);
|
|
35
|
+
if (runningKeys.size > 0)
|
|
36
|
+
and.push({
|
|
37
|
+
or: [
|
|
38
|
+
{ concurrencyKey: { exists: false } },
|
|
39
|
+
{ concurrencyKey: { not_in: [...runningKeys] } },
|
|
40
|
+
],
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return { and };
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Runs whatever is waiting in the Payload job queue.
|
|
47
|
+
*
|
|
48
|
+
* 🔴 Nothing else does. `draftVersions()` sets `schedulePublish: true`, so Payload injects a
|
|
49
|
+
* `schedulePublish` task and flips `jobs.enabled` - but there is no `autoRun`, no worker and no
|
|
50
|
+
* second cron, so without this a scheduled publish is enqueued with its `waitUntil` and then sits
|
|
51
|
+
* there forever while the admin UI goes on reporting it as scheduled.
|
|
52
|
+
*
|
|
53
|
+
* `allQueues` because the queue name is a per-job argument: anything queued onto a non-default queue
|
|
54
|
+
* would otherwise be invisible here and strand exactly as it did before.
|
|
55
|
+
*
|
|
56
|
+
* Failures are returned, not thrown: cron monitoring keys on the response status, so one bad job
|
|
57
|
+
* must not report an otherwise healthy run as failed. `[cron] job drain failed` is the log line to
|
|
58
|
+
* alert on.
|
|
59
|
+
*/
|
|
60
|
+
export const runQueuedJobs = async (payload, { dryRun }) => {
|
|
61
|
+
try {
|
|
62
|
+
if (dryRun) {
|
|
63
|
+
const { totalDocs } = await payload.count({
|
|
64
|
+
collection: 'payload-jobs',
|
|
65
|
+
where: await runnableJobsWhere(payload),
|
|
66
|
+
});
|
|
67
|
+
return { jobsRun: 0, jobsFailed: 0, jobsRemaining: totalDocs, jobsSkipped: null };
|
|
68
|
+
}
|
|
69
|
+
const result = await payload.jobs.run({ allQueues: true, limit: jobLimit });
|
|
70
|
+
const statuses = Object.values(result.jobStatus ?? {});
|
|
71
|
+
return {
|
|
72
|
+
jobsRun: statuses.length,
|
|
73
|
+
jobsFailed: statuses.filter((job) => job.status !== 'success').length,
|
|
74
|
+
jobsRemaining: result.remainingJobsFromQueried,
|
|
75
|
+
jobsSkipped: null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
payload.logger.error({ err: error }, '[cron] job drain failed');
|
|
80
|
+
return {
|
|
81
|
+
jobsRun: 0,
|
|
82
|
+
jobsFailed: 0,
|
|
83
|
+
jobsRemaining: 0,
|
|
84
|
+
jobsSkipped: error instanceof Error ? error.message : String(error),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { PayloadRequest } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Set boolean `req.context` flags for the duration of `work`, safely under concurrency.
|
|
4
|
+
*
|
|
5
|
+
* The obvious version - capture the current values, set true, restore in a `finally` - is broken on
|
|
6
|
+
* any hook that a BULK operation can reach. Payload builds every document's hook chain up front with
|
|
7
|
+
* an eager `docs.map(async …)` and runs them against ONE shared `req.context`, so with 2+ documents
|
|
8
|
+
* the second chain's capture reads the first's mid-flight `true`, and whichever `finally` lands last
|
|
9
|
+
* restores that `true` permanently - silently suppressing every remaining hook in the operation.
|
|
10
|
+
*
|
|
11
|
+
* Reference counting removes the race: the base value is recorded only on the outermost entry
|
|
12
|
+
* (0 -> 1) and restored only on the outermost exit (1 -> 0), so N interleaved chains raise the count
|
|
13
|
+
* to N and lower it back to 0 with the original value intact. Increment and decrement are
|
|
14
|
+
* synchronous, so they cannot interleave with each other.
|
|
15
|
+
*/
|
|
16
|
+
export declare const withSuppressedContext: <T>(req: PayloadRequest, flags: readonly string[], work: () => Promise<T>) => Promise<T>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { isRecord } from '@quitecustard/core/utils/is-record';
|
|
2
|
+
// Where the per-flag depth counters and the value each flag held before the outermost suppression
|
|
3
|
+
// live. Both hang off req.context so they share the request's lifetime.
|
|
4
|
+
const countsKey = 'suppressedContextCounts';
|
|
5
|
+
const baseKey = 'suppressedContextBase';
|
|
6
|
+
// req.context is open storage keyed by string, so a bag is read back structurally - anything else
|
|
7
|
+
// in the request could have written that key.
|
|
8
|
+
const contextBag = (req, key) => {
|
|
9
|
+
const existing = req.context[key];
|
|
10
|
+
if (isRecord(existing))
|
|
11
|
+
return existing;
|
|
12
|
+
const created = {};
|
|
13
|
+
req.context[key] = created;
|
|
14
|
+
return created;
|
|
15
|
+
};
|
|
16
|
+
const depthOf = (counts, flag) => typeof counts[flag] === 'number' ? counts[flag] : 0;
|
|
17
|
+
/**
|
|
18
|
+
* Set boolean `req.context` flags for the duration of `work`, safely under concurrency.
|
|
19
|
+
*
|
|
20
|
+
* The obvious version - capture the current values, set true, restore in a `finally` - is broken on
|
|
21
|
+
* any hook that a BULK operation can reach. Payload builds every document's hook chain up front with
|
|
22
|
+
* an eager `docs.map(async …)` and runs them against ONE shared `req.context`, so with 2+ documents
|
|
23
|
+
* the second chain's capture reads the first's mid-flight `true`, and whichever `finally` lands last
|
|
24
|
+
* restores that `true` permanently - silently suppressing every remaining hook in the operation.
|
|
25
|
+
*
|
|
26
|
+
* Reference counting removes the race: the base value is recorded only on the outermost entry
|
|
27
|
+
* (0 -> 1) and restored only on the outermost exit (1 -> 0), so N interleaved chains raise the count
|
|
28
|
+
* to N and lower it back to 0 with the original value intact. Increment and decrement are
|
|
29
|
+
* synchronous, so they cannot interleave with each other.
|
|
30
|
+
*/
|
|
31
|
+
export const withSuppressedContext = async (req, flags, work) => {
|
|
32
|
+
const counts = contextBag(req, countsKey);
|
|
33
|
+
const base = contextBag(req, baseKey);
|
|
34
|
+
for (const flag of flags) {
|
|
35
|
+
const depth = depthOf(counts, flag);
|
|
36
|
+
if (depth === 0)
|
|
37
|
+
base[flag] = req.context[flag];
|
|
38
|
+
counts[flag] = depth + 1;
|
|
39
|
+
req.context[flag] = true;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return await work();
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
for (const flag of flags) {
|
|
46
|
+
const depth = depthOf(counts, flag) || 1;
|
|
47
|
+
counts[flag] = depth - 1;
|
|
48
|
+
if (depth - 1 <= 0) {
|
|
49
|
+
delete counts[flag];
|
|
50
|
+
req.context[flag] = base[flag];
|
|
51
|
+
delete base[flag];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|