@sanity/workflows-cli 0.0.0-stage → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +1981 -0
  2. package/LICENSE +21 -0
  3. package/README.md +848 -2
  4. package/bin/run.js +8 -0
  5. package/dist/command-ids.d.ts +10 -0
  6. package/dist/command-ids.js +10 -0
  7. package/dist/commands/workflows/abort.d.ts +29 -0
  8. package/dist/commands/workflows/abort.js +50 -0
  9. package/dist/commands/workflows/blueprints/generate.d.ts +12 -0
  10. package/dist/commands/workflows/blueprints/generate.js +46 -0
  11. package/dist/commands/workflows/codemod/packages.d.ts +13 -0
  12. package/dist/commands/workflows/codemod/packages.js +41 -0
  13. package/dist/commands/workflows/definitions/delete.d.ts +44 -0
  14. package/dist/commands/workflows/definitions/delete.js +74 -0
  15. package/dist/commands/workflows/definitions/diff.d.ts +23 -0
  16. package/dist/commands/workflows/definitions/diff.js +55 -0
  17. package/dist/commands/workflows/definitions/list.d.ts +52 -0
  18. package/dist/commands/workflows/definitions/list.js +139 -0
  19. package/dist/commands/workflows/definitions/show.d.ts +66 -0
  20. package/dist/commands/workflows/definitions/show.js +129 -0
  21. package/dist/commands/workflows/definitions/validate.d.ts +14 -0
  22. package/dist/commands/workflows/definitions/validate.js +50 -0
  23. package/dist/commands/workflows/deploy.d.ts +117 -0
  24. package/dist/commands/workflows/deploy.js +266 -0
  25. package/dist/commands/workflows/diagnose.d.ts +53 -0
  26. package/dist/commands/workflows/diagnose.js +195 -0
  27. package/dist/commands/workflows/fire-action.d.ts +53 -0
  28. package/dist/commands/workflows/fire-action.js +182 -0
  29. package/dist/commands/workflows/list.d.ts +79 -0
  30. package/dist/commands/workflows/list.js +249 -0
  31. package/dist/commands/workflows/nuke.d.ts +73 -0
  32. package/dist/commands/workflows/nuke.js +175 -0
  33. package/dist/commands/workflows/reset-activity.d.ts +32 -0
  34. package/dist/commands/workflows/reset-activity.js +60 -0
  35. package/dist/commands/workflows/show.d.ts +30 -0
  36. package/dist/commands/workflows/show.js +156 -0
  37. package/dist/commands/workflows/start.d.ts +57 -0
  38. package/dist/commands/workflows/start.js +196 -0
  39. package/dist/commands/workflows/tail.d.ts +24 -0
  40. package/dist/commands/workflows/tail.js +83 -0
  41. package/dist/commands/workflows/whoami.d.ts +16 -0
  42. package/dist/commands/workflows/whoami.js +53 -0
  43. package/dist/help.d.ts +13 -0
  44. package/dist/help.js +50 -0
  45. package/dist/hooks/finally/telemetry.d.ts +3 -0
  46. package/dist/hooks/finally/telemetry.js +10 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +33 -0
  48. package/dist/hooks/prerun/telemetry.js +52 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +41 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +284 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +118 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +27 -0
  62. package/dist/lib/client.js +45 -0
  63. package/dist/lib/codemod/ast.d.ts +17 -0
  64. package/dist/lib/codemod/ast.js +14 -0
  65. package/dist/lib/codemod/export-rename.d.ts +19 -0
  66. package/dist/lib/codemod/export-rename.js +337 -0
  67. package/dist/lib/codemod/manifest-rewrite.d.ts +17 -0
  68. package/dist/lib/codemod/manifest-rewrite.js +133 -0
  69. package/dist/lib/codemod/package-map.d.ts +27 -0
  70. package/dist/lib/codemod/package-map.js +99 -0
  71. package/dist/lib/codemod/report.d.ts +4 -0
  72. package/dist/lib/codemod/report.js +51 -0
  73. package/dist/lib/codemod/run.d.ts +25 -0
  74. package/dist/lib/codemod/run.js +108 -0
  75. package/dist/lib/codemod/source-rewrite.d.ts +20 -0
  76. package/dist/lib/codemod/source-rewrite.js +150 -0
  77. package/dist/lib/command-context.d.ts +20 -0
  78. package/dist/lib/command-context.js +24 -0
  79. package/dist/lib/command-telemetry.d.ts +54 -0
  80. package/dist/lib/command-telemetry.js +82 -0
  81. package/dist/lib/context.d.ts +151 -0
  82. package/dist/lib/context.js +263 -0
  83. package/dist/lib/default-partition.d.ts +23 -0
  84. package/dist/lib/default-partition.js +47 -0
  85. package/dist/lib/definition-files.d.ts +14 -0
  86. package/dist/lib/definition-files.js +60 -0
  87. package/dist/lib/definitions.d.ts +63 -0
  88. package/dist/lib/definitions.js +84 -0
  89. package/dist/lib/diff.d.ts +12 -0
  90. package/dist/lib/diff.js +93 -0
  91. package/dist/lib/env.d.ts +7 -0
  92. package/dist/lib/env.js +8 -0
  93. package/dist/lib/fail.d.ts +36 -0
  94. package/dist/lib/fail.js +55 -0
  95. package/dist/lib/failure-kind.d.ts +7 -0
  96. package/dist/lib/failure-kind.js +66 -0
  97. package/dist/lib/flags.d.ts +53 -0
  98. package/dist/lib/flags.js +127 -0
  99. package/dist/lib/follow-up-command.d.ts +18 -0
  100. package/dist/lib/follow-up-command.js +12 -0
  101. package/dist/lib/history-rows.d.ts +3 -0
  102. package/dist/lib/history-rows.js +44 -0
  103. package/dist/lib/load-config.d.ts +51 -0
  104. package/dist/lib/load-config.js +108 -0
  105. package/dist/lib/nuke.d.ts +124 -0
  106. package/dist/lib/nuke.js +206 -0
  107. package/dist/lib/operation-args.d.ts +42 -0
  108. package/dist/lib/operation-args.js +21 -0
  109. package/dist/lib/ops-report.d.ts +45 -0
  110. package/dist/lib/ops-report.js +31 -0
  111. package/dist/lib/params.d.ts +3 -0
  112. package/dist/lib/params.js +21 -0
  113. package/dist/lib/pick-resource.d.ts +13 -0
  114. package/dist/lib/pick-resource.js +82 -0
  115. package/dist/lib/prompt.d.ts +35 -0
  116. package/dist/lib/prompt.js +11 -0
  117. package/dist/lib/read-fanout.d.ts +45 -0
  118. package/dist/lib/read-fanout.js +45 -0
  119. package/dist/lib/resource-target.d.ts +10 -0
  120. package/dist/lib/resource-target.js +12 -0
  121. package/dist/lib/select-deployment.d.ts +31 -0
  122. package/dist/lib/select-deployment.js +91 -0
  123. package/dist/lib/share-definitions.d.ts +101 -0
  124. package/dist/lib/share-definitions.js +188 -0
  125. package/dist/lib/telemetry-setup.d.ts +77 -0
  126. package/dist/lib/telemetry-setup.js +117 -0
  127. package/dist/lib/telemetry.d.ts +81 -0
  128. package/dist/lib/telemetry.js +90 -0
  129. package/dist/lib/ui.d.ts +88 -0
  130. package/dist/lib/ui.js +114 -0
  131. package/dist/standalone-argv.d.ts +14 -0
  132. package/dist/standalone-argv.js +57 -0
  133. package/oclif.manifest.json +1894 -0
  134. package/package.json +118 -3
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Render a user-facing error to stderr with no oclif framing or Node stack,
3
+ * and exit non-zero.
4
+ *
5
+ * Exits via oclif's `Errors.exit`, never `process.exit`: a raw `process.exit`
6
+ * would skip the command's `finally` hook, dropping the trace and any
7
+ * batched telemetry that hasn't flushed yet.
8
+ */
9
+ export declare function fail(headline: string, detail?: string): never;
10
+ /**
11
+ * {@link fail} with {@link failureDetail} of `cause` as the detail. The exit
12
+ * error keeps `cause`, so the telemetry hook can classify the failure.
13
+ */
14
+ export declare function failOn(cause: unknown, headline: string): never;
15
+ export declare function warnOnStderr(message: string): void;
16
+ /**
17
+ * Run `fn`, funnelling a thrown env/validation error through {@link failOn}
18
+ * so an expected, user-fixable failure (missing input, bad value) reads
19
+ * clean instead of as an oclif stack trace. Keeps the throwing `read*`
20
+ * helpers pure and unit-testable while giving callers one clean boundary.
21
+ */
22
+ export declare function failOnThrow<T>(headline: string, fn: () => T): T;
23
+ /** An API rejection of the auth token itself — as opposed to a 403, where
24
+ * the identity is valid but lacks the role for the operation. Walks the
25
+ * `cause` chain because the 401 often arrives wrapped: the engine's
26
+ * `/users/me` actor resolution rethrows it inside its own `Error`. */
27
+ export declare function isAuthRejection(err: unknown): boolean;
28
+ /** `err` followed by its `cause` links, depth-bounded against self-referencing chains. */
29
+ export declare function causeChain(err: unknown): unknown[];
30
+ /**
31
+ * The detail block for a command failure: the error's message, plus the
32
+ * auth recovery hint when the API rejected the token. Every site that
33
+ * renders a caught command error should build its detail here, so the
34
+ * hint reaches the user no matter which call the token died at.
35
+ */
36
+ export declare function failureDetail(err: unknown): string;
@@ -0,0 +1,55 @@
1
+ import { styleText } from 'node:util';
2
+ import { Errors } from '@oclif/core';
3
+ import { ClientError } from '@sanity/client';
4
+ import { errorMessage } from '@sanity/workflows';
5
+ import logSymbols from 'log-symbols';
6
+ import { envAuthToken } from './env.js';
7
+ export function fail(headline, detail) {
8
+ writeFailure(headline, detail);
9
+ return Errors.exit(1);
10
+ }
11
+ export function failOn(cause, headline) {
12
+ writeFailure(headline, failureDetail(cause));
13
+ throw Object.defineProperty(new Errors.ExitError(1), 'cause', { value: cause });
14
+ }
15
+ function writeFailure(headline, detail) {
16
+ process.stderr.write(`${styleText('red', `${logSymbols.error} ${headline}`)}\n`);
17
+ if (detail !== undefined && detail !== '') {
18
+ for (const line of detail.split('\n')) {
19
+ process.stderr.write(` ${line}\n`);
20
+ }
21
+ }
22
+ }
23
+ export function warnOnStderr(message) {
24
+ process.stderr.write(`${styleText('yellow', `${logSymbols.warning} ${message}`)}\n`);
25
+ }
26
+ export function failOnThrow(headline, fn) {
27
+ try {
28
+ return fn();
29
+ }
30
+ catch (err) {
31
+ failOn(err, headline);
32
+ }
33
+ }
34
+ export function isAuthRejection(err) {
35
+ return causeChain(err).some((link) => link instanceof ClientError && link.statusCode === 401);
36
+ }
37
+ export function causeChain(err) {
38
+ const chain = [];
39
+ let current = err;
40
+ while (current !== undefined && chain.length < 5) {
41
+ chain.push(current);
42
+ current = current instanceof Error ? current.cause : undefined;
43
+ }
44
+ return chain;
45
+ }
46
+ function authRecoveryHint() {
47
+ if (envAuthToken() !== undefined) {
48
+ return 'The SANITY_AUTH_TOKEN token was rejected — check it is valid and has access to this project.';
49
+ }
50
+ return 'Your `sanity login` session may have expired — run `sanity login` and retry.';
51
+ }
52
+ export function failureDetail(err) {
53
+ const message = errorMessage(err);
54
+ return isAuthRejection(err) ? `${message}\n${authRecoveryHint()}` : message;
55
+ }
@@ -0,0 +1,7 @@
1
+ import { type WorkflowErrorKind } from '@sanity/workflows';
2
+ import type { WorkflowCliCommandResult } from './telemetry.ts';
3
+ /** Why a command failed, as a closed label. It never carries text from the error. */
4
+ export type CliFailureKind = WorkflowErrorKind | 'usage' | 'auth-missing' | 'permission-denied' | 'resource-not-found' | 'request-failed' | 'config-invalid' | 'definition-file-invalid' | 'other';
5
+ /** Record `err` as a flag or argument parsing failure. */
6
+ export declare function markUsageError(err: unknown): void;
7
+ export declare function commandResult(error: unknown): WorkflowCliCommandResult;
@@ -0,0 +1,66 @@
1
+ import { ClientError, ConnectionFailedError, isTimeoutError, ServerError } from '@sanity/client';
2
+ import { WorkflowError } from '@sanity/workflows';
3
+ import { AuthMissingError } from './client.js';
4
+ import { DefinitionFileError } from './definition-files.js';
5
+ import { causeChain } from './fail.js';
6
+ import { ConfigLoadError } from './load-config.js';
7
+ const usageErrors = new WeakSet();
8
+ export function markUsageError(err) {
9
+ if (err instanceof Error) {
10
+ usageErrors.add(err);
11
+ }
12
+ }
13
+ const STATUS_KINDS = {
14
+ 401: 'permission-denied',
15
+ 403: 'permission-denied',
16
+ 404: 'resource-not-found',
17
+ };
18
+ const NETWORK_CODES = new Set([
19
+ 'ECONNREFUSED',
20
+ 'ECONNRESET',
21
+ 'ENOTFOUND',
22
+ 'EAI_AGAIN',
23
+ 'ETIMEDOUT',
24
+ 'EHOSTUNREACH',
25
+ 'ENETUNREACH',
26
+ 'ENETDOWN',
27
+ 'EPIPE',
28
+ 'UND_ERR_CONNECT_TIMEOUT',
29
+ 'UND_ERR_SOCKET',
30
+ ]);
31
+ function errorCode(err) {
32
+ return err instanceof Error && 'code' in err && typeof err.code === 'string' ? err.code : '';
33
+ }
34
+ function statusKind(status) {
35
+ return (status === undefined ? undefined : STATUS_KINDS[status]) ?? 'request-failed';
36
+ }
37
+ function requestKind(err) {
38
+ if (err instanceof ClientError || err instanceof ServerError) {
39
+ return statusKind(err.statusCode);
40
+ }
41
+ if (err instanceof ConnectionFailedError) {
42
+ return statusKind(err.status);
43
+ }
44
+ return isTimeoutError(err) || NETWORK_CODES.has(errorCode(err)) ? 'request-failed' : undefined;
45
+ }
46
+ const RULES = [
47
+ (err) => (err instanceof WorkflowError ? err.kind : undefined),
48
+ (err) => (err instanceof Error && usageErrors.has(err) ? 'usage' : undefined),
49
+ (err) => (err instanceof AuthMissingError ? 'auth-missing' : undefined),
50
+ requestKind,
51
+ (err) => (err instanceof ConfigLoadError ? 'config-invalid' : undefined),
52
+ (err) => (err instanceof DefinitionFileError ? 'definition-file-invalid' : undefined),
53
+ ];
54
+ function failureKind(error) {
55
+ const chain = causeChain(error);
56
+ for (const rule of RULES) {
57
+ const kind = chain.map(rule).find((match) => match !== undefined);
58
+ if (kind !== undefined) {
59
+ return kind;
60
+ }
61
+ }
62
+ return 'other';
63
+ }
64
+ export function commandResult(error) {
65
+ return error === undefined ? { success: true } : { success: false, failureKind: failureKind(error) };
66
+ }
@@ -0,0 +1,53 @@
1
+ import { type WorkflowResource } from '@sanity/workflows';
2
+ export declare function flagTokens(argv: string[]): string[];
3
+ export declare function isLongFlag(token: string, name: string): boolean;
4
+ /** The last value of a flag read straight off argv, by its long name or its
5
+ * `char` short form, for code that runs before oclif parses flags. */
6
+ export declare function rawFlagValue(argv: string[], flag: {
7
+ name: string;
8
+ char?: string | undefined;
9
+ }): string | undefined;
10
+ export declare function partitionFlag(options: {
11
+ description: string;
12
+ exclusive?: string[];
13
+ }): import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
+ /** For every command that reads `sanity.workflow.ts`. */
15
+ export declare const configFlags: {
16
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ };
18
+ /** Name one resource for a read command to inspect. `--workflow-resource`
19
+ * takes any resource type in the `<type>:<id>` form `parseResourceGdr`
20
+ * reads; `--project-id` / `--dataset` name a dataset the way the Sanity CLI
21
+ * does. Write commands never spread these: they act through a deployment
22
+ * from `sanity.workflow.ts`. */
23
+ export declare const resourceFlags: {
24
+ 'workflow-resource': import("@oclif/core/interfaces").OptionFlag<WorkflowResource | undefined, import("@oclif/core/interfaces").CustomOptions>;
25
+ 'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
26
+ dataset: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
27
+ 'media-library-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
28
+ };
29
+ /** Selectors for commands that list or show what is deployed. */
30
+ export declare const readFlags: {
31
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
32
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
33
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
34
+ };
35
+ export declare const instanceFlags: {
36
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
37
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
38
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
39
+ };
40
+ /** Deploy overrides the partition flag to select every matching deployment. */
41
+ export declare const deploymentFlags: {
42
+ path: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
43
+ deployment: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
44
+ partition: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
45
+ };
46
+ /** Structured stdout instead of the rendered view. One payload convention:
47
+ * verb commands emit their operation envelope (`instanceId` carries the doc
48
+ * `_id`); read commands emit document-shaped data — `show` commands print
49
+ * the fetched document as stored, list commands print the table's row view
50
+ * (plus each row's `resource`) under a `truncated` flag. */
51
+ export declare const jsonFlags: {
52
+ json: import("@oclif/core/interfaces").BooleanFlag<boolean>;
53
+ };
@@ -0,0 +1,127 @@
1
+ import { Flags } from '@oclif/core';
2
+ import { parseResourceGdr } from '@sanity/workflows';
3
+ const instancePartitionDescription = "Workflow environment partition (e.g. prod, test) — narrows which resources are searched for the instance; the instance's stored partition is what the command uses.";
4
+ const partitionAsFilterDescription = 'Workflow environment partition (e.g. prod, test) — an optional query filter that also narrows which resources are searched; omit to span them all.';
5
+ export function flagTokens(argv) {
6
+ const terminator = argv.indexOf('--');
7
+ return terminator === -1 ? argv : argv.slice(0, terminator);
8
+ }
9
+ export function isLongFlag(token, name) {
10
+ return token === `--${name}` || token.startsWith(`--${name}=`);
11
+ }
12
+ function isShortFlag(token, char) {
13
+ return char !== undefined && token.startsWith(`-${char}`) && !token.startsWith('--');
14
+ }
15
+ function inlineValue(token, name) {
16
+ if (token.startsWith(`--${name}=`)) {
17
+ return token.slice(`--${name}=`.length);
18
+ }
19
+ if (token.startsWith('--') || token.length < 3) {
20
+ return undefined;
21
+ }
22
+ return token.slice(token[2] === '=' ? 3 : 2);
23
+ }
24
+ export function rawFlagValue(argv, flag) {
25
+ const tokens = flagTokens(argv);
26
+ const index = tokens.findLastIndex((token) => isLongFlag(token, flag.name) || isShortFlag(token, flag.char));
27
+ const token = tokens[index];
28
+ if (token === undefined) {
29
+ return undefined;
30
+ }
31
+ return inlineValue(token, flag.name) ?? tokens[index + 1];
32
+ }
33
+ export function partitionFlag(options) {
34
+ return Flags.string({ aliases: ['tag'], ...options });
35
+ }
36
+ export const configFlags = {
37
+ path: Flags.string({
38
+ description: 'Path to a sanity.workflow file, or a directory to search from upward through its parents. Defaults to the current directory.',
39
+ helpValue: '<file|dir>',
40
+ }),
41
+ };
42
+ const OVERRIDES_CONFIG = ' (overrides sanity.workflow.ts)';
43
+ const CONFIG_SELECTORS = ['path', 'deployment'];
44
+ function nonEmpty(name) {
45
+ return async (input) => {
46
+ const trimmed = input.trim();
47
+ if (trimmed === '') {
48
+ throw new Error(`\`--${name}\` cannot be empty if provided`);
49
+ }
50
+ return trimmed;
51
+ };
52
+ }
53
+ export const resourceFlags = {
54
+ 'workflow-resource': Flags.custom({
55
+ description: `Resource to read, as <type>:<id>: dataset:<projectId>.<dataset>, media-library:<id>, canvas:<id> or dashboard:<id>${OVERRIDES_CONFIG}`,
56
+ helpGroup: 'OVERRIDE',
57
+ helpValue: '<type>:<id>',
58
+ exclusive: ['project-id', 'dataset', 'media-library-id', ...CONFIG_SELECTORS],
59
+ parse: async (input) => parseResourceGdr(await nonEmpty('workflow-resource')(input)),
60
+ })(),
61
+ 'project-id': Flags.string({
62
+ char: 'p',
63
+ description: `Project ID of the dataset to read, with --dataset${OVERRIDES_CONFIG}`,
64
+ helpGroup: 'OVERRIDE',
65
+ helpValue: '<id>',
66
+ dependsOn: ['dataset'],
67
+ exclusive: ['workflow-resource', 'media-library-id', ...CONFIG_SELECTORS],
68
+ parse: nonEmpty('project-id'),
69
+ }),
70
+ dataset: Flags.string({
71
+ char: 'd',
72
+ description: `Dataset to read, with --project-id${OVERRIDES_CONFIG}`,
73
+ helpGroup: 'OVERRIDE',
74
+ helpValue: '<name>',
75
+ dependsOn: ['project-id'],
76
+ exclusive: ['workflow-resource', 'media-library-id', ...CONFIG_SELECTORS],
77
+ parse: nonEmpty('dataset'),
78
+ }),
79
+ 'media-library-id': Flags.string({
80
+ description: `Media Library to read${OVERRIDES_CONFIG}`,
81
+ deprecated: { to: 'workflow-resource media-library:<id>' },
82
+ helpGroup: 'OVERRIDE',
83
+ helpValue: '<id>',
84
+ hidden: true,
85
+ exclusive: ['workflow-resource', 'project-id', 'dataset', ...CONFIG_SELECTORS],
86
+ parse: nonEmpty('media-library-id'),
87
+ }),
88
+ };
89
+ export const readFlags = {
90
+ ...configFlags,
91
+ deployment: Flags.string({
92
+ description: 'Deployment name — read only the resource and partition that deployment targets.',
93
+ exclusive: ['partition'],
94
+ }),
95
+ partition: partitionFlag({
96
+ description: partitionAsFilterDescription,
97
+ exclusive: ['deployment'],
98
+ }),
99
+ };
100
+ export const instanceFlags = {
101
+ ...configFlags,
102
+ deployment: Flags.string({
103
+ description: 'Deployment name — narrow the instance search to the resource that deployment targets; the partition still comes from the loaded instance.',
104
+ exclusive: ['partition'],
105
+ }),
106
+ partition: partitionFlag({
107
+ description: instancePartitionDescription,
108
+ exclusive: ['deployment'],
109
+ }),
110
+ };
111
+ export const deploymentFlags = {
112
+ ...configFlags,
113
+ deployment: Flags.string({
114
+ description: 'Deployment name — the unique identity of one deployment in the config.',
115
+ exclusive: ['partition'],
116
+ }),
117
+ partition: partitionFlag({
118
+ description: 'Workflow environment partition (e.g. prod, test) — selects the deployment to act on while the partition names exactly one; pass --deployment when it spans several.',
119
+ exclusive: ['deployment'],
120
+ }),
121
+ };
122
+ export const jsonFlags = {
123
+ json: Flags.boolean({
124
+ description: 'Emit structured JSON instead of rendered output.',
125
+ default: false,
126
+ }),
127
+ };
@@ -0,0 +1,18 @@
1
+ /** The deployment selection a run was given, repeated on every command it suggests. */
2
+ export interface CommandSelection {
3
+ deployment?: string | undefined;
4
+ partition?: string | undefined;
5
+ allPartitions?: boolean | undefined;
6
+ }
7
+ /** What a suggested command needs from the current run. */
8
+ export interface FollowUpContext {
9
+ /** `this.config.bin`: the standalone binary, or the host CLI mounting it. */
10
+ bin: string;
11
+ selection?: CommandSelection;
12
+ }
13
+ /**
14
+ * A complete command line to suggest to the user: the binary that is running,
15
+ * the `workflows` topic when mounted in a host CLI, `words`, then the selection
16
+ * flags of the current run.
17
+ */
18
+ export declare function followUpCommand({ bin, selection }: FollowUpContext, ...words: string[]): string;
@@ -0,0 +1,12 @@
1
+ import { STANDALONE_BIN, WORKFLOWS_TOPIC } from '../command-ids.js';
2
+ export function followUpCommand({ bin, selection = {} }, ...words) {
3
+ const prefix = bin === STANDALONE_BIN ? [bin] : [bin, WORKFLOWS_TOPIC];
4
+ return [...prefix, ...words, ...selectionFlags(selection)].join(' ');
5
+ }
6
+ function selectionFlags({ deployment, partition, allPartitions }) {
7
+ return [
8
+ ...(deployment === undefined ? [] : ['--deployment', deployment]),
9
+ ...(partition === undefined ? [] : ['--partition', partition]),
10
+ ...(allPartitions === true ? ['--all-partitions'] : []),
11
+ ];
12
+ }
@@ -0,0 +1,3 @@
1
+ import { type HistoryEntry } from '@sanity/workflows';
2
+ /** One `show --include history` row: the entry's title, what it was about, and who did it. */
3
+ export declare function historyRow(entry: HistoryEntry): string;
@@ -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
+ }