@sanity/workflows-cli 0.0.0-stage → 0.0.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 (126) hide show
  1. package/CHANGELOG.md +1574 -0
  2. package/LICENSE +21 -0
  3. package/README.md +797 -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 +51 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +65 -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 +52 -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 +78 -0
  30. package/dist/commands/workflows/list.js +248 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +176 -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 +29 -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 +23 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +15 -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 +9 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +28 -0
  48. package/dist/hooks/prerun/telemetry.js +37 -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 +34 -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 +205 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +88 -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 +24 -0
  62. package/dist/lib/client.js +40 -0
  63. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  64. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  65. package/dist/lib/codemod/package-map.d.ts +22 -0
  66. package/dist/lib/codemod/package-map.js +72 -0
  67. package/dist/lib/codemod/report.d.ts +5 -0
  68. package/dist/lib/codemod/report.js +43 -0
  69. package/dist/lib/codemod/run.d.ts +23 -0
  70. package/dist/lib/codemod/run.js +103 -0
  71. package/dist/lib/codemod/source-rewrite.d.ts +18 -0
  72. package/dist/lib/codemod/source-rewrite.js +155 -0
  73. package/dist/lib/command-context.d.ts +20 -0
  74. package/dist/lib/command-context.js +24 -0
  75. package/dist/lib/command-telemetry.d.ts +54 -0
  76. package/dist/lib/command-telemetry.js +82 -0
  77. package/dist/lib/context.d.ts +155 -0
  78. package/dist/lib/context.js +268 -0
  79. package/dist/lib/default-partition.d.ts +23 -0
  80. package/dist/lib/default-partition.js +48 -0
  81. package/dist/lib/definition-files.d.ts +11 -0
  82. package/dist/lib/definition-files.js +58 -0
  83. package/dist/lib/definitions.d.ts +63 -0
  84. package/dist/lib/definitions.js +84 -0
  85. package/dist/lib/diff.d.ts +12 -0
  86. package/dist/lib/diff.js +93 -0
  87. package/dist/lib/env.d.ts +7 -0
  88. package/dist/lib/env.js +8 -0
  89. package/dist/lib/fail.d.ts +29 -0
  90. package/dist/lib/fail.js +46 -0
  91. package/dist/lib/flags.d.ts +49 -0
  92. package/dist/lib/flags.js +117 -0
  93. package/dist/lib/follow-up-command.d.ts +18 -0
  94. package/dist/lib/follow-up-command.js +12 -0
  95. package/dist/lib/history-rows.d.ts +3 -0
  96. package/dist/lib/history-rows.js +44 -0
  97. package/dist/lib/load-config.d.ts +46 -0
  98. package/dist/lib/load-config.js +110 -0
  99. package/dist/lib/nuke.d.ts +124 -0
  100. package/dist/lib/nuke.js +206 -0
  101. package/dist/lib/operation-args.d.ts +42 -0
  102. package/dist/lib/operation-args.js +21 -0
  103. package/dist/lib/ops-report.d.ts +47 -0
  104. package/dist/lib/ops-report.js +31 -0
  105. package/dist/lib/params.d.ts +3 -0
  106. package/dist/lib/params.js +21 -0
  107. package/dist/lib/pick-dataset.d.ts +10 -0
  108. package/dist/lib/pick-dataset.js +30 -0
  109. package/dist/lib/prompt.d.ts +35 -0
  110. package/dist/lib/prompt.js +11 -0
  111. package/dist/lib/read-fanout.d.ts +45 -0
  112. package/dist/lib/read-fanout.js +44 -0
  113. package/dist/lib/select-deployment.d.ts +31 -0
  114. package/dist/lib/select-deployment.js +91 -0
  115. package/dist/lib/share-definitions.d.ts +101 -0
  116. package/dist/lib/share-definitions.js +188 -0
  117. package/dist/lib/telemetry-setup.d.ts +81 -0
  118. package/dist/lib/telemetry-setup.js +111 -0
  119. package/dist/lib/telemetry.d.ts +78 -0
  120. package/dist/lib/telemetry.js +90 -0
  121. package/dist/lib/ui.d.ts +91 -0
  122. package/dist/lib/ui.js +116 -0
  123. package/dist/standalone-argv.d.ts +14 -0
  124. package/dist/standalone-argv.js +57 -0
  125. package/oclif.manifest.json +1731 -0
  126. package/package.json +118 -3
