@sanity/workflows-cli 0.0.0-pr-744-20261109125055

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +1848 -0
  2. package/LICENSE +21 -0
  3. package/README.md +798 -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 +9 -0
  47. package/dist/hooks/prerun/telemetry.d.ts +28 -0
  48. package/dist/hooks/prerun/telemetry.js +37 -0
  49. package/dist/index.d.ts +1 -0
  50. package/dist/index.js +1 -0
  51. package/dist/lib/base-command.d.ts +14 -0
  52. package/dist/lib/base-command.js +34 -0
  53. package/dist/lib/blueprint-emit.d.ts +56 -0
  54. package/dist/lib/blueprint-emit.js +233 -0
  55. package/dist/lib/blueprint-needs.d.ts +5 -0
  56. package/dist/lib/blueprint-needs.js +205 -0
  57. package/dist/lib/blueprint-stacks.d.ts +6 -0
  58. package/dist/lib/blueprint-stacks.js +88 -0
  59. package/dist/lib/cause-detail.d.ts +9 -0
  60. package/dist/lib/cause-detail.js +112 -0
  61. package/dist/lib/client.d.ts +24 -0
  62. package/dist/lib/client.js +40 -0
  63. package/dist/lib/codemod/manifest-rewrite.d.ts +14 -0
  64. package/dist/lib/codemod/manifest-rewrite.js +97 -0
  65. package/dist/lib/codemod/package-map.d.ts +22 -0
  66. package/dist/lib/codemod/package-map.js +72 -0
  67. package/dist/lib/codemod/report.d.ts +5 -0
  68. package/dist/lib/codemod/report.js +43 -0
  69. package/dist/lib/codemod/run.d.ts +23 -0
  70. package/dist/lib/codemod/run.js +103 -0
  71. package/dist/lib/codemod/source-rewrite.d.ts +18 -0
  72. package/dist/lib/codemod/source-rewrite.js +155 -0
  73. package/dist/lib/command-context.d.ts +20 -0
  74. package/dist/lib/command-context.js +24 -0
  75. package/dist/lib/command-telemetry.d.ts +54 -0
  76. package/dist/lib/command-telemetry.js +82 -0
  77. package/dist/lib/context.d.ts +155 -0
  78. package/dist/lib/context.js +268 -0
  79. package/dist/lib/default-partition.d.ts +23 -0
  80. package/dist/lib/default-partition.js +48 -0
  81. package/dist/lib/definition-files.d.ts +11 -0
  82. package/dist/lib/definition-files.js +58 -0
  83. package/dist/lib/definitions.d.ts +63 -0
  84. package/dist/lib/definitions.js +84 -0
  85. package/dist/lib/diff.d.ts +12 -0
  86. package/dist/lib/diff.js +93 -0
  87. package/dist/lib/env.d.ts +7 -0
  88. package/dist/lib/env.js +8 -0
  89. package/dist/lib/fail.d.ts +29 -0
  90. package/dist/lib/fail.js +46 -0
  91. package/dist/lib/flags.d.ts +49 -0
  92. package/dist/lib/flags.js +117 -0
  93. package/dist/lib/follow-up-command.d.ts +18 -0
  94. package/dist/lib/follow-up-command.js +12 -0
  95. package/dist/lib/history-rows.d.ts +3 -0
  96. package/dist/lib/history-rows.js +44 -0
  97. package/dist/lib/load-config.d.ts +46 -0
  98. package/dist/lib/load-config.js +110 -0
  99. package/dist/lib/nuke.d.ts +124 -0
  100. package/dist/lib/nuke.js +206 -0
  101. package/dist/lib/operation-args.d.ts +42 -0
  102. package/dist/lib/operation-args.js +21 -0
  103. package/dist/lib/ops-report.d.ts +47 -0
  104. package/dist/lib/ops-report.js +31 -0
  105. package/dist/lib/params.d.ts +3 -0
  106. package/dist/lib/params.js +21 -0
  107. package/dist/lib/pick-dataset.d.ts +10 -0
  108. package/dist/lib/pick-dataset.js +30 -0
  109. package/dist/lib/prompt.d.ts +35 -0
  110. package/dist/lib/prompt.js +11 -0
  111. package/dist/lib/read-fanout.d.ts +45 -0
  112. package/dist/lib/read-fanout.js +44 -0
  113. package/dist/lib/select-deployment.d.ts +31 -0
  114. package/dist/lib/select-deployment.js +91 -0
  115. package/dist/lib/share-definitions.d.ts +101 -0
  116. package/dist/lib/share-definitions.js +188 -0
  117. package/dist/lib/telemetry-setup.d.ts +81 -0
  118. package/dist/lib/telemetry-setup.js +111 -0
  119. package/dist/lib/telemetry.d.ts +78 -0
  120. package/dist/lib/telemetry.js +90 -0
  121. package/dist/lib/ui.d.ts +91 -0
  122. package/dist/lib/ui.js +116 -0
  123. package/dist/standalone-argv.d.ts +14 -0
  124. package/dist/standalone-argv.js +57 -0
  125. package/oclif.manifest.json +1731 -0
  126. package/package.json +121 -0
