@abinnovision/payloadcms-mcpx 1.1.0-beta.6 → 2.0.0-beta.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -470
- package/dist/admin/capability-matrix.d.mts +33 -0
- package/dist/admin/capability-matrix.mjs +354 -0
- package/dist/admin/capability-toggles.mjs +73 -0
- package/dist/{client → admin}/setup-guide.d.mts +4 -2
- package/dist/{client → admin}/setup-guide.mjs +3 -10
- package/dist/api-keys/capability-matrix.d.mts +12 -8
- package/dist/api-keys/capability-matrix.mjs +14 -86
- package/dist/api-keys/collection.mjs +2 -1
- package/dist/api-keys/fields.mjs +36 -24
- package/dist/auth/resolve.mjs +71 -23
- package/dist/{tools/names.mjs → builtin-tool-names.mjs} +1 -1
- package/dist/capabilities.mjs +44 -46
- package/dist/define-tool.d.mts +23 -0
- package/dist/{types.mjs → define-tool.mjs} +1 -1
- package/dist/endpoint/errors.mjs +5 -6
- package/dist/endpoint/handler.mjs +73 -29
- package/dist/endpoint/server.mjs +85 -22
- package/dist/endpoint/upload.mjs +135 -0
- package/dist/entity.d.mts +9 -0
- package/dist/guards.mjs +7 -0
- package/dist/i18n.mjs +10 -8
- package/dist/index.d.mts +5 -2
- package/dist/index.mjs +3 -2
- package/dist/options.mjs +54 -47
- package/dist/plugin.d.mts +2 -2
- package/dist/plugin.mjs +13 -3
- package/dist/request.d.mts +2 -3
- package/dist/request.mjs +2 -3
- package/dist/result.d.mts +2 -3
- package/dist/result.mjs +3 -3
- package/dist/schema/admin-hidden.mjs +91 -0
- package/dist/schema/describe.mjs +17 -33
- package/dist/schema/errors.mjs +8 -0
- package/dist/schema/index.mjs +5 -2
- package/dist/schema/lexical-pointer.mjs +18 -20
- package/dist/schema/lexical.mjs +44 -93
- package/dist/schema/outline.mjs +5 -15
- package/dist/schema/path.mjs +28 -0
- package/dist/schema/pointer.mjs +18 -25
- package/dist/schema/shape.mjs +25 -71
- package/dist/schema/walk.mjs +43 -45
- package/dist/tools/builtin.mjs +4 -4
- package/dist/tools/create-document.mjs +50 -24
- package/dist/tools/describe-schema.mjs +38 -34
- package/dist/tools/document.mjs +124 -0
- package/dist/tools/find-documents.mjs +32 -19
- package/dist/tools/find-versions.mjs +22 -18
- package/dist/tools/get-document.mjs +60 -33
- package/dist/tools/list-capabilities.mjs +35 -19
- package/dist/tools/patch-document.mjs +122 -66
- package/dist/tools/publish-document.mjs +26 -32
- package/dist/tools/query-paths.mjs +57 -0
- package/dist/tools/read-request.d.mts +10 -0
- package/dist/tools/read-request.mjs +43 -0
- package/dist/tools/shared.mjs +74 -105
- package/dist/tools/validate-document.mjs +18 -30
- package/dist/tools/versions.mjs +37 -20
- package/dist/types.d.mts +135 -75
- package/dist/upload/file.mjs +166 -0
- package/dist/upload/grant.mjs +96 -0
- package/dist/version.mjs +3 -1
- package/dist/write/draft-guard.mjs +23 -41
- package/dist/write/patch.mjs +27 -183
- package/dist/write/publish-blockers.mjs +7 -14
- package/dist/write/publish-intent.mjs +6 -4
- package/dist/write/row-ids.mjs +46 -0
- package/dist/write/transaction.mjs +5 -8
- package/dist/write/write-data.mjs +64 -0
- package/package.json +11 -10
- package/dist/client/capability-matrix.d.mts +0 -26
- package/dist/client/capability-matrix.mjs +0 -349
- package/dist/endpoint/index.mjs +0 -4
- package/dist/tools/target.mjs +0 -45
- /package/dist/{client → admin}/index.d.mts +0 -0
- /package/dist/{client → admin}/index.mjs +0 -0
|
@@ -1,20 +1,29 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineMcpxTool } from "../define-tool.mjs";
|
|
2
2
|
import { jsonResult } from "../result.mjs";
|
|
3
|
-
import { translatorFor } from "../i18n.mjs";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { translateStatic, translatorFor } from "../i18n.mjs";
|
|
4
|
+
import { slugsFor } from "./shared.mjs";
|
|
5
|
+
import { MCPX_ISSUES_URL, MCPX_REPOSITORY_URL } from "../version.mjs";
|
|
6
6
|
import { hasDraftValidationEnabled } from "payload/shared";
|
|
7
|
+
//#region src/tools/list-capabilities.ts
|
|
8
|
+
const DESCRIPTION = `Lists what this key may do. Call it first. Returns each collection and global the key can read or write, with whether it can create, publish, has drafts and exposes versions to findVersions, and a collection's "idType". Also returns the locales, the "limits" on page size and depth, and the enabled custom tools.`;
|
|
9
|
+
const DIAGNOSTICS = ` Its "server" block holds the server version with repository and issue links, for a bug report.`;
|
|
10
|
+
const translateLabel = (scope, label, fallback) => {
|
|
11
|
+
const { i18n, t } = scope.req;
|
|
12
|
+
const resolved = typeof label === "function" ? label({
|
|
13
|
+
i18n,
|
|
14
|
+
t
|
|
15
|
+
}) : label;
|
|
16
|
+
return translateStatic(resolved, i18n) ?? fallback;
|
|
17
|
+
};
|
|
7
18
|
/**
|
|
8
|
-
* Registered for every key,
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
19
|
+
* Registered for every key, even one with no capabilities ticked, so a client
|
|
20
|
+
* always has a tool to call and gets an empty surface described instead of an
|
|
21
|
+
* empty tool list. The response comes from the request scope and the sanitized
|
|
22
|
+
* config, not the content model, so it stays the same size as a deployment
|
|
23
|
+
* grows.
|
|
13
24
|
*/ const listCapabilities = defineMcpxTool({
|
|
14
25
|
name: "listCapabilities",
|
|
15
|
-
description:
|
|
16
|
-
|
|
17
|
-
A global is a singleton: it has no id, is not listed by findDocuments and cannot be created. Address one with the "global" argument where a collection document would take "collection" and "id".`,
|
|
26
|
+
description: (scope) => scope.diagnostics ? `${DESCRIPTION}${DIAGNOSTICS}` : DESCRIPTION,
|
|
18
27
|
annotations: {
|
|
19
28
|
readOnlyHint: true,
|
|
20
29
|
openWorldHint: false
|
|
@@ -24,6 +33,7 @@ A global is a singleton: it has no id, is not listed by findDocuments and cannot
|
|
|
24
33
|
handler: ({ scope }) => {
|
|
25
34
|
const { payload } = scope.req;
|
|
26
35
|
const translate = translatorFor(scope.req.i18n);
|
|
36
|
+
const creatable = slugsFor(scope, "create").collections;
|
|
27
37
|
const collections = scope.exposure.collections.flatMap((entry) => {
|
|
28
38
|
const capability = scope.capabilities.collections[entry.slug];
|
|
29
39
|
const collection = payload.collections[entry.slug];
|
|
@@ -39,7 +49,7 @@ A global is a singleton: it has no id, is not listed by findDocuments and cannot
|
|
|
39
49
|
...description === void 0 ? {} : { description },
|
|
40
50
|
read: capability.read,
|
|
41
51
|
write: capability.write,
|
|
42
|
-
create:
|
|
52
|
+
create: creatable.includes(entry.slug),
|
|
43
53
|
publish: capability.publish,
|
|
44
54
|
drafts: entry.hasDrafts,
|
|
45
55
|
versions: entry.hasVersions,
|
|
@@ -64,16 +74,22 @@ A global is a singleton: it has no id, is not listed by findDocuments and cannot
|
|
|
64
74
|
draftValidation: hasDraftValidationEnabled(config)
|
|
65
75
|
}];
|
|
66
76
|
});
|
|
67
|
-
return
|
|
77
|
+
return jsonResult({
|
|
68
78
|
collections,
|
|
69
79
|
...globals.length > 0 ? { globals } : {},
|
|
70
|
-
locales: scope.
|
|
71
|
-
codes: scope.locales,
|
|
72
|
-
default: scope.defaultLocale
|
|
80
|
+
locales: scope.localization ? {
|
|
81
|
+
codes: scope.localization.locales,
|
|
82
|
+
default: scope.localization.defaultLocale
|
|
73
83
|
} : null,
|
|
74
84
|
limits: scope.limits,
|
|
75
|
-
tools: Object.entries(scope.capabilities.tools).filter(([, enabled]) => enabled).map(([name]) => name)
|
|
76
|
-
|
|
85
|
+
tools: Object.entries(scope.capabilities.tools).filter(([, enabled]) => enabled).map(([name]) => name),
|
|
86
|
+
...scope.diagnostics ? { server: {
|
|
87
|
+
name: scope.diagnostics.name,
|
|
88
|
+
version: scope.diagnostics.version,
|
|
89
|
+
repository: MCPX_REPOSITORY_URL,
|
|
90
|
+
issues: MCPX_ISSUES_URL
|
|
91
|
+
} } : {}
|
|
92
|
+
});
|
|
77
93
|
}
|
|
78
94
|
});
|
|
79
95
|
//#endregion
|
|
@@ -1,45 +1,70 @@
|
|
|
1
|
+
import { defineMcpxTool } from "../define-tool.mjs";
|
|
2
|
+
import { isPlainObject } from "../guards.mjs";
|
|
1
3
|
import { errorResult, jsonResult } from "../result.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import { defineMcpxTool } from "../types.mjs";
|
|
5
|
-
import { PATCH_OPERATION_SCHEMA, applyPatchOperations, buildWriteData, isElementPointer } from "../write/patch.mjs";
|
|
4
|
+
import { JSON_POINTER_PATTERN } from "../schema/path.mjs";
|
|
5
|
+
import "../schema/index.mjs";
|
|
6
6
|
import { collectPublishBlockers } from "../write/publish-blockers.mjs";
|
|
7
|
+
import { assertAcceptsFile, fileShape, fileSlugs, fileWriteRefusal, uploadHandoff, uploadedFile } from "../upload/file.mjs";
|
|
8
|
+
import { entityShape, idShape, liveWriteSentence, localeOf, localeShape } from "./shared.mjs";
|
|
9
|
+
import { identityOf, readDraft, resolveDocument, staleReadResult } from "./document.mjs";
|
|
10
|
+
import { applyPatchOperations, isElementPointer } from "../write/patch.mjs";
|
|
7
11
|
import { withTransaction } from "../write/transaction.mjs";
|
|
12
|
+
import { buildWriteData } from "../write/write-data.mjs";
|
|
13
|
+
import { APIError, Forbidden, NotFound } from "payload";
|
|
8
14
|
import { z } from "zod";
|
|
9
15
|
import { Pointer } from "rfc6902";
|
|
10
16
|
//#region src/tools/patch-document.ts
|
|
11
|
-
const DESCRIPTION = (scope) => `Applies
|
|
17
|
+
const DESCRIPTION = (scope) => `Applies JSON Patch operations to one document or global, e.g. {"op":"replace","path":"/title","value":"Home"}. If any operation fails, nothing is written and the response lists the problems.
|
|
12
18
|
|
|
13
|
-
|
|
19
|
+
${liveWriteSentence(scope, "write")}
|
|
14
20
|
|
|
15
|
-
|
|
21
|
+
Read the document with getDocument right before patching. Append to a list with "/-". A new block needs "blockType". To clear a field, "replace" it with null, or with [] for an array or blocks field. "remove" only removes list elements. Indices shift with every add or remove, so remove from the last index to the first.
|
|
16
22
|
|
|
17
|
-
|
|
23
|
+
In a rich text field a pointer continues into the rich text state: "/content/root/children/2" is a node, "/content/root/children/2/tag" one of its properties and "/content/root/children/3/fields/tone" a field of a block node. getDocument "outline" lists each node's pointer and "version". Build nodes from describeSchema "nodeProperties". Check a position before writing to it, e.g. {"op":"test","path":"/content/root/children/2/type","value":"heading"}.
|
|
18
24
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
Node positions shift as soon as anything is added or removed, so read immediately before patching, order removals from the last index to the first, and use a "test" operation on "/content/root/children/2/type" to assert a position is what you think it is before writing to it.
|
|
24
|
-
|
|
25
|
-
A successful write may come back with "publishBlockers": everything still wrong with the draft, such as required fields left empty. Those do not fail the write, because a draft is allowed to be incomplete, but the document cannot be published until the list is empty. "notApplied" lists pointers whose value Payload kept unchanged, which happens when field-level access denies the update. "publishBlockersUnavailable" means the check itself failed, so the empty list says nothing about whether the document is publishable.`;
|
|
26
|
-
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
The response carries "updatedAt" and, if any, "publishBlockers": what must be fixed before publishing. "publishBlockersUnavailable" means that check failed. The write stands either way. "notApplied" lists pointers whose value did not change or cannot be read back, for example where field access denies the update.`;
|
|
26
|
+
const POINTER = z.string().regex(JSON_POINTER_PATTERN);
|
|
27
|
+
const PATCHES_LIMIT = 500;
|
|
27
28
|
/**
|
|
28
|
-
*
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
* Discriminated on `op`, so an operation carries only its own members.
|
|
30
|
+
*/ const PATCH_OPERATION_SCHEMA = z.discriminatedUnion("op", [
|
|
31
|
+
z.strictObject({
|
|
32
|
+
op: z.literal("add"),
|
|
33
|
+
path: POINTER,
|
|
34
|
+
value: z.unknown()
|
|
35
|
+
}),
|
|
36
|
+
z.strictObject({
|
|
37
|
+
op: z.literal("remove"),
|
|
38
|
+
path: POINTER
|
|
39
|
+
}),
|
|
40
|
+
z.strictObject({
|
|
41
|
+
op: z.literal("replace"),
|
|
42
|
+
path: POINTER,
|
|
43
|
+
value: z.unknown()
|
|
44
|
+
}),
|
|
45
|
+
z.strictObject({
|
|
46
|
+
from: POINTER,
|
|
47
|
+
op: z.literal("move"),
|
|
48
|
+
path: POINTER
|
|
49
|
+
}),
|
|
50
|
+
z.strictObject({
|
|
51
|
+
from: POINTER,
|
|
52
|
+
op: z.literal("copy"),
|
|
53
|
+
path: POINTER
|
|
54
|
+
}),
|
|
55
|
+
z.strictObject({
|
|
56
|
+
op: z.literal("test"),
|
|
57
|
+
path: POINTER,
|
|
58
|
+
value: z.unknown()
|
|
59
|
+
})
|
|
60
|
+
]);
|
|
61
|
+
const survives = (expected, actual) => {
|
|
33
62
|
if (expected === void 0 || expected === null) return actual === void 0 || actual === null;
|
|
34
63
|
if (Array.isArray(expected)) return Array.isArray(actual) && expected.length === actual.length && expected.every((entry, index) => survives(entry, actual[index]));
|
|
35
64
|
if (isPlainObject(expected)) return isPlainObject(actual) && Object.entries(expected).every(([key, value]) => key === "id" || survives(value, actual[key]));
|
|
36
65
|
return isPlainObject(actual) || Array.isArray(actual) ? false : JSON.stringify(expected) === JSON.stringify(actual);
|
|
37
66
|
};
|
|
38
|
-
|
|
39
|
-
* Pointers whose intended value did not survive the write. Element pointers
|
|
40
|
-
* are skipped: an append pointer (`/-`) does not resolve against the saved
|
|
41
|
-
* document.
|
|
42
|
-
*/ const notAppliedPointers = (patches, intended, saved) => patches.flatMap((operation) => {
|
|
67
|
+
const notAppliedPointers = (patches, intended, saved) => patches.flatMap((operation) => {
|
|
43
68
|
if (operation.op !== "add" && operation.op !== "replace" || isElementPointer(operation.path)) return [];
|
|
44
69
|
const pointer = Pointer.fromJSON(operation.path);
|
|
45
70
|
const expected = pointer.get(intended);
|
|
@@ -48,10 +73,11 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
48
73
|
});
|
|
49
74
|
/**
|
|
50
75
|
* The handler validates the whole batch against the schema and the current
|
|
51
|
-
* document before
|
|
76
|
+
* document before writing anything, runs the write in a transaction, then
|
|
52
77
|
* re-reads the saved document to report which pointers survived and what still
|
|
53
|
-
* blocks publishing.
|
|
54
|
-
*
|
|
78
|
+
* blocks publishing. The draft guard, not this tool, decides where the write
|
|
79
|
+
* lands. With `file`, the patches and the file land as one update, and the
|
|
80
|
+
* transaction commits right after it because Payload has moved files by then.
|
|
55
81
|
*/ const patchDocument = defineMcpxTool({
|
|
56
82
|
name: "patchDocument",
|
|
57
83
|
description: DESCRIPTION,
|
|
@@ -61,39 +87,80 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
61
87
|
idempotentHint: false,
|
|
62
88
|
openWorldHint: false
|
|
63
89
|
},
|
|
64
|
-
isEnabled: (scope) => scope.writable.length + scope.
|
|
90
|
+
isEnabled: (scope) => scope.collections.writable.length + scope.globals.writable.length > 0,
|
|
65
91
|
inputSchema: (scope) => ({
|
|
66
|
-
...
|
|
67
|
-
collection: "Collection holding the document.",
|
|
68
|
-
global: "Global to patch."
|
|
69
|
-
}),
|
|
92
|
+
...entityShape(scope, "write"),
|
|
70
93
|
...idShape(scope, "write"),
|
|
71
94
|
...localeShape(scope, {
|
|
72
95
|
required: true,
|
|
73
|
-
description: "
|
|
96
|
+
description: "Localized fields are written in this locale only."
|
|
74
97
|
}),
|
|
75
|
-
patches: z.array(PATCH_OPERATION_SCHEMA).min(1).describe("
|
|
76
|
-
expectedUpdatedAt: z.string().optional().describe("
|
|
98
|
+
patches: fileSlugs(scope).length === 0 ? z.array(PATCH_OPERATION_SCHEMA).min(1).max(PATCHES_LIMIT) : z.array(PATCH_OPERATION_SCHEMA).max(PATCHES_LIMIT).describe("May be empty when \"file\" is given."),
|
|
99
|
+
expectedUpdatedAt: z.string().optional().describe("\"updatedAt\" from your last read. Refused if the document changed since."),
|
|
100
|
+
...fileShape(scope, (slugs) => `Replaces the file of a document in ${slugs}. The call returns an "upload" for the bytes instead of writing.`)
|
|
77
101
|
}),
|
|
78
102
|
handler: async ({ args, scope }) => {
|
|
79
|
-
const target =
|
|
80
|
-
const id = requireIdFor(target, args.id);
|
|
103
|
+
const target = resolveDocument(scope, args, "write");
|
|
81
104
|
const { payload } = scope.req;
|
|
82
105
|
const locale = localeOf(scope, args.locale);
|
|
83
106
|
const patches = args.patches;
|
|
84
|
-
|
|
85
|
-
|
|
107
|
+
const { file } = args;
|
|
108
|
+
const bytes = uploadedFile(scope.req);
|
|
109
|
+
if (file !== void 0) assertAcceptsFile(scope, target, file);
|
|
110
|
+
if (patches.length === 0 && file === void 0) throw new APIError("\"patches\" may be empty only when \"file\" is given.", 400);
|
|
111
|
+
const report = async (next) => {
|
|
112
|
+
const saved = await readDraft(scope, {
|
|
113
|
+
target,
|
|
114
|
+
locale,
|
|
115
|
+
privileged: true
|
|
116
|
+
});
|
|
117
|
+
const readable = await readDraft(scope, {
|
|
118
|
+
target,
|
|
119
|
+
locale
|
|
120
|
+
}).catch((error) => {
|
|
121
|
+
if (error instanceof NotFound || error instanceof Forbidden) return;
|
|
122
|
+
throw error;
|
|
123
|
+
});
|
|
124
|
+
const notApplied = readable ? notAppliedPointers(patches, next, readable) : [];
|
|
125
|
+
const validation = await collectPublishBlockers(scope.req, {
|
|
126
|
+
doc: saved,
|
|
127
|
+
entity: target
|
|
128
|
+
});
|
|
129
|
+
return jsonResult({
|
|
130
|
+
...identityOf(target, saved["id"]),
|
|
131
|
+
status: saved["_status"],
|
|
132
|
+
updatedAt: saved["updatedAt"],
|
|
133
|
+
...validation.blockers.length > 0 ? { publishBlockers: validation.blockers } : {},
|
|
134
|
+
...validation.unavailable ? { publishBlockersUnavailable: true } : {},
|
|
135
|
+
...notApplied.length > 0 ? { notApplied } : {}
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
const outcome = await withTransaction(scope.req, async () => {
|
|
139
|
+
const doc = await readDraft(scope, {
|
|
86
140
|
target,
|
|
87
|
-
id,
|
|
88
141
|
locale
|
|
89
142
|
});
|
|
90
|
-
|
|
143
|
+
const stale = staleReadResult(doc, args.expectedUpdatedAt, "The document changed since you read it. Read it again and re-apply the patch.");
|
|
144
|
+
if (stale) return { done: stale };
|
|
91
145
|
const applied = applyPatchOperations(payload.config, {
|
|
92
146
|
doc,
|
|
93
147
|
patches,
|
|
94
|
-
ref:
|
|
148
|
+
ref: target
|
|
95
149
|
});
|
|
96
|
-
if ("problems" in applied) return errorResult("No operation was applied.", { problems: applied.problems });
|
|
150
|
+
if ("problems" in applied) return { done: errorResult("No operation was applied.", { problems: applied.problems }) };
|
|
151
|
+
if (file !== void 0 && target.kind === "collection") {
|
|
152
|
+
const refusal = await fileWriteRefusal(scope, {
|
|
153
|
+
entity: target,
|
|
154
|
+
id: target.id,
|
|
155
|
+
data: applied.next
|
|
156
|
+
});
|
|
157
|
+
if (refusal) return { done: refusal };
|
|
158
|
+
if (!bytes) return { handoff: {
|
|
159
|
+
...args,
|
|
160
|
+
file,
|
|
161
|
+
expectedUpdatedAt: doc["updatedAt"]
|
|
162
|
+
} };
|
|
163
|
+
}
|
|
97
164
|
const write = {
|
|
98
165
|
data: buildWriteData(payload.config, target.config, applied.next),
|
|
99
166
|
depth: 0,
|
|
@@ -105,34 +172,23 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
105
172
|
if (target.kind === "collection") await payload.update({
|
|
106
173
|
...write,
|
|
107
174
|
collection: target.slug,
|
|
108
|
-
id
|
|
175
|
+
id: target.id,
|
|
176
|
+
...bytes === void 0 ? {} : { file: bytes }
|
|
109
177
|
});
|
|
110
178
|
else await payload.updateGlobal({
|
|
111
179
|
...write,
|
|
112
180
|
fallbackLocale: false,
|
|
113
181
|
slug: target.slug
|
|
114
182
|
});
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const notApplied = notAppliedPointers(patches, applied.next, saved);
|
|
122
|
-
const validation = await collectPublishBlockers(scope.req, {
|
|
123
|
-
doc: saved,
|
|
124
|
-
entity: target
|
|
125
|
-
});
|
|
126
|
-
return jsonResult({
|
|
127
|
-
...target.kind === "collection" ? { id: saved["id"] } : { global: target.slug },
|
|
128
|
-
status: saved["_status"],
|
|
129
|
-
updatedAt: saved["updatedAt"],
|
|
130
|
-
...validation.blockers.length > 0 ? { publishBlockers: validation.blockers } : {},
|
|
131
|
-
...validation.unavailable ? { publishBlockersUnavailable: true } : {},
|
|
132
|
-
...notApplied.length > 0 ? { notApplied } : {}
|
|
133
|
-
});
|
|
183
|
+
return bytes === void 0 ? { done: await report(applied.next) } : { written: applied.next };
|
|
184
|
+
});
|
|
185
|
+
if ("done" in outcome) return outcome.done;
|
|
186
|
+
if ("handoff" in outcome) return await uploadHandoff(scope, {
|
|
187
|
+
tool: "patchDocument",
|
|
188
|
+
args: outcome.handoff
|
|
134
189
|
});
|
|
190
|
+
return await report(outcome.written);
|
|
135
191
|
}
|
|
136
192
|
});
|
|
137
193
|
//#endregion
|
|
138
|
-
export { patchDocument };
|
|
194
|
+
export { PATCH_OPERATION_SCHEMA, patchDocument };
|
|
@@ -1,48 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { defineMcpxTool } from "../define-tool.mjs";
|
|
2
|
+
import { jsonResult } from "../result.mjs";
|
|
3
|
+
import { entityShape, idShape, localeOf, localeShape } from "./shared.mjs";
|
|
4
|
+
import { collectLocaleBlockers, identityOf, readDraft, resolveDocument, staleReadResult } from "./document.mjs";
|
|
5
5
|
import { withTransaction } from "../write/transaction.mjs";
|
|
6
6
|
import { withPublishIntent } from "../write/publish-intent.mjs";
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* `publish` checkboxes.
|
|
9
|
+
* Publishes a draft. Available where the config exposes `publish` on an entity
|
|
10
|
+
* with drafts and the key has both the `write` and `publish` checkboxes.
|
|
12
11
|
*/ const publishDocument = defineMcpxTool({
|
|
13
12
|
name: "publishDocument",
|
|
14
|
-
description: `
|
|
15
|
-
|
|
16
|
-
Pass exactly one of "collection" and "global". "id" is required with "collection" and must be omitted with "global", because a global is a singleton.
|
|
17
|
-
|
|
18
|
-
The whole document is published, but Payload only validates the locale the publish runs in, so a required field left empty in another locale goes live empty. That is how the admin panel behaves too. Publishing is refused while a human holds the document open in the admin panel, and republishing an unchanged document is accepted but writes another version.
|
|
19
|
-
|
|
20
|
-
There is no unpublish: reverting to a draft stays a human action in the admin panel.`,
|
|
13
|
+
description: `Makes the current draft of one document or global public, in every locale or only in "locale". A scoped publish keeps the other locales of localized fields as last published, and a never-published document goes live in full. A draft with publish blockers is refused, so call validateDocument first. Payload checks only the published locale, so "otherLocaleBlockers" lists what other locales still lack. There is no unpublish.`,
|
|
21
14
|
annotations: {
|
|
22
15
|
destructiveHint: true,
|
|
23
16
|
openWorldHint: false
|
|
24
17
|
},
|
|
25
|
-
isEnabled: (scope) => scope.publishable.length + scope.
|
|
18
|
+
isEnabled: (scope) => scope.collections.publishable.length + scope.globals.publishable.length > 0,
|
|
26
19
|
inputSchema: (scope) => ({
|
|
27
|
-
...
|
|
28
|
-
collection: "Collection holding the document.",
|
|
29
|
-
global: "Global to publish."
|
|
30
|
-
}),
|
|
20
|
+
...entityShape(scope, "publish"),
|
|
31
21
|
...idShape(scope, "publish"),
|
|
32
|
-
|
|
22
|
+
...localeShape(scope, { required: false }),
|
|
23
|
+
expectedUpdatedAt: z.string().optional().describe("\"updatedAt\" from your last read. Refused if the document changed since.")
|
|
33
24
|
}),
|
|
34
25
|
handler: async ({ args, scope }) => {
|
|
35
|
-
const target =
|
|
36
|
-
const id = requireIdFor(target, args.id);
|
|
26
|
+
const target = resolveDocument(scope, args, "publish");
|
|
37
27
|
const { payload } = scope.req;
|
|
38
|
-
const locale = localeOf(scope,
|
|
28
|
+
const locale = localeOf(scope, args.locale);
|
|
29
|
+
const { localization } = scope;
|
|
39
30
|
return await withTransaction(scope.req, async () => {
|
|
40
|
-
const doc = await
|
|
31
|
+
const doc = await readDraft(scope, {
|
|
41
32
|
target,
|
|
42
|
-
id,
|
|
43
33
|
locale
|
|
44
34
|
});
|
|
45
|
-
|
|
35
|
+
const stale = staleReadResult(doc, args.expectedUpdatedAt, "The document changed since you read it. Read it again before publishing.");
|
|
36
|
+
if (stale) return stale;
|
|
46
37
|
const write = {
|
|
47
38
|
data: withPublishIntent({}),
|
|
48
39
|
depth: 0,
|
|
@@ -50,27 +41,30 @@ There is no unpublish: reverting to a draft stays a human action in the admin pa
|
|
|
50
41
|
fallbackLocale: false,
|
|
51
42
|
overrideAccess: false,
|
|
52
43
|
req: scope.req,
|
|
53
|
-
...locale === void 0 ? {} : { locale }
|
|
44
|
+
...locale === void 0 ? {} : { locale },
|
|
45
|
+
...args.locale === void 0 ? {} : { publishSpecificLocale: args.locale }
|
|
54
46
|
};
|
|
55
47
|
if (target.kind === "collection") await payload.update({
|
|
56
48
|
...write,
|
|
57
49
|
collection: target.slug,
|
|
58
|
-
id
|
|
50
|
+
id: target.id
|
|
59
51
|
});
|
|
60
52
|
else await payload.updateGlobal({
|
|
61
53
|
...write,
|
|
62
54
|
slug: target.slug
|
|
63
55
|
});
|
|
64
|
-
const saved = await
|
|
56
|
+
const saved = await readDraft(scope, {
|
|
65
57
|
target,
|
|
66
|
-
id,
|
|
67
58
|
locale,
|
|
68
59
|
privileged: true
|
|
69
60
|
});
|
|
61
|
+
const others = await collectLocaleBlockers(scope, target, localization?.locales.filter((entry) => entry !== locale) ?? []);
|
|
70
62
|
return jsonResult({
|
|
71
|
-
...target
|
|
63
|
+
...identityOf(target, saved["id"]),
|
|
72
64
|
status: saved["_status"],
|
|
73
|
-
updatedAt: saved["updatedAt"]
|
|
65
|
+
updatedAt: saved["updatedAt"],
|
|
66
|
+
...others.blockers.length > 0 ? { otherLocaleBlockers: others.blockers } : {},
|
|
67
|
+
...others.unavailable ? { otherLocaleBlockersUnavailable: true } : {}
|
|
74
68
|
});
|
|
75
69
|
});
|
|
76
70
|
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { isPlainObject } from "../guards.mjs";
|
|
2
|
+
import { addressesAdminHidden } from "../schema/admin-hidden.mjs";
|
|
3
|
+
import "../schema/index.mjs";
|
|
4
|
+
import { APIError, getLocalizedPaths } from "payload";
|
|
5
|
+
//#region src/tools/query-paths.ts
|
|
6
|
+
/**
|
|
7
|
+
* The paths of a `where`, found the way Payload's `validateQueryPaths` finds
|
|
8
|
+
* them: `and` and `or` (any case) hold arrays of clauses, every other key is a
|
|
9
|
+
* path.
|
|
10
|
+
*/ const wherePaths = (where) => isPlainObject(where) ? Object.entries(where).flatMap(([key, clause]) => ["and", "or"].includes(key.toLowerCase()) && Array.isArray(clause) ? clause.flatMap(wherePaths) : [key]) : [];
|
|
11
|
+
/**
|
|
12
|
+
* The paths of a `sort`: a field name, `-` for descending, comma separated.
|
|
13
|
+
*/ const sortPaths = (sort) => (sort ?? "").split(",").map((entry) => entry.trim().replace(/^-/, "")).filter(Boolean);
|
|
14
|
+
const normalise = (path) => path === "_id" ? "id" : path.replaceAll("__", ".");
|
|
15
|
+
const isRefusedPath = (scope, args, seen = /* @__PURE__ */ new Set()) => {
|
|
16
|
+
const key = `${args.collection}:${args.path}`;
|
|
17
|
+
const { payload } = scope.req;
|
|
18
|
+
if (seen.has(key)) return false;
|
|
19
|
+
seen.add(key);
|
|
20
|
+
const hops = getLocalizedPaths({
|
|
21
|
+
collectionSlug: args.collection,
|
|
22
|
+
fields: payload.collections[args.collection]?.config.flattenedFields ?? [],
|
|
23
|
+
incomingPath: args.path,
|
|
24
|
+
...args.locale ? { locale: args.locale } : {},
|
|
25
|
+
payload
|
|
26
|
+
});
|
|
27
|
+
return hops.some((hop, index) => {
|
|
28
|
+
const { collectionSlug, field } = hop;
|
|
29
|
+
const via = hops[index - 1]?.field;
|
|
30
|
+
const isBareId = hop.path === "id" && (via?.type === "relationship" || via?.type === "upload" || via?.type === "join");
|
|
31
|
+
if (collectionSlug !== void 0 && addressesAdminHidden(payload.config, collectionSlug, hop.path)) return true;
|
|
32
|
+
if (index > 0 && collectionSlug !== void 0 && !scope.collections.readable.includes(collectionSlug) && !isBareId) return true;
|
|
33
|
+
return !hop.invalid && "virtual" in field && typeof field.virtual === "string" && isRefusedPath(scope, {
|
|
34
|
+
collection: collectionSlug ?? args.collection,
|
|
35
|
+
path: normalise(field.virtual),
|
|
36
|
+
locale: args.locale
|
|
37
|
+
}, seen);
|
|
38
|
+
});
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Refuses a `where` or `sort` that traverses a relationship, upload or join
|
|
42
|
+
* field into a collection the key cannot read, since Payload answers it from
|
|
43
|
+
* documents the key may not see, and one that names an `admin.hidden` field,
|
|
44
|
+
* whose value the read tools withhold. Naming the relation field itself, or
|
|
45
|
+
* its id, stays allowed, as does traversal into a readable collection. Unknown
|
|
46
|
+
* paths are left to Payload.
|
|
47
|
+
*/ const assertQueryable = (scope, args) => {
|
|
48
|
+
const reaches = (path) => isRefusedPath(scope, {
|
|
49
|
+
collection: args.collection,
|
|
50
|
+
path: normalise(path),
|
|
51
|
+
locale: args.locale ?? void 0
|
|
52
|
+
});
|
|
53
|
+
for (const path of wherePaths(args.where)) if (reaches(path)) throw new APIError(`This key cannot query through "${path}".`, 400);
|
|
54
|
+
for (const path of sortPaths(args.sort)) if (reaches(path) || normalise(path).split(".").some(reaches)) throw new APIError(`This key cannot query through "${path}".`, 400);
|
|
55
|
+
};
|
|
56
|
+
//#endregion
|
|
57
|
+
export { assertQueryable, sortPaths, wherePaths };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { McpxToolScope } from "../types.mjs";
|
|
2
|
+
import { PayloadRequest } from "payload";
|
|
3
|
+
//#region src/tools/read-request.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A read request that populates only into collections this key may read, at
|
|
6
|
+
* every depth, through a data loader of its own. A refused relation resolves to
|
|
7
|
+
* its id. Each call returns a fresh request.
|
|
8
|
+
*/
|
|
9
|
+
export declare const mcpxReadRequest: (scope: McpxToolScope) => PayloadRequest;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createDataloaderCacheKey, getDataLoader, isolateObjectProperty } from "payload";
|
|
2
|
+
//#region src/tools/read-request.ts
|
|
3
|
+
const LOADER_KEY = (() => {
|
|
4
|
+
const slug = "\0slug";
|
|
5
|
+
const id = "\0id";
|
|
6
|
+
const parts = JSON.parse(createDataloaderCacheKey({
|
|
7
|
+
collectionSlug: slug,
|
|
8
|
+
currentDepth: 0,
|
|
9
|
+
depth: 0,
|
|
10
|
+
docID: id,
|
|
11
|
+
draft: false,
|
|
12
|
+
fallbackLocale: false,
|
|
13
|
+
locale: "",
|
|
14
|
+
overrideAccess: false,
|
|
15
|
+
showHiddenFields: false,
|
|
16
|
+
transactionID: ""
|
|
17
|
+
}));
|
|
18
|
+
return Array.isArray(parts) ? {
|
|
19
|
+
slug: parts.indexOf(slug),
|
|
20
|
+
id: parts.indexOf(id)
|
|
21
|
+
} : {
|
|
22
|
+
slug: -1,
|
|
23
|
+
id: -1
|
|
24
|
+
};
|
|
25
|
+
})();
|
|
26
|
+
/**
|
|
27
|
+
* A read request that populates only into collections this key may read, at
|
|
28
|
+
* every depth, through a data loader of its own. A refused relation resolves to
|
|
29
|
+
* its id. Each call returns a fresh request.
|
|
30
|
+
*/ const mcpxReadRequest = (scope) => {
|
|
31
|
+
const req = isolateObjectProperty(scope.req, "payloadDataLoader");
|
|
32
|
+
const loader = getDataLoader(req);
|
|
33
|
+
const load = loader.load.bind(loader);
|
|
34
|
+
loader.load = (key) => {
|
|
35
|
+
const parts = JSON.parse(key);
|
|
36
|
+
const collection = parts[LOADER_KEY.slug];
|
|
37
|
+
return typeof collection === "string" && scope.collections.readable.includes(collection) ? load(key) : Promise.resolve(parts[LOADER_KEY.id]);
|
|
38
|
+
};
|
|
39
|
+
req.payloadDataLoader = loader;
|
|
40
|
+
return req;
|
|
41
|
+
};
|
|
42
|
+
//#endregion
|
|
43
|
+
export { mcpxReadRequest };
|