@abinnovision/payloadcms-mcpx 1.1.0-beta.6 → 2.0.0-beta.7
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 +141 -470
- package/dist/{client → admin}/capability-matrix.d.mts +3 -4
- package/dist/admin/capability-matrix.mjs +354 -0
- package/dist/admin/capability-toggles.mjs +73 -0
- package/dist/{client → admin}/setup-guide.d.mts +1 -1
- package/dist/{client → admin}/setup-guide.mjs +3 -10
- package/dist/api-keys/capability-matrix.d.mts +6 -6
- package/dist/api-keys/capability-matrix.mjs +15 -85
- package/dist/api-keys/fields.mjs +15 -24
- package/dist/auth/resolve.mjs +23 -5
- package/dist/{tools/names.mjs → builtin-tool-names.mjs} +1 -1
- package/dist/capabilities.mjs +34 -42
- package/dist/define-tool.d.mts +19 -0
- package/dist/{types.mjs → define-tool.mjs} +1 -1
- package/dist/endpoint/errors.mjs +5 -6
- package/dist/endpoint/handler.mjs +49 -19
- package/dist/endpoint/server.mjs +65 -19
- package/dist/entity.d.mts +9 -0
- package/dist/guards.mjs +5 -0
- package/dist/i18n.mjs +8 -8
- package/dist/index.d.mts +5 -2
- package/dist/index.mjs +3 -2
- package/dist/options.mjs +51 -45
- package/dist/plugin.mjs +0 -1
- 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 +39 -92
- package/dist/schema/outline.mjs +5 -15
- package/dist/schema/path.mjs +22 -0
- package/dist/schema/pointer.mjs +18 -25
- package/dist/schema/shape.mjs +25 -71
- package/dist/schema/walk.mjs +35 -45
- package/dist/tools/builtin.mjs +4 -4
- package/dist/tools/create-document.mjs +26 -23
- package/dist/tools/describe-schema.mjs +38 -34
- package/dist/tools/document.mjs +84 -0
- package/dist/tools/find-documents.mjs +32 -19
- package/dist/tools/find-versions.mjs +22 -18
- package/dist/tools/get-document.mjs +39 -32
- package/dist/tools/list-capabilities.mjs +23 -16
- package/dist/tools/patch-document.mjs +74 -50
- package/dist/tools/publish-document.mjs +17 -28
- package/dist/tools/query-paths.mjs +55 -0
- package/dist/tools/read-request.d.mts +10 -0
- package/dist/tools/read-request.mjs +43 -0
- package/dist/tools/shared.mjs +58 -99
- package/dist/tools/validate-document.mjs +16 -29
- package/dist/tools/versions.mjs +25 -17
- package/dist/types.d.mts +54 -56
- package/dist/write/draft-guard.mjs +17 -37
- package/dist/write/patch.mjs +27 -183
- package/dist/write/publish-blockers.mjs +7 -14
- package/dist/write/publish-intent.mjs +4 -4
- package/dist/write/row-ids.mjs +44 -0
- package/dist/write/transaction.mjs +5 -8
- package/dist/write/write-data.mjs +64 -0
- package/package.json +4 -4
- 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,28 +1,31 @@
|
|
|
1
|
+
import { defineMcpxTool } from "../define-tool.mjs";
|
|
1
2
|
import { errorResult, jsonResult } from "../result.mjs";
|
|
2
|
-
import { JSON_POINTER_PATTERN,
|
|
3
|
+
import { JSON_POINTER_PATTERN, prototypeSegmentProblem, splitPath } from "../schema/path.mjs";
|
|
4
|
+
import { findRichTextField } from "../schema/walk.mjs";
|
|
5
|
+
import { SchemaError } from "../schema/errors.mjs";
|
|
3
6
|
import { lexicalOutline } from "../schema/outline.mjs";
|
|
4
7
|
import { resolveDataPointer } from "../schema/pointer.mjs";
|
|
5
8
|
import "../schema/index.mjs";
|
|
6
|
-
import { depthShape, idSchema, idShape, localeOf, localeShape, slugsFor,
|
|
7
|
-
import {
|
|
8
|
-
import { defineMcpxTool } from "../types.mjs";
|
|
9
|
+
import { READ_LOCALE_DESCRIPTION, depthShape, entityShape, idSchema, idShape, localeOf, localeShape, slugsFor, widen } from "./shared.mjs";
|
|
10
|
+
import { identityOf, resolveDocument } from "./document.mjs";
|
|
9
11
|
import { diffDocuments, loadPublished, loadVersion, readLive } from "./versions.mjs";
|
|
10
12
|
import { APIError } from "payload";
|
|
11
13
|
import { z } from "zod";
|
|
12
14
|
import { Pointer } from "rfc6902";
|
|
13
15
|
//#region src/tools/get-document.ts
|
|
14
16
|
const OUTLINE_ERROR = "\"outline\" applies to a rich text field; give \"path\" for one.";
|
|
15
|
-
const
|
|
17
|
+
const VERSION_PARAGRAPH = `
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
19
|
+
"versionId" and "diffFrom" work where findVersions does. To revert, call getDocument with the old version as "versionId", the version findVersions marks "latest" as "diffFrom" and the locale you will write, then apply the returned "patch" with patchDocument.`;
|
|
20
|
+
const DESCRIPTION = `Reads one document or global, or with "path" only the value at that pointer. Returns the latest draft by default, with the "updatedAt" a write takes as "expectedUpdatedAt".`;
|
|
21
|
+
const exposesVersions = (scope) => {
|
|
22
|
+
const { collections, globals } = slugsFor(scope, "versions");
|
|
23
|
+
return collections.length + globals.length > 0;
|
|
24
|
+
};
|
|
25
|
+
const assertVersionArgs = (scope, target, args) => {
|
|
23
26
|
if (args.versionId === void 0 && args.diffFrom === void 0) return;
|
|
24
27
|
const { collections, globals } = slugsFor(scope, "versions");
|
|
25
|
-
if (!(target.kind === "collection" ? collections : globals).includes(target.slug)) throw new APIError(`"${target.slug}"
|
|
28
|
+
if (!(target.kind === "collection" ? collections : globals).includes(target.slug)) throw new APIError(`"${target.slug}" does not expose version history.`, 400);
|
|
26
29
|
if (args.versionId !== void 0 && args.draft !== void 0) throw new APIError("Pass either \"versionId\" or \"draft\", not both.", 400);
|
|
27
30
|
if (args.diffFrom !== void 0 && args.outline) throw new APIError("\"outline\" cannot be combined with \"diffFrom\".", 400);
|
|
28
31
|
};
|
|
@@ -36,39 +39,43 @@ const diffResult = async (scope, read, diff, doc) => {
|
|
|
36
39
|
patch: diffDocuments(from.version, doc, diff.pointer)
|
|
37
40
|
});
|
|
38
41
|
};
|
|
42
|
+
const versionShape = (scope) => {
|
|
43
|
+
if (!exposesVersions(scope)) return widen({});
|
|
44
|
+
return widen({
|
|
45
|
+
versionId: idSchema.optional().describe("From findVersions. Not with \"draft\"."),
|
|
46
|
+
diffFrom: idSchema.optional().describe("Version id, or \"published\" for the newest version published in any locale. Returns {from, to, patch}, the JSON Patch from that version to what is read.")
|
|
47
|
+
});
|
|
48
|
+
};
|
|
39
49
|
/**
|
|
40
50
|
* With `path` the handler returns the subtree plus the `id`, `_status` and
|
|
41
|
-
* `updatedAt` a client needs to write back, so
|
|
42
|
-
*
|
|
51
|
+
* `updatedAt` a client needs to write back, so reading one branch still gives
|
|
52
|
+
* the `expectedUpdatedAt` timestamp without a second call.
|
|
43
53
|
*/ const getDocument = defineMcpxTool({
|
|
44
54
|
name: "getDocument",
|
|
45
|
-
description: DESCRIPTION,
|
|
55
|
+
description: (scope) => exposesVersions(scope) ? DESCRIPTION + VERSION_PARAGRAPH : DESCRIPTION,
|
|
46
56
|
annotations: {
|
|
47
57
|
readOnlyHint: true,
|
|
48
58
|
openWorldHint: false
|
|
49
59
|
},
|
|
50
|
-
isEnabled: (scope) => scope.readable.length + scope.
|
|
60
|
+
isEnabled: (scope) => scope.collections.readable.length + scope.globals.readable.length > 0,
|
|
51
61
|
inputSchema: (scope) => ({
|
|
52
|
-
...
|
|
53
|
-
collection: "Collection holding the document.",
|
|
54
|
-
global: "Global to read."
|
|
55
|
-
}),
|
|
62
|
+
...entityShape(scope, "read"),
|
|
56
63
|
...idShape(scope, "read"),
|
|
57
|
-
path: z.string().regex(JSON_POINTER_PATTERN).optional().describe("
|
|
64
|
+
path: z.string().regex(JSON_POINTER_PATTERN).optional().describe("e.g. \"/layout/sections/0\"."),
|
|
58
65
|
...depthShape(scope),
|
|
59
66
|
...localeShape(scope, {
|
|
60
67
|
required: false,
|
|
61
|
-
description:
|
|
68
|
+
description: READ_LOCALE_DESCRIPTION
|
|
62
69
|
}),
|
|
63
|
-
draft: z.boolean().optional().describe("
|
|
64
|
-
outline: z.boolean().optional().describe("
|
|
65
|
-
|
|
66
|
-
diffFrom: idSchema.optional().describe("Version id, or \"published\" for the newest published version in any locale, to diff from. Returns {from, to, patch} instead of the document. Only for entities with versions.")
|
|
70
|
+
draft: z.boolean().optional().describe("Default true. false reads the published version."),
|
|
71
|
+
outline: z.boolean().optional().describe("With \"path\" at a rich text field: list each node's pointer, type, \"version\" and text."),
|
|
72
|
+
...versionShape(scope)
|
|
67
73
|
}),
|
|
68
74
|
handler: async ({ args, scope }) => {
|
|
69
|
-
const target =
|
|
70
|
-
const id = requireIdFor(target, args.id);
|
|
75
|
+
const target = resolveDocument(scope, args, "read");
|
|
71
76
|
assertVersionArgs(scope, target, args);
|
|
77
|
+
const prototyped = args.path ? prototypeSegmentProblem(args.path) : void 0;
|
|
78
|
+
if (prototyped !== void 0) return errorResult(prototyped);
|
|
72
79
|
let pointer;
|
|
73
80
|
try {
|
|
74
81
|
pointer = args.path ? Pointer.fromJSON(args.path) : void 0;
|
|
@@ -77,7 +84,6 @@ const diffResult = async (scope, read, diff, doc) => {
|
|
|
77
84
|
}
|
|
78
85
|
const read = {
|
|
79
86
|
target,
|
|
80
|
-
id,
|
|
81
87
|
depth: args.depth ?? 0,
|
|
82
88
|
locale: localeOf(scope, args.locale)
|
|
83
89
|
};
|
|
@@ -95,7 +101,7 @@ const diffResult = async (scope, read, diff, doc) => {
|
|
|
95
101
|
const path = pointer.toString();
|
|
96
102
|
const value = pointer.get(doc);
|
|
97
103
|
const envelope = {
|
|
98
|
-
...target.
|
|
104
|
+
...identityOf(target, args.id),
|
|
99
105
|
status: doc["_status"],
|
|
100
106
|
updatedAt: doc["updatedAt"],
|
|
101
107
|
path
|
|
@@ -109,10 +115,11 @@ const diffResult = async (scope, read, diff, doc) => {
|
|
|
109
115
|
resolution = resolveDataPointer(scope.req.payload.config, {
|
|
110
116
|
doc,
|
|
111
117
|
pointer: path,
|
|
112
|
-
ref:
|
|
118
|
+
ref: target
|
|
113
119
|
});
|
|
114
120
|
} catch (error) {
|
|
115
|
-
|
|
121
|
+
if (!(error instanceof SchemaError)) throw error;
|
|
122
|
+
return errorResult(error.message);
|
|
116
123
|
}
|
|
117
124
|
const field = resolution.descriptor?.type === "richText" && !resolution.lexical ? findRichTextField(resolution.fields, splitPath(resolution.descriptor.path)) : void 0;
|
|
118
125
|
if (!field) return errorResult(OUTLINE_ERROR);
|
|
@@ -1,20 +1,27 @@
|
|
|
1
|
+
import { defineMcpxTool } from "../define-tool.mjs";
|
|
1
2
|
import { canCreate } from "../capabilities.mjs";
|
|
2
3
|
import { jsonResult } from "../result.mjs";
|
|
3
|
-
import { translatorFor } from "../i18n.mjs";
|
|
4
|
-
import { translateLabel } from "./shared.mjs";
|
|
5
|
-
import { defineMcpxTool } from "../types.mjs";
|
|
4
|
+
import { translateStatic, translatorFor } from "../i18n.mjs";
|
|
6
5
|
import { hasDraftValidationEnabled } from "payload/shared";
|
|
6
|
+
//#region src/tools/list-capabilities.ts
|
|
7
|
+
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.`;
|
|
8
|
+
const translateLabel = (scope, label, fallback) => {
|
|
9
|
+
const { i18n, t } = scope.req;
|
|
10
|
+
const resolved = typeof label === "function" ? label({
|
|
11
|
+
i18n,
|
|
12
|
+
t
|
|
13
|
+
}) : label;
|
|
14
|
+
return translateStatic(resolved, i18n) ?? fallback;
|
|
15
|
+
};
|
|
7
16
|
/**
|
|
8
|
-
* Registered for every key,
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
17
|
+
* Registered for every key, even one with no capabilities ticked, so a client
|
|
18
|
+
* always has a tool to call and gets an empty surface described instead of an
|
|
19
|
+
* empty tool list. The response comes from the request scope and the sanitized
|
|
20
|
+
* config, not the content model, so it stays the same size as a deployment
|
|
21
|
+
* grows.
|
|
13
22
|
*/ const listCapabilities = defineMcpxTool({
|
|
14
23
|
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".`,
|
|
24
|
+
description: DESCRIPTION,
|
|
18
25
|
annotations: {
|
|
19
26
|
readOnlyHint: true,
|
|
20
27
|
openWorldHint: false
|
|
@@ -64,16 +71,16 @@ A global is a singleton: it has no id, is not listed by findDocuments and cannot
|
|
|
64
71
|
draftValidation: hasDraftValidationEnabled(config)
|
|
65
72
|
}];
|
|
66
73
|
});
|
|
67
|
-
return
|
|
74
|
+
return jsonResult({
|
|
68
75
|
collections,
|
|
69
76
|
...globals.length > 0 ? { globals } : {},
|
|
70
|
-
locales: scope.
|
|
71
|
-
codes: scope.locales,
|
|
72
|
-
default: scope.defaultLocale
|
|
77
|
+
locales: scope.localization ? {
|
|
78
|
+
codes: scope.localization.locales,
|
|
79
|
+
default: scope.localization.defaultLocale
|
|
73
80
|
} : null,
|
|
74
81
|
limits: scope.limits,
|
|
75
82
|
tools: Object.entries(scope.capabilities.tools).filter(([, enabled]) => enabled).map(([name]) => name)
|
|
76
|
-
})
|
|
83
|
+
});
|
|
77
84
|
}
|
|
78
85
|
});
|
|
79
86
|
//#endregion
|
|
@@ -1,45 +1,67 @@
|
|
|
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 {
|
|
5
|
-
import {
|
|
4
|
+
import { JSON_POINTER_PATTERN } from "../schema/path.mjs";
|
|
5
|
+
import "../schema/index.mjs";
|
|
6
|
+
import { entityShape, idShape, liveWriteSentence, localeOf, localeShape } from "./shared.mjs";
|
|
7
|
+
import { identityOf, readDraft, resolveDocument, staleReadResult } from "./document.mjs";
|
|
6
8
|
import { collectPublishBlockers } from "../write/publish-blockers.mjs";
|
|
9
|
+
import { applyPatchOperations, isElementPointer } from "../write/patch.mjs";
|
|
7
10
|
import { withTransaction } from "../write/transaction.mjs";
|
|
11
|
+
import { buildWriteData } from "../write/write-data.mjs";
|
|
12
|
+
import { Forbidden, NotFound } from "payload";
|
|
8
13
|
import { z } from "zod";
|
|
9
14
|
import { Pointer } from "rfc6902";
|
|
10
15
|
//#region src/tools/patch-document.ts
|
|
11
|
-
const DESCRIPTION = (scope) => `Applies
|
|
16
|
+
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
17
|
|
|
13
|
-
|
|
18
|
+
${liveWriteSentence(scope, "write")}
|
|
14
19
|
|
|
15
|
-
|
|
20
|
+
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
21
|
|
|
17
|
-
|
|
22
|
+
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
23
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
24
|
+
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.`;
|
|
25
|
+
const POINTER = z.string().regex(JSON_POINTER_PATTERN);
|
|
26
|
+
const PATCHES_LIMIT = 500;
|
|
27
|
+
/** Discriminated on `op`, so an operation carries only its own members. */ const PATCH_OPERATION_SCHEMA = z.discriminatedUnion("op", [
|
|
28
|
+
z.strictObject({
|
|
29
|
+
op: z.literal("add"),
|
|
30
|
+
path: POINTER,
|
|
31
|
+
value: z.unknown()
|
|
32
|
+
}),
|
|
33
|
+
z.strictObject({
|
|
34
|
+
op: z.literal("remove"),
|
|
35
|
+
path: POINTER
|
|
36
|
+
}),
|
|
37
|
+
z.strictObject({
|
|
38
|
+
op: z.literal("replace"),
|
|
39
|
+
path: POINTER,
|
|
40
|
+
value: z.unknown()
|
|
41
|
+
}),
|
|
42
|
+
z.strictObject({
|
|
43
|
+
from: POINTER,
|
|
44
|
+
op: z.literal("move"),
|
|
45
|
+
path: POINTER
|
|
46
|
+
}),
|
|
47
|
+
z.strictObject({
|
|
48
|
+
from: POINTER,
|
|
49
|
+
op: z.literal("copy"),
|
|
50
|
+
path: POINTER
|
|
51
|
+
}),
|
|
52
|
+
z.strictObject({
|
|
53
|
+
op: z.literal("test"),
|
|
54
|
+
path: POINTER,
|
|
55
|
+
value: z.unknown()
|
|
56
|
+
})
|
|
57
|
+
]);
|
|
58
|
+
const survives = (expected, actual) => {
|
|
33
59
|
if (expected === void 0 || expected === null) return actual === void 0 || actual === null;
|
|
34
60
|
if (Array.isArray(expected)) return Array.isArray(actual) && expected.length === actual.length && expected.every((entry, index) => survives(entry, actual[index]));
|
|
35
61
|
if (isPlainObject(expected)) return isPlainObject(actual) && Object.entries(expected).every(([key, value]) => key === "id" || survives(value, actual[key]));
|
|
36
62
|
return isPlainObject(actual) || Array.isArray(actual) ? false : JSON.stringify(expected) === JSON.stringify(actual);
|
|
37
63
|
};
|
|
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) => {
|
|
64
|
+
const notAppliedPointers = (patches, intended, saved) => patches.flatMap((operation) => {
|
|
43
65
|
if (operation.op !== "add" && operation.op !== "replace" || isElementPointer(operation.path)) return [];
|
|
44
66
|
const pointer = Pointer.fromJSON(operation.path);
|
|
45
67
|
const expected = pointer.get(intended);
|
|
@@ -48,10 +70,10 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
48
70
|
});
|
|
49
71
|
/**
|
|
50
72
|
* The handler validates the whole batch against the schema and the current
|
|
51
|
-
* document before
|
|
73
|
+
* document before writing anything, runs the write in a transaction, then
|
|
52
74
|
* re-reads the saved document to report which pointers survived and what still
|
|
53
|
-
* blocks publishing.
|
|
54
|
-
*
|
|
75
|
+
* blocks publishing. The draft guard, not this tool, decides where the write
|
|
76
|
+
* lands.
|
|
55
77
|
*/ const patchDocument = defineMcpxTool({
|
|
56
78
|
name: "patchDocument",
|
|
57
79
|
description: DESCRIPTION,
|
|
@@ -61,37 +83,33 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
61
83
|
idempotentHint: false,
|
|
62
84
|
openWorldHint: false
|
|
63
85
|
},
|
|
64
|
-
isEnabled: (scope) => scope.writable.length + scope.
|
|
86
|
+
isEnabled: (scope) => scope.collections.writable.length + scope.globals.writable.length > 0,
|
|
65
87
|
inputSchema: (scope) => ({
|
|
66
|
-
...
|
|
67
|
-
collection: "Collection holding the document.",
|
|
68
|
-
global: "Global to patch."
|
|
69
|
-
}),
|
|
88
|
+
...entityShape(scope, "write"),
|
|
70
89
|
...idShape(scope, "write"),
|
|
71
90
|
...localeShape(scope, {
|
|
72
91
|
required: true,
|
|
73
|
-
description: "
|
|
92
|
+
description: "Localized fields are written in this locale only."
|
|
74
93
|
}),
|
|
75
|
-
patches: z.array(PATCH_OPERATION_SCHEMA).min(1).
|
|
76
|
-
expectedUpdatedAt: z.string().optional().describe("
|
|
94
|
+
patches: z.array(PATCH_OPERATION_SCHEMA).min(1).max(PATCHES_LIMIT),
|
|
95
|
+
expectedUpdatedAt: z.string().optional().describe("\"updatedAt\" from your last read. Refused if the document changed since.")
|
|
77
96
|
}),
|
|
78
97
|
handler: async ({ args, scope }) => {
|
|
79
|
-
const target =
|
|
80
|
-
const id = requireIdFor(target, args.id);
|
|
98
|
+
const target = resolveDocument(scope, args, "write");
|
|
81
99
|
const { payload } = scope.req;
|
|
82
100
|
const locale = localeOf(scope, args.locale);
|
|
83
101
|
const patches = args.patches;
|
|
84
102
|
return await withTransaction(scope.req, async () => {
|
|
85
|
-
const doc = await
|
|
103
|
+
const doc = await readDraft(scope, {
|
|
86
104
|
target,
|
|
87
|
-
id,
|
|
88
105
|
locale
|
|
89
106
|
});
|
|
90
|
-
|
|
107
|
+
const stale = staleReadResult(doc, args.expectedUpdatedAt, "The document changed since you read it. Read it again and re-apply the patch.");
|
|
108
|
+
if (stale) return stale;
|
|
91
109
|
const applied = applyPatchOperations(payload.config, {
|
|
92
110
|
doc,
|
|
93
111
|
patches,
|
|
94
|
-
ref:
|
|
112
|
+
ref: target
|
|
95
113
|
});
|
|
96
114
|
if ("problems" in applied) return errorResult("No operation was applied.", { problems: applied.problems });
|
|
97
115
|
const write = {
|
|
@@ -105,26 +123,32 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
105
123
|
if (target.kind === "collection") await payload.update({
|
|
106
124
|
...write,
|
|
107
125
|
collection: target.slug,
|
|
108
|
-
id
|
|
126
|
+
id: target.id
|
|
109
127
|
});
|
|
110
128
|
else await payload.updateGlobal({
|
|
111
129
|
...write,
|
|
112
130
|
fallbackLocale: false,
|
|
113
131
|
slug: target.slug
|
|
114
132
|
});
|
|
115
|
-
const saved = await
|
|
133
|
+
const saved = await readDraft(scope, {
|
|
116
134
|
target,
|
|
117
|
-
id,
|
|
118
135
|
locale,
|
|
119
136
|
privileged: true
|
|
120
137
|
});
|
|
121
|
-
const
|
|
138
|
+
const readable = await readDraft(scope, {
|
|
139
|
+
target,
|
|
140
|
+
locale
|
|
141
|
+
}).catch((error) => {
|
|
142
|
+
if (error instanceof NotFound || error instanceof Forbidden) return;
|
|
143
|
+
throw error;
|
|
144
|
+
});
|
|
145
|
+
const notApplied = readable ? notAppliedPointers(patches, applied.next, readable) : [];
|
|
122
146
|
const validation = await collectPublishBlockers(scope.req, {
|
|
123
147
|
doc: saved,
|
|
124
148
|
entity: target
|
|
125
149
|
});
|
|
126
150
|
return jsonResult({
|
|
127
|
-
...target
|
|
151
|
+
...identityOf(target, saved["id"]),
|
|
128
152
|
status: saved["_status"],
|
|
129
153
|
updatedAt: saved["updatedAt"],
|
|
130
154
|
...validation.blockers.length > 0 ? { publishBlockers: validation.blockers } : {},
|
|
@@ -135,4 +159,4 @@ const isPlainObject = (value) => typeof value === "object" && value !== null &&
|
|
|
135
159
|
}
|
|
136
160
|
});
|
|
137
161
|
//#endregion
|
|
138
|
-
export { patchDocument };
|
|
162
|
+
export { PATCH_OPERATION_SCHEMA, patchDocument };
|
|
@@ -1,48 +1,38 @@
|
|
|
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 } from "./shared.mjs";
|
|
4
|
+
import { 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
|
-
* `
|
|
9
|
+
* Publishes a draft. Available where the config exposes
|
|
10
|
+
* `publish` on an entity with drafts and the key has both the `write` and
|
|
11
11
|
* `publish` checkboxes.
|
|
12
12
|
*/ const publishDocument = defineMcpxTool({
|
|
13
13
|
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.`,
|
|
14
|
+
description: `Makes the current draft of one document or global public. A draft with publish blockers is refused, so call validateDocument first. Publishing validates one locale only, normally the default, so a required field left empty in another locale goes live empty. Run validateDocument for each locale. There is no unpublish. A person takes content offline in the admin panel.`,
|
|
21
15
|
annotations: {
|
|
22
16
|
destructiveHint: true,
|
|
23
17
|
openWorldHint: false
|
|
24
18
|
},
|
|
25
|
-
isEnabled: (scope) => scope.publishable.length + scope.
|
|
19
|
+
isEnabled: (scope) => scope.collections.publishable.length + scope.globals.publishable.length > 0,
|
|
26
20
|
inputSchema: (scope) => ({
|
|
27
|
-
...
|
|
28
|
-
collection: "Collection holding the document.",
|
|
29
|
-
global: "Global to publish."
|
|
30
|
-
}),
|
|
21
|
+
...entityShape(scope, "publish"),
|
|
31
22
|
...idShape(scope, "publish"),
|
|
32
|
-
expectedUpdatedAt: z.string().optional().describe("
|
|
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
28
|
const locale = localeOf(scope, void 0);
|
|
39
29
|
return await withTransaction(scope.req, async () => {
|
|
40
|
-
const doc = await
|
|
30
|
+
const doc = await readDraft(scope, {
|
|
41
31
|
target,
|
|
42
|
-
id,
|
|
43
32
|
locale
|
|
44
33
|
});
|
|
45
|
-
|
|
34
|
+
const stale = staleReadResult(doc, args.expectedUpdatedAt, "The document changed since you read it. Read it again before publishing.");
|
|
35
|
+
if (stale) return stale;
|
|
46
36
|
const write = {
|
|
47
37
|
data: withPublishIntent({}),
|
|
48
38
|
depth: 0,
|
|
@@ -55,20 +45,19 @@ There is no unpublish: reverting to a draft stays a human action in the admin pa
|
|
|
55
45
|
if (target.kind === "collection") await payload.update({
|
|
56
46
|
...write,
|
|
57
47
|
collection: target.slug,
|
|
58
|
-
id
|
|
48
|
+
id: target.id
|
|
59
49
|
});
|
|
60
50
|
else await payload.updateGlobal({
|
|
61
51
|
...write,
|
|
62
52
|
slug: target.slug
|
|
63
53
|
});
|
|
64
|
-
const saved = await
|
|
54
|
+
const saved = await readDraft(scope, {
|
|
65
55
|
target,
|
|
66
|
-
id,
|
|
67
56
|
locale,
|
|
68
57
|
privileged: true
|
|
69
58
|
});
|
|
70
59
|
return jsonResult({
|
|
71
|
-
...target
|
|
60
|
+
...identityOf(target, saved["id"]),
|
|
72
61
|
status: saved["_status"],
|
|
73
62
|
updatedAt: saved["updatedAt"]
|
|
74
63
|
});
|
|
@@ -0,0 +1,55 @@
|
|
|
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
|
+
/** The paths of a `sort`: a field name, `-` for descending, comma separated. */ const sortPaths = (sort) => (sort ?? "").split(",").map((entry) => entry.trim().replace(/^-/, "")).filter(Boolean);
|
|
12
|
+
const normalise = (path) => path === "_id" ? "id" : path.replaceAll("__", ".");
|
|
13
|
+
const isRefusedPath = (scope, args, seen = /* @__PURE__ */ new Set()) => {
|
|
14
|
+
const key = `${args.collection}:${args.path}`;
|
|
15
|
+
const { payload } = scope.req;
|
|
16
|
+
if (seen.has(key)) return false;
|
|
17
|
+
seen.add(key);
|
|
18
|
+
const hops = getLocalizedPaths({
|
|
19
|
+
collectionSlug: args.collection,
|
|
20
|
+
fields: payload.collections[args.collection]?.config.flattenedFields ?? [],
|
|
21
|
+
incomingPath: args.path,
|
|
22
|
+
...args.locale ? { locale: args.locale } : {},
|
|
23
|
+
payload
|
|
24
|
+
});
|
|
25
|
+
return hops.some((hop, index) => {
|
|
26
|
+
const { collectionSlug, field } = hop;
|
|
27
|
+
const via = hops[index - 1]?.field;
|
|
28
|
+
const isBareId = hop.path === "id" && (via?.type === "relationship" || via?.type === "upload" || via?.type === "join");
|
|
29
|
+
if (collectionSlug !== void 0 && addressesAdminHidden(payload.config, collectionSlug, hop.path)) return true;
|
|
30
|
+
if (index > 0 && collectionSlug !== void 0 && !scope.collections.readable.includes(collectionSlug) && !isBareId) return true;
|
|
31
|
+
return !hop.invalid && "virtual" in field && typeof field.virtual === "string" && isRefusedPath(scope, {
|
|
32
|
+
collection: collectionSlug ?? args.collection,
|
|
33
|
+
path: normalise(field.virtual),
|
|
34
|
+
locale: args.locale
|
|
35
|
+
}, seen);
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Refuses a `where` or `sort` that traverses a relationship, upload or join
|
|
40
|
+
* field into a collection the key cannot read, since Payload answers it from
|
|
41
|
+
* documents the key may not see, and one that names an `admin.hidden` field,
|
|
42
|
+
* whose value the read tools withhold. Naming the relation field itself, or
|
|
43
|
+
* its id, stays allowed, as does traversal into a readable collection. Unknown
|
|
44
|
+
* paths are left to Payload.
|
|
45
|
+
*/ const assertQueryable = (scope, args) => {
|
|
46
|
+
const reaches = (path) => isRefusedPath(scope, {
|
|
47
|
+
collection: args.collection,
|
|
48
|
+
path: normalise(path),
|
|
49
|
+
locale: args.locale ?? void 0
|
|
50
|
+
});
|
|
51
|
+
for (const path of wherePaths(args.where)) if (reaches(path)) throw new APIError(`This key cannot query through "${path}".`, 400);
|
|
52
|
+
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);
|
|
53
|
+
};
|
|
54
|
+
//#endregion
|
|
55
|
+
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 };
|