@sanity/cli-core 2.5.0 → 2.6.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.
@@ -374,6 +374,22 @@ export declare abstract class SanityCommand<T extends typeof Command>
374
374
  * output (a caller parsing JSON can't answer a prompt).
375
375
  */
376
376
  isUnattended(): boolean;
377
+ /**
378
+ * Write to stdout — or, when running under an execution context (e.g. from
379
+ * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`
380
+ * semantics: suppressed when `--json` is enabled, printf-style formatting.
381
+ */
382
+ log(message?: string, ...args: unknown[]): void;
383
+ /**
384
+ * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the
385
+ * execution context's `stdout` sink, so programmatic callers don't have to
386
+ * strip ANSI codes.
387
+ */
388
+ logJson(json: unknown): void;
389
+ /**
390
+ * Like `log`, but for stderr / the context's `stderr` sink.
391
+ */
392
+ logToStderr(message?: string, ...args: unknown[]): void;
377
393
  /**
378
394
  * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
379
395
  *
@@ -389,6 +405,11 @@ export declare abstract class SanityCommand<T extends typeof Command>
389
405
  * @returns The CLI config, or an empty config object if no project root is found.
390
406
  */
391
407
  protected tryGetCliConfig(): Promise<CliConfig>;
408
+ /**
409
+ * Emit a warning — routed to the execution context's `stderr` sink when one
410
+ * is active, otherwise through oclif's standard warning printer.
411
+ */
412
+ warn(input: Error | string): Error | string;
392
413
  }
393
414
 
394
415
  /**
@@ -1,4 +1,4 @@
1
- import { styleText } from 'node:util';
1
+ import { format, styleText } from 'node:util';
2
2
  import { Command } from '@oclif/core';
3
3
  import { subdebug } from './_exports/debug.js';
4
4
  import { getGlobalCliClient, getProjectCliClient } from './apiClient.js';
@@ -6,6 +6,7 @@ import { getCliConfig } from './config/cli/getCliConfig.js';
6
6
  import { findProjectRoot } from './config/findProjectRoot.js';
7
7
  import { NonInteractiveError } from './errors/NonInteractiveError.js';
8
8
  import { ProjectRootNotFoundError } from './errors/ProjectRootNotFoundError.js';
9
+ import { getCliExecutionContext } from './executionContext.js';
9
10
  import { exitCodes } from './exitCodes.js';
10
11
  import { getCliTelemetry, reportCliTraceError } from './telemetry/getCliTelemetry.js';
11
12
  import { isInteractive } from './util/isInteractive.js';
@@ -61,6 +62,15 @@ export class SanityCommand extends Command {
61
62
  }
62
63
  // In other cases, we _do_ want to report the error
63
64
  reportCliTraceError(err);
65
+ // oclif's base `catch` sets `process.exitCode` as a side effect
66
+ // we do not want to write to the host's own exit status.
67
+ if (getCliExecutionContext()) {
68
+ if (this.jsonEnabled()) {
69
+ this.logJson(this.toErrorJson(err));
70
+ return;
71
+ }
72
+ throw err;
73
+ }
64
74
  return super.catch(err);
65
75
  }
66
76
  /**
@@ -171,6 +181,40 @@ export class SanityCommand extends Command {
171
181
  return this.flags.yes || this.flags.json || !this.resolveIsInteractive();
172
182
  }
173
183
  /**
184
+ * Write to stdout — or, when running under an execution context (e.g. from
185
+ * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`
186
+ * semantics: suppressed when `--json` is enabled, printf-style formatting.
187
+ */ log(message = '', ...args) {
188
+ const context = getCliExecutionContext();
189
+ if (!context?.stdout) {
190
+ super.log(message, ...args);
191
+ return;
192
+ }
193
+ if (!this.jsonEnabled()) context.stdout(format(message, ...args));
194
+ }
195
+ /**
196
+ * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the
197
+ * execution context's `stdout` sink, so programmatic callers don't have to
198
+ * strip ANSI codes.
199
+ */ logJson(json) {
200
+ const context = getCliExecutionContext();
201
+ if (!context?.stdout) {
202
+ super.logJson(json);
203
+ return;
204
+ }
205
+ context.stdout(JSON.stringify(json, null, 2));
206
+ }
207
+ /**
208
+ * Like `log`, but for stderr / the context's `stderr` sink.
209
+ */ logToStderr(message = '', ...args) {
210
+ const context = getCliExecutionContext();
211
+ if (!context?.stderr) {
212
+ super.logToStderr(message, ...args);
213
+ return;
214
+ }
215
+ if (!this.jsonEnabled()) context.stderr(format(message, ...args));
216
+ }
217
+ /**
174
218
  * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
175
219
  *
176
220
  * @returns Whether the terminal is interactive.
@@ -192,6 +236,17 @@ export class SanityCommand extends Command {
192
236
  return {};
193
237
  }
194
238
  }
239
+ /**
240
+ * Emit a warning — routed to the execution context's `stderr` sink when one
241
+ * is active, otherwise through oclif's standard warning printer.
242
+ */ warn(input) {
243
+ const context = getCliExecutionContext();
244
+ if (!context?.stderr) return super.warn(input);
245
+ if (!this.jsonEnabled()) {
246
+ context.stderr(`Warning: ${input instanceof Error ? input.message : input}`);
247
+ }
248
+ return input;
249
+ }
195
250
  }
196
251
 
197
252
  //# sourceMappingURL=SanityCommand.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n}\n"],"names":["styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","NonInteractiveError","ProjectRootNotFoundError","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","tryGetCliConfig"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,mBAAmB,QAAO,kCAAiC;AACnE,SAAQC,wBAAwB,QAAO,uCAAsC;AAC7E,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,eAAe,EAAEC,mBAAmB,QAAO,iCAAgC;AAGnF,SAAQC,aAAa,QAAO,0BAAyB;AAQrD,MAAMC,QAAQX,SAAS;AAmBvB,OAAO,MAAeY,sBACZb;IAGEc,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCZ,mBAAmBY,MAAK;IAEzF;;;;;;;GAOC,GACD,AAAUG,sBAAsB,CAACH,OAAkCX,oBAAoBW,MAAK;IAE5F;;;;;;;;;GASC,GACD,AAAOI,SAAiB;QACtBC,OAAO,IAAI,CAACA,KAAK,CAACC,IAAI,CAAC,IAAI;QAC3BC,KAAK,IAAI,CAACA,GAAG,CAACD,IAAI,CAAC,IAAI;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CAACQ,SAAS,GAAGd;QAEjB,MAAM,KAAK,CAAC0C;IACd;IAEA;;;;;;;;;;;GAWC,GACD,AAAOK,eAAwB;QAC7B,OAAO,IAAI,CAACzC,KAAK,CAAC0C,GAAG,IAAI,IAAI,CAAC1C,KAAK,CAAC2C,IAAI,IAAI,CAAC,IAAI,CAACC,oBAAoB;IACxE;IAEA;;;;GAIC,GACD,AAAOA,uBAAgC;QACrC,OAAOhD;IACT;IAEA;;;;;;;GAOC,GACD,MAAgBiD,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACxD,YAAY;QAChC,EAAE,OAAOqB,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAelB,wBAAuB,GAAI,MAAMkB;YACtD,OAAO,CAAC;QACV;IACF;AACF"}
1
+ {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return this.flags.yes || this.flags.json || !this.resolveIsInteractive()\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","isUnattended","yes","json","resolveIsInteractive","context","stdout","JSON","stringify","stderr","tryGetCliConfig","input","Error"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,mBAAmB,QAAO,kCAAiC;AACnE,SAAQC,wBAAwB,QAAO,uCAAsC;AAC7E,SAAQC,sBAAsB,QAAO,wBAAuB;AAC5D,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,eAAe,EAAEC,mBAAmB,QAAO,iCAAgC;AAGnF,SAAQC,aAAa,QAAO,0BAAyB;AAQrD,MAAMC,QAAQZ,SAAS;AAmBvB,OAAO,MAAea,sBACZd;IAGEe,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCb,mBAAmBa,MAAK;IAEzF;;;;;;;GAOC,GACD,AAAUG,sBAAsB,CAACH,OAAkCZ,oBAAoBY,MAAK;IAE5F;;;;;;;;;GASC,GACD,AAAOI,SAAiB;QACtBC,OAAO,IAAI,CAACA,KAAK,CAACC,IAAI,CAAC,IAAI;QAC3BC,KAAK,IAAI,CAACA,GAAG,CAACD,IAAI,CAAC,IAAI;QACvBE,MAAM,IAAI,CAACA,IAAI,CAACF,IAAI,CAAC,IAAI;IAC3B,EAAC;IAED;;;;GAIC,GACD,AAAUG,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I,CAAEA,CAAAA,eAAenB,wBAAuB,GAAI,MAAMmB;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAK+C,KAAqB,EAAkB;QAC1D,MAAMN,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ,OAAO,KAAK,CAAC7C,KAAK+C;QAExC,IAAI,CAAC,IAAI,CAACtC,WAAW,IAAI;YACvBgC,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEE,iBAAiBC,QAAQD,MAAM1C,OAAO,GAAG0C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
@@ -1400,6 +1400,22 @@ export declare abstract class SanityCommand<T extends typeof Command>
1400
1400
  * output (a caller parsing JSON can't answer a prompt).
1401
1401
  */
1402
1402
  isUnattended(): boolean;
1403
+ /**
1404
+ * Write to stdout — or, when running under an execution context (e.g. from
1405
+ * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`
1406
+ * semantics: suppressed when `--json` is enabled, printf-style formatting.
1407
+ */
1408
+ log(message?: string, ...args: unknown[]): void;
1409
+ /**
1410
+ * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the
1411
+ * execution context's `stdout` sink, so programmatic callers don't have to
1412
+ * strip ANSI codes.
1413
+ */
1414
+ logJson(json: unknown): void;
1415
+ /**
1416
+ * Like `log`, but for stderr / the context's `stderr` sink.
1417
+ */
1418
+ logToStderr(message?: string, ...args: unknown[]): void;
1403
1419
  /**
1404
1420
  * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
1405
1421
  *
@@ -1415,6 +1431,11 @@ export declare abstract class SanityCommand<T extends typeof Command>
1415
1431
  * @returns The CLI config, or an empty config object if no project root is found.
1416
1432
  */
1417
1433
  protected tryGetCliConfig(): Promise<CliConfig>;
1434
+ /**
1435
+ * Emit a warning — routed to the execution context's `stderr` sink when one
1436
+ * is active, otherwise through oclif's standard warning printer.
1437
+ */
1438
+ warn(input: Error | string): Error | string;
1418
1439
  }
1419
1440
 
1420
1441
  /**
@@ -1435,11 +1456,17 @@ export declare interface SanityCommandInterface {
1435
1456
  }
1436
1457
 
1437
1458
  export declare type SanityOrgUser = {
1438
- email: string;
1459
+ /**
1460
+ * Null when authenticating with an API token rather than a user account —
1461
+ * robot tokens resolve to a user whose `email` and `familyName` are null.
1462
+ * Use `getUserDisplayName()` for anything user-facing.
1463
+ */
1464
+ email: string | null;
1439
1465
  id: string;
1440
1466
  name: string;
1441
1467
  profileImage?: string;
1442
- provider: "github" | "google" | "sanity" | `saml-${string}`;
1468
+ /** `sanity-token` is returned when authenticating with an API token. */
1469
+ provider: "github" | "google" | "sanity" | "sanity-token" | `saml-${string}`;
1443
1470
  tosAcceptedAt?: string;
1444
1471
  };
