@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,3 @@
1
+ export declare function coerceValue(raw: string): unknown;
2
+ export declare function splitParams(pairs: string[]): Record<string, string>;
3
+ export declare function parseParams(pairs: string[]): Record<string, unknown>;
@@ -0,0 +1,21 @@
1
+ export function coerceValue(raw) {
2
+ try {
3
+ return JSON.parse(raw);
4
+ }
5
+ catch {
6
+ return raw;
7
+ }
8
+ }
9
+ function splitPair(pair) {
10
+ const eq = pair.indexOf('=');
11
+ if (eq < 1) {
12
+ throw new Error(`expected key=value, got "${pair}"`);
13
+ }
14
+ return [pair.slice(0, eq), pair.slice(eq + 1)];
15
+ }
16
+ export function splitParams(pairs) {
17
+ return Object.fromEntries(pairs.map(splitPair));
18
+ }
19
+ export function parseParams(pairs) {
20
+ return Object.fromEntries(Object.entries(splitParams(pairs)).map(([key, raw]) => [key, coerceValue(raw)]));
21
+ }
@@ -0,0 +1,10 @@
1
+ import type { SanityClient } from '@sanity/client';
2
+ import type { WorkflowResource } from '@sanity/workflows';
3
+ import { selectOnStderr } from './prompt.ts';
4
+ export declare const RESOURCE_FLAGS_HINT = "Pass --project-id with --dataset, or --media-library-id, to read one resource without a config.";
5
+ type Select = typeof selectOnStderr;
6
+ export declare function pickDataset(token: string, { client, select, }?: {
7
+ client?: SanityClient;
8
+ select?: Select;
9
+ }): Promise<WorkflowResource>;
10
+ export {};
@@ -0,0 +1,30 @@
1
+ import { styleText } from 'node:util';
2
+ import logSymbols from 'log-symbols';
3
+ import { globalClient } from './client.js';
4
+ import { fail } from './fail.js';
5
+ import { selectOnStderr } from './prompt.js';
6
+ export const RESOURCE_FLAGS_HINT = 'Pass --project-id with --dataset, or --media-library-id, to read one resource without a config.';
7
+ export async function pickDataset(token, { client = globalClient(token), select = selectOnStderr, } = {}) {
8
+ const projects = await client.projects.list({ includeMembers: false });
9
+ if (projects.length === 0) {
10
+ fail('No Sanity projects found for this login.', RESOURCE_FLAGS_HINT);
11
+ }
12
+ const projectId = await select({
13
+ message: 'Select a project to read',
14
+ choices: projects.map((project) => ({
15
+ name: project.displayName,
16
+ value: project.id,
17
+ description: project.id,
18
+ })),
19
+ });
20
+ const datasets = await client.withConfig({ projectId }).datasets.list();
21
+ if (datasets.length === 0) {
22
+ fail(`Project ${projectId} has no datasets.`, RESOURCE_FLAGS_HINT);
23
+ }
24
+ const dataset = await select({
25
+ message: 'Select a dataset to read',
26
+ choices: datasets.map(({ name }) => ({ name, value: name })),
27
+ });
28
+ process.stderr.write(`${logSymbols.info} To read this dataset again without the prompt, pass: ${styleText('bold', `--project-id ${projectId} --dataset ${dataset}`)}\n`);
29
+ return { type: 'dataset', id: `${projectId}.${dataset}` };
30
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Can this process ask a question on stderr? A strict superset of the
3
+ * {@link isInteractive} gate cli-core's own prompts enforce (stdin TTY,
4
+ * `TERM` not dumb, no `CI` — so its `NonInteractiveError` can never escape a
5
+ * caller that checked here first), adding stderr-TTY because this package's
6
+ * prompts render on stderr: a redirected stderr must refuse rather than block
7
+ * on stdin with the question swallowed. It classifies whether definition
8
+ * sharing can show its full first-run disclosure and guards interactive
9
+ * prompts such as nuke's confirmation.
10
+ */
11
+ export declare function canPromptOnStderr(): boolean;
12
+ /**
13
+ * Ask a `select` question on stderr — the channel this package renders prompts
14
+ * on so a redirected stdout can't swallow the question (the display side of the
15
+ * {@link canPromptOnStderr} gate). The single site that routes a `select` to
16
+ * stderr, so no `select` prompt can silently regress to stdout.
17
+ */
18
+ export declare function selectOnStderr(config: {
19
+ message: string;
20
+ choices: readonly {
21
+ name: string;
22
+ value: string;
23
+ description?: string;
24
+ }[];
25
+ /** The value the cursor starts on — e.g. an instance's current stage, so the
26
+ * picker opens where it already is. */
27
+ default?: string;
28
+ }): Promise<string>;
29
+ /**
30
+ * Ask a yes/no question on stderr — the {@link selectOnStderr} sibling.
31
+ * `defaultAnswer` is what a bare Enter returns and sets the `y/N` or `Y/n`
32
+ * hint. Keep it `false` for a destructive confirmation, so proceeding always
33
+ * takes a deliberate keystroke.
34
+ */
35
+ export declare function confirmOnStderr(message: string, defaultAnswer?: boolean): Promise<boolean>;
@@ -0,0 +1,11 @@
1
+ import { isInteractive } from '@sanity/cli-core';
2
+ import { confirm, select } from '@sanity/cli-core/ux';
3
+ export function canPromptOnStderr() {
4
+ return isInteractive() && process.stderr.isTTY === true;
5
+ }
6
+ export function selectOnStderr(config) {
7
+ return select(config, { output: process.stderr });
8
+ }
9
+ export function confirmOnStderr(message, defaultAnswer = false) {
10
+ return confirm({ message, default: defaultAnswer }, { output: process.stderr });
11
+ }
@@ -0,0 +1,45 @@
1
+ import type { WorkflowResource } from '@sanity/workflows';
2
+ import type { ReadTarget } from './context.ts';
3
+ /** A read target whose query threw — noted in place and reflected in the
4
+ * command's exit code. */
5
+ export interface ReadFailure {
6
+ resource: WorkflowResource;
7
+ message: string;
8
+ }
9
+ /**
10
+ * The `--json` tail of a list command — the structured counterpart of
11
+ * {@link runReadAcrossTargets} + the clipped table: fetch every target's
12
+ * rows, {@link clipToLimit} each target's page, map rows through the
13
+ * command's row view (`toRow`, the structured analogue of the table's
14
+ * `toCells`), annotate each with the resource it came from (the analogue of
15
+ * the banner), and log one `{<key>: rows, truncated}` payload.
16
+ * All-or-nothing, unlike the human path's per-resource tolerance: a script
17
+ * would mistake a listing that silently omitted an unreadable resource for
18
+ * the complete result, so any failure rejects the whole read.
19
+ */
20
+ export declare function logJsonListing<T, R>({ targets, fetch, toRow, key, limit, log, }: {
21
+ targets: ReadTarget[];
22
+ fetch: (target: ReadTarget) => Promise<{
23
+ rows: T[];
24
+ hasMore: boolean;
25
+ }>;
26
+ toRow: (row: T) => R;
27
+ /** The payload's row key — names what the rows are (`instances`, `definitions`). */
28
+ key: string;
29
+ limit: number;
30
+ log: (line: string) => void;
31
+ }): Promise<void>;
32
+ /**
33
+ * Run a read over every target, grouping output per resource: a banner when
34
+ * the read spans several, then whatever `run` logs for that target. A throw
35
+ * from one target is noted under its banner and the rest still render — a
36
+ * token that can't read one dataset must not sink the whole listing. A
37
+ * single-target run rethrows instead, keeping the plain unprefixed output
38
+ * and clean error rendering at the command boundary. Callers exit non-zero
39
+ * when failures come back.
40
+ */
41
+ export declare function runReadAcrossTargets({ targets, log, run, }: {
42
+ targets: ReadTarget[];
43
+ log: (line: string) => void;
44
+ run: (target: ReadTarget) => Promise<void>;
45
+ }): Promise<ReadFailure[]>;
@@ -0,0 +1,44 @@
1
+ import logSymbols from 'log-symbols';
2
+ import { failureDetail } from './fail.js';
3
+ import { clipToLimit, groupBanner, resourceLabel } from './ui.js';
4
+ export async function logJsonListing({ targets, fetch, toRow, key, limit, log, }) {
5
+ const fetched = await Promise.all(targets.map(async (target) => {
6
+ const { rows, hasMore } = await fetch(target);
7
+ return {
8
+ rows: clipToLimit(rows, limit).rows.map((row) => ({
9
+ ...toRow(row),
10
+ resource: target.resource,
11
+ })),
12
+ hasMore: hasMore || rows.length > limit,
13
+ };
14
+ }));
15
+ log(JSON.stringify({
16
+ [key]: fetched.flatMap((result) => result.rows),
17
+ truncated: fetched.some((result) => result.hasMore),
18
+ }, null, 2));
19
+ }
20
+ export async function runReadAcrossTargets({ targets, log, run, }) {
21
+ const failures = [];
22
+ for (const [index, target] of targets.entries()) {
23
+ const banner = groupBanner({
24
+ label: resourceLabel(target.resource),
25
+ index,
26
+ total: targets.length,
27
+ });
28
+ if (banner !== undefined) {
29
+ log(banner);
30
+ }
31
+ try {
32
+ await run(target);
33
+ }
34
+ catch (error) {
35
+ if (targets.length === 1) {
36
+ throw error;
37
+ }
38
+ const message = failureDetail(error);
39
+ failures.push({ resource: target.resource, message });
40
+ log(`${logSymbols.error} ${message}`);
41
+ }
42
+ }
43
+ return failures;
44
+ }
@@ -0,0 +1,31 @@
1
+ import { type AcknowledgedWorkflowDeployment, type DeployTarget, type WorkflowConfig, type WorkflowDefinition, type WorkflowDeployment } from '@sanity/workflows';
2
+ export type ChooseDeploymentName = (deployments: WorkflowDeployment[]) => Promise<string>;
3
+ export interface DeploymentSelectionOptions {
4
+ name: string | undefined;
5
+ partition: string | undefined;
6
+ allPartitions: boolean;
7
+ interactive?: boolean;
8
+ chooseName?: ChooseDeploymentName;
9
+ }
10
+ /** The one identity format for a deployment in output — banners, failure
11
+ * summaries, and "available deployments" listings all render it the same
12
+ * way. */
13
+ export declare function deploymentLabel({ name, partition, }: Pick<WorkflowDeployment, 'name' | 'partition'>): string;
14
+ /** Deployment names are unique across the config; partitions may repeat across resources. */
15
+ export declare function selectDeployment(config: WorkflowConfig, { name, partition, orAlternative, interactive, chooseName, }: {
16
+ name: string | undefined;
17
+ partition: string | undefined;
18
+ orAlternative?: string;
19
+ interactive?: boolean | undefined;
20
+ chooseName?: ChooseDeploymentName | undefined;
21
+ }): Promise<WorkflowDeployment>;
22
+ export declare function deploymentsForPartition(config: WorkflowConfig, partition: string): WorkflowDeployment[];
23
+ export declare function selectDeployments(config: WorkflowConfig, { name, partition, allPartitions, interactive, chooseName }: DeploymentSelectionOptions): Promise<WorkflowDeployment[]>;
24
+ /** The shared acknowledgement boundary for the CLI's definition-submission paths. */
25
+ export declare function acknowledgeDeployment(deployment: WorkflowDeployment, definitions: readonly WorkflowDefinition[]): AcknowledgedWorkflowDeployment;
26
+ /**
27
+ * Project a deployment into the engine's {@link DeployTarget} — the shape the
28
+ * deploy/diff verbs (`deployDefinitions`, `computeDiffEntries`, `diffEntry`)
29
+ * consume — expanding its handle bindings into the alias map in the same step.
30
+ */
31
+ export declare function deploymentToTarget(deployment: AcknowledgedWorkflowDeployment): DeployTarget;
@@ -0,0 +1,91 @@
1
+ import { assertReaderModelAcknowledgement, requiredDefinitionReaderModel, resourceAliasesToMap, } from '@sanity/workflows';
2
+ import { fail } from './fail.js';
3
+ import { canPromptOnStderr, selectOnStderr } from './prompt.js';
4
+ export function deploymentLabel({ name, partition, }) {
5
+ return `${name} (${partition})`;
6
+ }
7
+ export async function selectDeployment(config, { name, partition, orAlternative = '', interactive, chooseName = chooseDeploymentName, }) {
8
+ if (name !== undefined) {
9
+ const deployment = config.deployments.find((candidate) => candidate.name === name);
10
+ if (deployment === undefined) {
11
+ fail(`No deployment named "${name}".`, availableDeployments(config));
12
+ }
13
+ return deployment;
14
+ }
15
+ if (partition !== undefined) {
16
+ const matches = deploymentsForPartition(config, partition);
17
+ const [sole, ...rest] = matches;
18
+ if (sole === undefined || rest.length > 0) {
19
+ fail(`Multiple deployments in partition "${partition}" — pass --deployment to choose one.`, availableDeployments(config, matches));
20
+ }
21
+ return sole;
22
+ }
23
+ return selectDefaultDeployment(config, { orAlternative, interactive, chooseName });
24
+ }
25
+ async function selectDefaultDeployment(config, { orAlternative, interactive, chooseName, }) {
26
+ if (config.deployments.length > 1) {
27
+ if (interactive ?? canPromptOnStderr()) {
28
+ const selectedName = await chooseName(config.deployments);
29
+ return selectDeployment(config, { name: selectedName, partition: undefined });
30
+ }
31
+ fail(`Multiple deployments configured — pass --deployment or --partition${orAlternative}.`, availableDeployments(config));
32
+ }
33
+ const [sole] = config.deployments;
34
+ if (sole === undefined) {
35
+ fail('No deployments configured.');
36
+ }
37
+ return sole;
38
+ }
39
+ export function deploymentsForPartition(config, partition) {
40
+ const matches = config.deployments.filter((candidate) => candidate.partition === partition);
41
+ if (matches.length === 0) {
42
+ fail(`No deployment for partition "${partition}".`, availableDeployments(config));
43
+ }
44
+ return matches;
45
+ }
46
+ export async function selectDeployments(config, { name, partition, allPartitions, interactive, chooseName }) {
47
+ if (allPartitions) {
48
+ return config.deployments;
49
+ }
50
+ if (partition !== undefined) {
51
+ return deploymentsForPartition(config, partition);
52
+ }
53
+ return [
54
+ await selectDeployment(config, {
55
+ name,
56
+ partition,
57
+ orAlternative: ', or --all-partitions to deploy every deployment',
58
+ interactive,
59
+ chooseName,
60
+ }),
61
+ ];
62
+ }
63
+ async function chooseDeploymentName(deployments) {
64
+ return selectOnStderr({
65
+ message: 'Select a deployment',
66
+ choices: deployments.map(({ name, partition }) => ({
67
+ name,
68
+ value: name,
69
+ description: `partition: ${partition}`,
70
+ })),
71
+ });
72
+ }
73
+ function availableDeployments(config, deployments = config.deployments) {
74
+ return `Available deployments: ${deployments.map(deploymentLabel).join(', ')}`;
75
+ }
76
+ export function acknowledgeDeployment(deployment, definitions) {
77
+ const expectedMinReaderModel = deployment.expectedMinReaderModel;
78
+ assertReaderModelAcknowledgement(expectedMinReaderModel, {
79
+ context: `Deployment ${deployment.name}`,
80
+ requiredMinReaderModel: requiredDefinitionReaderModel(definitions),
81
+ });
82
+ return { ...deployment, expectedMinReaderModel };
83
+ }
84
+ export function deploymentToTarget(deployment) {
85
+ return {
86
+ expectedMinReaderModel: deployment.expectedMinReaderModel,
87
+ partition: deployment.partition,
88
+ workflowResource: deployment.workflowResource,
89
+ resourceAliases: resourceAliasesToMap(deployment.resourceAliases),
90
+ };
91
+ }
@@ -0,0 +1,101 @@
1
+ /** Consent model: opt-OUT. Sharing new definition versions defaults on; only
2
+ * --no-share-defs turns it off — CI, DO_NOT_TRACK, and non-TTY don't change that. */
3
+ import { type DeployDefinitionResult, type DeployedDefinition, type WorkflowResource } from '@sanity/workflows';
4
+ import { type FollowUpContext } from './follow-up-command.ts';
5
+ import type { UserConfigStore } from './telemetry-setup.ts';
6
+ import { type WorkflowDefinitionSharedData } from './telemetry.ts';
7
+ /** The client slice sharing uses — the read-back of just-deployed
8
+ * documents and the feedback POST, structurally, so a full
9
+ * `SanityClient` satisfies it and tests fake exactly these calls. */
10
+ export interface ShareClient {
11
+ fetch<T>(query: string, params: Record<string, unknown>, options: {
12
+ tag: string;
13
+ }): Promise<T>;
14
+ request<T>(opts: {
15
+ url: string;
16
+ method: string;
17
+ body: unknown;
18
+ tag: string;
19
+ }): Promise<T>;
20
+ }
21
+ /** One successfully deployed deployment's outcome, paired with the client
22
+ * that can read the just-deployed documents back and the resource the
23
+ * entries' deployment coordinates derive from. */
24
+ export interface ShareCandidate {
25
+ client: ShareClient;
26
+ partition: string;
27
+ resource: WorkflowResource;
28
+ results: DeployDefinitionResult[];
29
+ /** The deploy call's run id — the markers carry the same id the engine's
30
+ * deploy events minted, so donated definitions group with their deploy. */
31
+ deployId: string;
32
+ }
33
+ /** Sanity's first-party definition-feedback endpoint (editorial-ai-backend,
34
+ * routed project-agnostically through the API gateway). */
35
+ export declare const SHARE_ENDPOINT_URL = "/workflow/definition-feedback";
36
+ /**
37
+ * The first-run disclosure — a product contract, pinned by test. It must
38
+ * name the recipient (Sanity), state that the document ships VERBATIM with its
39
+ * deployment coordinates and is kept, name what is never shared, and disclose
40
+ * that the notice is remembered machine-wide and name the per-run opt-out.
41
+ * This is a notice, not a choice: sharing is the default unless the invocation
42
+ * supplies `--no-share-defs`.
43
+ */
44
+ export declare const SHARE_FIRST_RUN_NOTICE: string;
45
+ /**
46
+ * The status block printed on every flagless deploy that does not show the
47
+ * first-run disclosure. It keeps the default donation obvious in terminals and
48
+ * unattended logs and names both explicit controls as runnable commands.
49
+ */
50
+ export declare function shareReminder(followUp: FollowUpContext): string;
51
+ /**
52
+ * The content-free telemetry marker for one shared definition — projected
53
+ * from the engine's own deploy-event derivation ({@link definitionDeployedData})
54
+ * so `Workflows CLI Definition Shared` and `Workflows Engine Definition Deployed`
55
+ * can never disagree about one definition's structure. Status is dropped: only
56
+ * newly created versions are ever shared.
57
+ */
58
+ export declare function definitionShareMarker(args: {
59
+ definition: DeployedDefinition;
60
+ contentHash: string;
61
+ deployId: string;
62
+ }): WorkflowDefinitionSharedData;
63
+ /**
64
+ * Whether the invocation's telemetry should send despite the environment
65
+ * denial (CI / `DO_NOT_TRACK`). Every flagless or explicitly enabled deploy
66
+ * that can create versions forces it, because definition donation defaults on
67
+ * in those environments too. Account-level consent is never
68
+ * overridden (the intake still reads `/intake/telemetry-status`).
69
+ *
70
+ * Computed from raw argv because the prerun hook builds the store before oclif
71
+ * parses flags, so it must land on the same value oclif will: repeated
72
+ * `allowNo` booleans are **last-token-wins**, and tokens after `--` aren't
73
+ * flags. `--dry-run` / `--check` never create versions, so they never donate —
74
+ * no telemetry to force. The `share-defs` flag has no char/alias/env source,
75
+ * so `--share-defs` / `--no-share-defs` are its only tokens (add one and this
76
+ * match must learn it too).
77
+ */
78
+ export declare function shouldForceShareTelemetry(args: {
79
+ commandId: string | undefined;
80
+ argv: string[];
81
+ }): boolean;
82
+ /**
83
+ * The whole post-deploy sharing flow. An explicit flag decides directly;
84
+ * otherwise sharing defaults on after emitting either the one-time disclosure
85
+ * or recurring reminder. It always records the content-free per-invocation
86
+ * decision so adoption dashboards can measure opt-out rate. No newly created
87
+ * versions (unchanged re-deploys, dry runs, nothing succeeded) means no
88
+ * decision, notice, or POST.
89
+ *
90
+ * The optional args exist for the flow's dependencies, mirroring
91
+ * `setupCliTelemetry` — omitted, the real process surfaces apply.
92
+ */
93
+ export declare function shareDefinitionsAfterDeploy(args: {
94
+ flag: boolean | undefined;
95
+ followUp: FollowUpContext;
96
+ candidates: ShareCandidate[];
97
+ warn: (message: string) => void;
98
+ interactive?: boolean;
99
+ writeStderr?: (message: string) => void;
100
+ userConfig?: UserConfigStore;
101
+ }): Promise<void>;
@@ -0,0 +1,188 @@
1
+ import { styleText } from 'node:util';
2
+ import { getUserConfig } from '@sanity/cli-core';
3
+ import { assertReadableModel, definitionDeployedData, errorMessage, } from '@sanity/workflows';
4
+ import { WORKFLOWS_DEPLOY_COMMAND_ID } from '../command-ids.js';
5
+ import { buildDefinitionShowQuery } from './definitions.js';
6
+ import { flagTokens } from './flags.js';
7
+ import { followUpCommand } from './follow-up-command.js';
8
+ import { canPromptOnStderr } from './prompt.js';
9
+ import { cliTelemetry, WorkflowDefinitionShared, WorkflowDefinitionSharingDecided, } from './telemetry.js';
10
+ export const SHARE_ENDPOINT_URL = '/workflow/definition-feedback';
11
+ const SHARE_TAG = 'definition.share';
12
+ const SHARE_DECISION_KEY = 'workflowCliDefinitionSharing';
13
+ export const SHARE_FIRST_RUN_NOTICE = `${styleText('bold', 'Sharing new workflow definitions with Sanity')} to improve Workflows.\n` +
14
+ 'They are sent verbatim (structure, names, filters, effect configuration,\n' +
15
+ 'seeded values) with their deployment coordinates, and kept — never your\n' +
16
+ 'content documents, workflow instances, or Sanity auth token. This notice is\n' +
17
+ `shown once on this machine; opt out of any run with ${styleText('cyan', '--no-share-defs')}.\n`;
18
+ export function shareReminder(followUp) {
19
+ const examples = [
20
+ { flags: [], note: 'share by default' },
21
+ { flags: ['--share-defs'], note: 'share explicitly; hide this warning' },
22
+ { flags: ['--no-share-defs'], note: 'opt out' },
23
+ ].map(({ flags, note }) => ({ command: followUpCommand(followUp, 'deploy', ...flags), note }));
24
+ const width = Math.max(...examples.map(({ command }) => command.length));
25
+ return (`${styleText('bold', 'Definition sharing: ON (default)')}\n` +
26
+ 'New workflow definition versions are being shared with Sanity to improve Workflows.\n' +
27
+ 'Examples:\n' +
28
+ examples
29
+ .map(({ command, note }) => ` ${styleText('dim', '$')} ${command.padEnd(width)} ${styleText('dim', `# ${note}`)}\n`)
30
+ .join(''));
31
+ }
32
+ export function definitionShareMarker(args) {
33
+ const { status: _status, ...structural } = definitionDeployedData(args.definition, {
34
+ contentHash: args.contentHash,
35
+ status: 'created',
36
+ deployId: args.deployId,
37
+ });
38
+ return structural;
39
+ }
40
+ export function shouldForceShareTelemetry(args) {
41
+ const { commandId, argv } = args;
42
+ if (commandId !== WORKFLOWS_DEPLOY_COMMAND_ID) {
43
+ return false;
44
+ }
45
+ const tokens = flagTokens(argv);
46
+ if (tokens.includes('--dry-run') || tokens.includes('--check')) {
47
+ return false;
48
+ }
49
+ return (tokens.lastIndexOf('--share-defs') > tokens.lastIndexOf('--no-share-defs') ||
50
+ !tokens.includes('--no-share-defs'));
51
+ }
52
+ async function loadShareEntry(args) {
53
+ const { candidate, result, warn } = args;
54
+ const deployed = await loadDeployedForShare(args);
55
+ if (deployed === undefined) {
56
+ return undefined;
57
+ }
58
+ if (deployed.contentHash === undefined) {
59
+ warn(`${result.name} v${result.version} carries no content hash — not shared.`);
60
+ return undefined;
61
+ }
62
+ return {
63
+ definition: deployed,
64
+ contentHash: deployed.contentHash,
65
+ name: result.name,
66
+ version: result.version,
67
+ resourceType: candidate.resource.type,
68
+ resourceId: candidate.resource.id,
69
+ };
70
+ }
71
+ async function loadDeployedForShare(args) {
72
+ const { candidate, result, warn } = args;
73
+ const { groq, params } = buildDefinitionShowQuery({
74
+ name: result.name,
75
+ partition: candidate.partition,
76
+ version: result.version,
77
+ });
78
+ try {
79
+ const deployed = await candidate.client.fetch(groq, params, {
80
+ tag: SHARE_TAG,
81
+ });
82
+ if (deployed === null) {
83
+ warn(`Could not read back ${result.name} v${result.version} — not shared.`);
84
+ return undefined;
85
+ }
86
+ assertReadableModel(deployed);
87
+ return deployed;
88
+ }
89
+ catch (error) {
90
+ warn(`Could not read back ${result.name} v${result.version} — not shared. ${errorMessage(error)}`);
91
+ return undefined;
92
+ }
93
+ }
94
+ function collectCreated(candidates) {
95
+ return candidates.flatMap((candidate) => candidate.results
96
+ .filter((result) => result.status === 'created')
97
+ .map((result) => ({ candidate, result })));
98
+ }
99
+ function wasShareNoticeShown(userConfig) {
100
+ const value = userConfig.get(SHARE_DECISION_KEY);
101
+ return typeof value === 'boolean';
102
+ }
103
+ function rememberShareNotice(userConfig) {
104
+ try {
105
+ userConfig.set(SHARE_DECISION_KEY, true);
106
+ }
107
+ catch {
108
+ }
109
+ }
110
+ function resolveShareIntent(args) {
111
+ if (args.flag === true) {
112
+ return { share: true, decision: 'opt-in' };
113
+ }
114
+ if (args.flag === false) {
115
+ return { share: false, decision: 'opt-out' };
116
+ }
117
+ if (args.interactive && !wasShareNoticeShown(args.userConfig)) {
118
+ args.writeStderr(SHARE_FIRST_RUN_NOTICE);
119
+ rememberShareNotice(args.userConfig);
120
+ }
121
+ else {
122
+ args.writeStderr(shareReminder(args.followUp));
123
+ }
124
+ return { share: true, decision: 'default' };
125
+ }
126
+ async function donate(args) {
127
+ const shared = [];
128
+ try {
129
+ for (const item of args.created) {
130
+ const entry = await loadShareEntry({ ...item, warn: args.warn });
131
+ if (entry !== undefined) {
132
+ shared.push({ entry, candidate: item.candidate });
133
+ }
134
+ }
135
+ if (shared.length === 0) {
136
+ return false;
137
+ }
138
+ await shared[0].candidate.client.request({
139
+ url: SHARE_ENDPOINT_URL,
140
+ method: 'POST',
141
+ body: { definitions: shared.map(({ entry }) => entry) },
142
+ tag: SHARE_TAG,
143
+ });
144
+ }
145
+ catch (error) {
146
+ args.warn(`Definition sharing failed — nothing shared. ${errorMessage(error)}`);
147
+ return false;
148
+ }
149
+ emitShareMarkers(shared);
150
+ return true;
151
+ }
152
+ function emitShareMarkers(shared) {
153
+ try {
154
+ const { logger } = cliTelemetry();
155
+ for (const { entry, candidate } of shared) {
156
+ logger.log(WorkflowDefinitionShared, definitionShareMarker({ ...entry, deployId: candidate.deployId }));
157
+ }
158
+ }
159
+ catch {
160
+ }
161
+ }
162
+ function emitSharingDecided(data) {
163
+ try {
164
+ cliTelemetry().logger.log(WorkflowDefinitionSharingDecided, data);
165
+ }
166
+ catch {
167
+ }
168
+ }
169
+ export async function shareDefinitionsAfterDeploy(args) {
170
+ const created = collectCreated(args.candidates);
171
+ if (created.length === 0) {
172
+ return;
173
+ }
174
+ try {
175
+ const { share, decision } = resolveShareIntent({
176
+ flag: args.flag,
177
+ followUp: args.followUp,
178
+ interactive: args.interactive ?? canPromptOnStderr(),
179
+ userConfig: args.userConfig ?? getUserConfig(),
180
+ writeStderr: args.writeStderr ?? ((message) => void process.stderr.write(message)),
181
+ });
182
+ const shared = share ? await donate({ created, warn: args.warn }) : false;
183
+ emitSharingDecided({ decision, shared, definitionCount: created.length });
184
+ }
185
+ catch (error) {
186
+ args.warn(`Definition sharing skipped — ${errorMessage(error)}`);
187
+ }
188
+ }