@sanity/workflows-cli 0.0.0-main-039-20261113092657

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 (132) hide show
  1. package/CHANGELOG.md +1936 -0
  2. package/LICENSE +21 -0
  3. package/README.md +814 -0
  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 +10 -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 +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 +231 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +111 -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 +17 -0
  66. package/dist/lib/codemod/export-rename.js +253 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  69. package/dist/lib/codemod/package-map.d.ts +26 -0
  70. package/dist/lib/codemod/package-map.js +90 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +46 -0
  73. package/dist/lib/codemod/run.d.ts +23 -0
  74. package/dist/lib/codemod/run.js +106 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +149 -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 +155 -0
  82. package/dist/lib/context.js +272 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +48 -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 +49 -0
  98. package/dist/lib/flags.js +117 -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-dataset.d.ts +10 -0
  114. package/dist/lib/pick-dataset.js +30 -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 +44 -0
  119. package/dist/lib/select-deployment.d.ts +31 -0
  120. package/dist/lib/select-deployment.js +91 -0
  121. package/dist/lib/share-definitions.d.ts +101 -0
  122. package/dist/lib/share-definitions.js +188 -0
  123. package/dist/lib/telemetry-setup.d.ts +81 -0
  124. package/dist/lib/telemetry-setup.js +111 -0
  125. package/dist/lib/telemetry.d.ts +81 -0
  126. package/dist/lib/telemetry.js +90 -0
  127. package/dist/lib/ui.d.ts +91 -0
  128. package/dist/lib/ui.js +116 -0
  129. package/dist/standalone-argv.d.ts +14 -0
  130. package/dist/standalone-argv.js +57 -0
  131. package/oclif.manifest.json +1731 -0
  132. package/package.json +121 -0
