@sanity/workflows-cli 0.0.0-stage → 0.39.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.
Files changed (134) hide show
  1. package/CHANGELOG.md +1981 -0
  2. package/LICENSE +21 -0
  3. package/README.md +848 -2
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +52 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +66 -0
  20. package/dist/commands/workflows/definitions/show.js +129 -0
  21. package/dist/commands/workflows/definitions/validate.d.ts +14 -0
  22. package/dist/commands/workflows/definitions/validate.js +50 -0
  23. package/dist/commands/workflows/deploy.d.ts +117 -0
  24. package/dist/commands/workflows/deploy.js +266 -0
  25. package/dist/commands/workflows/diagnose.d.ts +53 -0
  26. package/dist/commands/workflows/diagnose.js +195 -0
  27. package/dist/commands/workflows/fire-action.d.ts +53 -0
  28. package/dist/commands/workflows/fire-action.js +182 -0
  29. package/dist/commands/workflows/list.d.ts +79 -0
  30. package/dist/commands/workflows/list.js +249 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +175 -0
  33. package/dist/commands/workflows/reset-activity.d.ts +32 -0
  34. package/dist/commands/workflows/reset-activity.js +60 -0
  35. package/dist/commands/workflows/show.d.ts +30 -0
  36. package/dist/commands/workflows/show.js +156 -0
  37. package/dist/commands/workflows/start.d.ts +57 -0
  38. package/dist/commands/workflows/start.js +196 -0
  39. package/dist/commands/workflows/tail.d.ts +24 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +16 -0
  42. package/dist/commands/workflows/whoami.js +53 -0
  43. package/dist/help.d.ts +13 -0
  44. package/dist/help.js +50 -0
  45. package/dist/hooks/finally/telemetry.d.ts +3 -0
  46. package/dist/hooks/finally/telemetry.js +10 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +33 -0
  48. package/dist/hooks/prerun/telemetry.js +52 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +41 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +284 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +118 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +27 -0
  62. package/dist/lib/client.js +45 -0
  63. package/dist/lib/codemod/ast.d.ts +17 -0
  64. package/dist/lib/codemod/ast.js +14 -0
  65. package/dist/lib/codemod/export-rename.d.ts +19 -0
  66. package/dist/lib/codemod/export-rename.js +337 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +133 -0
  69. package/dist/lib/codemod/package-map.d.ts +27 -0
  70. package/dist/lib/codemod/package-map.js +99 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +51 -0
  73. package/dist/lib/codemod/run.d.ts +25 -0
  74. package/dist/lib/codemod/run.js +108 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +150 -0
  77. package/dist/lib/command-context.d.ts +20 -0
  78. package/dist/lib/command-context.js +24 -0
  79. package/dist/lib/command-telemetry.d.ts +54 -0
  80. package/dist/lib/command-telemetry.js +82 -0
  81. package/dist/lib/context.d.ts +151 -0
  82. package/dist/lib/context.js +263 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +47 -0
  85. package/dist/lib/definition-files.d.ts +14 -0
  86. package/dist/lib/definition-files.js +60 -0
  87. package/dist/lib/definitions.d.ts +63 -0
  88. package/dist/lib/definitions.js +84 -0
  89. package/dist/lib/diff.d.ts +12 -0
  90. package/dist/lib/diff.js +93 -0
  91. package/dist/lib/env.d.ts +7 -0
  92. package/dist/lib/env.js +8 -0
  93. package/dist/lib/fail.d.ts +36 -0
  94. package/dist/lib/fail.js +55 -0
  95. package/dist/lib/failure-kind.d.ts +7 -0
  96. package/dist/lib/failure-kind.js +66 -0
  97. package/dist/lib/flags.d.ts +53 -0
  98. package/dist/lib/flags.js +127 -0
  99. package/dist/lib/follow-up-command.d.ts +18 -0
  100. package/dist/lib/follow-up-command.js +12 -0
  101. package/dist/lib/history-rows.d.ts +3 -0
  102. package/dist/lib/history-rows.js +44 -0
  103. package/dist/lib/load-config.d.ts +51 -0
  104. package/dist/lib/load-config.js +108 -0
  105. package/dist/lib/nuke.d.ts +124 -0
  106. package/dist/lib/nuke.js +206 -0
  107. package/dist/lib/operation-args.d.ts +42 -0
  108. package/dist/lib/operation-args.js +21 -0
  109. package/dist/lib/ops-report.d.ts +45 -0
  110. package/dist/lib/ops-report.js +31 -0
  111. package/dist/lib/params.d.ts +3 -0
  112. package/dist/lib/params.js +21 -0
  113. package/dist/lib/pick-resource.d.ts +13 -0
  114. package/dist/lib/pick-resource.js +82 -0
  115. package/dist/lib/prompt.d.ts +35 -0
  116. package/dist/lib/prompt.js +11 -0
  117. package/dist/lib/read-fanout.d.ts +45 -0
  118. package/dist/lib/read-fanout.js +45 -0
  119. package/dist/lib/resource-target.d.ts +10 -0
  120. package/dist/lib/resource-target.js +12 -0
  121. package/dist/lib/select-deployment.d.ts +31 -0
  122. package/dist/lib/select-deployment.js +91 -0
  123. package/dist/lib/share-definitions.d.ts +101 -0
  124. package/dist/lib/share-definitions.js +188 -0
  125. package/dist/lib/telemetry-setup.d.ts +77 -0
  126. package/dist/lib/telemetry-setup.js +117 -0
  127. package/dist/lib/telemetry.d.ts +81 -0
  128. package/dist/lib/telemetry.js +90 -0
  129. package/dist/lib/ui.d.ts +88 -0
  130. package/dist/lib/ui.js +114 -0
  131. package/dist/standalone-argv.d.ts +14 -0
  132. package/dist/standalone-argv.js +57 -0
  133. package/oclif.manifest.json +1894 -0
  134. package/package.json +118 -3