1445
1472
 
@@ -394,11 +394,17 @@ export declare interface SanityCommandInterface {
394
394
  }
395
395
 
396
396
  export declare type SanityOrgUser = {
397
- email: string;
397
+ /**
398
+ * Null when authenticating with an API token rather than a user account —
399
+ * robot tokens resolve to a user whose `email` and `familyName` are null.
400
+ * Use `getUserDisplayName()` for anything user-facing.
401
+ */
402
+ email: string | null;
398
403
  id: string;
399
404
  name: string;
400
405
  profileImage?: string;
401
- provider: "github" | "google" | "sanity" | `saml-${string}`;
406
+ /** `sanity-token` is returned when authenticating with an API token. */
407
+ provider: "github" | "google" | "sanity" | "sanity-token" | `saml-${string}`;
402
408
  tosAcceptedAt?: string;
403
409
  };
404
410
 
package/dist/apiClient.js CHANGED
@@ -2,6 +2,7 @@ import { styleText } from 'node:util';
2
2
  import { createClient, requester as defaultRequester, isHttpError } from '@sanity/client';
3
3
  import { getCliToken } from './config/cli/cliUserConfig.js';
4
4
  import { generateHelpUrl } from './util/generateHelpUrl.js';
5
+ import { getSanityUrl } from './util/getSanityUrl.js';
5
6
  const apiHosts = {
6
7
  staging: 'https://api.sanity.work'
7
8
  };
@@ -47,7 +48,7 @@ const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
47
48
  * @returns Promise that resolves to a configured Sanity API client.
