@sanity/cli 8.26.0 → 8.28.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/README.md +1534 -411
- package/dist/actions/context/commandTable.js +215 -0
- package/dist/actions/context/commandTable.js.map +1 -0
- package/dist/actions/context/contextCommand.js +246 -0
- package/dist/actions/context/contextCommand.js.map +1 -0
- package/dist/actions/context/contextSpec.js +18 -0
- package/dist/actions/context/contextSpec.js.map +1 -0
- package/dist/actions/context/distillContextOperations.js +335 -0
- package/dist/actions/context/distillContextOperations.js.map +1 -0
- package/dist/actions/context/mcpEndpoint.js +165 -0
- package/dist/actions/context/mcpEndpoint.js.map +1 -0
- package/dist/actions/context/operationInput.js +226 -0
- package/dist/actions/context/operationInput.js.map +1 -0
- package/dist/actions/context/operationTypes.js +3 -0
- package/dist/actions/context/operationTypes.js.map +1 -0
- package/dist/actions/context/removedCommands.js +26 -0
- package/dist/actions/context/removedCommands.js.map +1 -0
- package/dist/actions/context/renderOperationResult.js +72 -0
- package/dist/actions/context/renderOperationResult.js.map +1 -0
- package/dist/actions/context/resolveOrganizationId.js +8 -1
- package/dist/actions/context/resolveOrganizationId.js.map +1 -1
- package/dist/actions/context/sourceFile.js +31 -0
- package/dist/actions/context/sourceFile.js.map +1 -0
- package/dist/actions/context/syncOutput.js +17 -0
- package/dist/actions/context/syncOutput.js.map +1 -0
- package/dist/actions/context/table.js +13 -0
- package/dist/actions/context/table.js.map +1 -0
- package/dist/actions/context/waitForJob.js.map +1 -1
- package/dist/actions/context/waitForSourceSync.js +48 -0
- package/dist/actions/context/waitForSourceSync.js.map +1 -0
- package/dist/actions/context/watchJob.js.map +1 -1
- package/dist/actions/context/watchSourceSync.js +40 -0
- package/dist/actions/context/watchSourceSync.js.map +1 -0
- package/dist/commands/context/build.js +19 -81
- package/dist/commands/context/build.js.map +1 -1
- package/dist/commands/context/create.js +3 -104
- package/dist/commands/context/create.js.map +1 -1
- package/dist/commands/context/delete.js +3 -73
- package/dist/commands/context/delete.js.map +1 -1
- package/dist/commands/context/documents/content.js +117 -0
- package/dist/commands/context/documents/content.js.map +1 -0
- package/dist/commands/context/documents/delete.js +5 -0
- package/dist/commands/context/documents/delete.js.map +1 -0
- package/dist/commands/context/documents/edit.js +5 -0
- package/dist/commands/context/documents/edit.js.map +1 -0
- package/dist/commands/context/documents/get.js +5 -0
- package/dist/commands/context/documents/get.js.map +1 -0
- package/dist/commands/context/documents/list.js +5 -0
- package/dist/commands/context/documents/list.js.map +1 -0
- package/dist/commands/context/entries/list.js +2 -2
- package/dist/commands/context/entries/list.js.map +1 -1
- package/dist/commands/context/entries/rebuild.js +3 -93
- package/dist/commands/context/entries/rebuild.js.map +1 -1
- package/dist/commands/context/get.js +3 -88
- package/dist/commands/context/get.js.map +1 -1
- package/dist/commands/context/instructions/create.js +5 -0
- package/dist/commands/context/instructions/create.js.map +1 -0
- package/dist/commands/context/instructions/delete.js +5 -0
- package/dist/commands/context/instructions/delete.js.map +1 -0
- package/dist/commands/context/instructions/edit.js +5 -0
- package/dist/commands/context/instructions/edit.js.map +1 -0
- package/dist/commands/context/issues/apply.js +3 -84
- package/dist/commands/context/issues/apply.js.map +1 -1
- package/dist/commands/context/issues/dismiss.js +3 -50
- package/dist/commands/context/issues/dismiss.js.map +1 -1
- package/dist/commands/context/issues/list.js +0 -5
- package/dist/commands/context/issues/list.js.map +1 -1
- package/dist/commands/context/issues/reopen.js +3 -51
- package/dist/commands/context/issues/reopen.js.map +1 -1
- package/dist/commands/context/issues/resolve.js +23 -92
- package/dist/commands/context/issues/resolve.js.map +1 -1
- package/dist/commands/context/jobs/get.js +3 -88
- package/dist/commands/context/jobs/get.js.map +1 -1
- package/dist/commands/context/list.js +3 -103
- package/dist/commands/context/list.js.map +1 -1
- package/dist/commands/context/mcp/create.js +152 -0
- package/dist/commands/context/mcp/create.js.map +1 -0
- package/dist/commands/context/mcp/delete.js +82 -0
- package/dist/commands/context/mcp/delete.js.map +1 -0
- package/dist/commands/context/mcp/get.js +42 -0
- package/dist/commands/context/mcp/get.js.map +1 -0
- package/dist/commands/context/mcp/initial-context.js +5 -0
- package/dist/commands/context/mcp/initial-context.js.map +1 -0
- package/dist/commands/context/mcp/list.js +87 -0
- package/dist/commands/context/mcp/list.js.map +1 -0
- package/dist/commands/context/mcp/status.js +98 -0
- package/dist/commands/context/mcp/status.js.map +1 -0
- package/dist/commands/context/mcp/update.js +225 -0
- package/dist/commands/context/mcp/update.js.map +1 -0
- package/dist/commands/context/query.js +6 -14
- package/dist/commands/context/query.js.map +1 -1
- package/dist/commands/context/sources/create.js +175 -0
- package/dist/commands/context/sources/create.js.map +1 -0
- package/dist/commands/context/sources/delete.js +5 -0
- package/dist/commands/context/sources/delete.js.map +1 -0
- package/dist/commands/context/sources/edit.js +29 -0
- package/dist/commands/context/sources/edit.js.map +1 -0
- package/dist/commands/context/sources/get.js +5 -0
- package/dist/commands/context/sources/get.js.map +1 -0
- package/dist/commands/context/sources/list.js +5 -0
- package/dist/commands/context/sources/list.js.map +1 -0
- package/dist/commands/context/sources/sync.js +5 -0
- package/dist/commands/context/sources/sync.js.map +1 -0
- package/dist/commands/context/sources/syncs/confirm.js +5 -0
- package/dist/commands/context/sources/syncs/confirm.js.map +1 -0
- package/dist/commands/context/sources/syncs/discard.js +5 -0
- package/dist/commands/context/sources/syncs/discard.js.map +1 -0
- package/dist/commands/context/sources/syncs/get.js +5 -0
- package/dist/commands/context/sources/syncs/get.js.map +1 -0
- package/dist/commands/context/sources/syncs/list.js +5 -0
- package/dist/commands/context/sources/syncs/list.js.map +1 -0
- package/dist/commands/context/sources/upload.js +63 -0
- package/dist/commands/context/sources/upload.js.map +1 -0
- package/dist/commands/context/sync.js +5 -0
- package/dist/commands/context/sync.js.map +1 -0
- package/dist/commands/context/update.js +3 -136
- package/dist/commands/context/update.js.map +1 -1
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +47 -26
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
- package/dist/generated/apiRoutes.js +28 -0
- package/dist/generated/apiRoutes.js.map +1 -1
- package/dist/generated/contextOperations.js +1116 -0
- package/dist/generated/contextOperations.js.map +1 -0
- package/dist/hooks/commandNotFound/topicAliases.js +8 -2
- package/dist/hooks/commandNotFound/topicAliases.js.map +1 -1
- package/dist/prompts/promptForText.js +12 -0
- package/dist/prompts/promptForText.js.map +1 -0
- package/dist/services/context.js +276 -202
- package/dist/services/context.js.map +1 -1
- package/dist/util/sharedFlags.js.map +1 -1
- package/dist/util/telemetry/cliCommandIdentity.js +16 -18
- package/dist/util/telemetry/cliCommandIdentity.js.map +1 -1
- package/oclif.config.js +1 -1
- package/oclif.manifest.json +4854 -2834
- package/package.json +20 -19
- package/templates/app-quickstart/.claude/skills/sanity-app-sdk/SKILL.md +49 -0
- package/templates/app-quickstart/AGENTS.md +49 -0
- package/templates/app-sanity-ui/.claude/skills/sanity-app-sdk/SKILL.md +49 -0
- package/templates/app-sanity-ui/AGENTS.md +49 -0
- package/templates/shared/dashboard/app-quickstart/.claude/skills/sanity-app-sdk/SKILL.md +49 -0
- package/templates/shared/dashboard/app-quickstart/AGENTS.md +49 -0
- package/templates/shared/dashboard/app-sanity-ui/.claude/skills/sanity-app-sdk/SKILL.md +49 -0
- package/templates/shared/dashboard/app-sanity-ui/AGENTS.md +49 -0
- package/dist/commands/context/imports/create.js +0 -270
- package/dist/commands/context/imports/create.js.map +0 -1
- package/dist/commands/context/imports/delete.js +0 -73
- package/dist/commands/context/imports/delete.js.map +0 -1
- package/dist/commands/context/imports/download.js +0 -60
- package/dist/commands/context/imports/download.js.map +0 -1
- package/dist/commands/context/imports/get.js +0 -88
- package/dist/commands/context/imports/get.js.map +0 -1
- package/dist/commands/context/imports/list.js +0 -100
- package/dist/commands/context/imports/list.js.map +0 -1
- package/dist/commands/context/refresh.js +0 -46
- package/dist/commands/context/refresh.js.map +0 -1
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
const PATH_PREFIX = '/{apiVersion}/context';
|
|
2
|
+
const METHODS = [
|
|
3
|
+
'get',
|
|
4
|
+
'put',
|
|
5
|
+
'post',
|
|
6
|
+
'patch',
|
|
7
|
+
'delete'
|
|
8
|
+
];
|
|
9
|
+
function isSchema(value) {
|
|
10
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
function isOperation(value) {
|
|
13
|
+
return isSchema(value) && typeof value.operationId === 'string';
|
|
14
|
+
}
|
|
15
|
+
function schemas(value) {
|
|
16
|
+
return Array.isArray(value) ? value.filter((item)=>isSchema(item)) : [];
|
|
17
|
+
}
|
|
18
|
+
function strings(value) {
|
|
19
|
+
return Array.isArray(value) ? value.filter((item)=>typeof item === 'string') : [];
|
|
20
|
+
}
|
|
21
|
+
function text(value) {
|
|
22
|
+
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
|
|
23
|
+
}
|
|
24
|
+
function resolve(spec, schema) {
|
|
25
|
+
const ref = schema.$ref;
|
|
26
|
+
if (typeof ref !== 'string') return schema;
|
|
27
|
+
const name = ref.replace('#/components/schemas/', '');
|
|
28
|
+
const target = spec.components?.schemas?.[name];
|
|
29
|
+
if (!target) throw new Error(`Unresolved $ref ${ref}`);
|
|
30
|
+
return resolve(spec, target);
|
|
31
|
+
}
|
|
32
|
+
/** A schema without the `null` branch of a nullable union, and whether it had one */ function unwrapNullable(spec, schema) {
|
|
33
|
+
const resolved = resolve(spec, schema);
|
|
34
|
+
const branches = schemas(resolved.anyOf ?? resolved.oneOf).map((branch)=>resolve(spec, branch));
|
|
35
|
+
const isNull = (branch)=>branch.type === 'null';
|
|
36
|
+
if (branches.some((branch)=>isNull(branch))) {
|
|
37
|
+
const rest = branches.filter((branch)=>!isNull(branch));
|
|
38
|
+
return {
|
|
39
|
+
nullable: true,
|
|
40
|
+
schema: rest.length === 1 ? rest[0] : {
|
|
41
|
+
...resolved,
|
|
42
|
+
anyOf: rest
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
if (Array.isArray(resolved.type) && resolved.type.includes('null')) {
|
|
47
|
+
const type = resolved.type.filter((item)=>item !== 'null');
|
|
48
|
+
return {
|
|
49
|
+
nullable: true,
|
|
50
|
+
schema: {
|
|
51
|
+
...resolved,
|
|
52
|
+
type: type.length === 1 ? type[0] : type
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
const options = Array.isArray(resolved.enum) ? resolved.enum : [];
|
|
57
|
+
const withoutNull = options.includes(null) ? {
|
|
58
|
+
...resolved,
|
|
59
|
+
enum: options.filter((value)=>value !== null)
|
|
60
|
+
} : resolved;
|
|
61
|
+
// OpenAPI 3.0 marks a nullable schema with `nullable: true`
|
|
62
|
+
return {
|
|
63
|
+
nullable: options.includes(null) || resolved.nullable === true,
|
|
64
|
+
schema: withoutNull
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function fieldType(schema) {
|
|
68
|
+
const options = strings(schema.enum);
|
|
69
|
+
if (typeof schema.const === 'string') return {
|
|
70
|
+
options: [
|
|
71
|
+
schema.const
|
|
72
|
+
],
|
|
73
|
+
type: 'string'
|
|
74
|
+
};
|
|
75
|
+
switch(schema.type){
|
|
76
|
+
case 'array':
|
|
77
|
+
{
|
|
78
|
+
const items = isSchema(schema.items) ? schema.items : {};
|
|
79
|
+
return items.type === 'string' ? {
|
|
80
|
+
type: 'string[]'
|
|
81
|
+
} : {
|
|
82
|
+
type: 'json'
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
case 'boolean':
|
|
86
|
+
{
|
|
87
|
+
return {
|
|
88
|
+
type: 'boolean'
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
case 'integer':
|
|
92
|
+
{
|
|
93
|
+
return {
|
|
94
|
+
type: 'integer'
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
case 'number':
|
|
98
|
+
{
|
|
99
|
+
return {
|
|
100
|
+
type: 'number'
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
case 'string':
|
|
104
|
+
{
|
|
105
|
+
return options.length > 0 ? {
|
|
106
|
+
options,
|
|
107
|
+
type: 'string'
|
|
108
|
+
} : {
|
|
109
|
+
type: 'string'
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
default:
|
|
113
|
+
{
|
|
114
|
+
return {
|
|
115
|
+
type: 'json'
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function field(spec, location, name, rawSchema, extra) {
|
|
121
|
+
const { nullable, schema } = unwrapNullable(spec, rawSchema);
|
|
122
|
+
const { options, type } = fieldType(schema);
|
|
123
|
+
// Query booleans travel as the strings `true` and `false`
|
|
124
|
+
const isQueryBoolean = location === 'query' && options?.join(',') === 'true,false';
|
|
125
|
+
return {
|
|
126
|
+
in: location,
|
|
127
|
+
name,
|
|
128
|
+
...isQueryBoolean ? {
|
|
129
|
+
type: 'boolean'
|
|
130
|
+
} : {
|
|
131
|
+
type,
|
|
132
|
+
...options && {
|
|
133
|
+
options
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
...nullable && {
|
|
137
|
+
nullable
|
|
138
|
+
},
|
|
139
|
+
...extra,
|
|
140
|
+
...text(rawSchema.description ?? schema.description) && {
|
|
141
|
+
description: text(rawSchema.description ?? schema.description)
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** The fields of an object body, with nested objects' fields flattened under their parent */ function objectFields(spec, object) {
|
|
146
|
+
const required = new Set(strings(object.required));
|
|
147
|
+
const properties = isSchema(object.properties) ? object.properties : {};
|
|
148
|
+
return Object.entries(properties).flatMap(([name, raw])=>{
|
|
149
|
+
if (!isSchema(raw) || raw.deprecated === true) return [];
|
|
150
|
+
const { schema } = unwrapNullable(spec, raw);
|
|
151
|
+
if (schema.type === 'object' && isSchema(schema.properties)) {
|
|
152
|
+
// A nested field is never required on its own, and keeps its full path of parents
|
|
153
|
+
return objectFields(spec, schema).map(({ required: _required, ...child })=>({
|
|
154
|
+
...child,
|
|
155
|
+
parent: child.parent ? `${name}.${child.parent}` : name
|
|
156
|
+
}));
|
|
157
|
+
}
|
|
158
|
+
return [
|
|
159
|
+
field(spec, 'body', name, raw, required.has(name) ? {
|
|
160
|
+
required: true
|
|
161
|
+
} : {})
|
|
162
|
+
];
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/** Variants of a `oneOf` body merged into one field list, each field marked with its variants */ function bodyFields(spec, rawBody) {
|
|
166
|
+
const body = resolve(spec, rawBody);
|
|
167
|
+
const variants = schemas(body.oneOf ?? body.anyOf).map((variant)=>resolve(spec, variant));
|
|
168
|
+
if (variants.length === 0) return objectFields(spec, body);
|
|
169
|
+
const named = variants.map((variant)=>{
|
|
170
|
+
const properties = isSchema(variant.properties) ? variant.properties : {};
|
|
171
|
+
const discriminator = isSchema(properties.type) ? fieldType(properties.type).options : undefined;
|
|
172
|
+
return {
|
|
173
|
+
fields: objectFields(spec, variant),
|
|
174
|
+
name: discriminator?.[0] ?? ''
|
|
175
|
+
};
|
|
176
|
+
});
|
|
177
|
+
const merged = new Map();
|
|
178
|
+
for (const { fields, name } of named){
|
|
179
|
+
for (const item of fields){
|
|
180
|
+
const key = `${item.parent ?? ''}.${item.name}`;
|
|
181
|
+
const existing = merged.get(key);
|
|
182
|
+
if (!existing) {
|
|
183
|
+
merged.set(key, {
|
|
184
|
+
...item,
|
|
185
|
+
variants: [
|
|
186
|
+
name
|
|
187
|
+
]
|
|
188
|
+
});
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const options = [
|
|
192
|
+
...new Set([
|
|
193
|
+
...existing.options ?? [],
|
|
194
|
+
...item.options ?? []
|
|
195
|
+
])
|
|
196
|
+
];
|
|
197
|
+
merged.set(key, {
|
|
198
|
+
...existing,
|
|
199
|
+
...options.length > 0 && {
|
|
200
|
+
options
|
|
201
|
+
},
|
|
202
|
+
required: Boolean(existing.required && item.required),
|
|
203
|
+
variants: [
|
|
204
|
+
...existing.variants,
|
|
205
|
+
name
|
|
206
|
+
]
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return [
|
|
211
|
+
...merged.values()
|
|
212
|
+
].map(({ variants: fieldVariants, ...item })=>{
|
|
213
|
+
const inEvery = fieldVariants.length === named.length;
|
|
214
|
+
return {
|
|
215
|
+
...item,
|
|
216
|
+
required: inEvery && Boolean(item.required),
|
|
217
|
+
...!inEvery && {
|
|
218
|
+
variants: fieldVariants
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}).map(({ required, ...item })=>required ? {
|
|
222
|
+
...item,
|
|
223
|
+
required
|
|
224
|
+
} : item);
|
|
225
|
+
}
|
|
226
|
+
function successSchemas(spec, operation) {
|
|
227
|
+
return Object.entries(operation.responses ?? {}).filter(([status])=>status.startsWith('2') && status !== '204').flatMap(([, response])=>{
|
|
228
|
+
const schema = response.content?.['application/json']?.schema;
|
|
229
|
+
return schema ? [
|
|
230
|
+
resolve(spec, schema)
|
|
231
|
+
] : [];
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
function hasProperty(schema, name) {
|
|
235
|
+
return isSchema(schema.properties) && name in schema.properties;
|
|
236
|
+
}
|
|
237
|
+
/** The most items a paginated command asks for in one request, whatever the route allows */ const MAX_PAGE_SIZE = 200;
|
|
238
|
+
/** Distill one operation of the spec */ function distillOperation(spec, path, method, pathParameters, operation) {
|
|
239
|
+
const parameters = [
|
|
240
|
+
...pathParameters,
|
|
241
|
+
...operation.parameters ?? []
|
|
242
|
+
];
|
|
243
|
+
const pathParams = [
|
|
244
|
+
...path.matchAll(/\{([^}]+)\}/g)
|
|
245
|
+
].map((match)=>match[1]).filter((name)=>name !== 'apiVersion').map((name)=>{
|
|
246
|
+
const description = text(parameters.find((p)=>p.in === 'path' && p.name === name)?.description);
|
|
247
|
+
return {
|
|
248
|
+
name,
|
|
249
|
+
...description && {
|
|
250
|
+
description
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
});
|
|
254
|
+
// A deprecated parameter only works on the older API versions the CLI pins, so no flag offers it
|
|
255
|
+
const queryFields = parameters.filter((parameter)=>parameter.in === 'query' && !parameter.deprecated).map((parameter)=>field(spec, 'query', parameter.name, parameter.schema ?? {}, {
|
|
256
|
+
...parameter.required && {
|
|
257
|
+
required: true
|
|
258
|
+
},
|
|
259
|
+
...text(parameter.description) && {
|
|
260
|
+
description: text(parameter.description)
|
|
261
|
+
}
|
|
262
|
+
}));
|
|
263
|
+
const bodySchema = operation.requestBody?.content?.['application/json']?.schema;
|
|
264
|
+
const responses = successSchemas(spec, operation);
|
|
265
|
+
const paginated = queryFields.some((item)=>item.name === 'cursor') && responses.some((schema)=>hasProperty(schema, 'data') && hasProperty(schema, 'nextCursor'));
|
|
266
|
+
const limit = parameters.find((parameter)=>parameter.in === 'query' && parameter.name === 'limit');
|
|
267
|
+
const maximum = limit && resolve(spec, limit.schema ?? {}).maximum;
|
|
268
|
+
const statuses = Object.keys(operation.responses ?? {}).filter((status)=>status.startsWith('2'));
|
|
269
|
+
return {
|
|
270
|
+
body: bodySchema ? operation.requestBody?.required ? 'required' : 'optional' : 'none',
|
|
271
|
+
description: text(operation.description) ?? '',
|
|
272
|
+
fields: [
|
|
273
|
+
...queryFields,
|
|
274
|
+
...bodySchema ? bodyFields(spec, bodySchema) : []
|
|
275
|
+
],
|
|
276
|
+
noContent: statuses.length > 0 && statuses.every((status)=>status === '204'),
|
|
277
|
+
paginated,
|
|
278
|
+
...paginated && limit && {
|
|
279
|
+
pageSize: Math.min(MAX_PAGE_SIZE, typeof maximum === 'number' ? maximum : MAX_PAGE_SIZE)
|
|
280
|
+
},
|
|
281
|
+
pathParams,
|
|
282
|
+
// The route type is checked where the generated module is compiled
|
|
283
|
+
route: `${method.toUpperCase()} ${path.slice(PATH_PREFIX.length)}`,
|
|
284
|
+
startsJob: responses.some((schema)=>hasProperty(schema, 'jobId')),
|
|
285
|
+
summary: text(operation.summary) ?? ''
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/** Names the commands give flags of their own */ const RESERVED_FLAGS = new Set([
|
|
289
|
+
'json',
|
|
290
|
+
'organization',
|
|
291
|
+
'watch',
|
|
292
|
+
'yes'
|
|
293
|
+
]);
|
|
294
|
+
/**
|
|
295
|
+
* Each field becomes a flag named after it, nested fields included, so two
|
|
296
|
+
* fields with one name (under different parents) or a field named like a
|
|
297
|
+
* command's own flag would collide. Generation fails instead.
|
|
298
|
+
*/ function assertDistinctFlags(operationId, operation) {
|
|
299
|
+
const seen = new Set();
|
|
300
|
+
for (const { name } of operation.fields){
|
|
301
|
+
if (name === 'organizationId') continue;
|
|
302
|
+
if (seen.has(name) || RESERVED_FLAGS.has(name)) {
|
|
303
|
+
throw new Error(`Field "${name}" of ${operationId} would collide with another flag`);
|
|
304
|
+
}
|
|
305
|
+
seen.add(name);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* Distill the named operations of the Context API spec into what a command
|
|
310
|
+
* needs: the route, the summary and description, the path parameters, and the
|
|
311
|
+
* query and body fields with their types, enums and descriptions.
|
|
312
|
+
*/ export function distillContextOperations(spec, operationIds) {
|
|
313
|
+
const found = new Map();
|
|
314
|
+
for (const [path, item] of Object.entries(spec.paths)){
|
|
315
|
+
if (!path.startsWith(PATH_PREFIX)) continue;
|
|
316
|
+
const pathParameters = Array.isArray(item.parameters) ? item.parameters : [];
|
|
317
|
+
for (const method of METHODS){
|
|
318
|
+
const operation = item[method];
|
|
319
|
+
if (!isOperation(operation) || !operation.operationId) continue;
|
|
320
|
+
if (!operationIds.includes(operation.operationId)) continue;
|
|
321
|
+
found.set(operation.operationId, distillOperation(spec, path, method, pathParameters, operation));
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
for (const [operationId, operation] of found)assertDistinctFlags(operationId, operation);
|
|
325
|
+
const missing = operationIds.filter((id)=>!found.has(id));
|
|
326
|
+
if (missing.length > 0) {
|
|
327
|
+
throw new Error(`Operations missing from the Context API spec: ${missing.join(', ')}`);
|
|
328
|
+
}
|
|
329
|
+
return Object.fromEntries(operationIds.map((id)=>[
|
|
330
|
+
id,
|
|
331
|
+
found.get(id)
|
|
332
|
+
]));
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
//# sourceMappingURL=distillContextOperations.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/distillContextOperations.ts"],"sourcesContent":["import {\n type ContextOperation,\n type OperationField,\n type OperationFieldType,\n} from './operationTypes.js'\n\ntype Schema = Record<string, unknown>\n\ninterface SpecParameter {\n in: string\n name: string\n\n deprecated?: boolean\n description?: string\n required?: boolean\n schema?: Schema\n}\n\ninterface SpecOperation {\n description?: string\n operationId?: string\n parameters?: SpecParameter[]\n requestBody?: {content?: Record<string, {schema?: Schema}>; required?: boolean}\n responses?: Record<string, {content?: Record<string, {schema?: Schema}>}>\n summary?: string\n}\n\n/** The parts of an OpenAPI 3 document the distiller reads */\nexport interface ContextOpenApiDocument {\n paths: Record<string, Record<string, unknown>>\n\n components?: {schemas?: Record<string, Schema>}\n}\n\nconst PATH_PREFIX = '/{apiVersion}/context'\nconst METHODS = ['get', 'put', 'post', 'patch', 'delete']\n\nfunction isSchema(value: unknown): value is Schema {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isOperation(value: unknown): value is SpecOperation {\n return isSchema(value) && typeof value.operationId === 'string'\n}\n\nfunction schemas(value: unknown): Schema[] {\n return Array.isArray(value) ? value.filter((item) => isSchema(item)) : []\n}\n\nfunction strings(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : []\n}\n\nfunction text(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined\n}\n\nfunction resolve(spec: ContextOpenApiDocument, schema: Schema): Schema {\n const ref = schema.$ref\n if (typeof ref !== 'string') return schema\n const name = ref.replace('#/components/schemas/', '')\n const target = spec.components?.schemas?.[name]\n if (!target) throw new Error(`Unresolved $ref ${ref}`)\n return resolve(spec, target)\n}\n\n/** A schema without the `null` branch of a nullable union, and whether it had one */\nfunction unwrapNullable(\n spec: ContextOpenApiDocument,\n schema: Schema,\n): {nullable: boolean; schema: Schema} {\n const resolved = resolve(spec, schema)\n const branches = schemas(resolved.anyOf ?? resolved.oneOf).map((branch) => resolve(spec, branch))\n const isNull = (branch: Schema) => branch.type === 'null'\n if (branches.some((branch) => isNull(branch))) {\n const rest = branches.filter((branch) => !isNull(branch))\n return {nullable: true, schema: rest.length === 1 ? rest[0] : {...resolved, anyOf: rest}}\n }\n if (Array.isArray(resolved.type) && resolved.type.includes('null')) {\n const type = resolved.type.filter((item) => item !== 'null')\n return {nullable: true, schema: {...resolved, type: type.length === 1 ? type[0] : type}}\n }\n const options = Array.isArray(resolved.enum) ? resolved.enum : []\n const withoutNull = options.includes(null)\n ? {...resolved, enum: options.filter((value) => value !== null)}\n : resolved\n // OpenAPI 3.0 marks a nullable schema with `nullable: true`\n return {nullable: options.includes(null) || resolved.nullable === true, schema: withoutNull}\n}\n\nfunction fieldType(schema: Schema): {options?: string[]; type: OperationFieldType} {\n const options = strings(schema.enum)\n if (typeof schema.const === 'string') return {options: [schema.const], type: 'string'}\n switch (schema.type) {\n case 'array': {\n const items = isSchema(schema.items) ? schema.items : {}\n return items.type === 'string' ? {type: 'string[]'} : {type: 'json'}\n }\n case 'boolean': {\n return {type: 'boolean'}\n }\n case 'integer': {\n return {type: 'integer'}\n }\n case 'number': {\n return {type: 'number'}\n }\n case 'string': {\n return options.length > 0 ? {options, type: 'string'} : {type: 'string'}\n }\n default: {\n return {type: 'json'}\n }\n }\n}\n\nfunction field(\n spec: ContextOpenApiDocument,\n location: OperationField['in'],\n name: string,\n rawSchema: Schema,\n extra: Partial<OperationField>,\n): OperationField {\n const {nullable, schema} = unwrapNullable(spec, rawSchema)\n const {options, type} = fieldType(schema)\n // Query booleans travel as the strings `true` and `false`\n const isQueryBoolean = location === 'query' && options?.join(',') === 'true,false'\n return {\n in: location,\n name,\n ...(isQueryBoolean ? {type: 'boolean'} : {type, ...(options && {options})}),\n ...(nullable && {nullable}),\n ...extra,\n ...(text(rawSchema.description ?? schema.description) && {\n description: text(rawSchema.description ?? schema.description),\n }),\n }\n}\n\n/** The fields of an object body, with nested objects' fields flattened under their parent */\nfunction objectFields(spec: ContextOpenApiDocument, object: Schema): OperationField[] {\n const required = new Set(strings(object.required))\n const properties = isSchema(object.properties) ? object.properties : {}\n return Object.entries(properties).flatMap(([name, raw]) => {\n if (!isSchema(raw) || raw.deprecated === true) return []\n const {schema} = unwrapNullable(spec, raw)\n if (schema.type === 'object' && isSchema(schema.properties)) {\n // A nested field is never required on its own, and keeps its full path of parents\n return objectFields(spec, schema).map(({required: _required, ...child}) => ({\n ...child,\n parent: child.parent ? `${name}.${child.parent}` : name,\n }))\n }\n return [field(spec, 'body', name, raw, required.has(name) ? {required: true} : {})]\n })\n}\n\n/** Variants of a `oneOf` body merged into one field list, each field marked with its variants */\nfunction bodyFields(spec: ContextOpenApiDocument, rawBody: Schema): OperationField[] {\n const body = resolve(spec, rawBody)\n const variants = schemas(body.oneOf ?? body.anyOf).map((variant) => resolve(spec, variant))\n if (variants.length === 0) return objectFields(spec, body)\n\n const named = variants.map((variant) => {\n const properties = isSchema(variant.properties) ? variant.properties : {}\n const discriminator = isSchema(properties.type) ? fieldType(properties.type).options : undefined\n return {fields: objectFields(spec, variant), name: discriminator?.[0] ?? ''}\n })\n const merged = new Map<string, OperationField & {variants: string[]}>()\n for (const {fields, name} of named) {\n for (const item of fields) {\n const key = `${item.parent ?? ''}.${item.name}`\n const existing = merged.get(key)\n if (!existing) {\n merged.set(key, {...item, variants: [name]})\n continue\n }\n const options = [...new Set([...(existing.options ?? []), ...(item.options ?? [])])]\n merged.set(key, {\n ...existing,\n ...(options.length > 0 && {options}),\n required: Boolean(existing.required && item.required),\n variants: [...existing.variants, name],\n })\n }\n }\n return [...merged.values()]\n .map(({variants: fieldVariants, ...item}) => {\n const inEvery = fieldVariants.length === named.length\n return {\n ...item,\n required: inEvery && Boolean(item.required),\n ...(!inEvery && {variants: fieldVariants}),\n }\n })\n .map(({required, ...item}) => (required ? {...item, required} : item))\n}\n\nfunction successSchemas(spec: ContextOpenApiDocument, operation: SpecOperation): Schema[] {\n return Object.entries(operation.responses ?? {})\n .filter(([status]) => status.startsWith('2') && status !== '204')\n .flatMap(([, response]) => {\n const schema = response.content?.['application/json']?.schema\n return schema ? [resolve(spec, schema)] : []\n })\n}\n\nfunction hasProperty(schema: Schema, name: string): boolean {\n return isSchema(schema.properties) && name in schema.properties\n}\n\n/** The most items a paginated command asks for in one request, whatever the route allows */\nconst MAX_PAGE_SIZE = 200\n\n/** Distill one operation of the spec */\nfunction distillOperation(\n spec: ContextOpenApiDocument,\n path: string,\n method: string,\n pathParameters: SpecParameter[],\n operation: SpecOperation,\n): ContextOperation {\n const parameters = [...pathParameters, ...(operation.parameters ?? [])]\n const pathParams = [...path.matchAll(/\\{([^}]+)\\}/g)]\n .map((match) => match[1])\n .filter((name) => name !== 'apiVersion')\n .map((name) => {\n const description = text(\n parameters.find((p) => p.in === 'path' && p.name === name)?.description,\n )\n return {name, ...(description && {description})}\n })\n // A deprecated parameter only works on the older API versions the CLI pins, so no flag offers it\n const queryFields = parameters\n .filter((parameter) => parameter.in === 'query' && !parameter.deprecated)\n .map((parameter) =>\n field(spec, 'query', parameter.name, parameter.schema ?? {}, {\n ...(parameter.required && {required: true}),\n ...(text(parameter.description) && {description: text(parameter.description)}),\n }),\n )\n const bodySchema = operation.requestBody?.content?.['application/json']?.schema\n const responses = successSchemas(spec, operation)\n const paginated =\n queryFields.some((item) => item.name === 'cursor') &&\n responses.some((schema) => hasProperty(schema, 'data') && hasProperty(schema, 'nextCursor'))\n const limit = parameters.find(\n (parameter) => parameter.in === 'query' && parameter.name === 'limit',\n )\n const maximum = limit && resolve(spec, limit.schema ?? {}).maximum\n const statuses = Object.keys(operation.responses ?? {}).filter((status) => status.startsWith('2'))\n\n return {\n body: bodySchema ? (operation.requestBody?.required ? 'required' : 'optional') : 'none',\n description: text(operation.description) ?? '',\n fields: [...queryFields, ...(bodySchema ? bodyFields(spec, bodySchema) : [])],\n noContent: statuses.length > 0 && statuses.every((status) => status === '204'),\n paginated,\n ...(paginated &&\n limit && {\n pageSize: Math.min(MAX_PAGE_SIZE, typeof maximum === 'number' ? maximum : MAX_PAGE_SIZE),\n }),\n pathParams,\n // The route type is checked where the generated module is compiled\n route: `${method.toUpperCase()} ${path.slice(PATH_PREFIX.length)}` as ContextOperation['route'],\n startsJob: responses.some((schema) => hasProperty(schema, 'jobId')),\n summary: text(operation.summary) ?? '',\n }\n}\n\n/** Names the commands give flags of their own */\nconst RESERVED_FLAGS = new Set(['json', 'organization', 'watch', 'yes'])\n\n/**\n * Each field becomes a flag named after it, nested fields included, so two\n * fields with one name (under different parents) or a field named like a\n * command's own flag would collide. Generation fails instead.\n */\nfunction assertDistinctFlags(operationId: string, operation: ContextOperation): void {\n const seen = new Set<string>()\n for (const {name} of operation.fields) {\n if (name === 'organizationId') continue\n if (seen.has(name) || RESERVED_FLAGS.has(name)) {\n throw new Error(`Field \"${name}\" of ${operationId} would collide with another flag`)\n }\n seen.add(name)\n }\n}\n\n/**\n * Distill the named operations of the Context API spec into what a command\n * needs: the route, the summary and description, the path parameters, and the\n * query and body fields with their types, enums and descriptions.\n */\nexport function distillContextOperations(\n spec: ContextOpenApiDocument,\n operationIds: readonly string[],\n): Record<string, ContextOperation> {\n const found = new Map<string, ContextOperation>()\n for (const [path, item] of Object.entries(spec.paths)) {\n if (!path.startsWith(PATH_PREFIX)) continue\n const pathParameters = Array.isArray(item.parameters) ? item.parameters : []\n for (const method of METHODS) {\n const operation = item[method]\n if (!isOperation(operation) || !operation.operationId) continue\n if (!operationIds.includes(operation.operationId)) continue\n found.set(\n operation.operationId,\n distillOperation(spec, path, method, pathParameters, operation),\n )\n }\n }\n\n for (const [operationId, operation] of found) assertDistinctFlags(operationId, operation)\n\n const missing = operationIds.filter((id) => !found.has(id))\n if (missing.length > 0) {\n throw new Error(`Operations missing from the Context API spec: ${missing.join(', ')}`)\n }\n return Object.fromEntries(operationIds.map((id) => [id, found.get(id)!]))\n}\n"],"names":["PATH_PREFIX","METHODS","isSchema","value","Array","isArray","isOperation","operationId","schemas","filter","item","strings","text","trim","undefined","resolve","spec","schema","ref","$ref","name","replace","target","components","Error","unwrapNullable","resolved","branches","anyOf","oneOf","map","branch","isNull","type","some","rest","nullable","length","includes","options","enum","withoutNull","fieldType","const","items","field","location","rawSchema","extra","isQueryBoolean","join","in","description","objectFields","object","required","Set","properties","Object","entries","flatMap","raw","deprecated","_required","child","parent","has","bodyFields","rawBody","body","variants","variant","named","discriminator","fields","merged","Map","key","existing","get","set","Boolean","values","fieldVariants","inEvery","successSchemas","operation","responses","status","startsWith","response","content","hasProperty","MAX_PAGE_SIZE","distillOperation","path","method","pathParameters","parameters","pathParams","matchAll","match","find","p","queryFields","parameter","bodySchema","requestBody","paginated","limit","maximum","statuses","keys","noContent","every","pageSize","Math","min","route","toUpperCase","slice","startsJob","summary","RESERVED_FLAGS","assertDistinctFlags","seen","add","distillContextOperations","operationIds","found","paths","missing","id","fromEntries"],"mappings":"AAkCA,MAAMA,cAAc;AACpB,MAAMC,UAAU;IAAC;IAAO;IAAO;IAAQ;IAAS;CAAS;AAEzD,SAASC,SAASC,KAAc;IAC9B,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AACvE;AAEA,SAASG,YAAYH,KAAc;IACjC,OAAOD,SAASC,UAAU,OAAOA,MAAMI,WAAW,KAAK;AACzD;AAEA,SAASC,QAAQL,KAAc;IAC7B,OAAOC,MAAMC,OAAO,CAACF,SAASA,MAAMM,MAAM,CAAC,CAACC,OAASR,SAASQ,SAAS,EAAE;AAC3E;AAEA,SAASC,QAAQR,KAAc;IAC7B,OAAOC,MAAMC,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ACA;YAAIH,MAAMlD,GAAG,CAACqD;SAAK;AACzE"}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { Args } from '@oclif/core';
|
|
2
|
+
import { CLIError } from '@oclif/core/errors';
|
|
3
|
+
import { exitCodes } from '@sanity/cli-core';
|
|
4
|
+
import { getErrorMessage } from '@sanity/cli-core/errors';
|
|
5
|
+
import { getMcpEndpoint } from '../../services/context.js';
|
|
6
|
+
import { getOrganizationFlag } from '../../util/sharedFlags.js';
|
|
7
|
+
import { formatKeyValue } from '../debug/output.js';
|
|
8
|
+
/**
|
|
9
|
+
* The `<name>` argument of commands that act on an existing endpoint
|
|
10
|
+
*/ export const mcpEndpointNameArg = Args.string({
|
|
11
|
+
description: 'MCP endpoint name, as in its URL',
|
|
12
|
+
parse: parseEndpointName,
|
|
13
|
+
required: true
|
|
14
|
+
});
|
|
15
|
+
/**
|
|
16
|
+
* An argument `parse` that trims an endpoint name and rejects an empty one
|
|
17
|
+
*/ export async function parseEndpointName(input) {
|
|
18
|
+
const trimmed = input.trim();
|
|
19
|
+
if (trimmed === '') throw new Error('The MCP endpoint name cannot be empty');
|
|
20
|
+
return trimmed;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Get an endpoint by name or ID, failing the command when the lookup fails or finds nothing
|
|
24
|
+
*/ export async function findMcpEndpoint(organizationId, nameOrId) {
|
|
25
|
+
let endpoint;
|
|
26
|
+
try {
|
|
27
|
+
endpoint = await getMcpEndpoint(organizationId, nameOrId);
|
|
28
|
+
} catch (error) {
|
|
29
|
+
throw new CLIError(`Failed to get MCP endpoint: ${getErrorMessage(error)}`, {
|
|
30
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
if (!endpoint) {
|
|
34
|
+
throw new CLIError(`MCP endpoint "${nameOrId}" not found`, {
|
|
35
|
+
exit: exitCodes.RUNTIME_ERROR
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return endpoint;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The `--organization` flag of commands that act on an existing endpoint
|
|
42
|
+
*/ export const mcpEndpointOrganizationFlag = getOrganizationFlag({
|
|
43
|
+
description: 'Organization the MCP endpoint belongs to',
|
|
44
|
+
semantics: 'override'
|
|
45
|
+
});
|
|
46
|
+
/**
|
|
47
|
+
* A flag `parse` that trims the value and rejects an empty one
|
|
48
|
+
*/ export function parseNonEmpty(flag) {
|
|
49
|
+
return async (input)=>{
|
|
50
|
+
const trimmed = input.trim();
|
|
51
|
+
if (trimmed === '') {
|
|
52
|
+
throw new Error(`\`--${flag}\` cannot be empty if provided`);
|
|
53
|
+
}
|
|
54
|
+
return trimmed;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The API names a dataset source `<projectId>.<datasetName>`; the project comes from
|
|
59
|
+
* `--project` or the CLI configuration.
|
|
60
|
+
*/ export function datasetSourceId(dataset, projectId) {
|
|
61
|
+
if (dataset === undefined) return undefined;
|
|
62
|
+
if (!projectId) {
|
|
63
|
+
throw new CLIError('Pass `--project` with `--dataset`, or run the command in a Sanity project directory.', {
|
|
64
|
+
exit: exitCodes.USAGE_ERROR
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return `${projectId}.${dataset}`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Apply source changes to an endpoint's current sources, or to none when creating one. The dataset
|
|
71
|
+
* keeps its settings until it is switched for another one; `dataset: null`
|
|
72
|
+
* removes it. Sources are rebuilt from their known fields, since the stored
|
|
73
|
+
* configuration may carry more. `notes` names the changes that were already in
|
|
74
|
+
* place, which leave the sources as they were.
|
|
75
|
+
*/ export function editSources(current, changes) {
|
|
76
|
+
const notes = [];
|
|
77
|
+
const knowledgeBaseIds = current.filter((source)=>source.type === 'knowledge-base').map((source)=>source.id);
|
|
78
|
+
for (const id of new Set(changes.addKnowledgeBases)){
|
|
79
|
+
if (knowledgeBaseIds.includes(id)) {
|
|
80
|
+
notes.push(`Knowledge base "${id}" is already a source`);
|
|
81
|
+
} else {
|
|
82
|
+
knowledgeBaseIds.push(id);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
for (const id of new Set(changes.removeKnowledgeBases)){
|
|
86
|
+
if (!knowledgeBaseIds.includes(id)) notes.push(`Knowledge base "${id}" is not a source`);
|
|
87
|
+
}
|
|
88
|
+
const sources = knowledgeBaseIds.filter((id)=>!changes.removeKnowledgeBases.includes(id)).map((id)=>({
|
|
89
|
+
id,
|
|
90
|
+
type: 'knowledge-base'
|
|
91
|
+
}));
|
|
92
|
+
const dataset = findDatasetSource(current);
|
|
93
|
+
if (changes.dataset === null && !dataset) notes.push('The endpoint has no dataset');
|
|
94
|
+
const datasetId = changes.dataset === undefined ? dataset?.id : changes.dataset;
|
|
95
|
+
if (datasetId) {
|
|
96
|
+
const kept = dataset?.id === datasetId ? {
|
|
97
|
+
perspective: dataset.perspective,
|
|
98
|
+
semanticSearch: dataset.semanticSearch,
|
|
99
|
+
workspace: dataset.workspace
|
|
100
|
+
} : {};
|
|
101
|
+
sources.push({
|
|
102
|
+
id: datasetId,
|
|
103
|
+
type: 'dataset',
|
|
104
|
+
...kept,
|
|
105
|
+
...changes.settings
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
notes,
|
|
110
|
+
sources
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function findDatasetSource(sources) {
|
|
114
|
+
return sources.find((source)=>source.type === 'dataset');
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Key-value lines describing an endpoint, for `get`, `create` and `update` output
|
|
118
|
+
*/ export function formatMcpEndpoint(endpoint) {
|
|
119
|
+
const padTo = 15 // "Knowledge bases" and "Semantic search" are the longest keys
|
|
120
|
+
;
|
|
121
|
+
const knowledgeBaseIds = endpoint.sources.filter((source)=>source.type === 'knowledge-base').map((source)=>source.id);
|
|
122
|
+
const dataset = findDatasetSource(endpoint.sources);
|
|
123
|
+
const lines = [
|
|
124
|
+
formatKeyValue('ID', endpoint.id, {
|
|
125
|
+
padTo
|
|
126
|
+
}),
|
|
127
|
+
formatKeyValue('Name', endpoint.name, {
|
|
128
|
+
padTo
|
|
129
|
+
}),
|
|
130
|
+
formatKeyValue('Title', endpoint.title, {
|
|
131
|
+
padTo
|
|
132
|
+
}),
|
|
133
|
+
formatKeyValue('URL', endpoint.url, {
|
|
134
|
+
padTo
|
|
135
|
+
}),
|
|
136
|
+
formatKeyValue('Knowledge bases', knowledgeBaseIds.join(', ') || '-', {
|
|
137
|
+
padTo
|
|
138
|
+
}),
|
|
139
|
+
formatKeyValue('Dataset', dataset?.id ?? '-', {
|
|
140
|
+
padTo
|
|
141
|
+
})
|
|
142
|
+
];
|
|
143
|
+
if (dataset) {
|
|
144
|
+
lines.push(formatKeyValue('Workspace', dataset.workspace ?? '-', {
|
|
145
|
+
padTo
|
|
146
|
+
}), formatKeyValue('Perspective', dataset.perspective ?? '-', {
|
|
147
|
+
padTo
|
|
148
|
+
}), formatKeyValue('Semantic search', formatSemanticSearch(dataset.semanticSearch), {
|
|
149
|
+
padTo
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
lines.push(formatKeyValue('Instructions', endpoint.instructions ?? '-', {
|
|
153
|
+
padTo
|
|
154
|
+
}), formatKeyValue('GROQ filter', endpoint.groqFilter ?? '-', {
|
|
155
|
+
padTo
|
|
156
|
+
}));
|
|
157
|
+
return lines;
|
|
158
|
+
}
|
|
159
|
+
function formatSemanticSearch(semanticSearch) {
|
|
160
|
+
if (semanticSearch === true) return 'on';
|
|
161
|
+
if (semanticSearch === false) return 'off';
|
|
162
|
+
return '-';
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
//# sourceMappingURL=mcpEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/mcpEndpoint.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {CLIError} from '@oclif/core/errors'\nimport {exitCodes} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {type Context} from '@sanity/client'\n\nimport {getMcpEndpoint, type McpEndpoint} from '../../services/context.js'\nimport {getOrganizationFlag} from '../../util/sharedFlags.js'\nimport {formatKeyValue} from '../debug/output.js'\n\ntype McpSource = McpEndpoint['sources'][number]\ntype DatasetSource = Extract<McpSource, {type: 'dataset'}>\ntype McpSourceInput = Context.Body<'POST /organizations/{organizationId}/mcp'>['sources'][number]\nexport type DatasetSettings = Partial<\n Pick<DatasetSource, 'perspective' | 'semanticSearch' | 'workspace'>\n>\n\n/**\n * The `<name>` argument of commands that act on an existing endpoint\n */\nexport const mcpEndpointNameArg = Args.string({\n description: 'MCP endpoint name, as in its URL',\n parse: parseEndpointName,\n required: true,\n})\n\n/**\n * An argument `parse` that trims an endpoint name and rejects an empty one\n */\nexport async function parseEndpointName(input: string): Promise<string> {\n const trimmed = input.trim()\n if (trimmed === '') throw new Error('The MCP endpoint name cannot be empty')\n return trimmed\n}\n\n/**\n * Get an endpoint by name or ID, failing the command when the lookup fails or finds nothing\n */\nexport async function findMcpEndpoint(\n organizationId: string,\n nameOrId: string,\n): Promise<McpEndpoint> {\n let endpoint\n try {\n endpoint = await getMcpEndpoint(organizationId, nameOrId)\n } catch (error) {\n throw new CLIError(`Failed to get MCP endpoint: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n if (!endpoint) {\n throw new CLIError(`MCP endpoint \"${nameOrId}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n return endpoint\n}\n\n/**\n * The `--organization` flag of commands that act on an existing endpoint\n */\nexport const mcpEndpointOrganizationFlag = getOrganizationFlag({\n description: 'Organization the MCP endpoint belongs to',\n semantics: 'override',\n})\n\n/**\n * A flag `parse` that trims the value and rejects an empty one\n */\nexport function parseNonEmpty(flag: string): (input: string) => Promise<string> {\n return async (input) => {\n const trimmed = input.trim()\n if (trimmed === '') {\n throw new Error(`\\`--${flag}\\` cannot be empty if provided`)\n }\n return trimmed\n }\n}\n\n/**\n * The API names a dataset source `<projectId>.<datasetName>`; the project comes from\n * `--project` or the CLI configuration.\n */\nexport function datasetSourceId(\n dataset: string | undefined,\n projectId: string | undefined,\n): string | undefined {\n if (dataset === undefined) return undefined\n if (!projectId) {\n throw new CLIError(\n 'Pass `--project` with `--dataset`, or run the command in a Sanity project directory.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n return `${projectId}.${dataset}`\n}\n\n/**\n * Apply source changes to an endpoint's current sources, or to none when creating one. The dataset\n * keeps its settings until it is switched for another one; `dataset: null`\n * removes it. Sources are rebuilt from their known fields, since the stored\n * configuration may carry more. `notes` names the changes that were already in\n * place, which leave the sources as they were.\n */\nexport function editSources(\n current: McpSource[],\n changes: {\n addKnowledgeBases: string[]\n dataset: string | null | undefined\n removeKnowledgeBases: string[]\n settings: DatasetSettings\n },\n): {notes: string[]; sources: McpSourceInput[]} {\n const notes: string[] = []\n const knowledgeBaseIds = current\n .filter((source) => source.type === 'knowledge-base')\n .map((source) => source.id)\n\n for (const id of new Set(changes.addKnowledgeBases)) {\n if (knowledgeBaseIds.includes(id)) {\n notes.push(`Knowledge base \"${id}\" is already a source`)\n } else {\n knowledgeBaseIds.push(id)\n }\n }\n for (const id of new Set(changes.removeKnowledgeBases)) {\n if (!knowledgeBaseIds.includes(id)) notes.push(`Knowledge base \"${id}\" is not a source`)\n }\n const sources: McpSourceInput[] = knowledgeBaseIds\n .filter((id) => !changes.removeKnowledgeBases.includes(id))\n .map((id) => ({id, type: 'knowledge-base'}))\n\n const dataset = findDatasetSource(current)\n if (changes.dataset === null && !dataset) notes.push('The endpoint has no dataset')\n const datasetId = changes.dataset === undefined ? dataset?.id : changes.dataset\n if (datasetId) {\n const kept =\n dataset?.id === datasetId\n ? {\n perspective: dataset.perspective,\n semanticSearch: dataset.semanticSearch,\n workspace: dataset.workspace,\n }\n : {}\n sources.push({id: datasetId, type: 'dataset', ...kept, ...changes.settings})\n }\n\n return {notes, sources}\n}\n\nfunction findDatasetSource(sources: McpSource[]): DatasetSource | undefined {\n return sources.find((source): source is DatasetSource => source.type === 'dataset')\n}\n\n/**\n * Key-value lines describing an endpoint, for `get`, `create` and `update` output\n */\nexport function formatMcpEndpoint(endpoint: McpEndpoint): string[] {\n const padTo = 15 // \"Knowledge bases\" and \"Semantic search\" are the longest keys\n const knowledgeBaseIds = endpoint.sources\n .filter((source) => source.type === 'knowledge-base')\n .map((source) => source.id)\n const dataset = findDatasetSource(endpoint.sources)\n\n const lines = [\n formatKeyValue('ID', endpoint.id, {padTo}),\n formatKeyValue('Name', endpoint.name, {padTo}),\n formatKeyValue('Title', endpoint.title, {padTo}),\n formatKeyValue('URL', endpoint.url, {padTo}),\n formatKeyValue('Knowledge bases', knowledgeBaseIds.join(', ') || '-', {padTo}),\n formatKeyValue('Dataset', dataset?.id ?? '-', {padTo}),\n ]\n if (dataset) {\n lines.push(\n formatKeyValue('Workspace', dataset.workspace ?? '-', {padTo}),\n formatKeyValue('Perspective', dataset.perspective ?? '-', {padTo}),\n formatKeyValue('Semantic search', formatSemanticSearch(dataset.semanticSearch), {padTo}),\n )\n }\n lines.push(\n formatKeyValue('Instructions', endpoint.instructions ?? '-', {padTo}),\n formatKeyValue('GROQ filter', endpoint.groqFilter ?? '-', {padTo}),\n )\n return lines\n}\n\nfunction formatSemanticSearch(semanticSearch: boolean | null | undefined): string {\n if (semanticSearch === true) return 'on'\n if (semanticSearch === false) return 'off'\n return '-'\n}\n"],"names":["Args","CLIError","exitCodes","getErrorMessage","getMcpEndpoint","getOrganizationFlag","formatKeyValue","mcpEndpointNameArg","string","description","parse","parseEndpointName","required","input","trimmed","trim","Error","findMcpEndpoint","organizationId","nameOrId","endpoint","error","exit","RUNTIME_ERROR","mcpEndpointOrganizationFlag","semantics","parseNonEmpty","flag","datasetSourceId","dataset","projectId","undefined","USAGE_ERROR","editSources","current","changes","notes","knowledgeBaseIds","filter","source","type","map","id","Set","addKnowledgeBases","includes","push","removeKnowledgeBases","sources","findDatasetSource","datasetId","kept","perspective","semanticSearch","workspace","settings","find","formatMcpEndpoint","padTo","lines","name","title","url","join","formatSemanticSearch","instructions","groqFilter"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,eAAe,QAAO,0BAAyB;AAGvD,SAAQC,cAAc,QAAyB,4BAA2B;AAC1E,SAAQC,mBAAmB,QAAO,4BAA2B;AAC7D,SAAQC,cAAc,QAAO,qBAAoB;AASjD;;CAEC,GACD,OAAO,MAAMC,qBAAqBP,KAAKQ,MAAM,CAAC;IAC5CC,aAAa;IACbC,OAAOC;IACPC,UAAU;AACZ,GAAE;AAEF;;CAEC,GACD,OAAO,eAAeD,kBAAkBE,KAAa;IACnD,MAAMC,UAAUD,MAAME,IAAI;IAC1B,IAAID,YAAY,IAAI,MAAM,IAAIE,MAAM;IACpC,OAAOF;AACT;AAEA;;CAEC,GACD,OAAO,eAAeG,gBACpBC,cAAsB,EACtBC,QAAgB;IAEhB,IAAIC;IACJ,IAAI;QACFA,WAAW,MAAMhB,eAAec,gBAAgBC;IAClD,EAAE,OAAOE,OAAO;QACd,MAAM,IAAIpB,SAAS,CAAC,4BAA4B,EAAEE,gBAAgBkB,QAAQ,EAAE;YAC1EC,MAAMpB,UAAUqB,aAAa;QAC/B;IACF;IACA,IAAI,CAACH,UAAU;QACb,MAAM,IAAInB,SAAS,CAAC,cAAc,EAAEkB,SAAS,WAAW,CAAC,EAAE;YAACG,MAAMpB,UAAUqB,aAAa;QAAA;IAC3F;IACA,OAAOH;AACT;AAEA;;CAEC,GACD,OAAO,MAAMI,8BAA8BnB,oBAAoB;IAC7DI,aAAa;IACbgB,WAAW;AACb,GAAE;AAEF;;CAEC,GACD,OAAO,SAASC,cAAcC,IAAY;IACxC,OAAO,OAAO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