@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,226 @@
|
|
|
1
|
+
import { Args, Flags } from '@oclif/core';
|
|
2
|
+
import { getOrganizationFlag } from '../../util/sharedFlags.js';
|
|
3
|
+
const ORGANIZATION = 'organizationId';
|
|
4
|
+
const NULL = 'null';
|
|
5
|
+
/** `includePaths` → `include-paths` */ export function flagName(field) {
|
|
6
|
+
return field.name.replaceAll(/[A-Z]/g, (letter)=>`-${letter.toLowerCase()}`);
|
|
7
|
+
}
|
|
8
|
+
const ACRONYMS = new Set([
|
|
9
|
+
'api',
|
|
10
|
+
'groq',
|
|
11
|
+
'id',
|
|
12
|
+
'ids',
|
|
13
|
+
'mcp',
|
|
14
|
+
'url',
|
|
15
|
+
'uuid'
|
|
16
|
+
]);
|
|
17
|
+
/** `openIssueCount` → `Open issue count`, `sourceId` → `Source ID` */ export function humanize(name) {
|
|
18
|
+
const words = name.replaceAll(/([a-z\d])([A-Z])/g, '$1 $2').replaceAll('_', ' ').toLowerCase().split(' ').map((word)=>ACRONYMS.has(word) ? word.toUpperCase().replace(/S$/, 's') : word).join(' ');
|
|
19
|
+
return `${words[0].toUpperCase()}${words.slice(1)}`;
|
|
20
|
+
}
|
|
21
|
+
/** Whether the command resolves an organization: from `--organization`, the CLI config, or a prompt */ export function needsOrganization(operation) {
|
|
22
|
+
return operation.pathParams.some((param)=>param.name === ORGANIZATION) || operation.fields.some((field)=>field.name === ORGANIZATION);
|
|
23
|
+
}
|
|
24
|
+
/** The fields that become flags: not the organization, a variadic argument, an omitted field or a page cursor. A list's `limit` caps the total its pages add up to */ function flagFields(operation, entry) {
|
|
25
|
+
const omit = new Set(entry.omit);
|
|
26
|
+
return operation.fields.filter((field)=>field.name !== ORGANIZATION && field.name !== entry.variadicArg && !omit.has(field.name) && !(operation.paginated && field.in === 'query' && field.name === 'cursor'));
|
|
27
|
+
}
|
|
28
|
+
function describe(field) {
|
|
29
|
+
const notes = [
|
|
30
|
+
field.variants && `Only for type ${field.variants.join(' or ')}.`,
|
|
31
|
+
field.nullable && 'Pass `null` to clear it.'
|
|
32
|
+
].filter(Boolean);
|
|
33
|
+
return [
|
|
34
|
+
field.description ?? `${humanize(field.name)}.`,
|
|
35
|
+
...notes
|
|
36
|
+
].join(' ');
|
|
37
|
+
}
|
|
38
|
+
/** The `type` of a body with variants, which the variant's own fields can stand in for */ function isDiscriminator(operation, field) {
|
|
39
|
+
return field.in === 'body' && field.name === 'type' && !field.parent && operation.fields.some((other)=>other.variants);
|
|
40
|
+
}
|
|
41
|
+
function fieldFlag(field, inferred) {
|
|
42
|
+
const base = {
|
|
43
|
+
description: inferred ? `${describe(field)} Inferred from the other flags when left out.` : describe(field),
|
|
44
|
+
...field.required && !field.variants && !inferred && {
|
|
45
|
+
required: true
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
switch(field.type){
|
|
49
|
+
case 'boolean':
|
|
50
|
+
{
|
|
51
|
+
return Flags.boolean({
|
|
52
|
+
...base,
|
|
53
|
+
allowNo: true
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
case 'integer':
|
|
57
|
+
{
|
|
58
|
+
return field.nullable ? Flags.string(base) : Flags.integer(base);
|
|
59
|
+
}
|
|
60
|
+
case 'json':
|
|
61
|
+
{
|
|
62
|
+
return Flags.string({
|
|
63
|
+
...base,
|
|
64
|
+
helpValue: '<json>'
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
case 'string[]':
|
|
68
|
+
{
|
|
69
|
+
return Flags.string({
|
|
70
|
+
...base,
|
|
71
|
+
multiple: true
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
default:
|
|
75
|
+
{
|
|
76
|
+
const options = field.options && [
|
|
77
|
+
...field.options,
|
|
78
|
+
...field.nullable ? [
|
|
79
|
+
NULL
|
|
80
|
+
] : []
|
|
81
|
+
];
|
|
82
|
+
return Flags.string({
|
|
83
|
+
...base,
|
|
84
|
+
...options && {
|
|
85
|
+
options
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** A flag's value as the field's wire value: `null` to clear, parsed JSON or numbers */ function wireValue(field, value) {
|
|
92
|
+
if (typeof value !== 'string') return value;
|
|
93
|
+
if (field.nullable && value === NULL) return null;
|
|
94
|
+
if (field.type === 'json') {
|
|
95
|
+
try {
|
|
96
|
+
return JSON.parse(value);
|
|
97
|
+
} catch {
|
|
98
|
+
throw new Error(`\`--${flagName(field)}\` must be JSON`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (field.type === 'integer' || field.type === 'number') {
|
|
102
|
+
const number = Number(value);
|
|
103
|
+
if (value.trim() === '' || Number.isNaN(number)) {
|
|
104
|
+
throw new Error(`\`--${flagName(field)}\` must be a number`);
|
|
105
|
+
}
|
|
106
|
+
return number;
|
|
107
|
+
}
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
/** The flags of an operation's command: one per query or body field */ export function operationFlags(operation, entry) {
|
|
111
|
+
const flags = Object.fromEntries(flagFields(operation, entry).map((field)=>[
|
|
112
|
+
flagName(field),
|
|
113
|
+
fieldFlag(field, isDiscriminator(operation, field))
|
|
114
|
+
]));
|
|
115
|
+
if (needsOrganization(operation)) {
|
|
116
|
+
Object.assign(flags, getOrganizationFlag({
|
|
117
|
+
description: 'Organization ID',
|
|
118
|
+
semantics: 'override'
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
if (entry.watch) {
|
|
122
|
+
flags.watch = Flags.boolean({
|
|
123
|
+
default: false,
|
|
124
|
+
description: entry.watch === 'job' ? 'Wait for the job to finish, exiting non-zero if it fails' : 'Wait for the sync to settle, exiting non-zero unless it completes: when it fails, is cancelled or is held for confirmation'
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
if (operation.route.startsWith('DELETE ')) {
|
|
128
|
+
flags.yes = Flags.boolean({
|
|
129
|
+
char: 'y',
|
|
130
|
+
default: false,
|
|
131
|
+
description: 'Skip confirmation prompt (unattended mode)'
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return flags;
|
|
135
|
+
}
|
|
136
|
+
/** The arguments of an operation's command: its path parameters, then a variadic body field */ export function operationArgs(operation, entry) {
|
|
137
|
+
const args = {};
|
|
138
|
+
for (const param of operation.pathParams){
|
|
139
|
+
if (param.name === ORGANIZATION) continue;
|
|
140
|
+
args[param.name] = Args.string({
|
|
141
|
+
description: param.description ?? humanize(param.name),
|
|
142
|
+
required: true
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
const variadic = operation.fields.find((field)=>field.name === entry.variadicArg);
|
|
146
|
+
if (variadic) {
|
|
147
|
+
args[variadic.name] = Args.string({
|
|
148
|
+
description: describe(variadic),
|
|
149
|
+
multiple: true,
|
|
150
|
+
required: true
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return args;
|
|
154
|
+
}
|
|
155
|
+
/** Option flags whose values can hold free text, URLs or customer data, which telemetry leaves out */ export function redactedFlags(operation, entry) {
|
|
156
|
+
return flagFields(operation, entry).filter((field)=>field.type === 'string' && !field.options || field.type === 'string[]' || field.type === 'json').map((field)=>flagName(field));
|
|
157
|
+
}
|
|
158
|
+
function setNested(target, path, value) {
|
|
159
|
+
const [key, ...rest] = path;
|
|
160
|
+
if (rest.length === 0) {
|
|
161
|
+
target[key] = value;
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const existing = target[key];
|
|
165
|
+
const nested = typeof existing === 'object' && existing !== null ? {
|
|
166
|
+
...existing
|
|
167
|
+
} : {};
|
|
168
|
+
setNested(nested, rest, value);
|
|
169
|
+
target[key] = nested;
|
|
170
|
+
}
|
|
171
|
+
/** The variant of a discriminated body the given fields belong to, when exactly one fits */ function inferVariant(operation, given) {
|
|
172
|
+
const discriminator = operation.fields.find((field)=>isDiscriminator(operation, field));
|
|
173
|
+
if (!discriminator?.options) return undefined;
|
|
174
|
+
const fits = discriminator.options.filter((variant)=>given.every((field)=>!field.variants || field.variants.includes(variant)));
|
|
175
|
+
return fits.length === 1 ? fits[0] : undefined;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Build the request from a command's arguments and flags; throws on a flag
|
|
179
|
+
* value the field can't take. Query booleans
|
|
180
|
+
* travel as `true` or `false`; nested fields go back under their parent; a
|
|
181
|
+
* discriminated body without `--type` gets the one variant its fields fit.
|
|
182
|
+
*/ export function buildOperationRequest(operation, entry, input) {
|
|
183
|
+
const { args, flags, organizationId } = input;
|
|
184
|
+
const params = {};
|
|
185
|
+
for (const param of operation.pathParams){
|
|
186
|
+
const value = param.name === ORGANIZATION ? organizationId : args[param.name];
|
|
187
|
+
if (typeof value === 'string') params[param.name] = value;
|
|
188
|
+
}
|
|
189
|
+
const query = {};
|
|
190
|
+
const body = {};
|
|
191
|
+
const given = [];
|
|
192
|
+
for (const field of operation.fields){
|
|
193
|
+
let value;
|
|
194
|
+
if (field.name === ORGANIZATION) value = organizationId;
|
|
195
|
+
else if (field.name === entry.variadicArg) value = args[field.name];
|
|
196
|
+
else value = wireValue(field, flags[flagName(field)]);
|
|
197
|
+
if (value === undefined) continue;
|
|
198
|
+
given.push(field);
|
|
199
|
+
if (field.in === 'query') {
|
|
200
|
+
query[field.name] = String(value);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (field.parent) {
|
|
204
|
+
setNested(body, [
|
|
205
|
+
...field.parent.split('.'),
|
|
206
|
+
field.name
|
|
207
|
+
], value);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
body[field.name] = value;
|
|
211
|
+
}
|
|
212
|
+
if (operation.body !== 'none' && body.type === undefined) {
|
|
213
|
+
const variant = inferVariant(operation, given);
|
|
214
|
+
if (variant) body.type = variant;
|
|
215
|
+
}
|
|
216
|
+
const hasBody = operation.body === 'required' || Object.keys(body).length > 0;
|
|
217
|
+
return {
|
|
218
|
+
params,
|
|
219
|
+
query,
|
|
220
|
+
...operation.body !== 'none' && hasBody && {
|
|
221
|
+
body
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
//# sourceMappingURL=operationInput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/operationInput.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {type ArgInput, type FlagInput} from '@oclif/core/interfaces'\n\nimport {getOrganizationFlag} from '../../util/sharedFlags.js'\nimport {type ContextCommandEntry} from './commandTable.js'\nimport {type ContextOperation, type OperationField} from './operationTypes.js'\n\nconst ORGANIZATION = 'organizationId'\nconst NULL = 'null'\n\n/** What a command sends: the path parameters, query and body of `client.context.request` */\nexport interface OperationRequest {\n params: Record<string, string>\n query: Record<string, string>\n\n body?: Record<string, unknown>\n}\n\ntype Values = Readonly<Record<string, unknown>>\n\n/** `includePaths` → `include-paths` */\nexport function flagName(field: Pick<OperationField, 'name'>): string {\n return field.name.replaceAll(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)\n}\n\nconst ACRONYMS = new Set(['api', 'groq', 'id', 'ids', 'mcp', 'url', 'uuid'])\n\n/** `openIssueCount` → `Open issue count`, `sourceId` → `Source ID` */\nexport function humanize(name: string): string {\n const words = name\n .replaceAll(/([a-z\\d])([A-Z])/g, '$1 $2')\n .replaceAll('_', ' ')\n .toLowerCase()\n .split(' ')\n .map((word) => (ACRONYMS.has(word) ? word.toUpperCase().replace(/S$/, 's') : word))\n .join(' ')\n return `${words[0].toUpperCase()}${words.slice(1)}`\n}\n\n/** Whether the command resolves an organization: from `--organization`, the CLI config, or a prompt */\nexport function needsOrganization(operation: ContextOperation): boolean {\n return (\n operation.pathParams.some((param) => param.name === ORGANIZATION) ||\n operation.fields.some((field) => field.name === ORGANIZATION)\n )\n}\n\n/** The fields that become flags: not the organization, a variadic argument, an omitted field or a page cursor. A list's `limit` caps the total its pages add up to */\nfunction flagFields(operation: ContextOperation, entry: ContextCommandEntry): OperationField[] {\n const omit = new Set<string>(entry.omit)\n return operation.fields.filter(\n (field) =>\n field.name !== ORGANIZATION &&\n field.name !== entry.variadicArg &&\n !omit.has(field.name) &&\n !(operation.paginated && field.in === 'query' && field.name === 'cursor'),\n )\n}\n\nfunction describe(field: OperationField): string {\n const notes = [\n field.variants && `Only for type ${field.variants.join(' or ')}.`,\n field.nullable && 'Pass `null` to clear it.',\n ].filter(Boolean)\n return [field.description ?? `${humanize(field.name)}.`, ...notes].join(' ')\n}\n\n/** The `type` of a body with variants, which the variant's own fields can stand in for */\nfunction isDiscriminator(operation: ContextOperation, field: OperationField): boolean {\n return (\n field.in === 'body' &&\n field.name === 'type' &&\n !field.parent &&\n operation.fields.some((other) => other.variants)\n )\n}\n\nfunction fieldFlag(field: OperationField, inferred: boolean) {\n const base = {\n description: inferred\n ? `${describe(field)} Inferred from the other flags when left out.`\n : describe(field),\n ...(field.required && !field.variants && !inferred && {required: true}),\n }\n switch (field.type) {\n case 'boolean': {\n return Flags.boolean({...base, allowNo: true})\n }\n case 'integer': {\n return field.nullable ? Flags.string(base) : Flags.integer(base)\n }\n case 'json': {\n return Flags.string({...base, helpValue: '<json>'})\n }\n case 'string[]': {\n return Flags.string({...base, multiple: true})\n }\n default: {\n const options = field.options && [...field.options, ...(field.nullable ? [NULL] : [])]\n return Flags.string({...base, ...(options && {options})})\n }\n }\n}\n\n/** A flag's value as the field's wire value: `null` to clear, parsed JSON or numbers */\nfunction wireValue(field: OperationField, value: unknown): unknown {\n if (typeof value !== 'string') return value\n if (field.nullable && value === NULL) return null\n if (field.type === 'json') {\n try {\n return JSON.parse(value)\n } catch {\n throw new Error(`\\`--${flagName(field)}\\` must be JSON`)\n }\n }\n if (field.type === 'integer' || field.type === 'number') {\n const number = Number(value)\n if (value.trim() === '' || Number.isNaN(number)) {\n throw new Error(`\\`--${flagName(field)}\\` must be a number`)\n }\n return number\n }\n return value\n}\n\n/** The flags of an operation's command: one per query or body field */\nexport function operationFlags(operation: ContextOperation, entry: ContextCommandEntry): FlagInput {\n const flags: FlagInput = Object.fromEntries(\n flagFields(operation, entry).map((field) => [\n flagName(field),\n fieldFlag(field, isDiscriminator(operation, field)),\n ]),\n )\n if (needsOrganization(operation)) {\n Object.assign(\n flags,\n getOrganizationFlag({description: 'Organization ID', semantics: 'override'}),\n )\n }\n if (entry.watch) {\n flags.watch = Flags.boolean({\n default: false,\n description:\n entry.watch === 'job'\n ? 'Wait for the job to finish, exiting non-zero if it fails'\n : 'Wait for the sync to settle, exiting non-zero unless it completes: when it fails, is cancelled or is held for confirmation',\n })\n }\n if (operation.route.startsWith('DELETE ')) {\n flags.yes = Flags.boolean({\n char: 'y',\n default: false,\n description: 'Skip confirmation prompt (unattended mode)',\n })\n }\n return flags\n}\n\n/** The arguments of an operation's command: its path parameters, then a variadic body field */\nexport function operationArgs(operation: ContextOperation, entry: ContextCommandEntry): ArgInput {\n const args: ArgInput = {}\n for (const param of operation.pathParams) {\n if (param.name === ORGANIZATION) continue\n args[param.name] = Args.string({\n description: param.description ?? humanize(param.name),\n required: true,\n })\n }\n const variadic = operation.fields.find((field) => field.name === entry.variadicArg)\n if (variadic) {\n args[variadic.name] = Args.string({\n description: describe(variadic),\n multiple: true,\n required: true,\n })\n }\n return args\n}\n\n/** Option flags whose values can hold free text, URLs or customer data, which telemetry leaves out */\nexport function redactedFlags(operation: ContextOperation, entry: ContextCommandEntry): string[] {\n return flagFields(operation, entry)\n .filter(\n (field) =>\n (field.type === 'string' && !field.options) ||\n field.type === 'string[]' ||\n field.type === 'json',\n )\n .map((field) => flagName(field))\n}\n\nfunction setNested(target: Record<string, unknown>, path: string[], value: unknown): void {\n const [key, ...rest] = path\n if (rest.length === 0) {\n target[key] = value\n return\n }\n const existing = target[key]\n const nested: Record<string, unknown> =\n typeof existing === 'object' && existing !== null ? {...existing} : {}\n setNested(nested, rest, value)\n target[key] = nested\n}\n\n/** The variant of a discriminated body the given fields belong to, when exactly one fits */\nfunction inferVariant(operation: ContextOperation, given: OperationField[]): string | undefined {\n const discriminator = operation.fields.find((field) => isDiscriminator(operation, field))\n if (!discriminator?.options) return undefined\n const fits = discriminator.options.filter((variant) =>\n given.every((field) => !field.variants || field.variants.includes(variant)),\n )\n return fits.length === 1 ? fits[0] : undefined\n}\n\n/**\n * Build the request from a command's arguments and flags; throws on a flag\n * value the field can't take. Query booleans\n * travel as `true` or `false`; nested fields go back under their parent; a\n * discriminated body without `--type` gets the one variant its fields fit.\n */\nexport function buildOperationRequest(\n operation: ContextOperation,\n entry: ContextCommandEntry,\n input: {args: Values; flags: Values; organizationId?: string},\n): OperationRequest {\n const {args, flags, organizationId} = input\n const params: Record<string, string> = {}\n for (const param of operation.pathParams) {\n const value = param.name === ORGANIZATION ? organizationId : args[param.name]\n if (typeof value === 'string') params[param.name] = value\n }\n\n const query: Record<string, string> = {}\n const body: Record<string, unknown> = {}\n const given: OperationField[] = []\n for (const field of operation.fields) {\n let value: unknown\n if (field.name === ORGANIZATION) value = organizationId\n else if (field.name === entry.variadicArg) value = args[field.name]\n else value = wireValue(field, flags[flagName(field)])\n if (value === undefined) continue\n given.push(field)\n\n if (field.in === 'query') {\n query[field.name] = String(value)\n continue\n }\n if (field.parent) {\n setNested(body, [...field.parent.split('.'), field.name], value)\n continue\n }\n body[field.name] = value\n }\n\n if (operation.body !== 'none' && body.type === undefined) {\n const variant = inferVariant(operation, given)\n if (variant) body.type = variant\n }\n\n const hasBody = operation.body === 'required' || Object.keys(body).length > 0\n return {params, query, ...(operation.body !== 'none' && hasBody && {body})}\n}\n"],"names":["Args","Flags","getOrganizationFlag","ORGANIZATION","NULL","flagName","field","name","replaceAll","letter","toLowerCase","ACRONYMS","Set","humanize","words","split","map","word","has","toUpperCase","replace","join","slice","needsOrganization","operation","pathParams","some","param","fields","flagFields","entry","omit","filter","variadicArg","paginated","in","describe","notes","variants","nullable","Boolean","description","isDiscriminator","parent","other","fieldFlag","inferred","base","required","type","boolean","allowNo","string","integer","helpValue","multiple","options","wireValue","value","JSON","parse","Error","number","Number","trim","isNaN","operationFlags","flags","Object","fromEntries","assign","semantics","watch","default","route","startsWith","yes","char","operationArgs","args","variadic","find","redactedFlags","setNested","target","path","key","rest","length","existing","nested","inferVariant","given","discriminator","undefined","fits","variant","every","includes","buildOperationRequest","input","organizationId","params","query","body","push","String","hasBody","keys"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AAGvC,SAAQC,mBAAmB,QAAO,4BAA2B;AAI7D,MAAMC,eAAe;AACrB,MAAMC,OAAO;AAYb,qCAAqC,GACrC,OAAO,SAASC,SAASC,KAAmC;IAC1D,OAAOA,MAAMC,IAAI,CAACC,UAAU,CAAC,UAAU,CAACC,SAAW,CAAC,CAAC,EAAEA,OAAOC,WAAW,IAAI;AAC/E;AAEA,MAAMC,WAAW,IAAIC,IAAI;IAAC;IAAO;IAAQ;IAAM;IAAO;IAAO;IAAO;CAAO;AAE3E,oEAAoE,GACpE,OAAO,SAASC,SAASN,IAAY;IACnC,MAAMO,QAAQP,KACXC,UAAU,CAAC,qBAAqB,SAChCA,UAAU,CAAC,KAAK,KAChBE,WAAW,GACXK,KAAK,CAAC,KACNC,GAAG,CAAC,CAACC,OAAUN,SAASO,GAAG,CAACD,QAAQA,KAAKE,WAAW,GAAGC,OAAO,CAAC,MAAM,OAAOH,MAC5EI,IAAI,CAAC;IACR,OAAO,GAAGP,KAAK,CAAC,EAAE,CAACK,WAAW,KAAKL,MAAMQ,KAAK,CAAC,IAAI;AACrD;AAEA,qGAAqG,GACrG,OAAO,SAASC,kBAAkBC,SAA2B;IAC3D,OACEA,UAAUC,UAAU,CAACC,IAAI,CAAC,CAACC,QAAUA,MAAMpB,IAAI,KAAKJ,iBACpDqB,UAAUI,MAAM,CAACF,IAAI,CAAC,CAACpB,QAAUA,MAAMC,IAAI,KAAKJ;AAEpD;AAEA,oKAAoK,GACpK,SAAS0B,WAAWL,SAA2B,EAAEM,KAA0B;IACzE,MAAMC,OAAO,IAAInB,IAAYkB,MAAMC,IAAI;IACvC,OAAOP,UAAUI,MAAM,CAACI,MAAM,CAC5B,CAAC1B,QACCA,MAAMC,IAAI,KAAK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-0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/operationTypes.ts"],"sourcesContent":["import {type Context} from '@sanity/client'\n\n/**\n * How a field's flag parses its value. `json` takes a JSON value, for fields\n * the spec types as arrays of objects or free-form objects.\n */\nexport type OperationFieldType = 'boolean' | 'integer' | 'json' | 'number' | 'string' | 'string[]'\n\nexport interface OperationField {\n readonly in: 'body' | 'query'\n /** The wire name, such as `includePaths` */\n readonly name: string\n readonly type: OperationFieldType\n\n readonly description?: string\n /** Whether the field takes `null`, to clear it */\n readonly nullable?: boolean\n /** The enum's values */\n readonly options?: readonly string[]\n /** The object fields the field nests in, dot-separated, such as `crawlOptions` */\n readonly parent?: string\n readonly required?: boolean\n /** The body variants (values of the discriminating `type`) the field belongs to */\n readonly variants?: readonly string[]\n}\n\ninterface OperationPathParam {\n readonly name: string\n\n readonly description?: string\n}\n\n/** A Context API operation, distilled from the spec for building a command */\nexport interface ContextOperation {\n readonly body: 'none' | 'optional' | 'required'\n readonly description: string\n readonly fields: readonly OperationField[]\n /** The response has no body (`204 No Content`) */\n readonly noContent: boolean\n /** The response is a page (`data` and `nextCursor`) and the query takes a `cursor` */\n readonly paginated: boolean\n readonly pathParams: readonly OperationPathParam[]\n readonly route: Context.Route\n /** The response carries the `jobId` of the job it starts */\n readonly startsJob: boolean\n readonly summary: string\n\n /** Items a paginated list asks for per page: the most its `limit` allows, up to 200 */\n readonly pageSize?: number\n}\n"],"names":[],"mappings":"AAgCA,4EAA4E,GAC5E,WAgBC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Context commands removed when imports became sources, with what replaces
|
|
3
|
+
* each. The command_not_found hook names the replacement instead of guessing
|
|
4
|
+
* a similar name.
|
|
5
|
+
*/ const REPLACEMENTS = {
|
|
6
|
+
'context:imports': 'sanity context sources',
|
|
7
|
+
'context:imports:create': 'sanity context sources create',
|
|
8
|
+
'context:imports:delete': 'sanity context sources delete',
|
|
9
|
+
'context:imports:download': 'sanity context documents content --format raw',
|
|
10
|
+
'context:imports:get': 'sanity context sources get',
|
|
11
|
+
'context:imports:list': 'sanity context sources list',
|
|
12
|
+
'context:refresh': 'sanity context sync'
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* The message for a removed context command, or `undefined` for any other id. oclif joins the
|
|
16
|
+
* arguments onto the id it can't find (`context:refresh:kb123`), so the longest known prefix wins.
|
|
17
|
+
*/ export function removedContextCommandHint(fullId) {
|
|
18
|
+
const parts = fullId.split(':');
|
|
19
|
+
const id = parts.map((_, i)=>parts.slice(0, parts.length - i).join(':')).find((prefix)=>prefix in REPLACEMENTS);
|
|
20
|
+
if (id === undefined) return undefined;
|
|
21
|
+
const replacement = REPLACEMENTS[id];
|
|
22
|
+
const removed = `sanity ${id.replaceAll(':', ' ')}`;
|
|
23
|
+
return id === 'context:refresh' ? `\`${removed}\` was removed. To sync every source of a knowledge base, use \`${replacement}\`.` : `\`${removed}\` was removed: imports are now sources, and what they read are documents. Use \`${replacement}\`.`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
//# sourceMappingURL=removedCommands.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/removedCommands.ts"],"sourcesContent":["/**\n * Context commands removed when imports became sources, with what replaces\n * each. The command_not_found hook names the replacement instead of guessing\n * a similar name.\n */\nconst REPLACEMENTS: Record<string, string> = {\n 'context:imports': 'sanity context sources',\n 'context:imports:create': 'sanity context sources create',\n 'context:imports:delete': 'sanity context sources delete',\n 'context:imports:download': 'sanity context documents content --format raw',\n 'context:imports:get': 'sanity context sources get',\n 'context:imports:list': 'sanity context sources list',\n 'context:refresh': 'sanity context sync',\n}\n\n/**\n * The message for a removed context command, or `undefined` for any other id. oclif joins the\n * arguments onto the id it can't find (`context:refresh:kb123`), so the longest known prefix wins.\n */\nexport function removedContextCommandHint(fullId: string): string | undefined {\n const parts = fullId.split(':')\n const id = parts\n .map((_, i) => parts.slice(0, parts.length - i).join(':'))\n .find((prefix) => prefix in REPLACEMENTS)\n if (id === undefined) return undefined\n const replacement = REPLACEMENTS[id]\n const removed = `sanity ${id.replaceAll(':', ' ')}`\n return id === 'context:refresh'\n ? `\\`${removed}\\` was removed. To sync every source of a knowledge base, use \\`${replacement}\\`.`\n : `\\`${removed}\\` was removed: imports are now sources, and what they read are documents. Use \\`${replacement}\\`.`\n}\n"],"names":["REPLACEMENTS","removedContextCommandHint","fullId","parts","split","id","map","_","i","slice","length","join","find","prefix","undefined","replacement","removed","replaceAll"],"mappings":"AAAA;;;;CAIC,GACD,MAAMA,eAAuC;IAC3C,mBAAmB;IACnB,0BAA0B;IAC1B,0BAA0B;IAC1B,4BAA4B;IAC5B,uBAAuB;IACvB,wBAAwB;IACxB,mBAAmB;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASC,0BAA0BC,MAAc;IACtD,MAAMC,QAAQD,OAAOE,KAAK,CAAC;IAC3B,MAAMC,KAAKF,MACRG,GAAG,CAAC,CAACC,GAAGC,IAAML,MAAMM,KAAK,CAAC,GAAGN,MAAMO,MAAM,GAAGF,GAAGG,IAAI,CAAC,MACpDC,IAAI,CAAC,CAACC,SAAWA,UAAUb;IAC9B,IAAIK,OAAOS,WAAW,OAAOA;IAC7B,MAAMC,cAAcf,YAAY,CAACK,GAAG;IACpC,MAAMW,UAAU,CAAC,OAAO,EAAEX,GAAGY,UAAU,CAAC,KAAK,MAAM;IACnD,OAAOZ,OAAO,oBACV,CAAC,EAAE,EAAEW,QAAQ,gEAAgE,EAAED,YAAY,GAAG,CAAC,GAC/F,CAAC,EAAE,EAAEC,QAAQ,iFAAiF,EAAED,YAAY,GAAG,CAAC;AACtH"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { formatKeyValue } from '../debug/output.js';
|
|
2
|
+
import { humanize } from './operationInput.js';
|
|
3
|
+
import { contextTable } from './table.js';
|
|
4
|
+
const AUTO_COLUMNS = 6;
|
|
5
|
+
function isRow(value) {
|
|
6
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
|
+
}
|
|
8
|
+
function isScalar(value) {
|
|
9
|
+
return value === null || [
|
|
10
|
+
'boolean',
|
|
11
|
+
'number',
|
|
12
|
+
'string'
|
|
13
|
+
].includes(typeof value);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A value on one line: `-` for nothing, a comma list for an array,
|
|
17
|
+
* `id (status)` for an object with an ID, and `Key: value` pairs for any
|
|
18
|
+
* other object
|
|
19
|
+
*/ function cell(value) {
|
|
20
|
+
if (value === null || value === undefined) return '-';
|
|
21
|
+
if (typeof value === 'string') return value;
|
|
22
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
23
|
+
if (Array.isArray(value)) return value.length === 0 ? '-' : value.map((item)=>cell(item)).join(', ');
|
|
24
|
+
if (isRow(value)) {
|
|
25
|
+
if (typeof value.id === 'string') {
|
|
26
|
+
return typeof value.status === 'string' ? `${value.id} (${value.status})` : value.id;
|
|
27
|
+
}
|
|
28
|
+
const entries = Object.entries(value).filter(([, item])=>item !== undefined);
|
|
29
|
+
if (entries.length === 0) return '-';
|
|
30
|
+
return entries.map(([key, item])=>`${humanize(key)}: ${cell(item)}`).join('; ');
|
|
31
|
+
}
|
|
32
|
+
return JSON.stringify(value);
|
|
33
|
+
}
|
|
34
|
+
function renderTable(rows, columns) {
|
|
35
|
+
if (rows.length === 0) return 'No results';
|
|
36
|
+
const first = rows.find((row)=>isRow(row)) ?? {};
|
|
37
|
+
const names = columns ?? Object.entries(first).filter(([, value])=>isScalar(value)).map(([name])=>name).slice(0, AUTO_COLUMNS);
|
|
38
|
+
const table = contextTable({
|
|
39
|
+
columns: names.map((name)=>({
|
|
40
|
+
alignment: 'left',
|
|
41
|
+
name,
|
|
42
|
+
title: humanize(name)
|
|
43
|
+
}))
|
|
44
|
+
});
|
|
45
|
+
for (const row of rows){
|
|
46
|
+
if (!isRow(row)) continue;
|
|
47
|
+
table.addRow(Object.fromEntries(names.map((name)=>[
|
|
48
|
+
name,
|
|
49
|
+
cell(row[name])
|
|
50
|
+
])));
|
|
51
|
+
}
|
|
52
|
+
return table.render();
|
|
53
|
+
}
|
|
54
|
+
function renderObject(row) {
|
|
55
|
+
const entries = Object.entries(row);
|
|
56
|
+
const padTo = Math.max(...entries.map(([key])=>humanize(key).length));
|
|
57
|
+
return entries.map(([key, value])=>formatKeyValue(humanize(key), cell(value), {
|
|
58
|
+
padTo
|
|
59
|
+
})).join('\n');
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A response as terminal output: a table for a list, key-value lines for an
|
|
63
|
+
* object, the text of a text response, and a confirmation for no content
|
|
64
|
+
*/ export function renderOperationResult(result, options) {
|
|
65
|
+
if (result === undefined || result === null || result === '') return `${options.summary}: done`;
|
|
66
|
+
if (typeof result === 'string') return result;
|
|
67
|
+
if (Array.isArray(result)) return renderTable(result, options.columns);
|
|
68
|
+
if (isRow(result)) return renderObject(result);
|
|
69
|
+
return cell(result);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=renderOperationResult.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/renderOperationResult.ts"],"sourcesContent":["import {formatKeyValue} from '../debug/output.js'\nimport {humanize} from './operationInput.js'\nimport {contextTable} from './table.js'\n\nconst AUTO_COLUMNS = 6\n\ntype Row = Record<string, unknown>\n\nfunction isRow(value: unknown): value is Row {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction isScalar(value: unknown): boolean {\n return value === null || ['boolean', 'number', 'string'].includes(typeof value)\n}\n\n/**\n * A value on one line: `-` for nothing, a comma list for an array,\n * `id (status)` for an object with an ID, and `Key: value` pairs for any\n * other object\n */\nfunction cell(value: unknown): string {\n if (value === null || value === undefined) return '-'\n if (typeof value === 'string') return value\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (Array.isArray(value))\n return value.length === 0 ? '-' : value.map((item) => cell(item)).join(', ')\n if (isRow(value)) {\n if (typeof value.id === 'string') {\n return typeof value.status === 'string' ? `${value.id} (${value.status})` : value.id\n }\n const entries = Object.entries(value).filter(([, item]) => item !== undefined)\n if (entries.length === 0) return '-'\n return entries.map(([key, item]) => `${humanize(key)}: ${cell(item)}`).join('; ')\n }\n return JSON.stringify(value)\n}\n\nfunction renderTable(rows: readonly unknown[], columns?: readonly string[]): string {\n if (rows.length === 0) return 'No results'\n const first = rows.find((row) => isRow(row)) ?? {}\n const names =\n columns ??\n Object.entries(first)\n .filter(([, value]) => isScalar(value))\n .map(([name]) => name)\n .slice(0, AUTO_COLUMNS)\n const table = contextTable({\n columns: names.map((name) => ({alignment: 'left', name, title: humanize(name)})),\n })\n for (const row of rows) {\n if (!isRow(row)) continue\n table.addRow(Object.fromEntries(names.map((name) => [name, cell(row[name])])))\n }\n return table.render()\n}\n\nfunction renderObject(row: Row): string {\n const entries = Object.entries(row)\n const padTo = Math.max(...entries.map(([key]) => humanize(key).length))\n return entries\n .map(([key, value]) => formatKeyValue(humanize(key), cell(value), {padTo}))\n .join('\\n')\n}\n\n/**\n * A response as terminal output: a table for a list, key-value lines for an\n * object, the text of a text response, and a confirmation for no content\n */\nexport function renderOperationResult(\n result: unknown,\n options: {columns?: readonly string[]; summary: string},\n): string {\n if (result === undefined || result === null || result === '') return `${options.summary}: done`\n if (typeof result === 'string') return result\n if (Array.isArray(result)) return renderTable(result, options.columns)\n if (isRow(result)) return renderObject(result)\n return cell(result)\n}\n"],"names":["formatKeyValue","humanize","contextTable","AUTO_COLUMNS","isRow","value","Array","isArray","isScalar","includes","cell","undefined","String","length","map","item","join","id","status","entries","Object","filter","key","JSON","stringify","renderTable","rows","columns","first","find","row","names","name","slice","table","alignment","title","addRow","fromEntries","render","renderObject","padTo","Math","max","renderOperationResult","result","options","summary"],"mappings":"AAAA,SAAQA,cAAc,QAAO,qBAAoB;AACjD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,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,OAAOL,aAAaK;IACvC,OAAOnC,KAAKmC;AACd"}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
|
+
import { CLIError } from '@oclif/core/errors';
|
|
2
|
+
import { exitCodes } from '@sanity/cli-core';
|
|
1
3
|
import { promptForOrganization } from '../../prompts/promptForOrganization.js';
|
|
2
|
-
/** The organization could not be determined and prompting is not possible. */ export class MissingOrganizationError extends
|
|
4
|
+
/** The organization could not be determined and prompting is not possible. */ export class MissingOrganizationError extends CLIError {
|
|
5
|
+
constructor(message){
|
|
6
|
+
super(message, {
|
|
7
|
+
exit: exitCodes.USAGE_ERROR
|
|
8
|
+
});
|
|
9
|
+
}
|
|
3
10
|
}
|
|
4
11
|
/**
|
|
5
12
|
* Resolve the organization to operate on: the `--organization` flag wins,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/context/resolveOrganizationId.ts"],"sourcesContent":["import {promptForOrganization} from '../../prompts/promptForOrganization.js'\n\n/** The organization could not be determined and prompting is not possible. */\nexport class MissingOrganizationError extends
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/resolveOrganizationId.ts"],"sourcesContent":["import {CLIError} from '@oclif/core/errors'\nimport {exitCodes} from '@sanity/cli-core'\n\nimport {promptForOrganization} from '../../prompts/promptForOrganization.js'\n\n/** The organization could not be determined and prompting is not possible. */\nexport class MissingOrganizationError extends CLIError {\n constructor(message: string) {\n super(message, {exit: exitCodes.USAGE_ERROR})\n }\n}\n\n/**\n * Resolve the organization to operate on: the `--organization` flag wins,\n * then the CLI config's `app.organizationId`, then an interactive prompt.\n */\nexport async function resolveOrganizationId(options: {\n configuredOrganizationId: string | undefined\n flagOrganizationId: string | undefined\n unattended: boolean\n}): Promise<string> {\n const {configuredOrganizationId, flagOrganizationId, unattended} = options\n\n if (flagOrganizationId) return flagOrganizationId\n if (configuredOrganizationId) return configuredOrganizationId\n\n if (unattended) {\n throw new MissingOrganizationError(\n 'Organization ID is required. Provide it with the --organization flag.',\n )\n }\n\n return promptForOrganization()\n}\n"],"names":["CLIError","exitCodes","promptForOrganization","MissingOrganizationError","message","exit","USAGE_ERROR","resolveOrganizationId","options","configuredOrganizationId","flagOrganizationId","unattended"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,SAAS,QAAO,mBAAkB;AAE1C,SAAQC,qBAAqB,QAAO,yCAAwC;AAE5E,4EAA4E,GAC5E,OAAO,MAAMC,iCAAiCH;IAC5C,YAAYI,OAAe,CAAE;QAC3B,KAAK,CAACA,SAAS;YAACC,MAAMJ,UAAUK,WAAW;QAAA;IAC7C;AACF;AAEA;;;CAGC,GACD,OAAO,eAAeC,sBAAsBC,OAI3C;IACC,MAAM,EAACC,wBAAwB,EAAEC,kBAAkB,EAAEC,UAAU,EAAC,GAAGH;IAEnE,IAAIE,oBAAoB,OAAOA;IAC/B,IAAID,0BAA0B,OAAOA;IAErC,IAAIE,YAAY;QACd,MAAM,IAAIR,yBACR;IAEJ;IAEA,OAAOD;AACT"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, extname } from 'node:path';
|
|
3
|
+
const FILE_CONTENT_TYPES = {
|
|
4
|
+
'.csv': 'text/csv',
|
|
5
|
+
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
6
|
+
'.gz': 'application/gzip',
|
|
7
|
+
'.htm': 'text/html',
|
|
8
|
+
'.html': 'text/html',
|
|
9
|
+
'.json': 'application/json',
|
|
10
|
+
'.markdown': 'text/markdown',
|
|
11
|
+
'.md': 'text/markdown',
|
|
12
|
+
'.pdf': 'application/pdf',
|
|
13
|
+
'.tar': 'application/x-tar',
|
|
14
|
+
'.tgz': 'application/gzip',
|
|
15
|
+
'.txt': 'text/plain',
|
|
16
|
+
'.zip': 'application/zip'
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Read a local file for upload to a `files` source. The Context API signs the
|
|
20
|
+
* upload URL for a content type, so one is always sent: the given one, or one
|
|
21
|
+
* inferred from the file extension.
|
|
22
|
+
*/ export async function readSourceFile(filePath, contentType) {
|
|
23
|
+
const file = await readFile(filePath);
|
|
24
|
+
return {
|
|
25
|
+
contentType: contentType ?? FILE_CONTENT_TYPES[extname(filePath).toLowerCase()] ?? 'application/octet-stream',
|
|
26
|
+
file,
|
|
27
|
+
filename: basename(filePath)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=sourceFile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/sourceFile.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\nimport {basename, extname} from 'node:path'\n\nimport {type Context} from '@sanity/client'\n\nconst FILE_CONTENT_TYPES: Record<string, string> = {\n '.csv': 'text/csv',\n '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n '.gz': 'application/gzip',\n '.htm': 'text/html',\n '.html': 'text/html',\n '.json': 'application/json',\n '.markdown': 'text/markdown',\n '.md': 'text/markdown',\n '.pdf': 'application/pdf',\n '.tar': 'application/x-tar',\n '.tgz': 'application/gzip',\n '.txt': 'text/plain',\n '.zip': 'application/zip',\n}\n\n/**\n * Read a local file for upload to a `files` source. The Context API signs the\n * upload URL for a content type, so one is always sent: the given one, or one\n * inferred from the file extension.\n */\nexport async function readSourceFile(\n filePath: string,\n contentType?: string,\n): Promise<Context.FileUpload> {\n const file = await readFile(filePath)\n return {\n contentType:\n contentType ??\n FILE_CONTENT_TYPES[extname(filePath).toLowerCase()] ??\n 'application/octet-stream',\n file,\n filename: basename(filePath),\n }\n}\n"],"names":["readFile","basename","extname","FILE_CONTENT_TYPES","readSourceFile","filePath","contentType","file","toLowerCase","filename"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,QAAQ,EAAEC,OAAO,QAAO,YAAW;AAI3C,MAAMC,qBAA6C;IACjD,QAAQ;IACR,SAAS;IACT,OAAO;IACP,QAAQ;IACR,SAAS;IACT,SAAS;IACT,aAAa;IACb,OAAO;IACP,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;AACV;AAEA;;;;CAIC,GACD,OAAO,eAAeC,eACpBC,QAAgB,EAChBC,WAAoB;IAEpB,MAAMC,OAAO,MAAMP,SAASK;IAC5B,OAAO;QACLC,aACEA,eACAH,kBAAkB,CAACD,QAAQG,UAAUG,WAAW,GAAG,IACnD;QACFD;QACAE,UAAUR,SAASI;IACrB;AACF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { pluralize } from '../../util/pluralize.js';
|
|
2
|
+
function heldDocuments(count) {
|
|
3
|
+
return count === null ? 'some documents' : `${count} ${pluralize('document', count)}`;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Next steps for a sync held for confirmation, or `undefined` for any other sync
|
|
7
|
+
*/ export function heldSyncHint(knowledgeBaseId, sync) {
|
|
8
|
+
if (sync.status !== 'held') return undefined;
|
|
9
|
+
const ids = `${knowledgeBaseId} ${sync.sourceId} ${sync.id}`;
|
|
10
|
+
return [
|
|
11
|
+
`Sync held: it would delete ${heldDocuments(sync.heldDeletions)} it didn't find.`,
|
|
12
|
+
`Delete them with: sanity context sources syncs confirm ${ids}`,
|
|
13
|
+
`Keep them with: sanity context sources syncs discard ${ids}`
|
|
14
|
+
].join('\n');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=syncOutput.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/syncOutput.ts"],"sourcesContent":["import {type Sync} from '../../services/context.js'\nimport {pluralize} from '../../util/pluralize.js'\n\nfunction heldDocuments(count: number | null): string {\n return count === null ? 'some documents' : `${count} ${pluralize('document', count)}`\n}\n\n/**\n * Next steps for a sync held for confirmation, or `undefined` for any other sync\n */\nexport function heldSyncHint(knowledgeBaseId: string, sync: Sync): string | undefined {\n if (sync.status !== 'held') return undefined\n const ids = `${knowledgeBaseId} ${sync.sourceId} ${sync.id}`\n return [\n `Sync held: it would delete ${heldDocuments(sync.heldDeletions)} it didn't find.`,\n `Delete them with: sanity context sources syncs confirm ${ids}`,\n `Keep them with: sanity context sources syncs discard ${ids}`,\n ].join('\\n')\n}\n"],"names":["pluralize","heldDocuments","count","heldSyncHint","knowledgeBaseId","sync","status","undefined","ids","sourceId","id","heldDeletions","join"],"mappings":"AACA,SAAQA,SAAS,QAAO,0BAAyB;AAEjD,SAASC,cAAcC,KAAoB;IACzC,OAAOA,UAAU,OAAO,mBAAmB,GAAGA,MAAM,CAAC,EAAEF,UAAU,YAAYE,QAAQ;AACvF;AAEA;;CAEC,GACD,OAAO,SAASC,aAAaC,eAAuB,EAAEC,IAAU;IAC9D,IAAIA,KAAKC,MAAM,KAAK,QAAQ,OAAOC;IACnC,MAAMC,MAAM,GAAGJ,gBAAgB,CAAC,EAAEC,KAAKI,QAAQ,CAAC,CAAC,EAAEJ,KAAKK,EAAE,EAAE;IAC5D,OAAO;QACL,CAAC,2BAA2B,EAAET,cAAcI,KAAKM,aAAa,EAAE,gBAAgB,CAAC;QACjF,CAAC,uDAAuD,EAAEH,KAAK;QAC/D,CAAC,uDAAuD,EAAEA,KAAK;KAChE,CAACI,IAAI,CAAC;AACT"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Table } from '../../util/responsiveTable.js';
|
|
2
|
+
/**
|
|
3
|
+
* A table that leaves out colours when stdout can't show them: when it is a
|
|
4
|
+
* pipe or a file, or `NO_COLOR` is set
|
|
5
|
+
*/ export function contextTable(options) {
|
|
6
|
+
const hasColors = Boolean(process.stdout.isTTY) && process.stdout.hasColors();
|
|
7
|
+
return new Table({
|
|
8
|
+
shouldDisableColors: !hasColors,
|
|
9
|
+
...options
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=table.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/table.ts"],"sourcesContent":["import {Table} from '../../util/responsiveTable.js'\n\ntype TableOptions = ConstructorParameters<typeof Table>[0]\n\n/**\n * A table that leaves out colours when stdout can't show them: when it is a\n * pipe or a file, or `NO_COLOR` is set\n */\nexport function contextTable(options: TableOptions): Table {\n const hasColors = Boolean(process.stdout.isTTY) && process.stdout.hasColors()\n return new Table({shouldDisableColors: !hasColors, ...options})\n}\n"],"names":["Table","contextTable","options","hasColors","Boolean","process","stdout","isTTY","shouldDisableColors"],"mappings":"AAAA,SAAQA,KAAK,QAAO,gCAA+B;AAInD;;;CAGC,GACD,OAAO,SAASC,aAAaC,OAAqB;IAChD,MAAMC,YAAYC,QAAQC,QAAQC,MAAM,CAACC,KAAK,KAAKF,QAAQC,MAAM,CAACH,SAAS;IAC3E,OAAO,IAAIH,MAAM;QAACQ,qBAAqB,CAACL;QAAW,GAAGD,OAAO;IAAA;AAC/D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/context/waitForJob.ts"],"sourcesContent":["import {setTimeout as sleep} from 'node:timers/promises'\n\nimport {type
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/waitForJob.ts"],"sourcesContent":["import {setTimeout as sleep} from 'node:timers/promises'\n\nimport {getJob, type Job} from '../../services/context.js'\n\nconst JOB_POLL_INTERVAL_MS = 5000\n\nconst TERMINAL_JOB_STATUSES: ReadonlySet<Job['status']> = new Set([\n 'cancelled',\n 'failed',\n 'succeeded',\n])\n\n/**\n * Poll a knowledge base job until it reaches a terminal state\n * (succeeded, failed or cancelled), resolving with the final job.\n */\nexport async function waitForJob(\n knowledgeBaseId: string,\n jobId: string,\n options?: {\n onPoll?: (job: Job) => void\n pollIntervalMs?: number\n },\n): Promise<Job> {\n const pollIntervalMs = options?.pollIntervalMs ?? JOB_POLL_INTERVAL_MS\n\n while (true) {\n const job = await getJob(knowledgeBaseId, jobId)\n if (TERMINAL_JOB_STATUSES.has(job.status)) {\n return job\n }\n options?.onPoll?.(job)\n await sleep(pollIntervalMs)\n }\n}\n"],"names":["setTimeout","sleep","getJob","JOB_POLL_INTERVAL_MS","TERMINAL_JOB_STATUSES","Set","waitForJob","knowledgeBaseId","jobId","options","pollIntervalMs","job","has","status","onPoll"],"mappings":"AAAA,SAAQA,cAAcC,KAAK,QAAO,uBAAsB;AAExD,SAAQC,MAAM,QAAiB,4BAA2B;AAE1D,MAAMC,uBAAuB;AAE7B,MAAMC,wBAAoD,IAAIC,IAAI;IAChE;IACA;IACA;CACD;AAED;;;CAGC,GACD,OAAO,eAAeC,WACpBC,eAAuB,EACvBC,KAAa,EACbC,OAGC;IAED,MAAMC,iBAAiBD,SAASC,kBAAkBP;IAElD,MAAO,KAAM;QACX,MAAMQ,MAAM,MAAMT,OAAOK,iBAAiBC;QAC1C,IAAIJ,sBAAsBQ,GAAG,CAACD,IAAIE,MAAM,GAAG;YACzC,OAAOF;QACT;QACAF,SAASK,SAASH;QAClB,MAAMV,MAAMS;IACd;AACF"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import { getSource, getSync } from '../../services/context.js';
|
|
3
|
+
import { waitForJob } from './waitForJob.js';
|
|
4
|
+
import { formatJobFailure } from './watchJob.js';
|
|
5
|
+
const SYNC_POLL_INTERVAL_MS = 5000;
|
|
6
|
+
const SETTLED_SYNC_STATUSES = new Set([
|
|
7
|
+
'cancelled',
|
|
8
|
+
'completed',
|
|
9
|
+
'failed',
|
|
10
|
+
'held'
|
|
11
|
+
]);
|
|
12
|
+
/**
|
|
13
|
+
* Poll until the sync a request created or queued settles (completed, failed,
|
|
14
|
+
* cancelled, or held for confirmation), resolving with that sync. A known
|
|
15
|
+
* sync is followed by its ID; a `files` sync through its job, whose result
|
|
16
|
+
* names the sync. A website or dataset sync is queued behind any running sync
|
|
17
|
+
* of its source and the request returns no ID for it, so it is the first
|
|
18
|
+
* `latestSync` that isn't the one seen before the request.
|
|
19
|
+
*/ export async function waitForSourceSync(knowledgeBaseId, sourceId, target, options = {}) {
|
|
20
|
+
const pollIntervalMs = options.pollIntervalMs ?? SYNC_POLL_INTERVAL_MS;
|
|
21
|
+
let syncId = target.syncId;
|
|
22
|
+
if (target.jobId !== undefined) {
|
|
23
|
+
const job = await waitForJob(knowledgeBaseId, target.jobId, {
|
|
24
|
+
pollIntervalMs
|
|
25
|
+
});
|
|
26
|
+
const result = 'result' in job ? job.result : undefined;
|
|
27
|
+
const id = typeof result === 'object' && result !== null && 'syncId' in result ? result.syncId : undefined;
|
|
28
|
+
if (typeof id !== 'string') throw new Error(formatJobFailure('Sync', job));
|
|
29
|
+
syncId = id;
|
|
30
|
+
}
|
|
31
|
+
while(true){
|
|
32
|
+
let sync;
|
|
33
|
+
if (syncId === undefined) {
|
|
34
|
+
const { latestSync } = await getSource(knowledgeBaseId, sourceId);
|
|
35
|
+
const previous = 'previousSyncId' in target ? target.previousSyncId : null;
|
|
36
|
+
sync = latestSync && latestSync.id !== previous ? latestSync : null;
|
|
37
|
+
} else {
|
|
38
|
+
sync = await getSync(knowledgeBaseId, sourceId, syncId);
|
|
39
|
+
}
|
|
40
|
+
if (sync && SETTLED_SYNC_STATUSES.has(sync.status)) {
|
|
41
|
+
return sync;
|
|
42
|
+
}
|
|
43
|
+
options.onPoll?.(sync);
|
|
44
|
+
await sleep(pollIntervalMs);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=waitForSourceSync.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/waitForSourceSync.ts"],"sourcesContent":["import {setTimeout as sleep} from 'node:timers/promises'\n\nimport {getSource, getSync, type Sync} from '../../services/context.js'\nimport {waitForJob} from './waitForJob.js'\nimport {formatJobFailure} from './watchJob.js'\n\nconst SYNC_POLL_INTERVAL_MS = 5000\n\nconst SETTLED_SYNC_STATUSES: ReadonlySet<Sync['status']> = new Set([\n 'cancelled',\n 'completed',\n 'failed',\n 'held',\n])\n\n/** The sync to follow: the one a request created, the job a `files` sync runs in, or a website or dataset sync queued on the source */\nexport type SyncTarget =\n | {jobId: string; syncId?: undefined}\n | {jobId?: undefined; previousSyncId: string | null; syncId?: undefined}\n | {jobId?: undefined; syncId: string}\n\n/**\n * Poll until the sync a request created or queued settles (completed, failed,\n * cancelled, or held for confirmation), resolving with that sync. A known\n * sync is followed by its ID; a `files` sync through its job, whose result\n * names the sync. A website or dataset sync is queued behind any running sync\n * of its source and the request returns no ID for it, so it is the first\n * `latestSync` that isn't the one seen before the request.\n */\nexport async function waitForSourceSync(\n knowledgeBaseId: string,\n sourceId: string,\n target: SyncTarget,\n options: {onPoll?: (sync: Sync | null) => void; pollIntervalMs?: number} = {},\n): Promise<Sync> {\n const pollIntervalMs = options.pollIntervalMs ?? SYNC_POLL_INTERVAL_MS\n let syncId = target.syncId\n\n if (target.jobId !== undefined) {\n const job = await waitForJob(knowledgeBaseId, target.jobId, {pollIntervalMs})\n const result: unknown = 'result' in job ? job.result : undefined\n const id =\n typeof result === 'object' && result !== null && 'syncId' in result\n ? result.syncId\n : undefined\n if (typeof id !== 'string') throw new Error(formatJobFailure('Sync', job))\n syncId = id\n }\n\n while (true) {\n let sync: Sync | null\n if (syncId === undefined) {\n const {latestSync} = await getSource(knowledgeBaseId, sourceId)\n const previous = 'previousSyncId' in target ? target.previousSyncId : null\n sync = latestSync && latestSync.id !== previous ? latestSync : null\n } else {\n sync = await getSync(knowledgeBaseId, sourceId, syncId)\n }\n if (sync && SETTLED_SYNC_STATUSES.has(sync.status)) {\n return sync\n }\n options.onPoll?.(sync)\n await sleep(pollIntervalMs)\n }\n}\n"],"names":["setTimeout","sleep","getSource","getSync","waitForJob","formatJobFailure","SYNC_POLL_INTERVAL_MS","SETTLED_SYNC_STATUSES","Set","waitForSourceSync","knowledgeBaseId","sourceId","target","options","pollIntervalMs","syncId","jobId","undefined","job","result","id","Error","sync","latestSync","previous","previousSyncId","has","status","onPoll"],"mappings":"AAAA,SAAQA,cAAcC,KAAK,QAAO,uBAAsB;AAExD,SAAQC,SAAS,EAAEC,OAAO,QAAkB,4BAA2B;AACvE,SAAQC,UAAU,QAAO,kBAAiB;AAC1C,SAAQC,gBAAgB,QAAO,gBAAe;AAE9C,MAAMC,wBAAwB;AAE9B,MAAMC,wBAAqD,IAAIC,IAAI;IACjE;IACA;IACA;IACA;CACD;AAQD;;;;;;;CAOC,GACD,OAAO,eAAeC,kBACpBC,eAAuB,EACvBC,QAAgB,EAChBC,MAAkB,EAClBC,UAA2E,CAAC,CAAC;IAE7E,MAAMC,iBAAiBD,QAAQC,cAAc,IAAIR;IACjD,IAAIS,SAASH,OAAOG,MAAM;IAE1B,IAAIH,OAAOI,KAAK,KAAKC,WAAW;QAC9B,MAAMC,MAAM,MAAMd,WAAWM,iBAAiBE,OAAOI,KAAK,EAAE;YAACF;QAAc;QAC3E,MAAMK,SAAkB,YAAYD,MAAMA,IAAIC,MAAM,GAAGF;QACvD,MAAMG,KACJ,OAAOD,WAAW,YAAYA,WAAW,QAAQ,YAAYA,SACzDA,OAAOJ,MAAM,GACbE;QACN,IAAI,OAAOG,OAAO,UAAU,MAAM,IAAIC,MAAMhB,iBAAiB,QAAQa;QACrEH,SAASK;IACX;IAEA,MAAO,KAAM;QACX,IAAIE;QACJ,IAAIP,WAAWE,WAAW;YACxB,MAAM,EAACM,UAAU,EAAC,GAAG,MAAMrB,UAAUQ,iBAAiBC;YACtD,MAAMa,WAAW,oBAAoBZ,SAASA,OAAOa,cAAc,GAAG;YACtEH,OAAOC,cAAcA,WAAWH,EAAE,KAAKI,WAAWD,aAAa;QACjE,OAAO;YACLD,OAAO,MAAMnB,QAAQO,iBAAiBC,UAAUI;QAClD;QACA,IAAIO,QAAQf,sBAAsBmB,GAAG,CAACJ,KAAKK,MAAM,GAAG;YAClD,OAAOL;QACT;QACAT,QAAQe,MAAM,GAAGN;QACjB,MAAMrB,MAAMa;IACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/context/watchJob.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\nimport {type
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/context/watchJob.ts"],"sourcesContent":["import {spinner} from '@sanity/cli-core/ux'\n\nimport {type Job} from '../../services/context.js'\nimport {waitForJob} from './waitForJob.js'\n\n/**\n * Error message for a job that ended in a non-succeeded terminal state,\n * e.g. \"Build failed: <reason>\"\n */\nexport function formatJobFailure(noun: string, job: Job): string {\n return `${noun} ${job.status}${job.error ? `: ${job.error}` : ''}`\n}\n\n/**\n * Watch a knowledge base job with a spinner until it reaches a terminal\n * state, updating the spinner text with the job status on each poll.\n *\n * Fails the spinner and rethrows on polling errors, and fails it when the\n * terminal status is not `succeeded` — turning either outcome into a\n * command error (and exit code) is the caller's responsibility.\n */\nexport async function watchJob(\n knowledgeBaseId: string,\n jobId: string,\n options: {label: string; successText?: string},\n): Promise<Job> {\n const {label, successText} = options\n const spin = spinner(label).start()\n\n let job: Job\n try {\n job = await waitForJob(knowledgeBaseId, jobId, {\n onPoll: (pending) => {\n spin.text = `${label} (${pending.status})`\n },\n })\n } catch (error) {\n spin.fail(label)\n throw error\n }\n\n if (job.status === 'succeeded') {\n spin.succeed(successText ?? label)\n } else {\n spin.fail(label)\n }\n\n return job\n}\n"],"names":["spinner","waitForJob","formatJobFailure","noun","job","status","error","watchJob","knowledgeBaseId","jobId","options","label","successText","spin","start","onPoll","pending","text","fail","succeed"],"mappings":"AAAA,SAAQA,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,UAAU,QAAO,kBAAiB;AAE1C;;;CAGC,GACD,OAAO,SAASC,iBAAiBC,IAAY,EAAEC,GAAQ;IACrD,OAAO,GAAGD,KAAK,CAAC,EAAEC,IAAIC,MAAM,GAAGD,IAAIE,KAAK,GAAG,CAAC,EAAE,EAAEF,IAAIE,KAAK,EAAE,GAAG,IAAI;AACpE;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeC,SACpBC,eAAuB,EACvBC,KAAa,EACbC,OAA8C;IAE9C,MAAM,EAACC,KAAK,EAAEC,WAAW,EAAC,GAAGF;IAC7B,MAAMG,OAAOb,QAAQW,OAAOG,KAAK;IAEjC,IAAIV;IACJ,IAAI;QACFA,MAAM,MAAMH,WAAWO,iBAAiBC,OAAO;YAC7CM,QAAQ,CAACC;gBACPH,KAAKI,IAAI,GAAG,GAAGN,MAAM,EAAE,EAAEK,QAAQX,MAAM,CAAC,CAAC,CAAC;YAC5C;QACF;IACF,EAAE,OAAOC,OAAO;QACdO,KAAKK,IAAI,CAACP;QACV,MAAML;IACR;IAEA,IAAIF,IAAIC,MAAM,KAAK,aAAa;QAC9BQ,KAAKM,OAAO,CAACP,eAAeD;IAC9B,OAAO;QACLE,KAAKK,IAAI,CAACP;IACZ;IAEA,OAAOP;AACT"}
|