48
49
  */ export async function getProjectCliClient({ requireUser, token: providedToken, ...config }) {
49
50
  const requester = defaultRequester.clone();
50
- requester.use(authErrors());
51
+ requester.use(authErrors(config.projectId));
51
52
  const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production';
52
53
  const apiHost = apiHosts[sanityEnv];
53
54
  // Use the provided token if it is set, otherwise get the token from the config file
@@ -76,20 +77,29 @@ const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
76
77
  *
77
78
  * @returns get-it middleware with `onError` handler
78
79
  * @internal
79
- */ function authErrors() {
80
+ */ function authErrors(projectId) {
80
81
  return {
81
82
  onError: (err)=>{
82
83
  if (!err || !isReqResError(err)) {
83
84
  return err;
84
85
  }
85
- const statusCode = isHttpError(err) && err.response.body.statusCode;
86
+ const statusCode = isHttpError(err) && err.statusCode;
86
87
  if (statusCode === 401) {
88
+ if (projectId && isProjectUserNotFoundError(err.response.body)) {
89
+ err.message = `${err.message}. Add this account as a project member: ${getSanityUrl(`/manage/project/${encodeURIComponent(projectId)}/members`)}.`;
90
+ return err;
91
+ }
87
92
  err.message = `${err.message}. You may need to login again with ${styleText('cyan', 'sanity login')}.\nFor more information, see ${generateHelpUrl('cli-errors')}.`;
88
93
  }
89
94
  return err;
90
95
  }
91
96
  };
92
97
  }
98
+ function isProjectUserNotFoundError(body) {
99
+ if (typeof body !== 'object' || body === null || !('error' in body)) return false;
100
+ const { error } = body;
101
+ return typeof error === 'object' && error !== null && 'type' in error && error.type === 'projectUserNotFoundError';
102
+ }
93
103
  function isReqResError(err) {
94
104
  return Object.prototype.hasOwnProperty.call(err, 'response');
95
105
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apiClient.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {\n type ClientConfig,\n type ClientError,\n createClient,\n requester as defaultRequester,\n isHttpError,\n type SanityClient,\n type ServerError,\n} from '@sanity/client'\n\nimport {getCliToken} from './config/cli/cliUserConfig.js'\nimport {generateHelpUrl} from './util/generateHelpUrl.js'\n\nconst apiHosts: Record<string, string | undefined> = {\n staging: 'https://api.sanity.work',\n}\n\nconst CLI_REQUEST_TAG_PREFIX = 'sanity.cli'\n\n/**\n * @public\n */\nexport interface GlobalCliClientOptions extends ClientConfig {\n /**\n * The API version to use for this client.\n */\n apiVersion: string\n\n /**\n * Whether to require a user to be authenticated to use this client.\n * Default: `false`.\n * Throws an error if `true` and user is not authenticated.\n */\n requireUser?: boolean\n\n /**\n * Whether to skip reading the stored CLI token. When `true`, the client will\n * have no token unless one is explicitly provided.\n * Default: `false`.\n */\n unauthenticated?: boolean\n}\n\n/**\n * Create a \"global\" (unscoped) Sanity API client.\n *\n * @public\n *\n * @param options - The options to use for the client.\n * @returns Promise that resolves to a configured Sanity API client.\n */\nexport async function getGlobalCliClient({\n requireUser,\n token: providedToken,\n unauthenticated,\n ...config\n}: GlobalCliClientOptions): Promise<SanityClient> {\n const requester = defaultRequester.clone()\n requester.use(authErrors())\n\n const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production'\n\n const apiHost = apiHosts[sanityEnv]\n\n // Use the provided token if set, otherwise fall back to the stored CLI token (unless unauthenticated)\n const token = providedToken || (unauthenticated ? undefined : await getCliToken())\n\n // If the token is not set and requireUser is true, throw an error\n if (!token && requireUser) {\n throw new Error('You must login first - run \"sanity login\"')\n }\n\n return createClient({\n ...(apiHost ? {apiHost} : {}),\n // Suppress browser token warning since we mock browser environment in workers\n ignoreBrowserTokenWarning: true,\n requester,\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: false,\n ...config,\n })\n}\n\n/**\n * @public\n */\nexport interface ProjectCliClientOptions extends ClientConfig {\n /**\n * The API version to use for this client.\n */\n apiVersion: string\n\n /**\n * The project ID to use for this client.\n */\n projectId: string\n\n /**\n * The dataset to use for this client.\n */\n dataset?: string\n\n /**\n * Whether to require a user to be authenticated to use this client.\n * Default: `false`.\n * Throws an error if `true` and user is not authenticated.\n */\n requireUser?: boolean\n}\n\n/**\n * Create a \"project\" (scoped) Sanity API client.\n *\n * @public\n *\n * @param options - The options to use for the client.\n * @returns Promise that resolves to a configured Sanity API client.\n */\nexport async function getProjectCliClient({\n requireUser,\n token: providedToken,\n ...config\n}: ProjectCliClientOptions): Promise<SanityClient> {\n const requester = defaultRequester.clone()\n requester.use(authErrors())\n\n const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production'\n\n const apiHost = apiHosts[sanityEnv]\n\n // Use the provided token if it is set, otherwise get the token from the config file\n const token = providedToken || (await getCliToken())\n\n // If the token is not set and requireUser is true, throw an error\n if (!token && requireUser) {\n throw new Error('You must login first - run \"sanity login\"')\n }\n\n return createClient({\n ...(apiHost ? {apiHost} : {}),\n // Suppress browser token warning since we mock browser environment in workers\n ignoreBrowserTokenWarning: true,\n requester,\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: true,\n ...config,\n })\n}\n\n/**\n * `get-it` middleware that checks for 401 authentication errors and extends the error with more\n * helpful guidance on what to do next.\n *\n * @returns get-it middleware with `onError` handler\n * @internal\n */\nfunction authErrors() {\n return {\n onError: (err: Error | null) => {\n if (!err || !isReqResError(err)) {\n return err\n }\n\n const statusCode = isHttpError(err) && err.response.body.statusCode\n if (statusCode === 401) {\n err.message = `${err.message}. You may need to login again with ${styleText('cyan', 'sanity login')}.\\nFor more information, see ${generateHelpUrl('cli-errors')}.`\n }\n\n return err\n },\n }\n}\n\nfunction isReqResError(err: Error): err is ClientError | ServerError {\n return Object.prototype.hasOwnProperty.call(err, 'response')\n}\n"],"names":["styleText","createClient","requester","defaultRequester","isHttpError","getCliToken","generateHelpUrl","apiHosts","staging","CLI_REQUEST_TAG_PREFIX","getGlobalCliClient","requireUser","token","providedToken","unauthenticated","config","clone","use","authErrors","sanityEnv","process","env","SANITY_INTERNAL_ENV","apiHost","undefined","Error","ignoreBrowserTokenWarning","requestTagPrefix","useCdn","useProjectHostname","getProjectCliClient","onError","err","isReqResError","statusCode","response","body","message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AASD,aAAa;QACzB,MAAM,IAAIc,MAAM;IAClB;IAEA,OAAOxB,aAAa;QAClB,GAAIsB,UAAU;YAACA;QAAO,IAAI,CAAC,CAAC;QAC5B,8EAA8E;QAC9EG,2BAA2B;QAC3BxB;QACAyB,kBAAkBlB;QAClBG;QACAgB,QAAQ;QACRC,oBAAoB;QACpB,GAAGd,MAAM;IACX;AACF;AAEA;;;;;;CAMC,GACD,SAASG;IACP,OAAO;QACLa,SAAS,CAACC;YACR,IAAI,CAACA,OAAO,CAACC,cAAcD,MAAM;gBAC/B,OAAOA;YACT;YAEA,MAAME,aAAa9B,YAAY4B,QAAQA,IAAIG,QAAQ,CAACC,IAAI,CAACF,UAAU;YACnE,IAAIA,eAAe,KAAK;gBACtBF,IAAIK,OAAO,GAAG,GAAGL,IAAIK,OAAO,CAAC,mCAAmC,EAAErC,UAAU,QAAQ,gBAAgB,6BAA6B,EAAEM,gBAAgB,cAAc,CAAC,CAAC;YACrK;YAEA,OAAO0B;QACT;IACF;AACF;AAEA,SAASC,cAAcD,GAAU;IAC/B,OAAOM,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACT,KAAK;AACnD"}
1
+ {"version":3,"sources":["../src/apiClient.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {\n type ClientConfig,\n type ClientError,\n createClient,\n requester as defaultRequester,\n isHttpError,\n type SanityClient,\n type ServerError,\n} from '@sanity/client'\n\nimport {getCliToken} from './config/cli/cliUserConfig.js'\nimport {generateHelpUrl} from './util/generateHelpUrl.js'\nimport {getSanityUrl} from './util/getSanityUrl.js'\n\nconst apiHosts: Record<string, string | undefined> = {\n staging: 'https://api.sanity.work',\n}\n\nconst CLI_REQUEST_TAG_PREFIX = 'sanity.cli'\n\n/**\n * @public\n */\nexport interface GlobalCliClientOptions extends ClientConfig {\n /**\n * The API version to use for this client.\n */\n apiVersion: string\n\n /**\n * Whether to require a user to be authenticated to use this client.\n * Default: `false`.\n * Throws an error if `true` and user is not authenticated.\n */\n requireUser?: boolean\n\n /**\n * Whether to skip reading the stored CLI token. When `true`, the client will\n * have no token unless one is explicitly provided.\n * Default: `false`.\n */\n unauthenticated?: boolean\n}\n\n/**\n * Create a \"global\" (unscoped) Sanity API client.\n *\n * @public\n *\n * @param options - The options to use for the client.\n * @returns Promise that resolves to a configured Sanity API client.\n */\nexport async function getGlobalCliClient({\n requireUser,\n token: providedToken,\n unauthenticated,\n ...config\n}: GlobalCliClientOptions): Promise<SanityClient> {\n const requester = defaultRequester.clone()\n requester.use(authErrors())\n\n const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production'\n\n const apiHost = apiHosts[sanityEnv]\n\n // Use the provided token if set, otherwise fall back to the stored CLI token (unless unauthenticated)\n const token = providedToken || (unauthenticated ? undefined : await getCliToken())\n\n // If the token is not set and requireUser is true, throw an error\n if (!token && requireUser) {\n throw new Error('You must login first - run \"sanity login\"')\n }\n\n return createClient({\n ...(apiHost ? {apiHost} : {}),\n // Suppress browser token warning since we mock browser environment in workers\n ignoreBrowserTokenWarning: true,\n requester,\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: false,\n ...config,\n })\n}\n\n/**\n * @public\n */\nexport interface ProjectCliClientOptions extends ClientConfig {\n /**\n * The API version to use for this client.\n */\n apiVersion: string\n\n /**\n * The project ID to use for this client.\n */\n projectId: string\n\n /**\n * The dataset to use for this client.\n */\n dataset?: string\n\n /**\n * Whether to require a user to be authenticated to use this client.\n * Default: `false`.\n * Throws an error if `true` and user is not authenticated.\n */\n requireUser?: boolean\n}\n\n/**\n * Create a \"project\" (scoped) Sanity API client.\n *\n * @public\n *\n * @param options - The options to use for the client.\n * @returns Promise that resolves to a configured Sanity API client.\n */\nexport async function getProjectCliClient({\n requireUser,\n token: providedToken,\n ...config\n}: ProjectCliClientOptions): Promise<SanityClient> {\n const requester = defaultRequester.clone()\n requester.use(authErrors(config.projectId))\n\n const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production'\n\n const apiHost = apiHosts[sanityEnv]\n\n // Use the provided token if it is set, otherwise get the token from the config file\n const token = providedToken || (await getCliToken())\n\n // If the token is not set and requireUser is true, throw an error\n if (!token && requireUser) {\n throw new Error('You must login first - run \"sanity login\"')\n }\n\n return createClient({\n ...(apiHost ? {apiHost} : {}),\n // Suppress browser token warning since we mock browser environment in workers\n ignoreBrowserTokenWarning: true,\n requester,\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: true,\n ...config,\n })\n}\n\n/**\n * `get-it` middleware that checks for 401 authentication errors and extends the error with more\n * helpful guidance on what to do next.\n *\n * @returns get-it middleware with `onError` handler\n * @internal\n */\nfunction authErrors(projectId?: string) {\n return {\n onError: (err: Error | null) => {\n if (!err || !isReqResError(err)) {\n return err\n }\n\n const statusCode = isHttpError(err) && err.statusCode\n if (statusCode === 401) {\n if (projectId && isProjectUserNotFoundError(err.response.body)) {\n err.message = `${err.message}. Add this account as a project member: ${getSanityUrl(`/manage/project/${encodeURIComponent(projectId)}/members`)}.`\n return err\n }\n\n err.message = `${err.message}. You may need to login again with ${styleText('cyan', 'sanity login')}.\\nFor more information, see ${generateHelpUrl('cli-errors')}.`\n }\n\n return err\n },\n }\n}\n\nfunction isProjectUserNotFoundError(\n body: unknown,\n): body is {error: {type: 'projectUserNotFoundError'}} {\n if (typeof body !== 'object' || body === null || !('error' in body)) return false\n\n const {error} = body\n return (\n typeof error === 'object' &&\n error !== null &&\n 'type' in error &&\n error.type === 'projectUserNotFoundError'\n )\n}\n\nfunction isReqResError(err: Error): err is ClientError | ServerError {\n return Object.prototype.hasOwnProperty.call(err, 'response')\n}\n"],"names":["styleText","createClient","requester","defaultRequester","isHttpError","getCliToken","generateHelpUrl","getSanityUrl","apiHosts","staging","CLI_REQUEST_TAG_PREFIX","getGlobalCliClient","requireUser","token","providedToken","unauthenticated","config","clone","use","authErrors","sanityEnv","process","env","SANITY_INTERNAL_ENV","apiHost","undefined","Error","ignoreBrowserTokenWarning","requestTagPrefix","useCdn","useProjectHostname","getProjectCliClient","projectId","onError","err","isReqResError","statusCode","isProjectUserNotFoundError","response","body","message","encodeURIComponent","error","type","Object","prototype","hasOwnProperty","call"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAGEC,YAAY,EACZC,aAAaC,gBAAgB,EAC7BC,WAAW,QAGN,iBAAgB;AAEvB,SAAQC,WAAW,QAAO,gCAA+B;AACzD,SAAQC,eAAe,QAAO,4BAA2B;AACzD,SAAQC,YAAY,QAAO,yBAAwB;AAEnD,MAAMC,WAA+C;IACnDC,SAAS;AACX;AAEA,MAAMC,yBAAyB;AA0B/B;;;;;;;CAOC,GACD,OAAO,eAAeC,mBAAmB,EACvCC,WAAW,EACXC,OAAOC,aAAa,EACpBC,eAAe,EACf,GAAGC,QACoB;IACvB,MAAMd,YAAYC,iBAAiBc,KAAK;IACxCf,UAAUgB,GAAG,CAACC;IAEd,MAAMC,YAAYC,QAAQC,GAAG,CAACC,mBAAmB,IAAI;IAErD,MAAMC,UAAUhB,QAAQ,CAACY,UAAU;IAEnC,sGAAsG;IACtG,MAAMP,QAAQC,iBAAkBC,CAAAA,kBAAkBU,YAAY,MAAMpB,aAAY;IAEhF,kEAAkE;IAClE,IAAI,CAACQ,SAASD,aAAa;QACzB,MAAM,IAAIc,MAAM;IAClB;IAEA,OAAOzB,aAAa;QAClB,GAAIuB,UAAU;YAACA;QAAO,IAAI,CAAC,CAAC;QAC5B,8EAA8E;QAC9EG,2BAA2B;QAC3BzB;QACA0B,kBAAkBlB;QAClBG;QACAgB,QAAQ;QACRC,oBAAoB;QACpB,GAAGd,MAAM;IACX;AACF;AA6BA;;;;;;;CAOC,GACD,OAAO,eAAee,oBAAoB,EACxCnB,WAAW,EACXC,OAAOC,aAAa,EACpB,GAAGE,QACqB;IACxB,MAAMd,YAAYC,iBAAiBc,KAAK;IACxCf,UAAUgB,GAAG,CAACC,WAAWH,OAAOgB,SAAS;IAEzC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AAMC,IAAI,KAAK;AAEnB;AAEA,SAASR,cAAcD,GAAU;IAC/B,OAAOU,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACb,KAAK;AACnD"}
@@ -2,6 +2,7 @@ import { mkdirSync } from 'node:fs';
2
2
  import { dirname, join as joinPath } from 'node:path';
3
3
  import { z } from 'zod/mini';
4
4
  import { debug } from '../../_exports/debug.js';
5
+ import { getCliExecutionContext } from '../../executionContext.js';
5
6
  import { getSanityConfigDir } from '../../util/getSanityConfigDir.js';
6
7
  import { readJsonFileSync } from '../../util/readJsonFileSync.js';
7
8
  import { writeJsonFileSync } from '../../util/writeJsonFileSync.js';
@@ -18,6 +19,14 @@ export const _internals = {
18
19
  * @returns A promise that resolves to a CLI token, or undefined if no token is found
19
20
  * @internal
20
21
  */ export async function getCliToken() {
22
+ // A per-invocation execution context token (e.g. per-request from an MCP
23
+ // server) takes precedence and must bypass the process-wide cache entirely:
24
+ // reading the cache would leak another invocation's token, and writing it
25
+ // would leak this one's.
26
+ const contextToken = getCliExecutionContext()?.token;
27
+ if (contextToken) {
28
+ return contextToken;
29
+ }
21
30
  const cached = getCachedToken();
22
31
  if (cached !== undefined) {
23
32
  return cached;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {clearCliTokenCache, getCachedToken, setCachedToken} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token from the environment or the config file\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n const cached = getCachedToken()\n if (cached !== undefined) {\n return cached\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const trimmed = token.trim()\n setCachedToken(trimmed)\n return trimmed\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n setCachedToken(configToken)\n return configToken\n}\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedToken","setCachedToken","_internals","getCliUserConfig","getCliToken","cached","undefined","token","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","_","rest","pretty","data","getUserConfig","get","key","set","delete","Array","isArray","err","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SAAQC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,QAAO,qBAAoB;AAGrF,8CAA8C;AAC9C,SAAQF,kBAAkB,QAAO,qBAAoB;AAErD,wBAAwB;AACxB,OAAO,MAAMG,aAAa;IACxBC;AACF,EAAC;AAED;;;;;CAKC,GACD,OAAO,eAAeC;IACpB,MAAMC,SAASL;IACf,IAAIK,WAAWC,WAAW;QACxB,OAAOD;IACT;IAEA,MAAME,QAAQC,QAAQC,GAAG,CAACC,iBAAiB;IAC3C,IAAIH,OAAO;QACT,MAAMI,UAAUJ,MAAMK,IAAI;QAC1BX,eAAeU;QACf,OAAOA;IACT;IAEA,MAAME,cAAcX,WAAWC,gBAAgB,CAAC;IAChDF,eAAeY;IACf,OAAOA;AACT;AACA,MAAMC,sBAAsB;IAC1BC,WAAWrB,EAAEsB,QAAQ,CAACtB,EAAEuB,MAAM;AAChC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,IAAiB,EAAEC,KAAyB;IAC3E,MAAMC,SAASC;IACf,MAAMC,SAAST,mBAAmB,CAACK,KAAK,CAACK,SAAS,CAACJ;IACnD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YAC/CpC,kBAAkBkC,YAAY;gBAAC,GAAGX,MAAM;gBAAE,CAACoB,IAAI,EAAErB;YAAK,GAAG;gBAACiB,QAAQ;YAAI;YACtE,IAAII,QAAQ,aAAa1C;QAC3B;QAEA,+EAA+E;QAC/E4C,QAAOF,GAAW;YAChB,MAAMpB,SAASC;YACf,IAAI,CAAEmB,CAAAA,OAAOpB,MAAK,GAAI;YACtB,MAAM,EAAC,CAACoB,IAAI,EAAEN,CAAC,EAAE,GAAGC,MAAK,GAAGf;YAC5BvB,kBAAkBmC,wBAAwBG,MAAM;gBAACC,QAAQ;YAAI;YAC7D,IAAII,QAAQ,aAAa1C;QAC3B;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,SAASuB;IACP,IAAI;QACF,MAAMD,SAASxB,iBAAiBoC;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYuB,MAAMC,OAAO,CAACxB,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAOyB,KAAc;QACrBnD,MAAM,sCAAsCmD,eAAef,QAAQe,IAAIpB,OAAO,GAAG,GAAGoB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASb;IACP,OAAOzB,QAAQC,GAAG,CAACsC,sBAAsB,IAAItD,SAASG,sBAAsB;AAC9E"}
1
+ {"version":3,"sources":["../../../src/config/cli/cliUserConfig.ts"],"sourcesContent":["import {mkdirSync} from 'node:fs'\nimport {dirname, join as joinPath} from 'node:path'\n\nimport {z} from 'zod/mini'\n\nimport {debug} from '../../_exports/debug.js'\nimport {getCliExecutionContext} from '../../executionContext.js'\nimport {getSanityConfigDir} from '../../util/getSanityConfigDir.js'\nimport {readJsonFileSync} from '../../util/readJsonFileSync.js'\nimport {writeJsonFileSync} from '../../util/writeJsonFileSync.js'\nimport {clearCliTokenCache, getCachedToken, setCachedToken} from './cliTokenCache.js'\nimport {type ConfigStore} from './types/cliConfig.js'\n\n// Re-export so existing consumers don't break\nexport {clearCliTokenCache} from './cliTokenCache.js'\n\n// Only used for testing\nexport const _internals = {\n getCliUserConfig,\n}\n\n/**\n * Get the CLI authentication token from the environment or the config file\n *\n * @returns A promise that resolves to a CLI token, or undefined if no token is found\n * @internal\n */\nexport async function getCliToken(): Promise<string | undefined> {\n // A per-invocation execution context token (e.g. per-request from an MCP\n // server) takes precedence and must bypass the process-wide cache entirely:\n // reading the cache would leak another invocation's token, and writing it\n // would leak this one's.\n const contextToken = getCliExecutionContext()?.token\n if (contextToken) {\n return contextToken\n }\n\n const cached = getCachedToken()\n if (cached !== undefined) {\n return cached\n }\n\n const token = process.env.SANITY_AUTH_TOKEN\n if (token) {\n const trimmed = token.trim()\n setCachedToken(trimmed)\n return trimmed\n }\n\n const configToken = _internals.getCliUserConfig('authToken')\n setCachedToken(configToken)\n return configToken\n}\nconst cliUserConfigSchema = {\n authToken: z.optional(z.string()),\n}\n\n/**\n * Set the config value for the given property.\n * Validates that the passed value adheres to the defined CLI config schema.\n *\n * @param prop - The property to set the value for\n * @param value - The value to set\n * @internal\n */\nexport function setCliUserConfig(prop: 'authToken', value: string | undefined): void {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(value)\n if (!result.success) {\n const message = result.error.issues\n .map(({message, path}) => `[${path.join('.')}] ${message}`)\n .join('\\n')\n\n throw new Error(`Invalid value for config property \"${prop}\": ${message}`)\n }\n\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n\n // When value is undefined, explicitly delete the key rather than relying\n // on JSON.stringify silently dropping undefined values.\n if (value === undefined) {\n const {[prop]: _, ...rest} = config\n writeJsonFileSync(configPath, rest, {pretty: true})\n } else {\n writeJsonFileSync(configPath, {...config, [prop]: value}, {pretty: true})\n }\n\n // Invalidate the in-process token cache so subsequent getCliToken() calls\n // pick up the new value from disk.\n clearCliTokenCache()\n}\n\n/**\n * Get the config value for the given property\n *\n * @param prop - The property to get the value for\n * @returns The value of the given property\n */\nexport function getCliUserConfig(prop: 'authToken'): string | undefined {\n const config = readConfig()\n const result = cliUserConfigSchema[prop].safeParse(config[prop])\n if (!result.success) {\n debug('Ignoring invalid stored value for \"%s\", returning undefined', prop)\n return undefined\n }\n\n return result.data\n}\n\n/**\n * Get a key-value store backed by the CLI user configuration file\n * (`~/.config/sanity/config.json`).\n *\n * Each call to `get`, `set`, or `delete` performs a full synchronous\n * read-modify-write cycle. This is intentional: sync I/O prevents\n * intra-process race conditions that occurred with the previous async\n * (configstore-backed) implementation.\n *\n * Note: there is no file-level locking, so concurrent writes from\n * separate CLI processes could still conflict. In practice this is\n * unlikely since CLI config writes are rare and user-initiated.\n *\n * @returns A {@link ConfigStore} for the CLI config file\n * @public\n */\nexport function getUserConfig(): ConfigStore {\n return {\n get(key: string): unknown {\n const config = readConfig()\n return config[key]\n },\n\n set(key: string, value: unknown): void {\n const config = readConfig()\n const configPath = getCliUserConfigPath()\n mkdirSync(dirname(configPath), {recursive: true})\n writeJsonFileSync(configPath, {...config, [key]: value}, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n\n // No mkdirSync needed: if readConfig() succeeded the directory already exists.\n delete(key: string): void {\n const config = readConfig()\n if (!(key in config)) return\n const {[key]: _, ...rest} = config\n writeJsonFileSync(getCliUserConfigPath(), rest, {pretty: true})\n if (key === 'authToken') clearCliTokenCache()\n },\n }\n}\n\n/**\n * Read the whole configuration from file system. If the file does not exist,\n * is corrupt, or otherwise unreadable, an empty object is returned. This is\n * intentional: the config only holds recoverable data (auth tokens, telemetry\n * consent) so silently resetting is preferable to blocking the user.\n *\n * @returns The whole CLI configuration.\n * @internal\n */\nfunction readConfig(): Record<string, unknown> {\n try {\n const config = readJsonFileSync(getCliUserConfigPath())\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error('Invalid config file - expected an object')\n }\n return config\n } catch (err: unknown) {\n debug('Failed to read CLI config file: %s', err instanceof Error ? err.message : `${err}`)\n return {}\n }\n}\n\n/**\n * Get the file system location for the CLI user configuration file.\n * Takes into account the active environment (staging vs production).\n * The file is located in the user's home directory under the `.config` directory.\n *\n * @returns The path to the CLI configuration file.\n * @internal\n */\nfunction getCliUserConfigPath() {\n return process.env.SANITY_CLI_CONFIG_PATH || joinPath(getSanityConfigDir(), 'config.json')\n}\n"],"names":["mkdirSync","dirname","join","joinPath","z","debug","getCliExecutionContext","getSanityConfigDir","readJsonFileSync","writeJsonFileSync","clearCliTokenCache","getCachedToken","setCachedToken","_internals","getCliUserConfig","getCliToken","contextToken","token","cached","undefined","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","config","readConfig","result","safeParse","success","message","error","issues","map","path","Error","configPath","getCliUserConfigPath","recursive","_","rest","pretty","data","getUserConfig","get","key","set","delete","Array","isArray","err","SANITY_CLI_CONFIG_PATH"],"mappings":"AAAA,SAAQA,SAAS,QAAO,UAAS;AACjC,SAAQC,OAAO,EAAEC,QAAQC,QAAQ,QAAO,YAAW;AAEnD,SAAQC,CAAC,QAAO,WAAU;AAE1B,SAAQC,KAAK,QAAO,0BAAyB;AAC7C,SAAQC,sBAAsB,QAAO,4BAA2B;AAChE,SAAQC,kBAAkB,QAAO,mCAAkC;AACnE,SAAQC,gBAAgB,QAAO,iCAAgC;AAC/D,SAAQC,iBAAiB,QAAO,kCAAiC;AACjE,SAAQC,kBAAkB,EAAEC,cAAc,EAAEC,cAAc,QAAO,qBAAoB;AAGrF,8CAA8C;AAC9C,SAAQF,kBAAkB,QAAO,qBAAoB;AAErD,wBAAwB;AACxB,OAAO,MAAMG,aAAa;IACxBC;AACF,EAAC;AAED;;;;;CAKC,GACD,OAAO,eAAeC;IACpB,yEAAyE;IACzE,4EAA4E;IAC5E,0EAA0E;IAC1E,yBAAyB;IACzB,MAAMC,eAAeV,0BAA0BW;IAC/C,IAAID,cAAc;QAChB,OAAOA;IACT;IAEA,MAAME,SAASP;IACf,IAAIO,WAAWC,WAAW;QACxB,O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,QAAQC,GAAG,CAACsC,sBAAsB,IAAIxD,SAASI,sBAAsB;AAC9E"}
@@ -1,4 +1,5 @@
1
1
  import { ProjectRootNotFoundError } from '../errors/ProjectRootNotFoundError.js';
2
+ import { getCliExecutionContext } from '../executionContext.js';
2
3
  import { findAppConfigPath } from './util/findAppConfigPath.js';
3
4
  import { tryFindStudioConfigPath } from './util/findStudioConfigPath.js';
4
5
  import { recursivelyResolveProjectRoot } from './util/recursivelyResolveProjectRoot.js';
@@ -14,6 +15,14 @@ import { recursivelyResolveProjectRoot } from './util/recursivelyResolveProjectR
14
15
  *
15
16
  * @internal
16
17
  */ export async function findProjectRoot(cwd) {
18
+ // Programmatic invocations (execution context active) must never resolve
19
+ // project context from the host's filesystem: walking up from the host
20
+ // process's cwd could pick up an unrelated Sanity project, and resolving the
21
+ // CLI config from it would even execute that project's `sanity.cli.ts`.
22
+ // Callers must provide explicit flags (e.g. `--project-id`) instead.
23
+ if (getCliExecutionContext()) {
24
+ throw new ProjectRootNotFoundError('Project root resolution from the filesystem is disabled for programmatic invocations');
25
+ }
17
26
  try {
18
27
  // First try to find a studio project root, looks for `sanity.config.(ts|js)`
19
28
  const studioProjectRoot = await resolveProjectRootForStudio(cwd);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/findProjectRoot.ts"],"sourcesContent":["import {ProjectRootNotFoundError} from '../errors/ProjectRootNotFoundError.js'\nimport {findAppConfigPath} from './util/findAppConfigPath.js'\nimport {tryFindStudioConfigPath} from './util/findStudioConfigPath.js'\nimport {\n type ProjectRootResult,\n recursivelyResolveProjectRoot,\n} from './util/recursivelyResolveProjectRoot.js'\n\n/**\n * Resolve project root directory and type.\n *\n * Project root is:\n * - `studio` - A pre-blueprints Sanity studio root (containing `sanity.config.(ts|js)`)\n * - `app` - A Sanity app root (containing `sanity.cli.(ts|js)`)\n *\n * If a Sanity Studio v2/v1 root is found (containing `sanity.json` with `root: true`),\n * an error is thrown, as v2/v1 is no longer supported.\n *\n * @internal\n */\nexport async function findProjectRoot(cwd: string): Promise<ProjectRootResult> {\n try {\n // First try to find a studio project root, looks for `sanity.config.(ts|js)`\n const studioProjectRoot = await resolveProjectRootForStudio(cwd)\n if (studioProjectRoot) {\n return studioProjectRoot\n }\n\n // Second try to find a app project root, looks for `sanity.cli.(ts|js)`\n const appProjectRoot = await resolveProjectRootForApp(cwd)\n if (appProjectRoot) {\n return appProjectRoot\n }\n\n // If nothing is found throw a specific error\n throw new ProjectRootNotFoundError('No project root found')\n } catch (err: unknown) {\n if (err instanceof ProjectRootNotFoundError) {\n throw err\n }\n const message = err instanceof Error ? err.message : `${err}`\n throw new Error(`Error occurred trying to resolve project root:\\n${message}`, {cause: err})\n }\n}\n\n/**\n * Recursively searches for a project configuration file in the given directory and its parents.\n * Throws if Sanity v2 studio root is found.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns A promise that resolves to an object if config is found, false otherwise\n * @internal\n */\nasync function resolveProjectRootForStudio(\n basePath: string,\n iterations = 0,\n): Promise<false | ProjectRootResult> {\n return recursivelyResolveProjectRoot(basePath, tryFindStudioConfigPath, 'studio', iterations)\n}\n\n/**\n * Recursively searches for a app project configuration file in the given directory and its parents.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns A promise that resolves to an object if config is found, false otherwise\n * @internal\n */\nasync function resolveProjectRootForApp(\n basePath: string,\n iterations = 0,\n): Promise<false | ProjectRootResult> {\n return recursivelyResolveProjectRoot(basePath, findAppConfigPath, 'app', iterations)\n}\n"],"names":["ProjectRootNotFoundError","findAppConfigPath","tryFindStudioConfigPath","recursivelyResolveProjectRoot","findProjectRoot","cwd","studioProjectRoot","resolveProjectRootForStudio","appProjectRoot","resolveProjectRootForApp","err","message","Error","cause","basePath","iterations"],"mappings":"AAAA,SAAQA,wBAAwB,QAAO,wCAAuC;AAC9E,SAAQC,iBAAiB,QAAO,8BAA6B;AAC7D,SAAQC,uBAAuB,QAAO,iCAAgC;AACtE,SAEEC,6BAA6B,QACxB,0CAAyC;AAEhD;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,gBAAgBC,GAAW;IAC/C,IAAI;QACF,6EAA6E;QAC7E,MAAMC,oBAAoB,MAAMC,4BAA4BF;QAC5D,IAAIC,mBAAmB;YACrB,OAAOA;QACT;QAEA,wEAAwE;QACxE,MAAME,iBAAiB,MAAMC,yBAAyBJ;QACtD,IAAIG,gBAAgB;YAClB,OAAOA;QACT;QAEA,6CAA6C;QAC7C,MAAM,IAAIR,yBAAyB;IACrC,EAAE,OAAOU,KAAc;QACrB,IAAIA,eAAeV,0BAA0B;YAC3C,MAAMU;QACR;QACA,MAAMC,UAAUD,eAAeE,QAAQF,IAAIC,OAAO,GAAG,GAAGD,KAAK;QAC7D,MAAM,IAAIE,MAAM,CAAC,gDAAgD,EAAED,SAAS,EAAE;YAACE,OAAOH;QAAG;IAC3F;AACF;AAEA;;;;;;;;CAQC,GACD,eAAeH,4BACbO,QAAgB,EAChBC,aAAa,CAAC;IAEd,OAAOZ,8BAA8BW,UAAUZ,yBAAyB,UAAUa;AACpF;AAEA;;;;;;;CAOC,GACD,eAAeN,yBACbK,QAAgB,EAChBC,aAAa,CAAC;IAEd,OAAOZ,8BAA8BW,UAAUb,mBAAmB,OAAOc;AAC3E"}
1
+ {"version":3,"sources":["../../src/config/findProjectRoot.ts"],"sourcesContent":["import {ProjectRootNotFoundError} from '../errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from '../executionContext.js'\nimport {findAppConfigPath} from './util/findAppConfigPath.js'\nimport {tryFindStudioConfigPath} from './util/findStudioConfigPath.js'\nimport {\n type ProjectRootResult,\n recursivelyResolveProjectRoot,\n} from './util/recursivelyResolveProjectRoot.js'\n\n/**\n * Resolve project root directory and type.\n *\n * Project root is:\n * - `studio` - A pre-blueprints Sanity studio root (containing `sanity.config.(ts|js)`)\n * - `app` - A Sanity app root (containing `sanity.cli.(ts|js)`)\n *\n * If a Sanity Studio v2/v1 root is found (containing `sanity.json` with `root: true`),\n * an error is thrown, as v2/v1 is no longer supported.\n *\n * @internal\n */\nexport async function findProjectRoot(cwd: string): Promise<ProjectRootResult> {\n // Programmatic invocations (execution context active) must never resolve\n // project context from the host's filesystem: walking up from the host\n // process's cwd could pick up an unrelated Sanity project, and resolving the\n // CLI config from it would even execute that project's `sanity.cli.ts`.\n // Callers must provide explicit flags (e.g. `--project-id`) instead.\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n\n try {\n // First try to find a studio project root, looks for `sanity.config.(ts|js)`\n const studioProjectRoot = await resolveProjectRootForStudio(cwd)\n if (studioProjectRoot) {\n return studioProjectRoot\n }\n\n // Second try to find a app project root, looks for `sanity.cli.(ts|js)`\n const appProjectRoot = await resolveProjectRootForApp(cwd)\n if (appProjectRoot) {\n return appProjectRoot\n }\n\n // If nothing is found throw a specific error\n throw new ProjectRootNotFoundError('No project root found')\n } catch (err: unknown) {\n if (err instanceof ProjectRootNotFoundError) {\n throw err\n }\n const message = err instanceof Error ? err.message : `${err}`\n throw new Error(`Error occurred trying to resolve project root:\\n${message}`, {cause: err})\n }\n}\n\n/**\n * Recursively searches for a project configuration file in the given directory and its parents.\n * Throws if Sanity v2 studio root is found.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns A promise that resolves to an object if config is found, false otherwise\n * @internal\n */\nasync function resolveProjectRootForStudio(\n basePath: string,\n iterations = 0,\n): Promise<false | ProjectRootResult> {\n return recursivelyResolveProjectRoot(basePath, tryFindStudioConfigPath, 'studio', iterations)\n}\n\n/**\n * Recursively searches for a app project configuration file in the given directory and its parents.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns A promise that resolves to an object if config is found, false otherwise\n * @internal\n */\nasync function resolveProjectRootForApp(\n basePath: string,\n iterations = 0,\n): Promise<false | ProjectRootResult> {\n return recursivelyResolveProjectRoot(basePath, findAppConfigPath, 'app', iterations)\n}\n"],"names":["ProjectRootNotFoundError","getCliExecutionContext","findAppConfigPath","tryFindStudioConfigPath","recursivelyResolveProjectRoot","findProjectRoot","cwd","studioProjectRoot","resolveProjectRootForStudio","appProjectRoot","resolveProjectRootForApp","err","message","Error","cause","basePath","iterations"],"mappings":"AAAA,SAAQA,wBAAwB,QAAO,wCAAuC;AAC9E,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,iBAAiB,QAAO,8BAA6B;AAC7D,SAAQC,uBAAuB,QAAO,iCAAgC;AACtE,SAEEC,6BAA6B,QACxB,0CAAyC;AAEhD;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,gBAAgBC,GAAW;IAC/C,yEAAyE;IACzE,uEAAuE;IACvE,6EAA6E;IAC7E,wEAAwE;IACxE,qEAAqE;IACrE,IAAIL,0BAA0B;QAC5B,MAAM,IAAID,yBACR;IAEJ;IAEA,IAAI;QACF,6EAA6E;QAC7E,MAAMO,oBAAoB,MAAMC,4BAA4BF;QAC5D,IAAIC,mBAAmB;YACrB,OAAOA;QACT;QAEA,wEAAwE;QACxE,MAAME,iBAAiB,MAAMC,yBAAyBJ;QACtD,IAAIG,gBAAgB;YAClB,OAAOA;QACT;QAEA,6CAA6C;QAC7C,MAAM,IAAIT,yBAAyB;IACrC,EAAE,OAAOW,KAAc;QACrB,IAAIA,eAAeX,0BAA0B;YAC3C,MAAMW;QACR;QACA,MAAMC,UAAUD,eAAeE,QAAQF,IAAIC,OAAO,GAAG,GAAGD,KAAK;QAC7D,MAAM,IAAIE,MAAM,CAAC,gDAAgD,EAAED,SAAS,EAAE;YAACE,OAAOH;QAAG;IAC3F;AACF;AAEA;;;;;;;;CAQC,GACD,eAAeH,4BACbO,QAAgB,EAChBC,aAAa,CAAC;IAEd,OAAOZ,8BAA8BW,UAAUZ,yBAAyB,UAAUa;AACpF;AAEA;;;;;;;CAOC,GACD,eAAeN,yBACbK,QAAgB,EAChBC,aAAa,CAAC;IAEd,OAAOZ,8BAA8BW,UAAUb,mBAAmB,OAAOc;AAC3E"}
@@ -1,5 +1,6 @@
1
1
  import { dirname, resolve } from 'node:path';
2
2
  import { ProjectRootNotFoundError } from '../errors/ProjectRootNotFoundError.js';
3
+ import { getCliExecutionContext } from '../executionContext.js';
3
4
  import { findAppConfigPathSync, findStudioConfigPathSync } from './util/configPathsSync.js';
4
5
  /**
5
6
  * Generic recursive search function for project configuration files (synchronous version).
@@ -40,6 +41,11 @@ import { findAppConfigPathSync, findStudioConfigPathSync } from './util/configPa
40
41
  * @returns Project root result
41
42
  * @internal
42
43
  */ export function findProjectRootSync(cwd) {
44
+ // See the matching guard in findProjectRoot: programmatic invocations must
45
+ // never resolve project context from the host's filesystem.
46
+ if (getCliExecutionContext()) {
47
+ throw new ProjectRootNotFoundError('Project root resolution from the filesystem is disabled for programmatic invocations');
48
+ }
43
49
  try {
44
50
  // First try to find a studio project root, looks for `sanity.config.(ts|js)`
45
51
  const studioProjectRoot = resolveProjectRootForStudioSync(cwd);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/findProjectRootSync.ts"],"sourcesContent":["import {dirname, resolve} from 'node:path'\n\nimport {ProjectRootNotFoundError} from '../errors/ProjectRootNotFoundError.js'\nimport {findAppConfigPathSync, findStudioConfigPathSync} from './util/configPathsSync.js'\nimport {ProjectRootResult} from './util/recursivelyResolveProjectRoot.js'\n\n/**\n * Generic recursive search function for project configuration files (synchronous version).\n *\n * @param basePath - The base path to start searching from\n * @param findConfigFn - Function that looks for config files in a given directory\n * @param projectType - The type of project ('app' | 'studio')\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction recursivelyResolveProjectRootSync(\n basePath: string,\n findConfigFn: (path: string) => string | undefined,\n projectType: 'app' | 'studio',\n iterations = 0,\n): false | ProjectRootResult {\n const configPath = findConfigFn(basePath)\n\n if (configPath) {\n return {\n directory: dirname(configPath),\n path: configPath,\n type: projectType,\n }\n }\n\n const parentDir = resolve(basePath, '..')\n if (parentDir === basePath || iterations > 50) {\n // Reached root (or max depth), give up\n return false\n }\n\n return recursivelyResolveProjectRootSync(parentDir, findConfigFn, projectType, iterations + 1)\n}\n\n/**\n * Resolve project root directory and type synchronously.\n *\n * Project root is:\n * - `studio` - A pre-blueprints Sanity studio root (containing `sanity.config.(ts|js)`)\n * - `app` - A Sanity app root (containing `sanity.cli.(ts|js)`)\n *\n * If a Sanity Studio v2/v1 root is found (containing `sanity.json` with `root: true`),\n * an error is thrown, as v2/v1 is no longer supported.\n *\n * @param cwd - Current working directory to start searching from\n * @returns Project root result\n * @internal\n */\nexport function findProjectRootSync(cwd: string): ProjectRootResult {\n try {\n // First try to find a studio project root, looks for `sanity.config.(ts|js)`\n const studioProjectRoot = resolveProjectRootForStudioSync(cwd)\n if (studioProjectRoot) {\n return studioProjectRoot\n }\n\n // Second try to find a app project root, looks for `sanity.cli.(ts|js)`\n const appProjectRoot = resolveProjectRootForAppSync(cwd)\n if (appProjectRoot) {\n return appProjectRoot\n }\n\n // If nothing is found throw a specific error\n throw new ProjectRootNotFoundError(`No project root found in ${cwd}`)\n } catch (err: unknown) {\n if (err instanceof ProjectRootNotFoundError) {\n throw err\n }\n const message = err instanceof Error ? err.message : `${err}`\n throw new Error(`Error occurred trying to resolve project root:\\n${message}`, {cause: err})\n }\n}\n\n/**\n * Recursively searches for a project configuration file in the given directory and its parents.\n * Throws if Sanity v2 studio root is found.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction resolveProjectRootForStudioSync(\n basePath: string,\n iterations = 0,\n): false | ProjectRootResult {\n return recursivelyResolveProjectRootSync(basePath, findStudioConfigPathSync, 'studio', iterations)\n}\n\n/**\n * Recursively searches for a app project configuration file in the given directory and its parents.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction resolveProjectRootForAppSync(basePath: string, iterations = 0): false | ProjectRootResult {\n return recursivelyResolveProjectRootSync(basePath, findAppConfigPathSync, 'app', iterations)\n}\n"],"names":["dirname","resolve","ProjectRootNotFoundError","findAppConfigPathSync","findStudioConfigPathSync","recursivelyResolveProjectRootSync","basePath","findConfigFn","projectType","iterations","configPath","directory","path","type","parentDir","findProjectRootSync","cwd","studioProjectRoot","resolveProjectRootForStudioSync","appProjectRoot","resolveProjectRootForAppSync","err","message","Error","cause"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,OAAO,QAAO,YAAW;AAE1C,SAAQC,wBAAwB,QAAO,wCAAuC;AAC9E,SAAQC,qBAAqB,EAAEC,wBAAwB,QAAO,4BAA2B;AAGzF;;;;;;;;;CASC,GACD,SAASC,kCACPC,QAAgB,EAChBC,YAAkD,EAClDC,WAA6B,EAC7BC,aAAa,CAAC;IAEd,MAAMC,aAAaH,aAAaD;IAEhC,IAAII,YAAY;QACd,OAAO;YACLC,WAAWX,QAAQU;YACnBE,MAAMF;YACNG,MAAML;QACR;IACF;IAEA,MAAMM,YAAYb,QAAQK,UAAU;IACpC,IAAIQ,cAAcR,YAAYG,aAAa,IAAI;QAC7C,uCAAuC;QACvC,OAAO;IACT;IAEA,OAAOJ,kCAAkCS,WAAWP,cAAcC,aAAaC,aAAa;AAC9F;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASM,oBAAoBC,GAAW;IAC7C,IAAI;QACF,6EAA6E;QAC7E,MAAMC,oBAAoBC,gCAAgCF;QAC1D,IAAIC,mBAAmB;YACrB,OAAOA;QACT;QAEA,wEAAwE;QACxE,MAAME,iBAAiBC,6BAA6BJ;QACpD,IAAIG,gBAAgB;YAClB,OAAOA;QACT;QAEA,6CAA6C;QAC7C,MAAM,IAAIjB,yBAAyB,CAAC,yBAAyB,EAAEc,KAAK;IACtE,EAAE,OAAOK,KAAc;QACrB,IAAIA,eAAenB,0BAA0B;YAC3C,MAAMmB;QACR;QACA,MAAMC,UAAUD,eAAeE,QAAQF,IAAIC,OAAO,GAAG,GAAGD,KAAK;QAC7D,MAAM,IAAIE,MAAM,CAAC,gDAAgD,EAAED,SAAS,EAAE;YAACE,OAAOH;QAAG;IAC3F;AACF;AAEA;;;;;;;;CAQC,GACD,SAASH,gCACPZ,QAAgB,EAChBG,aAAa,CAAC;IAEd,OAAOJ,kCAAkCC,UAAUF,0BAA0B,UAAUK;AACzF;AAEA;;;;;;;CAOC,GACD,SAASW,6BAA6Bd,QAAgB,EAAEG,aAAa,CAAC;IACpE,OAAOJ,kCAAkCC,UAAUH,uBAAuB,OAAOM;AACnF"}
1
+ {"version":3,"sources":["../../src/config/findProjectRootSync.ts"],"sourcesContent":["import {dirname, resolve} from 'node:path'\n\nimport {ProjectRootNotFoundError} from '../errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from '../executionContext.js'\nimport {findAppConfigPathSync, findStudioConfigPathSync} from './util/configPathsSync.js'\nimport {ProjectRootResult} from './util/recursivelyResolveProjectRoot.js'\n\n/**\n * Generic recursive search function for project configuration files (synchronous version).\n *\n * @param basePath - The base path to start searching from\n * @param findConfigFn - Function that looks for config files in a given directory\n * @param projectType - The type of project ('app' | 'studio')\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction recursivelyResolveProjectRootSync(\n basePath: string,\n findConfigFn: (path: string) => string | undefined,\n projectType: 'app' | 'studio',\n iterations = 0,\n): false | ProjectRootResult {\n const configPath = findConfigFn(basePath)\n\n if (configPath) {\n return {\n directory: dirname(configPath),\n path: configPath,\n type: projectType,\n }\n }\n\n const parentDir = resolve(basePath, '..')\n if (parentDir === basePath || iterations > 50) {\n // Reached root (or max depth), give up\n return false\n }\n\n return recursivelyResolveProjectRootSync(parentDir, findConfigFn, projectType, iterations + 1)\n}\n\n/**\n * Resolve project root directory and type synchronously.\n *\n * Project root is:\n * - `studio` - A pre-blueprints Sanity studio root (containing `sanity.config.(ts|js)`)\n * - `app` - A Sanity app root (containing `sanity.cli.(ts|js)`)\n *\n * If a Sanity Studio v2/v1 root is found (containing `sanity.json` with `root: true`),\n * an error is thrown, as v2/v1 is no longer supported.\n *\n * @param cwd - Current working directory to start searching from\n * @returns Project root result\n * @internal\n */\nexport function findProjectRootSync(cwd: string): ProjectRootResult {\n // See the matching guard in findProjectRoot: programmatic invocations must\n // never resolve project context from the host's filesystem.\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n\n try {\n // First try to find a studio project root, looks for `sanity.config.(ts|js)`\n const studioProjectRoot = resolveProjectRootForStudioSync(cwd)\n if (studioProjectRoot) {\n return studioProjectRoot\n }\n\n // Second try to find a app project root, looks for `sanity.cli.(ts|js)`\n const appProjectRoot = resolveProjectRootForAppSync(cwd)\n if (appProjectRoot) {\n return appProjectRoot\n }\n\n // If nothing is found throw a specific error\n throw new ProjectRootNotFoundError(`No project root found in ${cwd}`)\n } catch (err: unknown) {\n if (err instanceof ProjectRootNotFoundError) {\n throw err\n }\n const message = err instanceof Error ? err.message : `${err}`\n throw new Error(`Error occurred trying to resolve project root:\\n${message}`, {cause: err})\n }\n}\n\n/**\n * Recursively searches for a project configuration file in the given directory and its parents.\n * Throws if Sanity v2 studio root is found.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction resolveProjectRootForStudioSync(\n basePath: string,\n iterations = 0,\n): false | ProjectRootResult {\n return recursivelyResolveProjectRootSync(basePath, findStudioConfigPathSync, 'studio', iterations)\n}\n\n/**\n * Recursively searches for a app project configuration file in the given directory and its parents.\n *\n * @param basePath - The base path to start searching from\n * @param iterations - Current iteration count, passed internally to prevent infinite recursion.\n * @returns An object if config is found, false otherwise\n * @internal\n */\nfunction resolveProjectRootForAppSync(basePath: string, iterations = 0): false | ProjectRootResult {\n return recursivelyResolveProjectRootSync(basePath, findAppConfigPathSync, 'app', iterations)\n}\n"],"names":["dirname","resolve","ProjectRootNotFoundError","getCliExecutionContext","findAppConfigPathSync","findStudioConfigPathSync","recursivelyResolveProjectRootSync","basePath","findConfigFn","projectType","iterations","configPath","directory","path","type","parentDir","findProjectRootSync","cwd","studioProjectRoot","resolveProjectRootForStudioSync","appProjectRoot","resolveProjectRootForAppSync","err","message","Error","cause"],"mappings":"AAAA,SAAQA,OAAO,EAAEC,OAAO,QAAO,YAAW;AAE1C,SAAQC,wBAAwB,QAAO,wCAAuC;AAC9E,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,qBAAqB,EAAEC,wBAAwB,QAAO,4BAA2B;AAGzF;;;;;;;;;CASC,GACD,SAASC,kCACPC,QAAgB,EAChBC,YAAkD,EAClDC,WAA6B,EAC7BC,aAAa,CAAC;IAEd,MAAMC,aAAaH,aAAaD;IAEhC,IAAII,YAAY;QACd,OAAO;YACLC,WAAWZ,QAAQW;YACnBE,MAAMF;YACNG,MAAML;QACR;IACF;IAEA,MAAMM,YAAYd,QAAQM,UAAU;IACpC,IAAIQ,cAAcR,YAAYG,aAAa,IAAI;QAC7C,uCAAuC;QACvC,OAAO;IACT;IAEA,OAAOJ,kCAAkCS,WAAWP,cAAcC,aAAaC,aAAa;AAC9F;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASM,oBAAoBC,GAAW;IAC7C,2EAA2E;IAC3E,4DAA4D;IAC5D,IAAId,0BAA0B;QAC5B,MAAM,IAAID,yBACR;IAEJ;IAEA,IAAI;QACF,6EAA6E;QAC7E,MAAMgB,oBAAoBC,gCAAgCF;QAC1D,IAAIC,mBAAmB;YACrB,OAAOA;QACT;QAEA,wEAAwE;QACxE,MAAME,iBAAiBC,6BAA6BJ;QACpD,IAAIG,gBAAgB;YAClB,OAAOA;QACT;QAEA,6CAA6C;QAC7C,MAAM,IAAIlB,yBAAyB,CAAC,yBAAyB,EAAEe,KAAK;IACtE,EAAE,OAAOK,KAAc;QACrB,IAAIA,eAAepB,0BAA0B;YAC3C,MAAMoB;QACR;QACA,MAAMC,UAAUD,eAAeE,QAAQF,IAAIC,OAAO,GAAG,GAAGD,KAAK;QAC7D,MAAM,IAAIE,MAAM,CAAC,gDAAgD,EAAED,SAAS,EAAE;YAACE,OAAOH;QAAG;IAC3F;AACF;AAEA;;;;;;;;CAQC,GACD,SAASH,gCACPZ,QAAgB,EAChBG,aAAa,CAAC;IAEd,OAAOJ,kCAAkCC,UAAUF,0BAA0B,UAAUK;AACzF;AAEA;;;;;;;CAOC,GACD,SAASW,6BAA6Bd,QAAgB,EAAEG,aAAa,CAAC;IACpE,OAAOJ,kCAAkCC,UAAUH,uBAAuB,OAAOM;AACnF"}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Explicit, per-invocation execution context for running CLI commands
3
+ * programmatically (e.g. from an MCP server or another embedding host).
4
+ *
5
+ * When a context is active, it overrides the process-global defaults the CLI
6
+ * normally relies on:
7
+ *
8
+ * - `token` takes precedence over `SANITY_AUTH_TOKEN` and the stored CLI
9
+ * config token, and never touches the process-wide token cache
10
+ * - `stdout`/`stderr` receive the output that commands would otherwise write
11
+ * to the process streams
12
+ * - interactivity checks report non-interactive, so commands fail fast with
13
+ * actionable errors instead of prompting
14
+ * - project root resolution from the filesystem is disabled: commands never
15
+ * read (or execute) `sanity.config.ts`/`sanity.cli.ts` files found near the
16
+ * host process's cwd, so project context must come from explicit flags
17
+ * (e.g. `--project-id`)
18
+ *
19
+ * The CLI binary never enters a context, so its behavior is unchanged.
20
+ *
21
+ * @public
22
+ */
23
+ export declare interface CliExecutionContext {
24
+ /**
25
+ * Sink for output the command would otherwise write to `process.stderr`.
26
+ * Called once per line, without a trailing newline.
27
+ */
28
+ stderr?: (line: string) => void;
29
+ /**
30
+ * Sink for output the command would otherwise write to `process.stdout`.
31
+ * Called once per line, without a trailing newline.
32
+ */
33
+ stdout?: (line: string) => void;
34
+ /**
35
+ * Auth token to use for API clients created during this invocation.
36
+ * Overrides `SANITY_AUTH_TOKEN` and the stored CLI config token.
37
+ */
38
+ token?: string;
39
+ }
40
+
41
+ /**
42
+ * Get the active execution context, if any. Returns `undefined` when running
43
+ * as the regular CLI (process-global behavior applies).
44
+ *
45
+ * @public
46
+ */
47
+ export declare function getCliExecutionContext():
48
+ CliExecutionContext | undefined;
49
+
50
+ /**
51
+ * Run `fn` with the given execution context active. The context is visible
52
+ * (via {@link getCliExecutionContext}) to all code in the async call graph of
53
+ * `fn`, and invisible to everything else — concurrent invocations with
54
+ * different contexts are fully isolated.
55
+ *
56
+ * @public
57
+ */
58
+ export declare function runWithCliExecutionContext<T>(
59
+ context: CliExecutionContext,
60
+ fn: () => T,
61
+ ): T;
62
+
63
+ export {};
@@ -0,0 +1,28 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ // Anchored on globalThis (same pattern as CLI_TELEMETRY_SYMBOL) so that the
3
+ // context survives dual module instances: an embedding host may import this
4
+ // module from source (e.g. via vitest or a bundler) while oclif loads command
5
+ // classes from dist, and both must observe the same AsyncLocalStorage.
6
+ const STORAGE_SYMBOL = Symbol.for('sanity.cli.executionContext');
7
+ const globalStorage = globalThis;
8
+ const storage = globalStorage[STORAGE_SYMBOL] ??= new AsyncLocalStorage();
9
+ /**
10
+ * Run `fn` with the given execution context active. The context is visible
11
+ * (via {@link getCliExecutionContext}) to all code in the async call graph of
12
+ * `fn`, and invisible to everything else — concurrent invocations with
13
+ * different contexts are fully isolated.
14
+ *
15
+ * @public
16
+ */ export function runWithCliExecutionContext(context, fn) {
17
+ return storage.run(context, fn);
18
+ }
19
+ /**
20
+ * Get the active execution context, if any. Returns `undefined` when running
21
+ * as the regular CLI (process-global behavior applies).
22
+ *
23
+ * @public
24
+ */ export function getCliExecutionContext() {
25
+ return storage.getStore();
26
+ }
27
+
28
+ //# sourceMappingURL=executionContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/executionContext.ts"],"sourcesContent":["import {AsyncLocalStorage} from 'node:async_hooks'\n\n/**\n * Explicit, per-invocation execution context for running CLI commands\n * programmatically (e.g. from an MCP server or another embedding host).\n *\n * When a context is active, it overrides the process-global defaults the CLI\n * normally relies on:\n *\n * - `token` takes precedence over `SANITY_AUTH_TOKEN` and the stored CLI\n * config token, and never touches the process-wide token cache\n * - `stdout`/`stderr` receive the output that commands would otherwise write\n * to the process streams\n * - interactivity checks report non-interactive, so commands fail fast with\n * actionable errors instead of prompting\n * - project root resolution from the filesystem is disabled: commands never\n * read (or execute) `sanity.config.ts`/`sanity.cli.ts` files found near the\n * host process's cwd, so project context must come from explicit flags\n * (e.g. `--project-id`)\n *\n * The CLI binary never enters a context, so its behavior is unchanged.\n *\n * @public\n */\nexport interface CliExecutionContext {\n /**\n * Sink for output the command would otherwise write to `process.stderr`.\n * Called once per line, without a trailing newline.\n */\n stderr?: (line: string) => void\n\n /**\n * Sink for output the command would otherwise write to `process.stdout`.\n * Called once per line, without a trailing newline.\n */\n stdout?: (line: string) => void\n\n /**\n * Auth token to use for API clients created during this invocation.\n * Overrides `SANITY_AUTH_TOKEN` and the stored CLI config token.\n */\n token?: string\n}\n\n// Anchored on globalThis (same pattern as CLI_TELEMETRY_SYMBOL) so that the\n// context survives dual module instances: an embedding host may import this\n// module from source (e.g. via vitest or a bundler) while oclif loads command\n// classes from dist, and both must observe the same AsyncLocalStorage.\nconst STORAGE_SYMBOL = Symbol.for('sanity.cli.executionContext')\n\nconst globalStorage = globalThis as {\n [STORAGE_SYMBOL]?: AsyncLocalStorage<CliExecutionContext>\n}\n\nconst storage = (globalStorage[STORAGE_SYMBOL] ??= new AsyncLocalStorage<CliExecutionContext>())\n\n/**\n * Run `fn` with the given execution context active. The context is visible\n * (via {@link getCliExecutionContext}) to all code in the async call graph of\n * `fn`, and invisible to everything else — concurrent invocations with\n * different contexts are fully isolated.\n *\n * @public\n */\nexport function runWithCliExecutionContext<T>(context: CliExecutionContext, fn: () => T): T {\n return storage.run(context, fn)\n}\n\n/**\n * Get the active execution context, if any. Returns `undefined` when running\n * as the regular CLI (process-global behavior applies).\n *\n * @public\n */\nexport function getCliExecutionContext(): CliExecutionContext | undefined {\n return storage.getStore()\n}\n"],"names":["AsyncLocalStorage","STORAGE_SYMBOL","Symbol","for","globalStorage","globalThis","storage","runWithCliExecutionContext","context","fn","run","getCliExecutionContext","getStore"],"mappings":"AAAA,SAAQA,iBAAiB,QAAO,mBAAkB;AA4ClD,4EAA4E;AAC5E,4EAA4E;AAC5E,8EAA8E;AAC9E,uEAAuE;AACvE,MAAMC,iBAAiBC,OAAOC,GAAG,CAAC;AAElC,MAAMC,gBAAgBC;AAItB,MAAMC,UAAWF,aAAa,CAACH,eAAe,KAAK,IAAID;AAEvD;;;;;;;CAOC,GACD,OAAO,SAASO,2BAA8BC,OAA4B,EAAEC,EAAW;IACrF,OAAOH,QAAQI,GAAG,CAACF,SAASC;AAC9B;AAEA;;;;;CAKC,GACD,OAAO,SAASE;IACd,OAAOL,QAAQM,QAAQ;AACzB"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import {type Command} from '@oclif/core'\n\nexport interface Output {\n error: Command['error']\n log: Command['log']\n warn: Command['warn']\n}\n\nexport type RequireProps<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>\n\n// @todo\n// Replace with SanityUser type from client once implemented\nexport type SanityOrgUser = {\n email: string\n id: string\n name: string\n profileImage?: string\n provider: 'github' | 'google' | 'sanity' | `saml-${string}`\n tosAcceptedAt?: string\n}\n"],"names":[],"mappings":"AAUA,QAAQ;AACR,4DAA4D;AAC5D,WAOC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import {type Command} from '@oclif/core'\n\nexport interface Output {\n error: Command['error']\n log: Command['log']\n warn: Command['warn']\n}\n\nexport type RequireProps<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>\n\n// @todo\n// Replace with SanityUser type from client once implemented\nexport type SanityOrgUser = {\n /**\n * Null when authenticating with an API token rather than a user account —\n * robot tokens resolve to a user whose `email` and `familyName` are null.\n * Use `getUserDisplayName()` for anything user-facing.\n */\n email: string | null\n id: string\n name: string\n profileImage?: string\n /** `sanity-token` is returned when authenticating with an API token. */\n provider: 'github' | 'google' | 'sanity' | 'sanity-token' | `saml-${string}`\n tosAcceptedAt?: string\n}\n"],"names":[],"mappings":"AAUA,QAAQ;AACR,4DAA4D;AAC5D,WAaC"}
@@ -1,4 +1,8 @@
1
+ import { getCliExecutionContext } from '../executionContext.js';
1
2
  export function isInteractive() {
3
+ // Programmatic invocations (execution context active) are never interactive,
4
+ // even if the host process happens to have a TTY.
5
+ if (getCliExecutionContext()) return false;
2
6
  return Boolean(process.stdin.isTTY) && process.env.TERM !== 'dumb' && !('CI' in process.env);
3
7
  }
4
8
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/isInteractive.ts"],"sourcesContent":["export function isInteractive(): boolean {\n return Boolean(process.stdin.isTTY) && process.env.TERM !== 'dumb' && !('CI' in process.env)\n}\n"],"names":["isInteractive","Boolean","process","stdin","isTTY","env","TERM"],"mappings":"AAAA,OAAO,SAASA;IACd,OAAOC,QAAQC,QAAQC,KAAK,CAACC,KAAK,KAAKF,QAAQG,GAAG,CAACC,IAAI,KAAK,UAAU,CAAE,CAAA,QAAQJ,QAAQG,GAAG,AAAD;AAC5F"}
1
+ {"version":3,"sources":["../../src/util/isInteractive.ts"],"sourcesContent":["import {getCliExecutionContext} from '../executionContext.js'\n\nexport function isInteractive(): boolean {\n // Programmatic invocations (execution context active) are never interactive,\n // even if the host process happens to have a TTY.\n if (getCliExecutionContext()) return false\n\n return Boolean(process.stdin.isTTY) && process.env.TERM !== 'dumb' && !('CI' in process.env)\n}\n"],"names":["getCliExecutionContext","isInteractive","Boolean","process","stdin","isTTY","env","TERM"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,yBAAwB;AAE7D,OAAO,SAASC;IACd,6EAA6E;IAC7E,kDAAkD;IAClD,IAAID,0BAA0B,OAAO;IAErC,OAAOE,QAAQC,QAAQC,KAAK,CAACC,KAAK,KAAKF,QAAQG,GAAG,CAACC,IAAI,KAAK,UAAU,CAAE,CAAA,QAAQJ,QAAQG,GAAG,AAAD;AAC5F"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "2.5.0",
3
+ "version": "2.6.0",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -53,6 +53,10 @@
53
53
  "source": "./src/_exports/errors.ts",
54
54
  "default": "./dist/_exports/errors.js"
55
55
  },
56
+ "./executionContext": {
57
+ "source": "./src/executionContext.ts",
58
+ "default": "./dist/executionContext.js"
59
+ },
56
60
  "./package-manager": {
57
61
  "source": "./src/_exports/package-manager.ts",
58
62
  "default": "./dist/_exports/package-manager.js"