@@ -0,0 +1,284 @@
1
+ import { styleText } from 'node:util';
2
+ import { everyUpdateCause, } from '@sanity/workflows/blueprints/generate';
3
+ import { directoryProjectId, resourceLabel } from '@sanity/workflows/generate';
4
+ import logSymbols from 'log-symbols';
5
+ import { deploymentLabel } from './select-deployment.js';
6
+ import { pluralize, sectionHeader } from './ui.js';
7
+ export function needsFunctions(plan) {
8
+ return plan.deployments.some((deployment) => deployment.emission !== undefined);
9
+ }
10
+ export function needsReportLines(plan) {
11
+ return [
12
+ sectionHeader('Runtime needs'),
13
+ ...plan.deployments.flatMap((deployment) => ['', ...deploymentNeedsLines(deployment)]),
14
+ ];
15
+ }
16
+ export function needsSummaryLines(plan) {
17
+ return [
18
+ sectionHeader('Runtime needs'),
19
+ ...plan.deployments.flatMap((deployment) => deployment.emission === undefined ? [] : [summaryLine(deployment, deployment.emission)]),
20
+ ];
21
+ }
22
+ export function needsBriefLines(plan) {
23
+ return [
24
+ sectionHeader('Runtime needs'),
25
+ ...plan.deployments.flatMap((deployment) => [
26
+ deployment.emission === undefined
27
+ ? ` ${planLabel(deployment)} needs no Sanity Functions`
28
+ : summaryLine(deployment, deployment.emission),
29
+ ...warningLines(deployment),
30
+ ]),
31
+ ];
32
+ }
33
+ function summaryLine(plan, emission) {
34
+ const kinds = [
35
+ { count: emission.drains.length, noun: 'effect drain' },
36
+ { count: emission.heartbeat === undefined ? 0 : 1, noun: 'heartbeat' },
37
+ { count: emission.startWatchers.length, noun: 'start watcher' },
38
+ ].filter((kind) => kind.count > 0);
39
+ const total = kinds.reduce((sum, kind) => sum + kind.count, 0);
40
+ const breakdown = kinds.map((kind) => pluralize(kind.count, kind.noun)).join(', ');
41
+ return ` ${planLabel(plan)} needs ${pluralize(total, 'Sanity Function')} (${breakdown})`;
42
+ }
43
+ function planLabel(plan) {
44
+ return deploymentLabel({ name: plan.deploymentName, partition: plan.partition });
45
+ }
46
+ const DETAIL = ' → ';
47
+ const REASON = ' ';
48
+ function deploymentNeedsLines(plan) {
49
+ const { emission } = plan;
50
+ return [
51
+ styleText('bold', `▸ ${planLabel(plan)}`),
52
+ ...hostingLines(plan),
53
+ ...(emission === undefined
54
+ ? [' no functions needed — the reactive session is already this deployment runtime']
55
+ : [...drainLines(plan, emission), ...clockLines(plan, emission), ...watcherLines(emission)]),
56
+ ...selfHostedLines(plan),
57
+ ...warningLines(plan),
58
+ ];
59
+ }
60
+ const HOSTING_NOTE = {
61
+ function: '',
62
+ durableFunction: 'no functions are emitted for these yet',
63
+ selfHosted: 'nothing is emitted — your own process runs these',
64
+ };
65
+ const HOSTING_ORDER = ['function', 'durableFunction', 'selfHosted'];
66
+ function hostingLines(plan) {
67
+ return [
68
+ ` hosting: this deployment declares ${plan.runtimeKind}, and each level below inherits it`,
69
+ ...kindLines('workflow', plan.hosting.workflows),
70
+ ...kindLines('effect', plan.hosting.effects),
71
+ ];
72
+ }
73
+ function kindLines(what, byKind) {
74
+ return HOSTING_ORDER.flatMap((kind) => {
75
+ const names = byKind[kind];
76
+ if (names.length === 0)
77
+ return [];
78
+ const note = HOSTING_NOTE[kind];
79
+ const suffix = note === '' ? '' : ` — ${note}`;
80
+ return [`${DETAIL}${kind} ${what}(s): ${names.join(', ')}${suffix}`];
81
+ });
82
+ }
83
+ const SELF_HOSTED_TASKS = [
84
+ { key: 'startInstances', task: 'start instances of' },
85
+ { key: 'tickDeadlines', task: 'tick the $now deadlines of' },
86
+ { key: 'drainEffects', task: 'drain the effects' },
87
+ { key: 'reevaluateParents', task: 're-evaluate the parents that missed a child settling in' },
88
+ ];
89
+ function selfHostedLines(plan) {
90
+ const tasks = SELF_HOSTED_TASKS.flatMap(({ key, task }) => {
91
+ const names = plan.selfHosted[key];
92
+ return names.length === 0 ? [] : [`${REASON}${task} ${names.join(', ')}`];
93
+ });
94
+ if (tasks.length === 0)
95
+ return [];
96
+ return [' self-hosted: nothing below is emitted, so your own process must', ...tasks];
97
+ }
98
+ function drainLines(plan, emission) {
99
+ const declared = plan.needs.drain.effectNames;
100
+ if (declared.length === 0)
101
+ return [];
102
+ return [
103
+ ` effects: ${declared.length} declared — ${declared.join(', ')}`,
104
+ ...emission.drains.map((drain) => `${DETAIL}${DRAIN_KIND[drain.trigger]} ${drain.name} runs ${drain.effectNames.join(', ')}`),
105
+ ];
106
+ }
107
+ const DRAIN_KIND = {
108
+ document: 'drain function',
109
+ scheduled: 'scheduled drain function (heartbeat stack, every minute)',
110
+ };
111
+ function clockLines(plan, emission) {
112
+ const { heartbeat } = emission;
113
+ if (heartbeat === undefined)
114
+ return [];
115
+ const ticked = new Set(heartbeat.definitions);
116
+ return [
117
+ ` clock: ${heartbeatSentence(heartbeat)}`,
118
+ ...timeSiteLines(plan.needs.heartbeat.timeSites.filter((site) => ticked.has(site.definition))),
119
+ ...spawnSiteLines(plan.needs.heartbeat.spawnSites.filter((site) => ticked.has(site.definition))),
120
+ `${DETAIL}scheduled function ${heartbeat.name} on ${heartbeat.schedule}`,
121
+ ...(heartbeat.definitions.length === 0
122
+ ? []
123
+ : [`${REASON}ticks instances of ${heartbeat.definitions.join(', ')}`]),
124
+ ...clockStartLines(heartbeat),
125
+ `${REASON}plan cadence: every minute on Enterprise, hourly on Growth, daily on Free` +
126
+ ` (https://www.sanity.io/docs/functions/functions-introduction)`,
127
+ ];
128
+ }
129
+ function clockStartLines(heartbeat) {
130
+ const { clockStarts } = heartbeat;
131
+ if (clockStarts.length === 0)
132
+ return [];
133
+ return [
134
+ ...clockStarts.map((start) => `${REASON}starts ${start.definition} on documents in ${watchedLabel(start.resource)}` +
135
+ ' whose start filter has come true, with no write'),
136
+ `${REASON}after the deploy: starts every document the filter already admits that no` +
137
+ ' instance holds, not only those that become eligible later, a share per run',
138
+ ...windowLines(heartbeat.clockStartWindow),
139
+ `${REASON}cost: up to ${heartbeat.clockStartQueries.total} queries on every run,` +
140
+ ` ${heartbeat.clockStartQueries.workflowResource} of them to the workflow resource`,
141
+ ];
142
+ }
143
+ function windowLines(window) {
144
+ if (window === undefined)
145
+ return [];
146
+ return [
147
+ `${REASON}outside the workflow resource each run checks ${window} matching documents,` +
148
+ ` held ones included: with n matching, a run every minute checks every window within` +
149
+ ` 2 * ceil(n / ${window}) - 1 runs`,
150
+ ];
151
+ }
152
+ function heartbeatSentence(heartbeat) {
153
+ const [first, ...rest] = heartbeat.reasons;
154
+ const more = rest.map((reason) => `, and ${reason}`).join('');
155
+ return `a scheduled function ${first} each minute, subject to plan cadence${more}`;
156
+ }
157
+ function timeSiteLines(sites) {
158
+ return sites.map((site) => `${REASON}${site.definition} · ${site.stage ?? 'definition'} · ${site.address.kind} · ` +
159
+ site.condition);
160
+ }
161
+ function spawnSiteLines(sites) {
162
+ return sites.map((site) => `${REASON}${site.definition} · ${site.stage} · ${site.activity} · ${site.action} spawns ` +
163
+ site.spawn.definition.name);
164
+ }
165
+ function watcherLines(emission) {
166
+ if (emission.startWatchers.length === 0)
167
+ return [];
168
+ const started = [
169
+ ...new Set(emission.startWatchers.flatMap((watcher) => watcher.definitions)),
170
+ ].toSorted();
171
+ return [
172
+ ` autonomous starts: ${started.length} definition(s) — ${started.join(', ')}`,
173
+ ...emission.startWatchers.flatMap((watcher) => [
174
+ `${DETAIL}start watcher ${watcher.name} on ${watchedLabel(watcher.resource)}` +
175
+ ` — ${watcher.definitions.join(', ')}`,
176
+ ...watcherReasonLines(watcher.updates),
177
+ ]),
178
+ ];
179
+ }
180
+ function watchedLabel(resource) {
181
+ return directoryProjectId(resource) === undefined
182
+ ? `${resourceLabel(resource.type)} ${resource.id}`
183
+ : resource.id;
184
+ }
185
+ function organizationAccessLines(emission) {
186
+ if (emission === undefined)
187
+ return [];
188
+ const watched = emission.startWatchers.map((watcher) => watcher.resource);
189
+ const { ids, labels } = outsideProjects([emission.workflowResource, ...watched]);
190
+ if (ids.length === 0)
191
+ return [];
192
+ const store = emission.workflowResource.id;
193
+ const read = ids.filter((id) => id !== store);
194
+ const access = [
195
+ ...(ids.includes(store) ? [`read and write ${store}`] : []),
196
+ ...(read.length === 0 ? [] : [`read ${read.join(', ')}`]),
197
+ ].join(', and ');
198
+ const robots = [emission.robotName, ...(emission.heartbeat ? [emission.heartbeat.robotName] : [])];
199
+ return [
200
+ ` ${logSymbols.warning} ${robots.join(' and ')} must ${access}, and so` +
201
+ ` must the identity that deploys the project stack: confirm their ${labels.join(' and ')}` +
202
+ ` access in the organization that owns the library, or the deploy or every start there fails`,
203
+ ];
204
+ }
205
+ function clockStartAccessLines(emission) {
206
+ const heartbeat = emission?.heartbeat;
207
+ if (emission === undefined || heartbeat === undefined)
208
+ return [];
209
+ const named = new Set([emission.workflowResource, ...emission.startWatchers.map((watcher) => watcher.resource)].map((resource) => resource.id));
210
+ const { ids, labels } = outsideProjects(heartbeat.clockStarts
211
+ .map((start) => start.resource)
212
+ .filter((resource) => !named.has(resource.id)));
213
+ if (ids.length === 0)
214
+ return [];
215
+ return [
216
+ ` ${logSymbols.warning} ${heartbeat.robotName} must read ${ids.join(', ')} for its` +
217
+ ` clock starts: confirm its ${labels.join(' and ')} access in the organization that owns` +
218
+ ` the library, or every clock start there fails`,
219
+ ];
220
+ }
221
+ function outsideProjects(resources) {
222
+ const outside = resources.filter((resource) => directoryProjectId(resource) === undefined);
223
+ return {
224
+ ids: [...new Set(outside.map((resource) => resource.id))],
225
+ labels: [...new Set(outside.map((resource) => resourceLabel(resource.type)))],
226
+ };
227
+ }
228
+ function heartbeatProjectReadLines(heartbeat) {
229
+ if (heartbeat === undefined || directoryProjectId(heartbeat.workflowResource) !== undefined) {
230
+ return [];
231
+ }
232
+ const datasets = heartbeat.aliasResources
233
+ .filter((resource) => directoryProjectId(resource) !== undefined)
234
+ .map((resource) => resource.id);
235
+ if (datasets.length === 0)
236
+ return [];
237
+ const clocked = heartbeat.clockStarts.some((start) => datasets.includes(start.resource.id));
238
+ return [
239
+ ` ${logSymbols.warning} ${heartbeat.robotName} holds no project role, so it cannot read` +
240
+ ` ${datasets.join(', ')}: a scheduled drain or tick whose effect or condition reads` +
241
+ ` that alias fails${clocked ? ', and so does every clock start there' : ''}`,
242
+ ];
243
+ }
244
+ function watcherReasonLines(updates) {
245
+ if (updates.kind === 'noUpdate') {
246
+ return [
247
+ `${REASON}starts a document when it is created; one that existed before this` +
248
+ ` watcher deployed starts only when you start it (sanity-workflows start)`,
249
+ ];
250
+ }
251
+ if (updates.kind === 'risingEdge') {
252
+ return [
253
+ `${REASON}starts a document on the write that makes its start filter true;` +
254
+ ` a write that keeps it true starts nothing`,
255
+ ];
256
+ }
257
+ return [];
258
+ }
259
+ const EVERY_WRITE_REMEDY = {
260
+ readsOtherDocuments: 'move the cross-document condition into a stage',
261
+ readsNow: 'move the time condition into a stage',
262
+ readsVariable: 'move the $tag or $definition condition into a stage',
263
+ notBoolean: 'rewrite it as a boolean expression (comparisons, &&, ||, !, defined(), references()),' +
264
+ ' such as count(tags) > 0',
265
+ };
266
+ function warningLines(plan) {
267
+ return [
268
+ ...plan.anyTypeSubjects.map((name) => ` ${logSymbols.warning} ${name} declares a subject with no types, so a write to any` +
269
+ ` document type invokes its watcher — declare types unless that is intended`),
270
+ ...organizationAccessLines(plan.emission),
271
+ ...clockStartAccessLines(plan.emission),
272
+ ...heartbeatProjectReadLines(plan.emission?.heartbeat),
273
+ ...plan.everyWriteStartFilters.map(({ definition, reason }) => ` ${logSymbols.warning} ${definition} has a start filter that ${everyUpdateCause[reason]},` +
274
+ ` so every matching write starts it and a later matching write can start another` +
275
+ ` instance for the same document — ${EVERY_WRITE_REMEDY[reason]}`),
276
+ ...plan.unclockedStartFilters.map((name) => ` ${logSymbols.warning} ${name} has a start filter that reads $now, but the heartbeat` +
277
+ ` does not start it on the clock: the filter also reads another document or is not a` +
278
+ ` boolean expression, its subject is not taken from the started document, or its` +
279
+ ` start.roles admit no role the heartbeat robot holds, so a document the filter admits` +
280
+ ` by time alone starts only on a later write`),
281
+ ...plan.subjectlessDefinitions.map((name) => ` ${logSymbols.warning} ${name} starts autonomously but declares no subject, so no` +
282
+ ` document write can start it and it gets no watcher`),
283
+ ];
284
+ }
@@ -0,0 +1,6 @@
1
+ import { type AppliedWrite, type RuntimeEmissionPlan } from '@sanity/workflows/blueprints/generate';
2
+ export declare function stackDeployLines(args: {
3
+ plan: RuntimeEmissionPlan;
4
+ applied: readonly AppliedWrite[];
5
+ verbose: boolean;
6
+ }): string[];
@@ -0,0 +1,118 @@
1
+ import { FUNCTIONS_DIR, hasDocumentFunctions, HEARTBEAT_BLUEPRINT_PATH, HEARTBEAT_STACK_DIR, scheduledDrains, } from '@sanity/workflows/blueprints/generate';
2
+ import logSymbols from 'log-symbols';
3
+ import { sectionHeader } from './ui.js';
4
+ const DEPLOY_COMMAND = 'npx sanity@latest blueprints deploy';
5
+ function heartbeatStackWrites(args) {
6
+ const functionDirs = args.plan.deployments.flatMap(({ emission }) => emission?.heartbeat === undefined
7
+ ? []
8
+ : [emission.heartbeat.name, ...scheduledDrains(emission).map((drain) => drain.name)].map((name) => `${FUNCTIONS_DIR}/${name}/`));
9
+ return args.applied.filter((write) => write.path.startsWith(`${HEARTBEAT_STACK_DIR}/`) ||
10
+ functionDirs.some((dir) => write.path.startsWith(dir)));
11
+ }
12
+ export function stackDeployLines(args) {
13
+ const lines = [
14
+ ...projectStackLines(args.plan),
15
+ ...heartbeatStackLines({ ...args, heartbeat: heartbeatStackWrites(args) }),
16
+ ];
17
+ return lines.length === 0 ? [] : [sectionHeader('Deploy'), ...lines];
18
+ }
19
+ const changedWrites = (writes) => writes.filter((write) => write.status !== 'unchanged');
20
+ function projectStackLines(plan) {
21
+ const projectStack = plan.deployments.some(({ emission }) => emission !== undefined && hasDocumentFunctions(emission));
22
+ if (!projectStack)
23
+ return [];
24
+ return [
25
+ ` project stack: \`${DEPLOY_COMMAND}\` here, with a token that can deploy to the` +
26
+ ` project. It holds every document function; redeploy it after any definition change.`,
27
+ ];
28
+ }
29
+ function heartbeatStackLines(args) {
30
+ const { heartbeat, verbose } = args;
31
+ if (heartbeat.length === 0)
32
+ return [];
33
+ const changed = changedWrites(heartbeat);
34
+ const created = changed.some((write) => write.path === HEARTBEAT_BLUEPRINT_PATH && write.status === 'created');
35
+ const drains = hasScheduledDrains(args.plan);
36
+ if (!verbose && !drains && changed.length === 0)
37
+ return [];
38
+ const redeploy = created ? [] : redeployLines({ changed, drains });
39
+ return [
40
+ ` heartbeat stack: \`${DEPLOY_COMMAND}\` in ${HEARTBEAT_STACK_DIR}/, with an` +
41
+ ` organization deploy token. It holds ${heartbeatStackHolds(drains)}.`,
42
+ ...redeploy,
43
+ ...(verbose || created ? missingHeartbeatLines(args.plan) : []),
44
+ ];
45
+ }
46
+ function redeployLines(args) {
47
+ if (args.drains && args.changed.length === 0)
48
+ return [];
49
+ return [heartbeatRedeployLine(args.changed)];
50
+ }
51
+ function hasScheduledDrains(plan) {
52
+ return plan.deployments.some(({ emission }) => emission !== undefined && scheduledDrains(emission).length > 0);
53
+ }
54
+ function heartbeatStackHolds(drains) {
55
+ if (!drains)
56
+ return 'only the scheduled heartbeat';
57
+ return ('the scheduled heartbeat and the scheduled drains, which bundle your effect handlers;' +
58
+ ' redeploy it after any handler or definition change and after upgrading the Workflows packages');
59
+ }
60
+ function heartbeatRedeployLine(changed) {
61
+ if (changed.length === 0) {
62
+ return (` ${logSymbols.info} the heartbeat stack's files are unchanged: these definitions need no` +
63
+ ` heartbeat redeploy. Redeploy both stacks after upgrading the Workflows packages.`);
64
+ }
65
+ return (` ${logSymbols.warning} ${changed.map((write) => write.path).join(', ')} changed: if you` +
66
+ ` have deployed the heartbeat stack, redeploy it with the organization deploy token.`);
67
+ }
68
+ function missingHeartbeatLines(plan) {
69
+ const waiting = plan.deployments.flatMap(waitingWithoutHeartbeat);
70
+ if (waiting.length === 0)
71
+ return [];
72
+ return [
73
+ ` ${logSymbols.warning} Without the heartbeat stack nothing checks these on a schedule, and nothing reports it:`,
74
+ ...waiting.map((line) => ` ${line}`),
75
+ ];
76
+ }
77
+ function waitingWithoutHeartbeat(plan) {
78
+ const { emission } = plan;
79
+ const heartbeat = emission?.heartbeat;
80
+ if (emission === undefined || heartbeat === undefined)
81
+ return [];
82
+ const ticked = new Set(heartbeat.definitions);
83
+ const within = (sites) => [
84
+ ...new Set(sites.map((site) => site.definition).filter((name) => ticked.has(name))),
85
+ ];
86
+ const deadlines = within(plan.needs.heartbeat.timeSites);
87
+ const spawners = within(plan.needs.heartbeat.spawnSites);
88
+ const scheduled = scheduledDrains(emission).flatMap((drain) => drain.effectNames);
89
+ const effects = plan.hosting.effects.function.filter((name) => !scheduled.includes(name));
90
+ const clocked = [...new Set(heartbeat.clockStarts.map((start) => start.definition))];
91
+ return [
92
+ ...(scheduled.length === 0
93
+ ? []
94
+ : [`no effect runs at all, because its drain runs from this stack: ${scheduled.join(', ')}`]),
95
+ ...(deadlines.length === 0
96
+ ? []
97
+ : [
98
+ `$now deadlines take effect only when another engine call evaluates them in ${deadlines.join(', ')}`,
99
+ ]),
100
+ ...(spawners.length === 0
101
+ ? []
102
+ : [
103
+ `a parent that missed a child settling waits for another engine call in ${spawners.join(', ')}`,
104
+ ]),
105
+ ...(effects.length === 0
106
+ ? []
107
+ : [
108
+ `an effect queued before its drain existed, or whose drain timed out, waits until` +
109
+ ` a later drain picks it up: ${effects.join(', ')}`,
110
+ ]),
111
+ ...(clocked.length === 0
112
+ ? []
113
+ : [
114
+ `a document whose start filter comes true by time alone starts only on a later write,` +
115
+ ` or never in a Media Library: ${clocked.join(', ')}`,
116
+ ]),
117
+ ];
118
+ }
@@ -0,0 +1,9 @@
1
+ import { type Diagnosis, type MissingDocument, type StuckCause, type SuggestedRemediation } from '@sanity/workflows';
2
+ export declare function stuckHeadline(cause: StuckCause): string;
3
+ export interface InstanceDiagnostic {
4
+ diagnosis: Diagnosis;
5
+ /** Full evaluation evidence, including references outside the blocking subset. */
6
+ allMissingDocuments?: MissingDocument[] | undefined;
7
+ remediations: SuggestedRemediation[];
8
+ }
9
+ export declare function stuckDiagnosisLines({ diagnosis, allMissingDocuments, remediations, }: InstanceDiagnostic): string[];
@@ -0,0 +1,112 @@
1
+ import { styleText } from 'node:util';
2
+ import { formatDateTime } from '@sanity/cli-core/dates';
3
+ import { _additionalMissingDocuments, _fieldTargetLabel, _missingDocumentsSummary, } from '@sanity/workflows';
4
+ import logSymbols from 'log-symbols';
5
+ import { sectionHeader } from './ui.js';
6
+ function missingDocumentsDetail(documents) {
7
+ return {
8
+ headline: 'referenced document missing',
9
+ why: [
10
+ ...documents.map(({ target, reference }) => `${_fieldTargetLabel(target)}: ${reference.id}`),
11
+ _missingDocumentsSummary(documents),
12
+ ],
13
+ };
14
+ }
15
+ function additionalDocumentLines(diagnosis, allMissingDocuments) {
16
+ const documents = _additionalMissingDocuments(diagnosis, allMissingDocuments);
17
+ if (documents.length === 0)
18
+ return [];
19
+ return ['', sectionHeader('Missing references'), ...missingDocumentsDetail(documents).why];
20
+ }
21
+ function failedEffectDetail(effect) {
22
+ const ran = effect.durationMs !== undefined ? ` (after ${effect.durationMs}ms)` : '';
23
+ return {
24
+ headline: `a failed effect from action '${effect.origin.name}' is blocking its activity`,
25
+ why: [
26
+ styleText('red', `${logSymbols.error} failed effect: ${effect.name}`),
27
+ ` queued by action '${effect.origin.name}', failed ${formatDateTime(effect.ranAt)}${ran}`,
28
+ ...(effect.error !== undefined ? [` error: ${effect.error.message}`] : []),
29
+ '',
30
+ `The activity that fired '${effect.origin.name}' is waiting on this effect. It failed`,
31
+ `against an external system, so the activity never resolves and the stage can't advance.`,
32
+ ],
33
+ };
34
+ }
35
+ function hungEffectDetail(effect) {
36
+ return {
37
+ headline: `effect '${effect.name}' was claimed but never completed`,
38
+ why: [
39
+ styleText('yellow', `${logSymbols.warning} hung effect: ${effect.name}`),
40
+ ` claimed ${formatDateTime(effect.claim?.claimedAt ?? '?')} but never reported back — the`,
41
+ ` drainer likely died mid-dispatch, so it won't drain on its own.`,
42
+ ],
43
+ };
44
+ }
45
+ function failedActivityDetail(activity) {
46
+ return {
47
+ headline: `activity '${activity}' failed`,
48
+ why: [
49
+ styleText('red', `${logSymbols.error} activity '${activity}' is in a terminal failed state.`),
50
+ `Any exit transition gated on '${activity}' being done can never fire.`,
51
+ ],
52
+ };
53
+ }
54
+ function noTransitionDetail() {
55
+ return {
56
+ headline: `no exit transition's trigger is satisfied`,
57
+ why: [
58
+ `${logSymbols.info} every activity is resolved, but no exit transition's \`when\` is true.`,
59
+ `Likely a routing state value a trigger reads never got written.`,
60
+ ],
61
+ };
62
+ }
63
+ function transitionUnevaluableDetail(transitions) {
64
+ return {
65
+ headline: `an exit transition's trigger could not be evaluated`,
66
+ why: [
67
+ `${logSymbols.info} every activity is resolved, but ${transitions.join(', ')} reads an operand`,
68
+ `that is missing or unreadable (GROQ null), so routing is held rather than`,
69
+ `falling through. Make the data the trigger reads readable — publish the`,
70
+ `subject (or fill the field) — and the next tick or commit re-checks the`,
71
+ `transitions; the instance advances only if one is then satisfied. No`,
72
+ `remediation verb fixes this.`,
73
+ ],
74
+ };
75
+ }
76
+ function remediationLines(remediations) {
77
+ return remediations.map((r) => ` • ${r.verb} — ${r.rationale}`);
78
+ }
79
+ function causeDetail(cause) {
80
+ switch (cause.kind) {
81
+ case 'document-missing':
82
+ return missingDocumentsDetail(cause.documents);
83
+ case 'failed-effect':
84
+ return failedEffectDetail(cause.effect);
85
+ case 'hung-effect':
86
+ return hungEffectDetail(cause.effect);
87
+ case 'failed-activity':
88
+ return failedActivityDetail(cause.activity);
89
+ case 'no-transition-fires':
90
+ return noTransitionDetail();
91
+ case 'transition-unevaluable':
92
+ return transitionUnevaluableDetail(cause.transitions);
93
+ }
94
+ }
95
+ export function stuckHeadline(cause) {
96
+ return `${logSymbols.warning} ${styleText('yellow', 'STUCK')} — ${causeDetail(cause).headline}`;
97
+ }
98
+ export function stuckDiagnosisLines({ diagnosis, allMissingDocuments, remediations, }) {
99
+ if (diagnosis.state !== 'stuck')
100
+ return [];
101
+ const detail = causeDetail(diagnosis.cause);
102
+ const runnable = remediations.filter((remediation) => remediation.available);
103
+ return [
104
+ '',
105
+ sectionHeader("Why it's stuck"),
106
+ ...detail.why,
107
+ ...additionalDocumentLines(diagnosis, allMissingDocuments),
108
+ ...(runnable.length > 0
109
+ ? ['', sectionHeader('Suggested fix'), ...remediationLines(runnable)]
110
+ : []),
111
+ ];
112
+ }
@@ -0,0 +1,27 @@
1
+ import { type SanityClient } from '@sanity/client';
2
+ import { type WorkflowResource } from '@sanity/workflows';
3
+ /**
4
+ * The API host to hit: an explicit `SANITY_API_HOST` wins; otherwise mirror
5
+ * the Sanity CLI — staging routes to the staging API, prod falls through to
6
+ * `@sanity/client`'s default (`undefined` here). Pairs with
7
+ * {@link resolveToken}, which reads the matching session token. Exported so a
8
+ * destructive command can display the environment its clients will hit.
9
+ */
10
+ export declare function resolveApiHost(): string | undefined;
11
+ /**
12
+ * Resolve the Sanity auth token. An explicit `SANITY_AUTH_TOKEN` wins (CI /
13
+ * scripted use); otherwise fall back to the `sanity login` session token.
14
+ * Throws when neither exists rather than building an unauthenticated client
15
+ * that only 401s once it hits the API.
16
+ */
17
+ export declare function resolveToken(): Promise<string>;
18
+ export declare class AuthMissingError extends Error {
19
+ constructor();
20
+ }
21
+ /** {@link resolveToken}, funnelling the no-token case through the clean
22
+ * {@link failOn} path rather than letting it surface as an oclif stack. */
23
+ export declare function resolveTokenOrFail(): Promise<string>;
24
+ /** Build a client for a workflow resource, authenticated with `token`. */
25
+ export declare function clientFor(resource: WorkflowResource, token: string): SanityClient;
26
+ /** Build a client for the global API host, not bound to any project or resource. */
27
+ export declare function globalClient(token: string): SanityClient;
@@ -0,0 +1,45 @@
1
+ import { getCliToken, isStaging } from '@sanity/cli-core';
2
+ import { createClient } from '@sanity/client';
3
+ import { clientConfigFromResource, ENGINE_API_VERSION, } from '@sanity/workflows';
4
+ import { ENV, envAuthToken } from './env.js';
5
+ import { failOn } from './fail.js';
6
+ const API_VERSION = ENGINE_API_VERSION;
7
+ const STAGING_API_HOST = 'https://api.sanity.work';
8
+ export function resolveApiHost() {
9
+ return process.env[ENV.SANITY_API_HOST] ?? (isStaging() ? STAGING_API_HOST : undefined);
10
+ }
11
+ export async function resolveToken() {
12
+ const fromEnv = envAuthToken();
13
+ if (fromEnv !== undefined) {
14
+ return fromEnv;
15
+ }
16
+ const fromSession = await getCliToken();
17
+ if (fromSession) {
18
+ return fromSession;
19
+ }
20
+ throw new AuthMissingError();
21
+ }
22
+ export class AuthMissingError extends Error {
23
+ constructor() {
24
+ super('No Sanity token found — run `sanity login`, or set SANITY_AUTH_TOKEN.');
25
+ }
26
+ }
27
+ export async function resolveTokenOrFail() {
28
+ return resolveToken().catch((err) => failOn(err, 'Authentication required:'));
29
+ }
30
+ function baseClientConfig(token) {
31
+ const apiHost = resolveApiHost();
32
+ return {
33
+ token,
34
+ apiVersion: API_VERSION,
35
+ useCdn: false,
36
+ requestTagPrefix: 'sanity.workflows.cli',
37
+ ...(apiHost ? { apiHost } : {}),
38
+ };
39
+ }
40
+ export function clientFor(resource, token) {
41
+ return createClient({ ...baseClientConfig(token), ...clientConfigFromResource(resource) });
42
+ }
43
+ export function globalClient(token) {
44
+ return createClient({ ...baseClientConfig(token), useProjectHostname: false });
45
+ }
@@ -0,0 +1,17 @@
1
+ export interface Span {
2
+ start: number;
3
+ end: number;
4
+ }
5
+ export interface AstNode extends Span {
6
+ type: string;
7
+ [key: string]: unknown;
8
+ }
9
+ /** Replaces `start`..`end` (UTF-16 offsets) of the original source. */
10
+ export interface Edit extends Span {
11
+ text: string;
12
+ }
13
+ export declare function isNode(value: unknown): value is AstNode;
14
+ /** Child nodes, each with the key that holds it. */
15
+ export declare function childEntries(node: AstNode): Array<[string, AstNode]>;
16
+ /** `edits` must not overlap. */
17
+ export declare function applyEdits(source: string, edits: readonly Edit[]): string;
@@ -0,0 +1,14 @@
1
+ export function isNode(value) {
2
+ return (typeof value === 'object' && value !== null && typeof Reflect.get(value, 'type') === 'string');
3
+ }
4
+ export function childEntries(node) {
5
+ return Object.entries(node)
6
+ .filter(([key]) => key !== 'parent')
7
+ .flatMap(([key, value]) => (Array.isArray(value) ? value : [value]).map((child) => [key, child]))
8
+ .filter((entry) => isNode(entry[1]));
9
+ }
10
+ export function applyEdits(source, edits) {
11
+ return edits
12
+ .toSorted((a, b) => b.start - a.start)
13
+ .reduce((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), source);
14
+ }
@@ -0,0 +1,19 @@
1
+ import { type AstNode, type Edit, type Span } from './ast.ts';
2
+ export type RenameReportKind = 'shadowed-rename' | 'shadowed-namespace';
3
+ /** A rename aliased or skipped because the file reuses a name. */
4
+ export interface RenameReport extends Span {
5
+ kind: RenameReportKind;
6
+ text: string;
7
+ }
8
+ export interface ExportRenameResult {
9
+ edits: Edit[];
10
+ reports: RenameReport[];
11
+ }
12
+ /**
13
+ * Renames imports of renamed exports and every reference to them. An import
14
+ * whose new name the file already imports from the same entry merges into that
15
+ * import. If the file binds the old or new name otherwise, the import is
16
+ * aliased instead; if it reuses a namespace name, that namespace's members are
17
+ * reported for a hand rename.
18
+ */
19
+ export declare function renameExports(program: AstNode, source: string): ExportRenameResult;