@@ -0,0 +1,65 @@
1
+ import { type DeployedDefinition, type WorkflowDefinition } from '@sanity/workflows';
2
+ import { WorkflowCommand } from '../../../lib/base-command.ts';
3
+ import { type Ambiguity, type ChooseCandidate, type ReadTarget } from '../../../lib/context.ts';
4
+ export default class DefinitionShow extends WorkflowCommand {
5
+ static hiddenAliases: string[];
6
+ static description: string;
7
+ static args: {
8
+ name: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
9
+ };
10
+ static flags: {
11
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ dataset: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ 'media-library-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
15
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
18
+ version: import("@oclif/core/interfaces").OptionFlag<number | undefined, import("@oclif/core/interfaces").CustomOptions>;
19
+ };
20
+ run(): Promise<void>;
21
+ }
22
+ type DefinitionCandidate = ReadTarget & {
23
+ partition: string;
24
+ };
25
+ /**
26
+ * The definition `name` resolves to across `targets`. Without `partition`,
27
+ * every partition holding the name is a candidate, so a name deployed to
28
+ * several partitions or resources goes through {@link soleHitOrChoose}
29
+ * rather than showing the highest version from an environment the caller did
30
+ * not mean.
31
+ */
32
+ export declare function resolveShownDefinition({ targets, name, partition, version, ambiguity, choose, }: {
33
+ targets: ReadTarget[];
34
+ name: string;
35
+ partition: string | undefined;
36
+ version: number | undefined;
37
+ ambiguity: Ambiguity;
38
+ choose?: ChooseCandidate;
39
+ }): Promise<DeployedDefinition | undefined>;
40
+ /** How a lookup names the version it asked for: `vN` for a pinned
41
+ * `--version`, `latest` when unpinned. */
42
+ export declare function versionLabel(version: number | undefined): string;
43
+ /**
44
+ * The deployed document each candidate holds under the name: the authored
45
+ * {@link WorkflowDefinition} plus the deploy-stamped envelope (`version`,
46
+ * `contentHash`, `tag`). A probe failure propagates — with an unreadable
47
+ * resource, "which dataset holds this name" is unanswerable, unlike an
48
+ * instance-id lookup where any hit IS the instance.
49
+ */
50
+ export declare function fetchDefinitionHits({ candidates, name, version, }: {
51
+ candidates: DefinitionCandidate[];
52
+ name: string;
53
+ version: number | undefined;
54
+ }): Promise<(DefinitionCandidate & {
55
+ def: DeployedDefinition;
56
+ })[]>;
57
+ export declare function definitionHeader(def: WorkflowDefinition & {
58
+ version: number;
59
+ }, partition?: string): string;
60
+ /**
61
+ * The body lines for `definitions show`: every stage with its activities and each
62
+ * activity's actions. Pure so it can be asserted without driving the oclif command.
63
+ */
64
+ export declare function describeDefinition(def: WorkflowDefinition): string[];
65
+ export {};
@@ -0,0 +1,129 @@
1
+ import { styleText } from 'node:util';
2
+ import { Args, Flags } from '@oclif/core';
3
+ import { assertReadableModel, isTerminalStage, } from '@sanity/workflows';
4
+ import { WorkflowCommand } from '../../../lib/base-command.js';
5
+ import { ambiguityFor, resolveReadTargets, soleHitOrChoose, } from '../../../lib/context.js';
6
+ import { buildDefinitionShowQuery, buildDefinitionPartitionsQuery } from '../../../lib/definitions.js';
7
+ import { fail } from '../../../lib/fail.js';
8
+ import { jsonFlags, readFlags, resourceFlags } from '../../../lib/flags.js';
9
+ import { formatKeyValue, searchedScope, sectionHeader } from '../../../lib/ui.js';
10
+ export default class DefinitionShow extends WorkflowCommand {
11
+ static hiddenAliases = ['workflows:definition:show'];
12
+ static description = 'Show a deployed workflow definition.';
13
+ static args = {
14
+ name: Args.string({ required: true, description: 'Workflow definition name.' }),
15
+ };
16
+ static flags = {
17
+ ...readFlags,
18
+ ...resourceFlags,
19
+ version: Flags.integer({ description: 'Specific version (default: latest).' }),
20
+ ...jsonFlags,
21
+ };
22
+ async run() {
23
+ const { args, flags } = await this.parse(DefinitionShow);
24
+ const { targets, partition } = await resolveReadTargets(flags);
25
+ const def = await resolveShownDefinition({
26
+ targets,
27
+ name: args.name,
28
+ partition,
29
+ version: flags.version,
30
+ ambiguity: ambiguityFor(flags),
31
+ });
32
+ if (!def) {
33
+ const scope = searchedScope({
34
+ partition,
35
+ resources: targets.map(({ resource }) => resource),
36
+ deployment: flags.deployment,
37
+ });
38
+ fail(`no definition "${args.name}" (${versionLabel(flags.version)}) ${scope}`);
39
+ }
40
+ if (flags.json) {
41
+ this.log(JSON.stringify(def, null, 2));
42
+ return;
43
+ }
44
+ this.log(definitionHeader(def, def.tag));
45
+ this.log('');
46
+ for (const line of describeDefinition(def)) {
47
+ this.log(line);
48
+ }
49
+ }
50
+ }
51
+ export async function resolveShownDefinition({ targets, name, partition, version, ambiguity, choose, }) {
52
+ const candidates = partition === undefined
53
+ ? await partitionCandidates({ targets, name })
54
+ : targets.map((target) => ({ ...target, partition }));
55
+ const hits = await fetchDefinitionHits({ candidates, name, version });
56
+ const sole = await soleHitOrChoose(hits, {
57
+ subject: `Definition "${name}"`,
58
+ partitionOf: (hit) => hit.partition,
59
+ ambiguity,
60
+ ...(choose === undefined ? {} : { choose }),
61
+ });
62
+ return sole?.def;
63
+ }
64
+ export function versionLabel(version) {
65
+ return version === undefined ? 'latest' : `v${version}`;
66
+ }
67
+ async function partitionCandidates({ targets, name, }) {
68
+ const { groq, params } = buildDefinitionPartitionsQuery(name);
69
+ const perTarget = await Promise.all(targets.map(async (target) => {
70
+ const partitions = await target.client.fetch(groq, params, {
71
+ tag: 'definition.show',
72
+ });
73
+ return partitions.map((held) => ({ ...target, partition: held }));
74
+ }));
75
+ return perTarget.flat();
76
+ }
77
+ export async function fetchDefinitionHits({ candidates, name, version, }) {
78
+ const probes = await Promise.all(candidates.map(async (candidate) => {
79
+ const { groq, params } = buildDefinitionShowQuery({
80
+ name,
81
+ partition: candidate.partition,
82
+ version,
83
+ });
84
+ const def = await candidate.client.fetch(groq, params, {
85
+ tag: 'definition.show',
86
+ });
87
+ return def === null ? undefined : { ...candidate, def: assertReadableModel(def) };
88
+ }));
89
+ return probes.filter((hit) => hit !== undefined);
90
+ }
91
+ const HEADER_PAD = 11;
92
+ export function definitionHeader(def, partition) {
93
+ const rows = [
94
+ formatKeyValue({ key: 'Title', value: def.title, padTo: HEADER_PAD }),
95
+ formatKeyValue({
96
+ key: 'Description',
97
+ value: def.description ?? styleText('dim', '—'),
98
+ padTo: HEADER_PAD,
99
+ }),
100
+ ];
101
+ if (partition !== undefined) {
102
+ rows.push(formatKeyValue({ key: 'Partition', value: partition, padTo: HEADER_PAD }));
103
+ }
104
+ return [styleText('bold', `${def.name} v${def.version}`), ...rows].join('\n');
105
+ }
106
+ function actionLine(action) {
107
+ const statusOp = (action.ops ?? []).find((op) => op.type === 'status.set');
108
+ const status = statusOp ? styleText('dim', ` → ${statusOp.status}`) : '';
109
+ return ` · ${action.name}${status}`;
110
+ }
111
+ function activityBlock(activity) {
112
+ const title = activity.title ? styleText('dim', ` — ${activity.title}`) : '';
113
+ return [` - ${activity.name}${title}`, ...(activity.actions ?? []).map(actionLine)];
114
+ }
115
+ function stageBlock(stage, initialStage) {
116
+ const title = stage.title ? styleText('dim', ` — ${stage.title}`) : '';
117
+ const terminal = isTerminalStage(stage) ? styleText('dim', ' (terminal)') : '';
118
+ const initial = stage.name === initialStage ? styleText('cyan', ' [initial]') : '';
119
+ return [
120
+ ` • ${stage.name}${title}${terminal}${initial}`,
121
+ ...(stage.activities ?? []).flatMap(activityBlock),
122
+ ];
123
+ }
124
+ export function describeDefinition(def) {
125
+ return [
126
+ sectionHeader('Stages'),
127
+ ...def.stages.flatMap((stage) => stageBlock(stage, def.initialStage)),
128
+ ];
129
+ }
@@ -0,0 +1,14 @@
1
+ import { WorkflowCommand } from '../../../lib/base-command.ts';
2
+ export default class DefinitionValidate extends WorkflowCommand {
3
+ static hiddenAliases: string[];
4
+ static description: string;
5
+ static examples: string[];
6
+ static strict: boolean;
7
+ static args: {
8
+ file: import("@oclif/core/interfaces").Arg<string, Record<string, unknown>>;
9
+ };
10
+ static flags: {
11
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
+ };
13
+ run(): Promise<void>;
14
+ }
@@ -0,0 +1,50 @@
1
+ import { Args } from '@oclif/core';
2
+ import { errorMessage, validateDefinitionInputs } from '@sanity/workflows';
3
+ import logSymbols from 'log-symbols';
4
+ import { WorkflowCommand } from '../../../lib/base-command.js';
5
+ import { describeValidation, readDefinitionFiles } from '../../../lib/definition-files.js';
6
+ import { fail } from '../../../lib/fail.js';
7
+ import { jsonFlags } from '../../../lib/flags.js';
8
+ export default class DefinitionValidate extends WorkflowCommand {
9
+ static hiddenAliases = ['workflows:definition:validate'];
10
+ static description = 'Validate workflow definitions in JSON files without a config, login, or network access. Checks shape, cross-field rules, and GROQ syntax; deploy additionally checks duplicate names, spawn dependencies, resource bindings, project roles, and the reader-model acknowledgement. Exits non-zero when any definition is invalid. A file that cannot be read, is not valid JSON, or does not hold definition objects stops the command with an error message instead of a report, including with --json.';
11
+ static examples = [
12
+ '<%= config.bin %> workflows definitions validate review.json',
13
+ '<%= config.bin %> workflows definitions validate parent.json child.json',
14
+ '<%= config.bin %> workflows definitions validate review.json --json',
15
+ ];
16
+ static strict = false;
17
+ static args = {
18
+ file: Args.string({
19
+ required: true,
20
+ description: 'JSON file holding one definition or an array of them. Pass several files to validate a parent and its child workflows together.',
21
+ }),
22
+ };
23
+ static flags = { ...jsonFlags };
24
+ async run() {
25
+ const { argv, flags } = await this.parse(DefinitionValidate);
26
+ const paths = argv.map(String);
27
+ let entries;
28
+ try {
29
+ entries = await readDefinitionFiles(paths);
30
+ }
31
+ catch (err) {
32
+ fail('Could not read definitions:', errorMessage(err));
33
+ }
34
+ const report = validateDefinitionInputs(entries.map((entry) => entry.definition));
35
+ if (flags.json) {
36
+ this.log(JSON.stringify(report, null, 2));
37
+ if (!report.valid) {
38
+ this.exit(1);
39
+ }
40
+ return;
41
+ }
42
+ const { passed, failed } = describeValidation(entries, report);
43
+ for (const line of passed) {
44
+ this.log(`${logSymbols.success} ${line}`);
45
+ }
46
+ if (failed.length > 0) {
47
+ fail(`${failed.length} of ${entries.length} definitions failed validation:`, failed.join('\n'));
48
+ }
49
+ }
50
+ }
@@ -0,0 +1,117 @@
1
+ import { type AcknowledgedWorkflowDeployment, type DeployDefinitionResult, type WorkflowConfig, type WorkflowDefinition, type WorkflowDeployment } from '@sanity/workflows';
2
+ import { WorkflowCommand } from '../../lib/base-command.ts';
3
+ import { type DeploymentSelectionOptions } from '../../lib/select-deployment.ts';
4
+ /** A deployment paired with the definitions selected + validated for it. */
5
+ interface DeployBatch {
6
+ deployment: WorkflowDeployment;
7
+ defs: WorkflowDefinition[];
8
+ }
9
+ interface AcknowledgedDeployBatch extends DeployBatch {
10
+ deployment: AcknowledgedWorkflowDeployment;
11
+ }
12
+ /** A deployment whose deploy/diff threw, kept for the closing summary. */
13
+ interface DeployFailure {
14
+ deployment: Pick<WorkflowDeployment, 'name' | 'partition'>;
15
+ message: string;
16
+ }
17
+ export default class Deploy extends WorkflowCommand {
18
+ static description: string;
19
+ static examples: string[];
20
+ static flags: {
21
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
22
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
23
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
24
+ 'all-partitions': import("@oclif/core/interfaces").BooleanFlag<boolean>;
25
+ 'dry-run': import("@oclif/core/interfaces").BooleanFlag<boolean>;
26
+ check: import("@oclif/core/interfaces").BooleanFlag<boolean>;
27
+ verbose: import("@oclif/core/interfaces").BooleanFlag<boolean>;
28
+ only: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
29
+ 'share-defs': import("@oclif/core/interfaces").BooleanFlag<boolean>;
30
+ };
31
+ run(): Promise<void>;
32
+ /** Deploy (or diff, for `--dry-run`) one deployment's definitions.
33
+ * Returns the per-definition results for a real deploy; `undefined`
34
+ * for a dry run, which writes nothing. */
35
+ private processDeployment;
36
+ private executeDeploy;
37
+ private runDryRun;
38
+ }
39
+ /** Reject the contradictory `--check --dry-run` combination. */
40
+ export declare function validateModeFlags(check: boolean, dryRun: boolean): void;
41
+ /**
42
+ * The batches a run acts on. The order is load-bearing: gating `--only` before
43
+ * selection is what spares the user an interactive deployment picker they were
44
+ * always going to fail behind.
45
+ */
46
+ export declare function resolveBatches(config: WorkflowConfig, { only, selection }: {
47
+ only: string | undefined;
48
+ selection: DeploymentSelectionOptions;
49
+ }): Promise<AcknowledgedDeployBatch[]>;
50
+ /**
51
+ * Select and validate every deployment's definitions up front. Validation runs
52
+ * before any network write ({@link validateOrFail} exits on a bad definition),
53
+ * so a whole-config deploy can never leave a partial reconcile behind a broken
54
+ * batch. Also asserts each selected deployment's reader-floor acknowledgement —
55
+ * including `--check`, which never reaches {@link deploymentToTarget}. In a
56
+ * multi-deployment run the failure names its deployment — it exits before any
57
+ * banner could attribute it.
58
+ */
59
+ export declare function buildBatches(deployments: WorkflowDeployment[], only: string | undefined): AcknowledgedDeployBatch[];
60
+ /**
61
+ * Run `processBatch` over each batch, continuing past a failure so one bad
62
+ * deployment can't strand the rest — deployments are independent, and deploys
63
+ * are idempotent, so a partial run is safe to re-run. Failures are flattened
64
+ * to their message for {@link deploySummary}. A single-batch run rethrows
65
+ * instead: it has no summary, so a throw from before the deploy spinner starts
66
+ * would otherwise surface nowhere — and propagating keeps the stack visible.
67
+ * An auth rejection also rethrows regardless of batch count: a dead token is
68
+ * never batch-local, so continuing would just repeat the same failure.
69
+ */
70
+ export declare function reconcileBatches<T extends DeployBatch>({ batches, log, processBatch, }: {
71
+ batches: T[];
72
+ log: (line: string) => void;
73
+ processBatch: (batch: T) => Promise<void>;
74
+ }): Promise<DeployFailure[]>;
75
+ /**
76
+ * The closing summary for a multi-deployment run that had failures: the
77
+ * succeeded/failed tally and each failed deployment. Empty for a clean run.
78
+ * The wording is mode-neutral because a `--dry-run` failure lands here too,
79
+ * where nothing was deployed. Single-batch runs never reach it — their lone
80
+ * failure rethrows out of {@link reconcileBatches}.
81
+ */
82
+ export declare function deploySummary({ total, failures, }: {
83
+ total: number;
84
+ failures: DeployFailure[];
85
+ }): string[];
86
+ /**
87
+ * The banner printed above a deployment's output so a multi-deployment run is
88
+ * attributable. `undefined` for a single-target run — it keeps its original
89
+ * unprefixed output.
90
+ */
91
+ export declare function deploymentBanner({ deployment, index, total, }: {
92
+ deployment: Pick<WorkflowDeployment, 'name' | 'partition'>;
93
+ index: number;
94
+ total: number;
95
+ }): string | undefined;
96
+ /** The deploy target as one label — the deployment's friendly name/partition
97
+ * ({@link deploymentLabel}) and the resource it writes to
98
+ * ({@link resourceLabel}) — so every progress and result line names where a
99
+ * deploy landed, including the common single-deployment run that prints no
100
+ * banner. */
101
+ export declare function targetLabel(deployment: WorkflowDeployment): string;
102
+ /** The deploy spinner's progress line — names the full target it writes to. */
103
+ export declare function deployStartLine(count: number, where: string): string;
104
+ /** The dry-run spinner's progress line — a diff reads the resource's deployed
105
+ * state, so it names the resource it compares against, not the deployment. */
106
+ export declare function dryRunStartLine(count: number, resource: string): string;
107
+ /** A completed deploy/dry-run result line: the past-tense verb, the count, and
108
+ * the full target, so a finished run always shows where it landed. */
109
+ export declare function resultLine({ verb, count, where, }: {
110
+ verb: 'Processed' | 'Diffed';
111
+ count: number;
112
+ where: string;
113
+ }): string;
114
+ /** One line per deployed definition, symbol-tagged by its result status,
115
+ * followed by the deploy's advisory warnings indented beneath it. */
116
+ export declare function deployResultLines(results: DeployDefinitionResult[]): string[];
117
+ export {};
@@ -0,0 +1,266 @@
1
+ import { styleText } from 'node:util';
2
+ import { Flags } from '@oclif/core';
3
+ import { computeDiffEntries, deployedPartitionsGroq, errorMessage, workflow, } from '@sanity/workflows';
4
+ import logSymbols from 'log-symbols';
5
+ import ora from 'ora';
6
+ import { WorkflowCommand } from '../../lib/base-command.js';
7
+ import { checkDeployAlignment } from '../../lib/blueprint-emit.js';
8
+ import { clientFor, resolveTokenOrFail } from '../../lib/client.js';
9
+ import { confirmDefaultPartitions } from '../../lib/default-partition.js';
10
+ import { assertKnownDefinition, selectDefinitions, validateOrFail } from '../../lib/definitions.js';
11
+ import { diffReport } from '../../lib/diff.js';
12
+ import { fail, isAuthRejection } from '../../lib/fail.js';
13
+ import { deploymentFlags, partitionFlag } from '../../lib/flags.js';
14
+ import { loadWorkflowConfigModule } from '../../lib/load-config.js';
15
+ import { acknowledgeDeployment, deploymentLabel, deploymentToTarget, selectDeployments, } from '../../lib/select-deployment.js';
16
+ import { shareDefinitionsAfterDeploy } from '../../lib/share-definitions.js';
17
+ import { cliTelemetry } from '../../lib/telemetry.js';
18
+ import { groupBanner, resourceLabel, terminalWidth, warningLines } from '../../lib/ui.js';
19
+ export default class Deploy extends WorkflowCommand {
20
+ static description = 'Validate workflow definitions, check any generated runtime beside the config against them, then diff and deploy to the resource bound by the selected deployment. A generated runtime that no longer matches the definitions fails the deploy before anything is written; regenerate it with `sanity-workflows blueprints generate`.';
21
+ static examples = [
22
+ '<%= config.bin %> workflows deploy --deployment review-prod',
23
+ '<%= config.bin %> workflows deploy --partition prod',
24
+ '<%= config.bin %> workflows deploy --all-partitions',
25
+ '<%= config.bin %> workflows deploy --check',
26
+ '<%= config.bin %> workflows deploy --dry-run',
27
+ '<%= config.bin %> workflows deploy --check --verbose',
28
+ '<%= config.bin %> workflows deploy --only product-launch',
29
+ ];
30
+ static flags = {
31
+ ...deploymentFlags,
32
+ partition: partitionFlag({
33
+ description: 'Workflow partition (e.g. prod, test) — deploys every deployment using that partition across configured resources.',
34
+ exclusive: ['deployment'],
35
+ }),
36
+ 'all-partitions': Flags.boolean({
37
+ aliases: ['all-tags'],
38
+ description: 'Deploy every deployment in the config, not just a selection.',
39
+ default: false,
40
+ exclusive: ['partition', 'deployment'],
41
+ }),
42
+ 'dry-run': Flags.boolean({
43
+ description: 'Validate definitions, check any generated runtime against them, and diff against the deployed version; do not write.',
44
+ default: false,
45
+ }),
46
+ check: Flags.boolean({
47
+ description: 'Validate definitions and check any generated runtime against them; do not contact the dataset.',
48
+ default: false,
49
+ }),
50
+ verbose: Flags.boolean({
51
+ description: 'When no generated runtime is here, print the full report of the Sanity Functions the selected deployments need, in place of the summary.',
52
+ default: false,
53
+ }),
54
+ only: Flags.string({
55
+ description: 'Limit deploy/check/diff to a single workflow definition by name (deployments are selected with --deployment). Every targeted deployment must contain it. The generated-runtime check still covers the whole config, because the generated tree declares every deployment in it.',
56
+ }),
57
+ 'share-defs': Flags.boolean({
58
+ allowNo: true,
59
+ description: 'Share the definition documents newly created by this deploy with Sanity — the full document, verbatim (structure, names, filters, effect configuration, seeded values), plus its deployment coordinates (project and dataset, or resource id); never content documents, instances, or your Sanity auth token. Sharing is the default in every environment, including CI / non-TTY / DO_NOT_TRACK. Use --no-share-defs to opt out.',
60
+ }),
61
+ };
62
+ async run() {
63
+ const { flags } = await this.parse(Deploy);
64
+ validateModeFlags(flags.check, flags['dry-run']);
65
+ const { root, config, configFile, exportedNames } = await loadWorkflowConfigModule(flags.path);
66
+ const batches = await resolveBatches(config, {
67
+ only: flags.only,
68
+ selection: {
69
+ name: flags.deployment,
70
+ partition: flags.partition,
71
+ allPartitions: flags['all-partitions'],
72
+ },
73
+ });
74
+ const log = (line) => this.log(line);
75
+ checkDeployAlignment({
76
+ root,
77
+ config,
78
+ configFile,
79
+ exportedNames,
80
+ log,
81
+ warn: (message) => void this.warn(message),
82
+ selected: batches.map(({ deployment }) => deployment.name),
83
+ verbose: flags.verbose,
84
+ bin: this.config.bin,
85
+ width: terminalWidth(),
86
+ });
87
+ if (flags.check) {
88
+ await reconcileBatches({
89
+ batches,
90
+ log,
91
+ processBatch: async ({ defs }) => {
92
+ log(`${logSymbols.success} ${defs.length} definition(s) passed validation (check only — dataset not contacted).`);
93
+ },
94
+ });
95
+ return;
96
+ }
97
+ const token = await resolveTokenOrFail();
98
+ await confirmDefaultPartitions({
99
+ deployments: batches.map(({ deployment }) => deployment),
100
+ deployedPartitions: ({ workflowResource }) => clientFor(workflowResource, token).fetch(deployedPartitionsGroq(), {}, { tag: 'deploy.partitions' }),
101
+ dryRun: flags['dry-run'],
102
+ warn: (message) => void this.warn(message),
103
+ });
104
+ const candidates = [];
105
+ const failures = await reconcileBatches({
106
+ batches,
107
+ log,
108
+ processBatch: async ({ deployment, defs }) => {
109
+ const client = clientFor(deployment.workflowResource, token);
110
+ const deployed = await this.processDeployment({
111
+ deployment,
112
+ defs,
113
+ dryRun: flags['dry-run'],
114
+ client,
115
+ });
116
+ if (deployed !== undefined) {
117
+ candidates.push({
118
+ client,
119
+ partition: deployment.partition,
120
+ resource: deployment.workflowResource,
121
+ results: deployed.results,
122
+ deployId: deployed.deployId,
123
+ });
124
+ }
125
+ },
126
+ });
127
+ for (const line of deploySummary({ total: batches.length, failures })) {
128
+ log(line);
129
+ }
130
+ await shareDefinitionsAfterDeploy({
131
+ flag: flags['share-defs'],
132
+ followUp: {
133
+ bin: this.config.bin,
134
+ selection: {
135
+ deployment: flags.deployment,
136
+ partition: flags.partition,
137
+ allPartitions: flags['all-partitions'],
138
+ },
139
+ },
140
+ candidates,
141
+ warn: (message) => this.warn(message),
142
+ });
143
+ if (failures.length > 0) {
144
+ this.exit(1);
145
+ }
146
+ }
147
+ async processDeployment({ deployment, defs, dryRun, client, }) {
148
+ const target = deploymentToTarget(deployment);
149
+ const where = targetLabel(deployment);
150
+ const resource = resourceLabel(deployment.workflowResource);
151
+ if (dryRun) {
152
+ await this.runDryRun({ client, defs, target, where, resource });
153
+ return undefined;
154
+ }
155
+ return this.executeDeploy({ client, defs, target, where });
156
+ }
157
+ async executeDeploy({ client, defs, target, where, }) {
158
+ const spinner = ora(deployStartLine(defs.length, where)).start();
159
+ try {
160
+ const deployed = await workflow.deployDefinitions({
161
+ ...target,
162
+ client,
163
+ definitions: defs,
164
+ telemetry: cliTelemetry().logger,
165
+ });
166
+ spinner.succeed(resultLine({ verb: 'Processed', count: deployed.results.length, where }));
167
+ for (const line of deployResultLines(deployed.results))
168
+ this.log(line);
169
+ return deployed;
170
+ }
171
+ catch (error) {
172
+ spinner.fail('Deploy failed');
173
+ throw error;
174
+ }
175
+ }
176
+ async runDryRun({ client, defs, target, where, resource, }) {
177
+ const spinner = ora(dryRunStartLine(defs.length, resource)).start();
178
+ try {
179
+ const entries = await computeDiffEntries({ client, defs, target });
180
+ spinner.succeed(resultLine({ verb: 'Diffed', count: defs.length, where }));
181
+ for (const line of diffReport(entries))
182
+ this.log(line);
183
+ }
184
+ catch (error) {
185
+ spinner.fail('Diff failed');
186
+ throw error;
187
+ }
188
+ }
189
+ }
190
+ export function validateModeFlags(check, dryRun) {
191
+ if (check && dryRun) {
192
+ fail('Pass either --check or --dry-run, not both.');
193
+ }
194
+ }
195
+ export async function resolveBatches(config, { only, selection }) {
196
+ assertKnownDefinition(config, only);
197
+ return buildBatches(await selectDeployments(config, selection), only);
198
+ }
199
+ export function buildBatches(deployments, only) {
200
+ return deployments.map((deployment) => {
201
+ const context = deployments.length > 1 ? `${deploymentLabel(deployment)} — ` : '';
202
+ const defs = selectDefinitions(deployment.definitions, { only, context });
203
+ validateOrFail(defs, context);
204
+ return { deployment: acknowledgeDeployment(deployment, defs), defs };
205
+ });
206
+ }
207
+ export async function reconcileBatches({ batches, log, processBatch, }) {
208
+ const failures = [];
209
+ for (const [index, batch] of batches.entries()) {
210
+ const banner = deploymentBanner({ deployment: batch.deployment, index, total: batches.length });
211
+ if (banner !== undefined) {
212
+ log(banner);
213
+ }
214
+ try {
215
+ await processBatch(batch);
216
+ }
217
+ catch (error) {
218
+ if (batches.length === 1 || isAuthRejection(error)) {
219
+ throw error;
220
+ }
221
+ failures.push({ deployment: batch.deployment, message: errorMessage(error) });
222
+ }
223
+ }
224
+ return failures;
225
+ }
226
+ export function deploySummary({ total, failures, }) {
227
+ if (failures.length === 0) {
228
+ return [];
229
+ }
230
+ return [
231
+ '',
232
+ styleText('bold', `${total - failures.length} of ${total} deployments succeeded — ${failures.length} failed:`),
233
+ ...failures.flatMap((f) => {
234
+ const [first = '', ...rest] = f.message.split('\n');
235
+ return [
236
+ styleText('red', ` ${logSymbols.error} ${deploymentLabel(f.deployment)} — ${first}`),
237
+ ...rest.map((line) => styleText('red', ` ${line}`)),
238
+ ];
239
+ }),
240
+ ];
241
+ }
242
+ export function deploymentBanner({ deployment, index, total, }) {
243
+ return groupBanner({ label: deploymentLabel(deployment), index, total });
244
+ }
245
+ export function targetLabel(deployment) {
246
+ return `${deploymentLabel(deployment)} → ${resourceLabel(deployment.workflowResource)}`;
247
+ }
248
+ export function deployStartLine(count, where) {
249
+ return `Deploying ${count} definition(s) to ${where}…`;
250
+ }
251
+ export function dryRunStartLine(count, resource) {
252
+ return `Diffing ${count} definition(s) against ${resource}…`;
253
+ }
254
+ export function resultLine({ verb, count, where, }) {
255
+ return `${verb} ${count} definition(s) · ${where}`;
256
+ }
257
+ export function deployResultLines(results) {
258
+ const symbols = {
259
+ created: logSymbols.success,
260
+ unchanged: logSymbols.info,
261
+ };
262
+ return results.flatMap((r) => {
263
+ const head = ` ${symbols[r.status]} ${r.status.padEnd(9)} ${r.name} v${r.version}`;
264
+ return [head, ...warningLines(r.warnings)];
265
+ });
266
+ }