@@ -0,0 +1,9 @@
1
+ import { finishCliTelemetry } from '../../lib/telemetry.js';
2
+ const hook = async function (options) {
3
+ try {
4
+ await finishCliTelemetry({ success: options.error === undefined });
5
+ }
6
+ catch {
7
+ }
8
+ };
9
+ export default hook;
@@ -0,0 +1,28 @@
1
+ import type { Hook } from '@oclif/core';
2
+ import type { CommandTelemetry, FlagShape } from '../../lib/command-telemetry.ts';
3
+ export declare const CLI_PACKAGE_NAME = "@sanity/workflows-cli";
4
+ /** Under a host CLI, oclif passes this plugin's hooks the host's config, so
5
+ * `config.version` is the host's version; the plugin entry holds ours. */
6
+ export declare function cliPackageVersion(config: {
7
+ plugins: ReadonlyMap<string, {
8
+ version: string;
9
+ }>;
10
+ }): string | undefined;
11
+ /** Builds and installs the invocation's telemetry shell before the command
12
+ * runs; the `finally` hook completes the trace and flushes. Never throws.
13
+ * A deploy that may share definitions—flagless by default or explicitly
14
+ * enabled—forces the store to send despite CI / `DO_NOT_TRACK`. This is
15
+ * resolved from raw argv because the store is built before oclif parses
16
+ * flags. Skips non-workflows commands when this package is mounted as a
17
+ * host plugin so `sanity dataset list` does not inherit the shell. */
18
+ export declare function installPrerunTelemetry(args: {
19
+ bin: string;
20
+ version: string | undefined;
21
+ commandId: string | undefined;
22
+ argv: string[];
23
+ flagDefs?: Record<string, FlagShape> | undefined;
24
+ commandTelemetry?: CommandTelemetry | undefined;
25
+ env?: Record<string, string | undefined>;
26
+ }): Promise<void>;
27
+ declare const hook: Hook<'prerun'>;
28
+ export default hook;
@@ -0,0 +1,37 @@
1
+ import { shouldRunWorkflowCliTelemetry } from '../../command-ids.js';
2
+ import { commandTraceContext } from '../../lib/command-context.js';
3
+ import { rawFlagValue, resourceFlags } from '../../lib/flags.js';
4
+ import { shouldForceShareTelemetry } from '../../lib/share-definitions.js';
5
+ import { setupCliTelemetry } from '../../lib/telemetry-setup.js';
6
+ export const CLI_PACKAGE_NAME = '@sanity/workflows-cli';
7
+ export function cliPackageVersion(config) {
8
+ return config.plugins.get(CLI_PACKAGE_NAME)?.version;
9
+ }
10
+ export async function installPrerunTelemetry(args) {
11
+ const { bin, version, commandId, argv, flagDefs, commandTelemetry, env = process.env } = args;
12
+ if (!shouldRunWorkflowCliTelemetry({ bin, commandId })) {
13
+ return;
14
+ }
15
+ await setupCliTelemetry({
16
+ cliVersion: version,
17
+ configPath: rawFlagValue(argv, { name: 'path' }),
18
+ target: {
19
+ projectId: rawFlagValue(argv, { name: 'project-id', char: resourceFlags['project-id'].char }),
20
+ dataset: rawFlagValue(argv, { name: 'dataset', char: resourceFlags.dataset.char }),
21
+ },
22
+ forceSend: shouldForceShareTelemetry({ commandId, argv }),
23
+ context: commandTraceContext({ commandId, argv, flagDefs, commandTelemetry, env }),
24
+ env,
25
+ });
26
+ }
27
+ const hook = async function ({ config, Command, argv }) {
28
+ await installPrerunTelemetry({
29
+ bin: config.bin,
30
+ version: cliPackageVersion(config),
31
+ commandId: Command?.id,
32
+ argv,
33
+ flagDefs: Command?.flags,
34
+ commandTelemetry: Command?.telemetry,
35
+ });
36
+ };
37
+ export default hook;
@@ -0,0 +1 @@
1
+ export { execute } from '@oclif/core';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { execute } from '@oclif/core';
@@ -0,0 +1,14 @@
1
+ import { Command } from '@oclif/core';
2
+ /**
3
+ * Base for workflow commands: prompt interrupts exit with the conventional
4
+ * SIGINT code and no stack; an auth rejection, a reader-floor acknowledgement
5
+ * failure, and an unknown-project-roles or spawn-contract rejection — all
6
+ * expected, user-fixable — render through the clean {@link fail} path. Every
7
+ * other error propagates to oclif unchanged.
8
+ */
9
+ export declare abstract class WorkflowCommand extends Command {
10
+ protected init(): Promise<void>;
11
+ protected catch(err: Error & {
12
+ exitCode?: number;
13
+ }): Promise<unknown>;
14
+ }
@@ -0,0 +1,34 @@
1
+ import { styleText } from 'node:util';
2
+ import { Command } from '@oclif/core';
3
+ import { exitCodes } from '@sanity/cli-core';
4
+ import { ReaderModelAcknowledgementError, SpawnContractsInvalidError, UnknownProjectRolesError, } from '@sanity/workflows';
5
+ import { fail, failureDetail, isAuthRejection } from './fail.js';
6
+ import { flagTokens, isLongFlag } from './flags.js';
7
+ export class WorkflowCommand extends Command {
8
+ async init() {
9
+ const tokens = flagTokens(this.argv);
10
+ const deprecated = Object.entries(this.ctor.flags ?? {}).flatMap(([name, flag]) => (flag.aliases ?? [])
11
+ .filter((alias) => tokens.some((token) => isLongFlag(token, alias)))
12
+ .map((alias) => ({ alias, name })));
13
+ deprecated.forEach(({ alias, name }) => {
14
+ this.warn(`The --${alias} flag is deprecated and will be removed. Use --${name} instead; keep the same partition value.`);
15
+ });
16
+ await super.init();
17
+ }
18
+ async catch(err) {
19
+ if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {
20
+ this.logToStderr(`${styleText('yellow', '›')} Aborted by user`);
21
+ return this.exit(exitCodes.SIGINT);
22
+ }
23
+ if (isAuthRejection(err)) {
24
+ fail('Authentication failed:', failureDetail(err));
25
+ }
26
+ if (err instanceof ReaderModelAcknowledgementError) {
27
+ fail('Reader-floor acknowledgement:', err.message);
28
+ }
29
+ if (err instanceof UnknownProjectRolesError || err instanceof SpawnContractsInvalidError) {
30
+ fail('Definitions rejected:', err.message);
31
+ }
32
+ return super.catch(err);
33
+ }
34
+ }
@@ -0,0 +1,56 @@
1
+ import { type WorkflowConfig } from '@sanity/workflows';
2
+ export interface BlueprintGenerationArgs {
3
+ /** The directory the config was loaded from. Every planned path is relative
4
+ * to it, and the tree is written under it. */
5
+ root: string;
6
+ config: WorkflowConfig;
7
+ /** The config file's name as discovered in `root`. Decides the specifier the
8
+ * generated modules import their deployment from, and names the file in a
9
+ * diagnostic. */
10
+ configFile: string;
11
+ exportedNames: readonly string[];
12
+ log: (line: string) => void;
13
+ /** Columns to wrap the needs report to; `undefined` leaves every line whole. */
14
+ width: number | undefined;
15
+ }
16
+ export interface BlueprintWriteArgs extends BlueprintGenerationArgs {
17
+ /** Print every needs detail, every file, and the heartbeat stack's
18
+ * instructions even when its files are unchanged. */
19
+ verbose: boolean;
20
+ }
21
+ export interface BlueprintCheckArgs extends BlueprintGenerationArgs {
22
+ /** `this.config.bin`, for the `blueprints generate` command a failed check suggests. */
23
+ bin: string;
24
+ }
25
+ /**
26
+ * Writes the runtime tree `config` requires under `root`. A handler stub is
27
+ * written only where none exists, and nothing is ever deleted.
28
+ *
29
+ * Exits through the clean `fail` path, writing nothing, when a definition fails
30
+ * deploy-time validation, when the definitions cannot produce a plan, when the
31
+ * config module does not export a deployment by name, or when the project
32
+ * declares no version for a dependency the generated functions import.
33
+ */
34
+ export declare function generateBlueprint(args: BlueprintWriteArgs): void;
35
+ /**
36
+ * Compares the runtime tree `config` requires with the files under `root`,
37
+ * writing nothing. Logs one success line when they match, and otherwise exits
38
+ * non-zero through the clean `fail` path with one entry per problem, a stale
39
+ * generated function directory included. Takes the same exits as
40
+ * {@link generateBlueprint} before it can compare anything.
41
+ */
42
+ export declare function checkBlueprint(args: BlueprintCheckArgs): void;
43
+ export interface DeployAlignmentArgs extends BlueprintCheckArgs {
44
+ warn: (message: string) => void;
45
+ /** The names of the deployments this run deploys. With no generated tree,
46
+ * only their needs are reported; the drift check still covers the whole
47
+ * config. */
48
+ selected: readonly string[];
49
+ /** Print the full needs report in place of the per-deployment summary. */
50
+ verbose: boolean;
51
+ }
52
+ /** Exits non-zero through `fail` when a generated tree exists and drifts from
53
+ * the definitions; returns normally otherwise, including when no tree
54
+ * exists. A stale generated function directory is warned about and does not
55
+ * stop the deploy, because the generated blueprint does not deploy it. */
56
+ export declare function checkDeployAlignment(args: DeployAlignmentArgs): void;
@@ -0,0 +1,233 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { styleText } from 'node:util';
4
+ import { errorMessage } from '@sanity/workflows';
5
+ import { applyEmissionWritePlan, deploymentExportIdentifier, generatedRuntimeAlignment, runtimeEmissionPlan, WORKFLOW_RESOURCES_PATH, } from '@sanity/workflows/blueprints/generate';
6
+ import logSymbols from 'log-symbols';
7
+ import { needsBriefLines, needsFunctions, needsReportLines, needsSummaryLines, } from './blueprint-needs.js';
8
+ import { stackDeployLines } from './blueprint-stacks.js';
9
+ import { validateOrFail } from './definitions.js';
10
+ import { fail, failOnThrow } from './fail.js';
11
+ import { followUpCommand } from './follow-up-command.js';
12
+ import { deploymentLabel } from './select-deployment.js';
13
+ import { sectionHeader, wrapLines } from './ui.js';
14
+ export function generateBlueprint(args) {
15
+ const planned = planGeneration(args);
16
+ const { verbose } = args;
17
+ const needs = verbose ? needsReportLines(planned.needs) : needsBriefLines(planned.needs);
18
+ for (const line of wrapLines(needs, args.width))
19
+ args.log(line);
20
+ const applied = failOnThrow('Failed to write the generated tree:', () => applyEmissionWritePlan({ root: args.root, plan: planned.plan }));
21
+ args.log('');
22
+ for (const line of emitReportLines({ applied, planned, verbose }))
23
+ args.log(line);
24
+ const deploy = stackDeployLines({ plan: planned.needs, applied, verbose });
25
+ const tail = [
26
+ ...(deploy.length === 0 ? [] : ['', ...deploy]),
27
+ ...(verbose ? [] : ['', VERBOSE_HINT]),
28
+ ];
29
+ for (const line of wrapLines(tail, args.width))
30
+ args.log(line);
31
+ }
32
+ const VERBOSE_HINT = 'Pass --verbose for the full report.';
33
+ export function checkBlueprint(args) {
34
+ const planned = planGeneration(args);
35
+ failOnProblems(args, [...driftReports(planned), ...staleDirectoryReports(planned)]);
36
+ }
37
+ export function checkDeployAlignment(args) {
38
+ if (existsSync(join(args.root, WORKFLOW_RESOURCES_PATH))) {
39
+ const planned = planGeneration(args);
40
+ for (const directory of planned.staleFunctionDirectories) {
41
+ args.warn(`${directory} — ${STALE_DIRECTORY_NOTE}`);
42
+ }
43
+ failOnProblems(args, driftReports(planned));
44
+ return;
45
+ }
46
+ const needs = ungeneratedNeeds(args);
47
+ if (needs === undefined || !needsFunctions(needs))
48
+ return;
49
+ const report = args.verbose ? needsReportLines(needs) : needsSummaryLines(needs);
50
+ const hint = `${logSymbols.warning} No generated runtime is here. Run \`${generateCommand(args)}\` to emit one, ` +
51
+ `unless a runtime you maintain yourself already serves these definitions.` +
52
+ (args.verbose ? '' : ` ${VERBOSE_HINT}`);
53
+ for (const line of wrapLines([...report, '', hint], args.width))
54
+ args.log(line);
55
+ }
56
+ function generateCommand({ bin }) {
57
+ return followUpCommand({ bin }, 'blueprints', 'generate');
58
+ }
59
+ function failOnProblems(args, problems) {
60
+ if (problems.length === 0) {
61
+ args.log(`${logSymbols.success} the generated tree matches the definitions`);
62
+ return;
63
+ }
64
+ fail(`The generated tree does not match the definitions (${problems.length}):`, [...problems.flat(), `Run \`${generateCommand(args)}\` to bring it back in line.`].join('\n'));
65
+ }
66
+ function driftReports(planned) {
67
+ return [
68
+ ...planned.divergences.map((divergence) => [divergenceRow(divergence)]),
69
+ ...misalignmentReports(planned.plan),
70
+ ];
71
+ }
72
+ function ungeneratedNeeds(args) {
73
+ const selected = new Set(args.selected);
74
+ const deployments = args.config.deployments.filter(({ name }) => selected.has(name));
75
+ try {
76
+ return runtimeEmissionPlan({ ...args.config, deployments });
77
+ }
78
+ catch (err) {
79
+ args.warn(`Could not work out which runtime these definitions need: ${errorMessage(err)}`);
80
+ return undefined;
81
+ }
82
+ }
83
+ function planGeneration(args) {
84
+ validateEveryDeployment(args.config);
85
+ const alignment = failOnThrow('Cannot plan the generated tree:', () => generatedRuntimeAlignment({
86
+ root: args.root,
87
+ config: args.config,
88
+ configFile: args.configFile,
89
+ }));
90
+ assertDeploymentsAreExported(args);
91
+ return alignment;
92
+ }
93
+ function validateEveryDeployment(config) {
94
+ const attributed = config.deployments.length > 1;
95
+ for (const deployment of config.deployments) {
96
+ validateOrFail(deployment.definitions, attributed ? `${deploymentLabel(deployment)} — ` : '');
97
+ }
98
+ }
99
+ function assertDeploymentsAreExported(args) {
100
+ const exported = new Set(args.exportedNames);
101
+ const missing = args.config.deployments
102
+ .map((deployment) => deploymentExportIdentifier(deployment.name))
103
+ .filter((identifier) => !exported.has(identifier));
104
+ if (missing.length === 0)
105
+ return;
106
+ const [first = ''] = missing;
107
+ fail(`${args.configFile} does not export ${missing.map((name) => `"${name}"`).join(', ')}:`, [
108
+ `Every generated module imports its deployment by name from ${args.configFile}, so each`,
109
+ `deployment needs its own named export, and that export must be the deployment object`,
110
+ `itself. Declare it once and reuse it:`,
111
+ '',
112
+ ` export const ${first} = {name: '${first}', /* … */}`,
113
+ ` export default defineWorkflowConfig({deployments: [${missing.join(', ')}]})`,
114
+ '',
115
+ `Only the name is checked here, so make sure each export is the deployment this config`,
116
+ `lists. A typecheck of the generated modules catches a wrong export only where a`,
117
+ `generated function uses it.`,
118
+ ].join('\n'));
119
+ }
120
+ const STATUS_WIDTH = 10;
121
+ const WRITE_NOTES = {
122
+ generated: '',
123
+ scaffold: 'yours now — implement the effect',
124
+ wired: 'the workflow resources spread',
125
+ };
126
+ const DIVERGENCE_NOTES = {
127
+ generated: '',
128
+ scaffold: 'no handler for a declared effect',
129
+ wired: 'the workflow resources spread is absent',
130
+ };
131
+ function statusRow(args) {
132
+ const tail = args.note === '' ? '' : ` ${styleText('dim', args.note)}`;
133
+ return ` ${args.status.padEnd(STATUS_WIDTH)} ${args.path}${tail}`;
134
+ }
135
+ const STALE_DIRECTORY_NOTE = 'generated for a function the definitions no longer produce — remove the directory';
136
+ function warningRow(path, note) {
137
+ return ` ${logSymbols.warning} ${path} — ${note}`;
138
+ }
139
+ function emitReportLines(args) {
140
+ const { applied, planned, verbose } = args;
141
+ const kept = ownedStubPaths(planned);
142
+ const misalignments = [...misalignmentReports(planned.plan), ...staleDirectoryReports(planned)];
143
+ const attention = misalignments.length === 0 ? '' : `, ${misalignments.length} need your attention`;
144
+ const rows = [
145
+ ...applied
146
+ .filter((write) => verbose || needsDeveloper(write))
147
+ .map((write) => statusRow({ status: write.status, path: write.path, note: WRITE_NOTES[write.ownership] })),
148
+ ...(verbose
149
+ ? kept.map((path) => statusRow({ status: 'kept', path, note: 'yours, left untouched' }))
150
+ : []),
151
+ ...misalignments.flat(),
152
+ ];
153
+ return [
154
+ ...(rows.length === 0 ? [] : [sectionHeader('Generated tree'), ...rows, '']),
155
+ `${logSymbols.success} ${applied.length} file(s) written${statusCounts(applied)}, ` +
156
+ `${kept.length} left untouched${attention}`,
157
+ ];
158
+ }
159
+ function needsDeveloper(write) {
160
+ return write.status !== 'unchanged' && write.ownership !== 'generated';
161
+ }
162
+ const WRITE_STATUSES = ['created', 'updated', 'unchanged'];
163
+ function statusCounts(applied) {
164
+ const counts = WRITE_STATUSES.flatMap((status) => {
165
+ const count = applied.filter((write) => write.status === status).length;
166
+ return count === 0 ? [] : [`${count} ${status}`];
167
+ });
168
+ return counts.length === 0 ? '' : ` (${counts.join(', ')})`;
169
+ }
170
+ function ownedStubPaths(planned) {
171
+ const written = new Set(planned.plan.writes.map((write) => write.path));
172
+ const reported = new Set(reportedPaths(planned.plan));
173
+ return planned.existingPaths
174
+ .filter((path) => path.endsWith('.ts') && !written.has(path) && !reported.has(path))
175
+ .toSorted();
176
+ }
177
+ function reportedPaths(plan) {
178
+ return [
179
+ ...plan.orphanedStubs.map((stub) => stub.path),
180
+ ...plan.caseCollisions.map((collision) => collision.existingPath),
181
+ ...(plan.orphanedRegistry === undefined ? [] : [plan.orphanedRegistry]),
182
+ ...(plan.orphanedHeartbeatBlueprint === undefined ? [] : [plan.orphanedHeartbeatBlueprint]),
183
+ ];
184
+ }
185
+ function divergenceRow(divergence) {
186
+ return statusRow({
187
+ status: divergence.reason,
188
+ path: divergence.path,
189
+ note: DIVERGENCE_NOTES[divergence.ownership],
190
+ });
191
+ }
192
+ function staleDirectoryReports(planned) {
193
+ return planned.staleFunctionDirectories.map((directory) => [
194
+ warningRow(directory, STALE_DIRECTORY_NOTE),
195
+ ]);
196
+ }
197
+ function misalignmentReports(plan) {
198
+ const wiring = plan.manualBlueprintWiring;
199
+ return [
200
+ ...plan.orphanedStubs.map((stub) => [
201
+ warningRow(stub.path, `no definition declares the effect "${stub.effectName}" — delete it`),
202
+ ]),
203
+ ...(plan.orphanedHeartbeatBlueprint === undefined
204
+ ? []
205
+ : [
206
+ [
207
+ warningRow(plan.orphanedHeartbeatBlueprint, 'no deployment needs a heartbeat any more — destroy its stack ' +
208
+ '(npx sanity@latest blueprints destroy, from that directory, with the organization ' +
209
+ 'deploy token), then delete the directory'),
210
+ ],
211
+ ]),
212
+ ...(plan.orphanedRegistry === undefined
213
+ ? []
214
+ : [
215
+ [
216
+ warningRow(plan.orphanedRegistry, 'no definition declares an effect, so nothing imports the registry — delete it'),
217
+ ],
218
+ ]),
219
+ ...plan.caseCollisions.map((collision) => [
220
+ warningRow(collision.plannedPath, `not written: ${collision.existingPath} differs from it only in case — rename that file ` +
221
+ `to match the effect "${collision.effectName}"`),
222
+ ]),
223
+ ...(wiring === undefined
224
+ ? []
225
+ : [
226
+ [
227
+ warningRow(wiring.path, 'could not be wired automatically — add these two lines by hand'),
228
+ ` ${wiring.importLine}`,
229
+ ` ${wiring.spreadLine}`,
230
+ ],
231
+ ]),
232
+ ];
233
+ }
@@ -0,0 +1,5 @@
1
+ import type { RuntimeEmissionPlan } from '@sanity/workflows/blueprints/generate';
2
+ export declare function needsFunctions(plan: RuntimeEmissionPlan): boolean;
3
+ export declare function needsReportLines(plan: RuntimeEmissionPlan): string[];
4
+ export declare function needsSummaryLines(plan: RuntimeEmissionPlan): string[];
5
+ export declare function needsBriefLines(plan: RuntimeEmissionPlan): string[];
@@ -0,0 +1,205 @@
1
+ import { styleText } from 'node:util';
2
+ import logSymbols from 'log-symbols';
3
+ import { deploymentLabel } from './select-deployment.js';
4
+ import { pluralize, sectionHeader } from './ui.js';
5
+ export function needsFunctions(plan) {
6
+ return plan.deployments.some((deployment) => deployment.emission !== undefined);
7
+ }
8
+ export function needsReportLines(plan) {
9
+ return [
10
+ sectionHeader('Runtime needs'),
11
+ ...plan.deployments.flatMap((deployment) => ['', ...deploymentNeedsLines(deployment)]),
12
+ ];
13
+ }
14
+ export function needsSummaryLines(plan) {
15
+ return [
16
+ sectionHeader('Runtime needs'),
17
+ ...plan.deployments.flatMap((deployment) => deployment.emission === undefined ? [] : [summaryLine(deployment, deployment.emission)]),
18
+ ];
19
+ }
20
+ export function needsBriefLines(plan) {
21
+ return [
22
+ sectionHeader('Runtime needs'),
23
+ ...plan.deployments.flatMap((deployment) => [
24
+ deployment.emission === undefined
25
+ ? ` ${planLabel(deployment)} needs no Sanity Functions`
26
+ : summaryLine(deployment, deployment.emission),
27
+ ...warningLines(deployment),
28
+ ]),
29
+ ];
30
+ }
31
+ function summaryLine(plan, emission) {
32
+ const kinds = [
33
+ { count: emission.drains.length, noun: 'effect drain' },
34
+ { count: emission.heartbeat === undefined ? 0 : 1, noun: 'heartbeat' },
35
+ { count: emission.startWatchers.length, noun: 'start watcher' },
36
+ ].filter((kind) => kind.count > 0);
37
+ const total = kinds.reduce((sum, kind) => sum + kind.count, 0);
38
+ const breakdown = kinds.map((kind) => pluralize(kind.count, kind.noun)).join(', ');
39
+ return ` ${planLabel(plan)} needs ${pluralize(total, 'Sanity Function')} (${breakdown})`;
40
+ }
41
+ function planLabel(plan) {
42
+ return deploymentLabel({ name: plan.deploymentName, partition: plan.partition });
43
+ }
44
+ const DETAIL = ' → ';
45
+ const REASON = ' ';
46
+ function deploymentNeedsLines(plan) {
47
+ const { emission } = plan;
48
+ return [
49
+ styleText('bold', `▸ ${planLabel(plan)}`),
50
+ ...hostingLines(plan),
51
+ ...(emission === undefined
52
+ ? [' no functions needed — the reactive session is already this deployment runtime']
53
+ : [...drainLines(plan, emission), ...clockLines(plan, emission), ...watcherLines(emission)]),
54
+ ...selfHostedLines(plan),
55
+ ...warningLines(plan),
56
+ ];
57
+ }
58
+ const HOSTING_NOTE = {
59
+ function: '',
60
+ durableFunction: 'no functions are emitted for these yet',
61
+ selfHosted: 'nothing is emitted — your own process runs these',
62
+ };
63
+ const HOSTING_ORDER = ['function', 'durableFunction', 'selfHosted'];
64
+ function hostingLines(plan) {
65
+ return [
66
+ ` hosting: this deployment declares ${plan.runtimeKind}, and each level below inherits it`,
67
+ ...kindLines('workflow', plan.hosting.workflows),
68
+ ...kindLines('effect', plan.hosting.effects),
69
+ ];
70
+ }
71
+ function kindLines(what, byKind) {
72
+ return HOSTING_ORDER.flatMap((kind) => {
73
+ const names = byKind[kind];
74
+ if (names.length === 0)
75
+ return [];
76
+ const note = HOSTING_NOTE[kind];
77
+ const suffix = note === '' ? '' : ` — ${note}`;
78
+ return [`${DETAIL}${kind} ${what}(s): ${names.join(', ')}${suffix}`];
79
+ });
80
+ }
81
+ const SELF_HOSTED_TASKS = [
82
+ { key: 'startInstances', task: 'start instances of' },
83
+ { key: 'tickDeadlines', task: 'tick the $now deadlines of' },
84
+ { key: 'drainEffects', task: 'drain the effects' },
85
+ { key: 'reevaluateParents', task: 're-evaluate the parents that missed a child settling in' },
86
+ ];
87
+ function selfHostedLines(plan) {
88
+ const tasks = SELF_HOSTED_TASKS.flatMap(({ key, task }) => {
89
+ const names = plan.selfHosted[key];
90
+ return names.length === 0 ? [] : [`${REASON}${task} ${names.join(', ')}`];
91
+ });
92
+ if (tasks.length === 0)
93
+ return [];
94
+ return [' self-hosted: nothing below is emitted, so your own process must', ...tasks];
95
+ }
96
+ function drainLines(plan, emission) {
97
+ const declared = plan.needs.drain.effectNames;
98
+ if (declared.length === 0)
99
+ return [];
100
+ return [
101
+ ` effects: ${declared.length} declared — ${declared.join(', ')}`,
102
+ ...emission.drains.map((drain) => `${DETAIL}drain function ${drain.name} runs ${drain.effectNames.join(', ')}`),
103
+ ];
104
+ }
105
+ function clockLines(plan, emission) {
106
+ const { heartbeat } = emission;
107
+ if (heartbeat === undefined)
108
+ return [];
109
+ const ticked = new Set(heartbeat.definitions);
110
+ return [
111
+ ` clock: ${heartbeatSentence(heartbeat)}`,
112
+ ...timeSiteLines(plan.needs.heartbeat.timeSites.filter((site) => ticked.has(site.definition))),
113
+ ...spawnSiteLines(plan.needs.heartbeat.spawnSites.filter((site) => ticked.has(site.definition))),
114
+ `${DETAIL}scheduled function ${heartbeat.name} on ${heartbeat.schedule}`,
115
+ ...(heartbeat.definitions.length === 0
116
+ ? []
117
+ : [`${REASON}ticks instances of ${heartbeat.definitions.join(', ')}`]),
118
+ `${REASON}plan cadence: every minute on Enterprise, hourly on Growth, daily on Free` +
119
+ ` (https://www.sanity.io/docs/functions/functions-introduction)`,
120
+ ];
121
+ }
122
+ function heartbeatSentence(heartbeat) {
123
+ const [first, ...rest] = heartbeat.reasons;
124
+ const more = rest.map((reason) => `, and ${reason}`).join('');
125
+ return `a scheduled function ${first} each minute, subject to plan cadence${more}`;
126
+ }
127
+ function timeSiteLines(sites) {
128
+ return sites.map((site) => `${REASON}${site.definition} · ${site.stage ?? 'definition'} · ${site.address.kind} · ` +
129
+ site.condition);
130
+ }
131
+ function spawnSiteLines(sites) {
132
+ return sites.map((site) => `${REASON}${site.definition} · ${site.stage} · ${site.activity} · ${site.action} spawns ` +
133
+ site.spawn.definition.name);
134
+ }
135
+ function watcherLines(emission) {
136
+ if (emission.startWatchers.length === 0)
137
+ return [];
138
+ const started = [
139
+ ...new Set(emission.startWatchers.flatMap((watcher) => watcher.definitions)),
140
+ ].toSorted();
141
+ return [
142
+ ` autonomous starts: ${started.length} definition(s) — ${started.join(', ')}`,
143
+ ...emission.startWatchers.flatMap((watcher) => [
144
+ `${DETAIL}start watcher ${watcher.name} on ${watchedLabel(watcher.resource)}` +
145
+ ` — ${watcher.definitions.join(', ')}`,
146
+ ...watcherReasonLines(watcher.updates),
147
+ ]),
148
+ ...mediaLibraryAccessLines(emission),
149
+ ];
150
+ }
151
+ function watchedLabel(resource) {
152
+ return resource.type === 'dataset' ? resource.id : `media library ${resource.id}`;
153
+ }
154
+ function mediaLibraryAccessLines(emission) {
155
+ const libraries = [
156
+ ...new Set(emission.startWatchers.flatMap((watcher) => watcher.resource.type === 'media-library' ? [watcher.resource.id] : [])),
157
+ ];
158
+ if (libraries.length === 0)
159
+ return [];
160
+ const robots = [emission.robotName, ...(emission.heartbeat ? [emission.heartbeat.robotName] : [])];
161
+ return [
162
+ ` ${logSymbols.warning} ${robots.join(' and ')} must read ${libraries.join(', ')}, and so` +
163
+ ` must the identity that deploys the project stack: confirm their Media Library access` +
164
+ ` in the organization that owns the library, or the deploy or every start there fails`,
165
+ ];
166
+ }
167
+ function watcherReasonLines(updates) {
168
+ if (updates.kind === 'noUpdate') {
169
+ return [
170
+ `${REASON}starts a document when it is created; one that existed before this` +
171
+ ` watcher deployed starts only when you start it (sanity-workflows start)`,
172
+ ];
173
+ }
174
+ if (updates.kind === 'risingEdge') {
175
+ return [
176
+ `${REASON}starts a document on the write that makes its start filter true;` +
177
+ ` a write that keeps it true starts nothing`,
178
+ ];
179
+ }
180
+ return [];
181
+ }
182
+ const EVERY_WRITE_CAUSE = {
183
+ readsOtherDocuments: 'reads another document, which a trigger cannot evaluate',
184
+ readsNow: 'reads $now, which a trigger cannot bind',
185
+ readsVariable: 'reads $tag or $definition, which a trigger cannot bind',
186
+ notBoolean: 'is not recognized as a boolean expression',
187
+ };
188
+ const EVERY_WRITE_REMEDY = {
189
+ readsOtherDocuments: 'move the cross-document condition into a stage',
190
+ readsNow: 'move the time condition into a stage',
191
+ readsVariable: 'move the $tag or $definition condition into a stage',
192
+ notBoolean: 'rewrite it as a boolean expression (comparisons, &&, ||, !, defined(), references()),' +
193
+ ' such as count(tags) > 0',
194
+ };
195
+ function warningLines(plan) {
196
+ return [
197
+ ...plan.anyTypeSubjects.map((name) => ` ${logSymbols.warning} ${name} declares a subject with no types, so a write to any` +
198
+ ` document type invokes its watcher — declare types unless that is intended`),
199
+ ...plan.everyWriteStartFilters.map(({ definition, reason }) => ` ${logSymbols.warning} ${definition} has a start filter that ${EVERY_WRITE_CAUSE[reason]},` +
200
+ ` so every matching write starts it and a later matching write can start another` +
201
+ ` instance for the same document — ${EVERY_WRITE_REMEDY[reason]}, or self-host the start`),
202
+ ...plan.subjectlessDefinitions.map((name) => ` ${logSymbols.warning} ${name} starts autonomously but declares no subject, so no` +
203
+ ` document write can start it and it gets no watcher`),
204
+ ];
205
+ }
@@ -0,0 +1,6 @@
1
+ import { type AppliedWrite, type RuntimeEmissionPlan } from '@sanity/workflows/blueprints/generate';
2
+ export declare function stackDeployLines(args: {
3
+ plan: RuntimeEmissionPlan;
4
+ applied: readonly AppliedWrite[];
5
+ verbose: boolean;
6
+ }): string[];