@@ -0,0 +1,44 @@
1
+ import { displayTitle } from '@sanity/workflows';
2
+ function withNotes(text, ...notes) {
3
+ const present = notes.filter((note) => note !== undefined);
4
+ return present.length === 0 ? text : `${text} (${present.join(': ')})`;
5
+ }
6
+ function withMoveNotes(text, { via, reason }) {
7
+ return withNotes(text, via === 'setStage' ? 'forced' : undefined, reason);
8
+ }
9
+ function transitionName(move) {
10
+ return move.via === 'setStage' || move.transition === undefined ? '' : `${move.transition}, `;
11
+ }
12
+ const detailOf = {
13
+ stageEntered: (entry) => withMoveNotes(entry.stage, entry),
14
+ stageExited: (entry) => entry.stage,
15
+ activityStatusChanged: (entry) => `${entry.activity} ${entry.from} → ${entry.to}`,
16
+ actionFired: (entry) => withNotes(`${entry.activity} → ${entry.action}`, entry.triggered ? 'triggered' : undefined),
17
+ transitionFired: (entry) => withMoveNotes(`${transitionName(entry)}${entry.fromStage} → ${entry.toStage}`, entry),
18
+ effectQueued: (entry) => entry.effect,
19
+ effectCompleted: (entry) => withNotes(entry.effect, entry.status, entry.detail),
20
+ effectClaimReleased: (entry) => entry.effect,
21
+ spawned: (entry) => `${entry.activity} → ${entry.instanceRef.id}`,
22
+ subworkflowAdopted: (entry) => `${entry.activity} → ${entry.instanceRef.id}`,
23
+ subworkflowResolved: (entry) => withNotes(entry.activity, entry.status),
24
+ subworkflowOrphaned: (entry) => entry.instanceRef.id,
25
+ aborted: (entry) => entry.reason,
26
+ opApplied: (entry) => {
27
+ const subject = entry.target?.field ?? entry.activity;
28
+ return subject === undefined ? entry.opType : `${entry.opType} ${subject}`;
29
+ },
30
+ fieldQueryDiscarded: (entry) => entry.field,
31
+ };
32
+ function actorOf(entry) {
33
+ if (entry._type === 'actionFired' && entry.triggered) {
34
+ return undefined;
35
+ }
36
+ return 'actor' in entry ? entry.actor : undefined;
37
+ }
38
+ export function historyRow(entry) {
39
+ const detail = detailOf[entry._type](entry);
40
+ const actor = actorOf(entry);
41
+ const title = displayTitle(entry._type);
42
+ const described = detail === undefined ? title : `${title}: ${detail}`;
43
+ return actor === undefined ? described : `${described} (by ${actor.id})`;
44
+ }
@@ -0,0 +1,51 @@
1
+ import { type WorkflowConfig } from '@sanity/workflows';
2
+ /** A config file that could not be found, loaded, or validated. The message is the detail line under `headline`. */
3
+ export declare class ConfigLoadError extends Error {
4
+ readonly headline: string;
5
+ constructor(headline: string, detail: string);
6
+ }
7
+ /**
8
+ * The validated config a `sanity.workflow` module exports, and the names that
9
+ * module exports it alongside.
10
+ */
11
+ export interface LoadedWorkflowConfig {
12
+ config: WorkflowConfig;
13
+ /** The discovered file's name, so a diagnostic names the file the user
14
+ * actually has among the supported config filenames. */
15
+ configFile: string;
16
+ /** Every name the module exports, `default` included. `blueprints generate`
17
+ * reads it because each generated module imports its deployment as a named
18
+ * export from this file. */
19
+ exportedNames: readonly string[];
20
+ /** The config file's directory. Generated Blueprint files are written here,
21
+ * not to the working directory the search started from. */
22
+ root: string;
23
+ }
24
+ /**
25
+ * Find the `sanity.workflow.{ts,js,mjs}` config, import its default export,
26
+ * and validate it through {@link defineWorkflowConfig}. `path` is a config
27
+ * file, or a directory to search from and then upward through its parents.
28
+ * Any problem — no file, unloadable module, invalid config — exits through
29
+ * the clean `fail` path.
30
+ */
31
+ export declare function loadWorkflowConfig(path?: string): Promise<WorkflowConfig>;
32
+ /**
33
+ * {@link loadWorkflowConfig} plus the module's exported names and directory,
34
+ * for a caller that writes beside the config or checks one of its exports.
35
+ * Takes the same clean `fail` path on every problem.
36
+ */
37
+ export declare function loadWorkflowConfigModule(path?: string): Promise<LoadedWorkflowConfig>;
38
+ /**
39
+ * {@link loadWorkflowConfig}, or `undefined` when no config file is found, for
40
+ * a read that can target a resource without one. Every other problem takes
41
+ * the same clean `fail` path.
42
+ */
43
+ export declare function loadWorkflowConfigIfFound(path?: string): Promise<WorkflowConfig | undefined>;
44
+ export declare function noConfigFound(path?: string): string;
45
+ /**
46
+ * {@link loadWorkflowConfig} for telemetry setup, which must never break (or
47
+ * exit) a command: `undefined` when the file is absent or unusable. A broken
48
+ * config is not swallowed for real — the command's own load reports it through
49
+ * the clean `fail` path; this caller just runs with telemetry off.
50
+ */
51
+ export declare function loadWorkflowConfigIfPresent(path?: string): Promise<WorkflowConfig | undefined>;
@@ -0,0 +1,108 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { existsSync, statSync } from 'node:fs';
10
+ import { basename, dirname, resolve } from 'node:path';
11
+ import { pathToFileURL } from 'node:url';
12
+ import { errorMessage } from '@sanity/workflows';
13
+ import { CONFIG_FILE_NAMES } from '@sanity/workflows/blueprints';
14
+ import { defineWorkflowConfig } from '@sanity/workflows/define';
15
+ import * as find from 'empathic/find';
16
+ import { createJiti } from 'jiti';
17
+ import { fail, failOn, warnOnStderr } from './fail.js';
18
+ export class ConfigLoadError extends Error {
19
+ headline;
20
+ constructor(headline, detail) {
21
+ super(detail);
22
+ this.headline = headline;
23
+ }
24
+ }
25
+ function findConfigFile(path) {
26
+ if (!existsSync(path)) {
27
+ throw new ConfigLoadError(`Nothing found at ${path}.`, 'Pass --path a config file or an existing directory.');
28
+ }
29
+ const absolute = resolve(path);
30
+ if (statSync(absolute).isFile()) {
31
+ return absolute;
32
+ }
33
+ return find.any([...CONFIG_FILE_NAMES], { cwd: absolute, type: 'file' });
34
+ }
35
+ async function importModule(filePath) {
36
+ const url = pathToFileURL(filePath).href;
37
+ try {
38
+ const loaded = filePath.endsWith('.ts')
39
+ ? await createJiti(dirname(filePath)).import(url)
40
+ : await import(__rewriteRelativeImportExtension(url, true));
41
+ return { default: loaded.default, names: Object.keys(loaded) };
42
+ }
43
+ catch (err) {
44
+ throw new ConfigLoadError(`Failed to load ${basename(filePath)}:`, errorMessage(err));
45
+ }
46
+ }
47
+ const parsedConfigs = new Map();
48
+ function parseConfigFile(filePath) {
49
+ const cached = parsedConfigs.get(filePath);
50
+ if (cached !== undefined) {
51
+ return cached;
52
+ }
53
+ const parsed = importModule(filePath).then((loaded) => {
54
+ let config;
55
+ try {
56
+ config = defineWorkflowConfig(loaded.default);
57
+ }
58
+ catch (err) {
59
+ throw new ConfigLoadError(`Invalid config in ${basename(filePath)}:`, errorMessage(err));
60
+ }
61
+ config.warnings.forEach(warnOnStderr);
62
+ return {
63
+ config,
64
+ configFile: basename(filePath),
65
+ exportedNames: loaded.names,
66
+ root: dirname(filePath),
67
+ };
68
+ });
69
+ parsedConfigs.set(filePath, parsed);
70
+ return parsed;
71
+ }
72
+ export async function loadWorkflowConfig(path) {
73
+ return (await loadWorkflowConfigModule(path)).config;
74
+ }
75
+ export async function loadWorkflowConfigModule(path = process.cwd()) {
76
+ return ((await loadIfFound(path)) ??
77
+ fail(noConfigFound(path), 'Create one that `export default defineWorkflowConfig({deployments: [...]})`, or pass --path to point at one.'));
78
+ }
79
+ export async function loadWorkflowConfigIfFound(path = process.cwd()) {
80
+ return (await loadIfFound(path))?.config;
81
+ }
82
+ export function noConfigFound(path = process.cwd()) {
83
+ return `No ${CONFIG_FILE_NAMES[0]} found in ${resolve(path)} or any parent directory.`;
84
+ }
85
+ async function loadIfFound(path) {
86
+ try {
87
+ const filePath = findConfigFile(path);
88
+ return filePath === undefined ? undefined : await parseConfigFile(filePath);
89
+ }
90
+ catch (err) {
91
+ if (err instanceof ConfigLoadError) {
92
+ failOn(err, err.headline);
93
+ }
94
+ throw err;
95
+ }
96
+ }
97
+ export async function loadWorkflowConfigIfPresent(path = process.cwd()) {
98
+ try {
99
+ const filePath = findConfigFile(path);
100
+ return filePath === undefined ? undefined : (await parseConfigFile(filePath)).config;
101
+ }
102
+ catch (err) {
103
+ if (err instanceof ConfigLoadError) {
104
+ return undefined;
105
+ }
106
+ throw err;
107
+ }
108
+ }
@@ -0,0 +1,124 @@
1
+ import { type WorkflowClient, type WorkflowDeployment, type WorkflowResource } from '@sanity/workflows';
2
+ /** A resource a nuke may delete from, with the client that reads/writes it and
3
+ * whether it is the engine's own resource — the only one that holds instances
4
+ * and definitions (guards can co-locate with subjects in any resource). */
5
+ export interface NukeTarget {
6
+ resource: WorkflowResource;
7
+ client: WorkflowClient;
8
+ holdsEngineDocs: boolean;
9
+ }
10
+ /** One resolved resource of a {@link NukePlan}: the ids to delete, by doc type. */
11
+ export interface NukeResourcePlan {
12
+ resource: WorkflowResource;
13
+ /** The `project.dataset` (or `<type>:<id>`) label the plan shows this resource
14
+ * as — and, in tag mode, the one the operator confirms by. */
15
+ label: string;
16
+ client: WorkflowClient;
17
+ holdsEngineDocs: boolean;
18
+ instanceIds: string[];
19
+ definitionIds: string[];
20
+ guardIds: string[];
21
+ }
22
+ /** Which selector resolved a plan. Decides the delete wave order — see
23
+ * {@link WAVE_ORDER} — so it travels with the plan rather than being re-derived. */
24
+ export type NukeMode = 'partition' | 'instance';
25
+ export interface NukePlan {
26
+ partition: string;
27
+ mode: NukeMode;
28
+ resources: NukeResourcePlan[];
29
+ }
30
+ /** Per-doc-type totals across the whole plan, plus the count of resources that
31
+ * actually hold something to delete ({@link involvedTargets}). */
32
+ export interface PlanCounts {
33
+ instances: number;
34
+ definitions: number;
35
+ guards: number;
36
+ datasets: number;
37
+ total: number;
38
+ }
39
+ /** Every resource a deployment's nuke sweeps: its own workflow resource (which
40
+ * holds instances + definitions + guards) plus each alias-bound resource
41
+ * (guards co-locate with the subjects they lock). */
42
+ export declare function sweptResources(deployment: WorkflowDeployment): WorkflowResource[];
43
+ /**
44
+ * Fail before any nuke work when another same-tag deployment sweeps a resource
45
+ * the selected one does. Guard document ids embed only the partition
46
+ * (`temp.system.guard.<tag>.wf-instance.*`), so within a shared resource the
47
+ * sweep cannot tell such deployments' guards apart — nuking one would delete
48
+ * the others' live locks, invisibly to the plan. Config validation already
49
+ * forbids sharing tag + workflow resource, so an overlap can only arrive
50
+ * through alias bindings.
51
+ */
52
+ export declare function refuseOverlappingNuke(deployments: WorkflowDeployment[], selected: WorkflowDeployment): void;
53
+ /**
54
+ * Resolve what a tag-scoped nuke would delete, per resource — the dry-run plan
55
+ * printed before any deletion. Instances and definitions are read only from the
56
+ * engine's own resource; guards are read from every target, since a guard
57
+ * co-locates with the subject it locks and may live in a foreign dataset.
58
+ *
59
+ * Every read uses the raw perspective, so a draft-form or otherwise
60
+ * perspective-hidden copy is still surfaced (and swept).
61
+ */
62
+ export declare function resolveNukePlan(args: {
63
+ partition: string;
64
+ targets: NukeTarget[];
65
+ }): Promise<NukePlan>;
66
+ /** An instance a caller has already located: its id plus the resource whose
67
+ * document the locate actually read. The plan derives its instance row from
68
+ * that resource rather than assuming the engine one holds it, so a plan can
69
+ * only ever claim an instance the caller really found. */
70
+ export interface LocatedInstance {
71
+ id: string;
72
+ resource: WorkflowResource;
73
+ }
74
+ /**
75
+ * Resolve what deleting ONE located instance sweeps, per resource — the
76
+ * single-instance sibling of {@link resolveNukePlan}. The instance document is
77
+ * deleted from the resource that held it; its guards are read from every target,
78
+ * since a guard co-locates with the subject it locks and may live in an
79
+ * alias-bound dataset. Definitions are never in scope. Raw perspective, like the
80
+ * tag-scoped plan.
81
+ */
82
+ export declare function resolveInstanceNukePlan(args: {
83
+ instance: LocatedInstance;
84
+ partition: string;
85
+ targets: NukeTarget[];
86
+ }): Promise<NukePlan>;
87
+ /** The `project.dataset` labels of resources the plan actually deletes from. A
88
+ * resource with nothing to delete is not "involved" and is omitted. Tag mode
89
+ * makes the operator type this set back; instance mode confirms with a plain
90
+ * y/N and consumes it only for the dataset count in its summary. */
91
+ export declare function involvedTargets(plan: NukePlan): string[];
92
+ /** Roll the plan up into per-doc-type totals for the summary and the
93
+ * nothing-to-do short-circuit. */
94
+ export declare function planCounts(plan: NukePlan): PlanCounts;
95
+ /**
96
+ * Does the operator's typed confirmation name every involved target, and only
97
+ * those? Order-independent, whitespace-tolerant set equality: the operator
98
+ * pastes back all `project.dataset` targets the plan listed.
99
+ */
100
+ export declare function confirmationMatches(input: string, targets: string[]): boolean;
101
+ /** The dry-run plan as printable lines: a heading, the content-safety
102
+ * invariant, the API host the deletes will hit (plan rows alone can't tell
103
+ * same-named projects on different environments apart), and a per-resource,
104
+ * per-doc-type count table. A guard-only foreign resource shows `—` for the
105
+ * engine-only columns, since those docs can't live there. */
106
+ export declare function renderNukePlan(plan: NukePlan, { apiHost, heading }: {
107
+ apiHost: string;
108
+ heading?: string;
109
+ }): string[];
110
+ /** The line printed before a partition delete is confirmed or forced. */
111
+ export declare function formatNukePreview(partition: string, counts: PlanCounts): string;
112
+ /** The success line for a partition delete. */
113
+ export declare function formatNukeSummary(partition: string, counts: PlanCounts): string;
114
+ /** The success line for a single-instance delete; guards are named only when some were deleted. */
115
+ export declare function formatInstanceNukeSummary(instanceId: string, counts: Pick<PlanCounts, 'guards'>): string;
116
+ /**
117
+ * Delete exactly what the plan printed, in uniform waves over every resource,
118
+ * ordered by the plan's mode ({@link WAVE_ORDER}). Non-engine resources simply
119
+ * carry empty instance/definition lists. Idempotent: an empty plan deletes
120
+ * nothing.
121
+ */
122
+ export declare function executeNuke(plan: NukePlan): Promise<void>;
123
+ /** The `definitions:` line under the plan table; undefined when there are no definitions. */
124
+ export declare function definitionNamesLine(definitionIds: string[]): string | undefined;
@@ -0,0 +1,206 @@
1
+ import { styleText } from 'node:util';
2
+ import { GUARD_DOC_TYPE, WORKFLOW_DEFINITION_TYPE, WORKFLOW_INSTANCE_TYPE, resourceGdr, partitionScopeFilter, } from '@sanity/workflows';
3
+ import { fail } from './fail.js';
4
+ import { deploymentLabel } from './select-deployment.js';
5
+ import { formatTable, pluralize, resourceLabel, sectionHeader } from './ui.js';
6
+ const CHUNK = 200;
7
+ const DEFINITION_ID_TAIL = /([^.]+)\.v(\d+)$/;
8
+ const REQUEST_TAG = 'nuke';
9
+ export function sweptResources(deployment) {
10
+ return [
11
+ deployment.workflowResource,
12
+ ...(deployment.resourceAliases ?? []).map((binding) => binding.resource),
13
+ ];
14
+ }
15
+ export function refuseOverlappingNuke(deployments, selected) {
16
+ const swept = new Set(sweptResources(selected).map(resourceGdr));
17
+ const clashing = deployments.filter((candidate) => candidate.name !== selected.name &&
18
+ candidate.partition === selected.partition &&
19
+ sweptResources(candidate).some((resource) => swept.has(resourceGdr(resource))));
20
+ if (clashing.length === 0) {
21
+ return;
22
+ }
23
+ fail(`Refusing to nuke "${deploymentLabel(selected)}" — its guards are indistinguishable ` +
24
+ `from ${clashing.map(deploymentLabel).join(', ')}'s in the shared resource(s).`, `Guard ids embed only the partition, and these deployments share partition "${selected.partition}" plus ` +
25
+ "a swept resource — the sweep would delete the other deployments' live guards. " +
26
+ 'Give them distinct partitions first.');
27
+ }
28
+ export async function resolveNukePlan(args) {
29
+ const { partition, targets } = args;
30
+ const resources = await Promise.all(targets.map((target) => resolveResourcePlan({ partition, target })));
31
+ return { partition, mode: 'partition', resources };
32
+ }
33
+ async function resolveResourcePlan(args) {
34
+ const { partition, target } = args;
35
+ const { client, holdsEngineDocs } = target;
36
+ const noIds = [];
37
+ const [instanceIds, definitionIds, guardIds] = await Promise.all([
38
+ holdsEngineDocs ? engineDocIds({ client, type: WORKFLOW_INSTANCE_TYPE, partition }) : noIds,
39
+ holdsEngineDocs ? engineDocIds({ client, type: WORKFLOW_DEFINITION_TYPE, partition }) : noIds,
40
+ partitionGuardIds({ client, partition }),
41
+ ]);
42
+ return resourcePlan(target, { instanceIds, definitionIds, guardIds });
43
+ }
44
+ function resourcePlan(target, ids) {
45
+ return {
46
+ resource: target.resource,
47
+ label: resourceLabel(target.resource),
48
+ client: target.client,
49
+ holdsEngineDocs: target.holdsEngineDocs,
50
+ ...ids,
51
+ };
52
+ }
53
+ export async function resolveInstanceNukePlan(args) {
54
+ const { instance, partition, targets } = args;
55
+ const resources = await Promise.all(targets.map((target) => resolveInstanceResourcePlan({ instance, target })));
56
+ return { partition, mode: 'instance', resources };
57
+ }
58
+ async function resolveInstanceResourcePlan(args) {
59
+ const { instance, target } = args;
60
+ const guardIds = await instanceGuardIds({ client: target.client, instanceId: instance.id });
61
+ const holdsInstance = resourceGdr(target.resource) === resourceGdr(instance.resource);
62
+ return resourcePlan(target, {
63
+ instanceIds: holdsInstance ? [instance.id] : [],
64
+ definitionIds: [],
65
+ guardIds,
66
+ });
67
+ }
68
+ function instanceGuardIds(args) {
69
+ return guardIdsMatching({
70
+ client: args.client,
71
+ match: 'sourceInstanceId == $instanceId || string::startsWith(_id, $guardIdPrefix)',
72
+ params: {
73
+ instanceId: args.instanceId,
74
+ guardIdPrefix: `${GUARD_DOC_TYPE}.${args.instanceId}.`,
75
+ },
76
+ });
77
+ }
78
+ function engineDocIds(args) {
79
+ return args.client.fetch(`*[_type == $type && ${partitionScopeFilter()}]._id`, { type: args.type, tag: args.partition }, { perspective: 'raw', tag: REQUEST_TAG });
80
+ }
81
+ function partitionGuardIds(args) {
82
+ const instancePrefix = `${args.partition}.wf-instance.`;
83
+ return guardIdsMatching({
84
+ client: args.client,
85
+ match: 'string::startsWith(sourceInstanceId, $instancePrefix) || string::startsWith(_id, $guardIdPrefix)',
86
+ params: { instancePrefix, guardIdPrefix: `${GUARD_DOC_TYPE}.${instancePrefix}` },
87
+ });
88
+ }
89
+ function guardIdsMatching(args) {
90
+ return args.client.fetch(`*[_type == $type && (${args.match})]._id`, { type: GUARD_DOC_TYPE, ...args.params }, { perspective: 'raw', tag: REQUEST_TAG });
91
+ }
92
+ export function involvedTargets(plan) {
93
+ return plan.resources
94
+ .filter((resource) => resourceTotal(resource) > 0)
95
+ .map((resource) => resource.label);
96
+ }
97
+ function resourceTotal(resource) {
98
+ return resource.instanceIds.length + resource.definitionIds.length + resource.guardIds.length;
99
+ }
100
+ export function planCounts(plan) {
101
+ const totals = plan.resources.reduce((acc, resource) => ({
102
+ instances: acc.instances + resource.instanceIds.length,
103
+ definitions: acc.definitions + resource.definitionIds.length,
104
+ guards: acc.guards + resource.guardIds.length,
105
+ }), { instances: 0, definitions: 0, guards: 0 });
106
+ return {
107
+ ...totals,
108
+ datasets: involvedTargets(plan).length,
109
+ total: totals.instances + totals.definitions + totals.guards,
110
+ };
111
+ }
112
+ export function confirmationMatches(input, targets) {
113
+ const typed = new Set(input.trim().split(/\s+/).filter(Boolean));
114
+ const expected = new Set(targets);
115
+ return typed.size === expected.size && [...expected].every((target) => typed.has(target));
116
+ }
117
+ export function renderNukePlan(plan, { apiHost, heading = `nuke — partition "${plan.partition}"` }) {
118
+ const rows = plan.resources.map((resource) => [
119
+ resource.label,
120
+ resource.holdsEngineDocs ? String(resource.instanceIds.length) : styleText('dim', '—'),
121
+ resource.holdsEngineDocs ? String(resource.definitionIds.length) : styleText('dim', '—'),
122
+ String(resource.guardIds.length),
123
+ ]);
124
+ const definitionsLine = definitionNamesLine(plan.resources.flatMap((resource) => resource.definitionIds));
125
+ return [
126
+ sectionHeader(heading),
127
+ styleText('dim', 'engine-owned documents only — content is never touched'),
128
+ styleText('dim', `API host: ${apiHost}`),
129
+ ...formatTable(['target', 'instances', 'definitions', 'guards'], rows),
130
+ ...(definitionsLine === undefined ? [] : [definitionsLine]),
131
+ ];
132
+ }
133
+ function countsPhrase(counts) {
134
+ const parts = [
135
+ [counts.instances, 'instance'],
136
+ [counts.definitions, 'definition'],
137
+ [counts.guards, 'guard'],
138
+ ];
139
+ return new Intl.ListFormat('en', { type: 'conjunction' }).format(parts.filter(([count]) => count > 0).map(([count, noun]) => pluralize(count, noun)));
140
+ }
141
+ export function formatNukePreview(partition, counts) {
142
+ return `This will delete ${countsPhrase(counts)} from partition "${partition}".`;
143
+ }
144
+ export function formatNukeSummary(partition, counts) {
145
+ return `Deleted from partition "${partition}": ${countsPhrase(counts)}.`;
146
+ }
147
+ export function formatInstanceNukeSummary(instanceId, counts) {
148
+ if (counts.guards === 0) {
149
+ return `Deleted instance ${instanceId}.`;
150
+ }
151
+ const guards = counts.guards === 1 ? 'its guard' : `its ${counts.guards} guards`;
152
+ return `Deleted instance ${instanceId} and ${guards}.`;
153
+ }
154
+ const WAVE_ORDER = {
155
+ instance: ['guardIds', 'definitionIds', 'instanceIds'],
156
+ partition: ['instanceIds', 'definitionIds', 'guardIds'],
157
+ };
158
+ export async function executeNuke(plan) {
159
+ for (const idField of WAVE_ORDER[plan.mode]) {
160
+ for (const resource of plan.resources) {
161
+ await deleteIds(resource.client, resource[idField]);
162
+ }
163
+ }
164
+ }
165
+ async function deleteIds(client, ids) {
166
+ for (let start = 0; start < ids.length; start += CHUNK) {
167
+ const tx = client.transaction();
168
+ for (const id of ids.slice(start, start + CHUNK))
169
+ tx.delete(id);
170
+ await tx.commit({ tag: REQUEST_TAG });
171
+ }
172
+ }
173
+ function versionRanges(versions) {
174
+ const runs = [];
175
+ for (const version of [...new Set(versions)].sort((a, b) => a - b)) {
176
+ const run = runs.at(-1);
177
+ if (run !== undefined && version === run.last + 1) {
178
+ run.last = version;
179
+ }
180
+ else {
181
+ runs.push({ first: version, last: version });
182
+ }
183
+ }
184
+ return runs
185
+ .map(({ first, last }) => (first === last ? `v${first}` : `v${first}–v${last}`))
186
+ .join(', ');
187
+ }
188
+ export function definitionNamesLine(definitionIds) {
189
+ const versionsByName = new Map();
190
+ for (const id of definitionIds) {
191
+ const [, name, version] = DEFINITION_ID_TAIL.exec(id) ?? [];
192
+ if (name === undefined || version === undefined) {
193
+ throw new Error(`Unexpected definition id "${id}"`);
194
+ }
195
+ const versions = versionsByName.get(name) ?? [];
196
+ versions.push(Number(version));
197
+ versionsByName.set(name, versions);
198
+ }
199
+ if (versionsByName.size === 0) {
200
+ return undefined;
201
+ }
202
+ const entries = [...versionsByName.keys()]
203
+ .sort()
204
+ .map((name) => `${name} (${versionRanges(versionsByName.get(name) ?? [])})`);
205
+ return `definitions: ${entries.join(', ')}`;
206
+ }
@@ -0,0 +1,42 @@
1
+ import { type Engine, type EngineScopeArgs, type WorkflowClient, type OperationArgs, type WorkflowTelemetryLogger } from '@sanity/workflows';
2
+ /**
3
+ * The engine-scope a CLI verb needs: which partition and which resource
4
+ * the engine's own data lives in, plus the clients for the resources the
5
+ * deployment binds in `resourceAliases`; {@link EngineScopeArgs} minus the
6
+ * client. Runtime-supplied refs may target the workflow resource or an
7
+ * alias-bound resource. `resourceClients` is required because an engine
8
+ * without it accepts refs into any addressable resource.
9
+ */
10
+ export type EngineScope = Pick<EngineScopeArgs, 'partition' | 'workflowResource'> & Required<Pick<EngineScopeArgs, 'resourceClients'>>;
11
+ /**
12
+ * The engine args every CLI verb shares: partition scope, workflow resource,
13
+ * the CLI's declared execution context — the advisory "via what" stamped
14
+ * on history; identity itself is always the token behind the client
15
+ * (`/users/me`), never injected — and the invocation's telemetry logger,
16
+ * so the engine's adoption vocabulary flows from CLI-driven operations
17
+ * (the raw-verb equivalent of `createEngine({telemetry})`). Spread by the
18
+ * instance verbs ({@link buildOperationArgs}), the definition verbs
19
+ * (e.g. `definitions delete`), and reads like `diagnose`.
20
+ */
21
+ export declare function baseEngineArgs(scope: EngineScope): EngineScope & Pick<EngineScopeArgs, 'executionContext'> & {
22
+ telemetry: WorkflowTelemetryLogger;
23
+ };
24
+ /**
25
+ * {@link baseEngineArgs} plus the instance-operation fields (everything
26
+ * but the client and the verb-specific fields). The `reason` is spread
27
+ * conditionally because the engine's optional field rejects an explicit
28
+ * `undefined` under `exactOptionalPropertyTypes`.
29
+ */
30
+ export declare function buildOperationArgs({ scope, instanceId, reason, }: {
31
+ scope: EngineScope;
32
+ instanceId: string;
33
+ reason: string | undefined;
34
+ }): OperationArgs & ReturnType<typeof baseEngineArgs> & {
35
+ reason?: string;
36
+ };
37
+ /**
38
+ * The engine the instance write commands (`start`, `fire-action`, `abort`)
39
+ * run their verb on. Its writes go to the project's Workflows service when
40
+ * the client's token cannot write instances, as for any engine.
41
+ */
42
+ export declare function cliEngine(client: WorkflowClient, scope: EngineScope): Engine;
@@ -0,0 +1,21 @@
1
+ import { createEngine, EXECUTION_KINDS, } from '@sanity/workflows';
2
+ import { cliTelemetry } from './telemetry.js';
3
+ export function baseEngineArgs(scope) {
4
+ return {
5
+ partition: scope.partition,
6
+ workflowResource: scope.workflowResource,
7
+ resourceClients: scope.resourceClients,
8
+ executionContext: { kind: EXECUTION_KINDS.cli, id: 'workflow-cli' },
9
+ telemetry: cliTelemetry().logger,
10
+ };
11
+ }
12
+ export function buildOperationArgs({ scope, instanceId, reason, }) {
13
+ return {
14
+ ...baseEngineArgs(scope),
15
+ instanceId,
16
+ ...(reason !== undefined ? { reason } : {}),
17
+ };
18
+ }
19
+ export function cliEngine(client, scope) {
20
+ return createEngine({ client, ...baseEngineArgs(scope) });
21
+ }
@@ -0,0 +1,45 @@
1
+ /** A single engine primitive that ran during a write commit — the
2
+ * reportable subset of the engine's `OpAppliedSummary`. */
3
+ export interface RanOp {
4
+ opType: string;
5
+ target?: {
6
+ scope: string;
7
+ field: string;
8
+ };
9
+ }
10
+ /** Empty when nothing ran, so callers append it unconditionally. */
11
+ export declare function opsAppliedLines(ranOps: RanOp[] | undefined): string[];
12
+ /** The subset of an engine `OperationResult` the write-verb reports read. */
13
+ export interface WriteOutcome {
14
+ changed: boolean;
15
+ cascaded: number;
16
+ instance: {
17
+ currentStage: string;
18
+ };
19
+ ranOps?: RanOp[];
20
+ }
21
+ /** The spinner message + ops block a write verb prints once its engine
22
+ * call returns. {@link opsAppliedLines} builds `opsLines`; verbs whose
23
+ * commits never run ops omit it. */
24
+ export interface WriteReport {
25
+ changed: boolean;
26
+ message: string;
27
+ opsLines?: string[];
28
+ }
29
+ /** The ", then cascaded N auto-transition(s)" suffix a write report appends
30
+ * when the commit cascaded the instance onward; empty when it didn't. */
31
+ export declare function cascadeTail(cascaded: number): string;
32
+ /**
33
+ * Run a write verb behind its spinner: start it, run the engine call, and
34
+ * emit the report — warn and bail on a no-op (`changed: false`), otherwise
35
+ * succeed and print the ops block. A throw fails the spinner and exits
36
+ * through {@link failOn}.
37
+ */
38
+ export declare function runWriteVerb<T>({ startLabel, failLabel, failHeadline, run, report, log, }: {
39
+ startLabel: string;
40
+ failLabel: string;
41
+ failHeadline: string;
42
+ run: () => Promise<T>;
43
+ report: (result: T) => WriteReport;
44
+ log: (line: string) => void;
45
+ }): Promise<void>;
@@ -0,0 +1,31 @@
1
+ import { styleText } from 'node:util';
2
+ import logSymbols from 'log-symbols';
3
+ import ora from 'ora';
4
+ import { failOn } from './fail.js';
5
+ export function opsAppliedLines(ranOps) {
6
+ const details = (ranOps ?? []).map((op) => {
7
+ const target = op.target ? styleText('dim', ` → ${op.target.scope}.${op.target.field}`) : '';
8
+ return ` ${logSymbols.info} ${op.opType}${target}`;
9
+ });
10
+ return details.length > 0 ? ['', styleText('dim', 'ops applied:'), ...details] : [];
11
+ }
12
+ export function cascadeTail(cascaded) {
13
+ return cascaded > 0 ? `, then cascaded ${cascaded} auto-transition(s)` : '';
14
+ }
15
+ export async function runWriteVerb({ startLabel, failLabel, failHeadline, run, report, log, }) {
16
+ const spinner = ora(startLabel).start();
17
+ try {
18
+ const result = await run();
19
+ const emitted = report(result);
20
+ if (!emitted.changed) {
21
+ spinner.warn(emitted.message);
22
+ return;
23
+ }
24
+ spinner.succeed(emitted.message);
25
+ emitted.opsLines?.forEach(log);
26
+ }
27
+ catch (error) {
28
+ spinner.fail(failLabel);
29
+ failOn(error, failHeadline);
30
+ }
31
+ }