@sanity/cli-core 2.6.0 → 2.7.1

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.
@@ -396,6 +396,13 @@ export declare abstract class SanityCommand<T extends typeof Command>
396
396
  * @returns Whether the terminal is interactive.
397
397
  */
398
398
  resolveIsInteractive(): boolean;
399
+ /**
400
+ * Execute an already-constructed command without oclif's static runner:
401
+ * `Command.run()` performs a full `Config.load()` — filesystem reads, env
402
+ * consultation, and a process-global config cache write — on every call,
403
+ * which programmatic invocations must not repeat per request.
404
+ */
405
+ runInExecutionContext<TResult>(): Promise<TResult>;
399
406
  /**
400
407
  * Get the CLI config, returning an empty config if no project root is found.
401
408
  *
@@ -151,6 +151,9 @@ export class SanityCommand extends Command {
151
151
  *
152
152
  * @returns The project root result.
153
153
  */ getProjectRoot() {
154
+ if (getCliExecutionContext()) {
155
+ throw new ProjectRootNotFoundError('Project root resolution from the filesystem is disabled for programmatic invocations');
156
+ }
154
157
  return findProjectRoot(process.cwd());
155
158
  }
156
159
  async init() {
@@ -222,6 +225,17 @@ export class SanityCommand extends Command {
222
225
  return isInteractive();
223
226
  }
224
227
  /**
228
+ * Execute an already-constructed command without oclif's static runner:
229
+ * `Command.run()` performs a full `Config.load()` — filesystem reads, env
230
+ * consultation, and a process-global config cache write — on every call,
231
+ * which programmatic invocations must not repeat per request.
232
+ */ runInExecutionContext() {
233
+ if (!getCliExecutionContext()) {
234
+ throw new Error('runInExecutionContext requires a CLI execution context');
235
+ }
236
+ return this._run();
237
+ }
238
+ /**
225
239
  * Get the CLI config, returning an empty config if no project root is found.
226
240
  *
227
241
  * Use this instead of `getCliConfig()` in commands that can operate without a
@@ -1 +1 @@
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,S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AChB,IAAI,CAACwD,SAASC,QAAQ;YACpB,KAAK,CAAChC,QAAQ6B;YACd;QACF;QACAE,QAAQC,MAAM,CAACC,KAAKC,SAAS,CAACL,MAAM,MAAM;IAC5C;IAEA;;GAEC,GACD,AAAgBjC,YAAYD,UAAU,EAAE,EAAE,GAAGb,IAAe,EAAQ;QAClE,MAAMiD,UAAUxD;QAChB,IAAI,CAACwD,SAASI,QAAQ;YACpB,KAAK,CAACvC,YAAYD,YAAYb;YAC9B;QACF;QACA,IAAI,CAAC,IAAI,CAACiB,WAAW,IAAIgC,QAAQI,MAAM,CAACtE,OAAO8B,YAAYb;IAC7D;IAEA;;;;GAIC,GACD,AAAOgD,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;;;GAOC,GACD,MAAgByD,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACjE,YAAY;QAChC,EAAE,OAAOsB,KAAK;YACZ,IAAI,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"}
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 if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\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 * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\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","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SACEC,kBAAkB,EAClBC,mB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I;YACvBgC,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEK,iBAAiBH,QAAQG,MAAM7C,OAAO,GAAG6C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
@@ -1422,6 +1422,13 @@ export declare abstract class SanityCommand<T extends typeof Command>
1422
1422
  * @returns Whether the terminal is interactive.
1423
1423
  */
1424
1424
  resolveIsInteractive(): boolean;
1425
+ /**
1426
+ * Execute an already-constructed command without oclif's static runner:
1427
+ * `Command.run()` performs a full `Config.load()` — filesystem reads, env
1428
+ * consultation, and a process-global config cache write — on every call,
1429
+ * which programmatic invocations must not repeat per request.
1430
+ */
1431
+ runInExecutionContext<TResult>(): Promise<TResult>;
1425
1432
  /**
1426
1433
  * Get the CLI config, returning an empty config if no project root is found.
1427
1434
  *
@@ -5,14 +5,12 @@ import { CLIError } from "@oclif/core/errors";
5
5
  import { CustomBorderStyle } from "boxen";
6
6
  import * as inquirer from "@inquirer/prompts";
7
7
  import { default as logSymbols } from "log-symbols";
8
+ import { Options } from "ora";
9
+ import { Ora } from "ora";
10
+ import { PromiseOptions } from "ora";
8
11
  import { Separator } from "@inquirer/prompts";
9
12
  import { Spacing } from "boxen";
10
- import { Spinner } from "ora";
11
- import { default as spinner } from "ora";
12
- import { Ora as SpinnerInstance } from "ora";
13
- import { Options as SpinnerOptions } from "ora";
14
- import { oraPromise as spinnerPromise } from "ora";
15
- import { PromiseOptions as SpinnerPromiseOptions } from "ora";
13
+ import { Spinner as Spinner_2 } from "ora";
16
14
 
17
15
  export { boxen };
18
16
 
@@ -68,17 +66,20 @@ export { Separator };
68
66
 
69
67
  export { Spacing };
70
68
 
71
- export { Spinner };
69
+ export declare type Spinner = Spinner_2;
72
70
 
73
- export { spinner };
71
+ export declare function spinner(options?: Options | string): Ora;
74
72
 
75
- export { SpinnerInstance };
73
+ export declare type SpinnerInstance = Ora;
76
74
 
77
- export { SpinnerOptions };
75
+ export declare type SpinnerOptions = Options;
78
76
 
79
- export { spinnerPromise };
77
+ export declare function spinnerPromise<T>(
78
+ action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,
79
+ options?: PromiseOptions<T> | string,
80
+ ): Promise<T>;
80
81
 
81
- export { SpinnerPromiseOptions };
82
+ export declare type SpinnerPromiseOptions<T> = PromiseOptions<T>;
82
83
 
83
84
  declare interface TimeMeasurer {
84
85
  end: (name: string) => number;
package/dist/apiClient.js CHANGED
@@ -3,9 +3,8 @@ import { createClient, requester as defaultRequester, isHttpError } from '@sanit
3
3
  import { getCliToken } from './config/cli/cliUserConfig.js';
4
4
  import { generateHelpUrl } from './util/generateHelpUrl.js';
5
5
  import { getSanityUrl } from './util/getSanityUrl.js';
6
- const apiHosts = {
7
- staging: 'https://api.sanity.work'
8
- };
6
+ import { isStaging } from './util/isStaging.js';
7
+ const STAGING_API_HOST = 'https://api.sanity.work';
9
8
  const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
10
9
  /**
11
10
  * Create a "global" (unscoped) Sanity API client.
@@ -17,8 +16,7 @@ const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
17
16
  */ export async function getGlobalCliClient({ requireUser, token: providedToken, unauthenticated, ...config }) {
18
17
  const requester = defaultRequester.clone();
19
18
  requester.use(authErrors());
20
- const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production';
21
- const apiHost = apiHosts[sanityEnv];
19
+ const apiHost = isStaging() ? STAGING_API_HOST : undefined;
22
20
  // Use the provided token if set, otherwise fall back to the stored CLI token (unless unauthenticated)
23
21
  const token = providedToken || (unauthenticated ? undefined : await getCliToken());
24
22
  // If the token is not set and requireUser is true, throw an error
@@ -49,8 +47,7 @@ const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
49
47
  */ export async function getProjectCliClient({ requireUser, token: providedToken, ...config }) {
50
48
  const requester = defaultRequester.clone();
51
49
  requester.use(authErrors(config.projectId));
52
- const sanityEnv = process.env.SANITY_INTERNAL_ENV || 'production';
53
- const apiHost = apiHosts[sanityEnv];
50
+ const apiHost = isStaging() ? STAGING_API_HOST : undefined;
54
51
  // Use the provided token if it is set, otherwise get the token from the config file
55
52
  const token = providedToken || await getCliToken();
56
53
  // If the token is not set and requireUser is true, throw an error
@@ -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'\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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,UAAU;YACrD,IAAIA,eAAe,KAAK;gBACtB,IAAIJ,aAAaK,2BAA2BH,IAAII,QAAQ,CAACC,IAAI,GAAG;oBAC9DL,IAAIM,OAAO,GAAG,GAAGN,IAAIM,OAAO,CAAC,wCAAwC,EAAEjC,aAAa,CAAC,gBAAgB,EAAEkC,mBAAmBT,WAAW,QAAQ,CAAC,EAAE,CAAC,CAAC;oBAClJ,OAAOE;gBACT;gBAEAA,IAAIM,OAAO,GAAG,GAAGN,IAAIM,OAAO,CAAC,mCAAmC,EAAExC,UAAU,QAAQ,gBAAgB,6BAA6B,EAAEM,gBAAgB,cAAc,CAAC,CAAC;YACrK;YAEA,OAAO4B;QACT;IACF;AACF;AAEA,SAASG,2BACPE,IAAa;IAEb,IAAI,OAAOA,SAAS,YAAYA,SAAS,QAAQ,CAAE,CAAA,WAAWA,IAAG,GAAI,OAAO;IAE5E,MAAM,EAACG,KAAK,EAAC,GAAGH;IAChB,OACE,OAAOG,UAAU,YACjBA,UAAU,QACV,UAAUA,SACVA,MAAMC,IAAI,KAAK;AAEnB;AAEA,SAASR,cAAcD,GAAU;IAC/B,OAAOU,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACb,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'\nimport {isStaging} from './util/isStaging.js'\n\nconst STAGING_API_HOST = 'https://api.sanity.work'\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 apiHost = isStaging() ? STAGING_API_HOST : undefined\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 apiHost = isStaging() ? STAGING_API_HOST : undefined\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","isStaging","STAGING_API_HOST","CLI_REQUEST_TAG_PREFIX","getGlobalCliClient","requireUser","token","providedToken","unauthenticated","config","clone","use","authErrors","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;AACnD,SAAQC,SAAS,QAAO,sBAAqB;AAE7C,MAAMC,mBAAmB;AAEzB,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,UAAUZ,cAAcC,mBAAmBY;IAEjD,sGAAsG;IACtG,MAAMR,QAAQC,iBAAkBC,CAAAA,kBAAkBM,YAAY,MAAMhB,aAAY;IAEhF,kEAAkE;IAClE,IAAI,CAACQ,SAASD,aAAa;QACzB,MAAM,IAAIU,MAAM;IAClB;IAEA,OAAOrB,aAAa;QAClB,GAAImB,UAAU;YAACA;QAAO,IAAI,CAAC,CAAC;QAC5B,8EAA8E;QAC9EG,2BAA2B;QAC3BrB;QACAsB,kBAAkBd;QAClBG;QACAY,QAAQ;QACRC,oBAAoB;QACpB,GAAGV,MAAM;IACX;AACF;AA6BA;;;;;;;CAOC,GACD,OAAO,eAAeW,oBAAoB,EACxCf,WAAW,EACXC,OAAOC,aAAa,EACpB,GAAGE,QACqB;IACxB,MAAMd,YAAYC,iBAAiBc,KAAK;IACxCf,UAAUgB,GAAG,CAACC,WAAWH,OAAOY,SAAS;IAEzC,MAAMR,UAAUZ,cAAcC,mBAAmBY;IAEjD,oFAAoF;IACpF,MAAMR,QAAQC,iBAAkB,MAAMT;IAEtC,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23
23
  // server) takes precedence and must bypass the process-wide cache entirely:
24
24
  // reading the cache would leak another invocation's token, and writing it
25
25
  // would leak this one's.
26
- const contextToken = getCliExecutionContext()?.token;
27
- if (contextToken) {
28
- return contextToken;
29
- }
26
+ const context = getCliExecutionContext();
27
+ if (context) return context.token;
30
28
  const cached = getCachedToken();
31
29
  if (cached !== undefined) {
32
30
  return cached;
@@ -52,6 +50,7 @@ const cliUserConfigSchema = {
52
50
  * @param value - The value to set
53
51
  * @internal
54
52
  */ export function setCliUserConfig(prop, value) {
53
+ assertCanAccessHostUserConfig();
55
54
  const config = readConfig();
56
55
  const result = cliUserConfigSchema[prop].safeParse(value);
57
56
  if (!result.success) {
@@ -87,6 +86,7 @@ const cliUserConfigSchema = {
87
86
  * @param prop - The property to get the value for
88
87
  * @returns The value of the given property
89
88
  */ export function getCliUserConfig(prop) {
89
+ assertCanAccessHostUserConfig();
90
90
  const config = readConfig();
91
91
  const result = cliUserConfigSchema[prop].safeParse(config[prop]);
92
92
  if (!result.success) {
@@ -111,6 +111,7 @@ const cliUserConfigSchema = {
111
111
  * @returns A {@link ConfigStore} for the CLI config file
112
112
  * @public
113
113
  */ export function getUserConfig() {
114
+ assertCanAccessHostUserConfig();
114
115
  return {
115
116
  get (key) {
116
117
  const config = readConfig();
@@ -142,6 +143,11 @@ const cliUserConfigSchema = {
142
143
  }
143
144
  };
144
145
  }
146
+ function assertCanAccessHostUserConfig() {
147
+ if (getCliExecutionContext()) {
148
+ throw new Error('Host CLI user configuration is unavailable during programmatic invocations');
149
+ }
150
+ }
145
151
  /**
146
152
  * Read the whole configuration from file system. If the file does not exist,
147
153
  * is corrupt, or otherwise unreadable, an empty object is returned. This is
@@ -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 {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,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SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAOyB,KAAc;QACrBrD,MAAM,sCAAsCqD,eAAef,QAAQe,IAAIpB,OAAO,GAAG,GAAGoB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASb;IACP,OAAOzB,QAAQC,GAAG,CAACsC,sBAAsB,IAAIxD,SAASI,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 context = getCliExecutionContext()\n if (context) return context.token\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 assertCanAccessHostUserConfig()\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 assertCanAccessHostUserConfig()\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 assertCanAccessHostUserConfig()\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\nfunction assertCanAccessHostUserConfig(): void {\n if (getCliExecutionContext()) {\n throw new Error('Host CLI user configuration is unavailable during programmatic invocations')\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","context","token","cached","undefined","process","env","SANITY_AUTH_TOKEN","trimmed","trim","configToken","cliUserConfigSchema","authToken","optional","string","setCliUserConfig","prop","value","assertCanAccessHostUserConfig","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,UAAUV;IAChB,IAAIU,SAAS,OAAOA,QAAQC,KAAK;IAEjC,MAAMC,SAASP;IACf,IAAIO,WAAWC,WAAW;QACxB,OAAOD;IACT;IAEA,MAAMD,QAAQG,QAAQC,GAAG,CAACC,iBAAiB;IAC3C,IAAIL,OAAO;QACT,MAAMM,UAAUN,MAAMO,IAAI;QAC1BZ,eAAeW;QACf,OAAOA;IACT;IAEA,MAAME,cAAcZ,WAAWC,gBAAgB,CAAC;IAChDF,eAAea;IACf,OAAOA;AACT;AACA,MAAMC,sBAAsB;IAC1BC,WAAWvB,EAAEwB,QAAQ,CAACxB,EAAEyB,MAAM;AAChC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,IAAiB,EAAEC,KAAyB;IAC3EC;IACA,MAAMC,SAASC;IACf,MAAMC,SAASV,mBAA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,aAAaC;YACnB9C,UAAUC,QAAQ4C,aAAa;gBAACE,WAAW;YAAI;YAC/CtC,kBAAkBoC,YAAY;gBAAC,GAAGX,MAAM;gBAAE,CAACoB,IAAI,EAAEtB;YAAK,GAAG;gBAACkB,QAAQ;YAAI;YACtE,IAAII,QAAQ,aAAa5C;QAC3B;QAEA,+EAA+E;QAC/E8C,QAAOF,GAAW;YAChB,MAAMpB,SAASC;YACf,IAAI,CAAEmB,CAAAA,OAAOpB,MAAK,GAAI;YACtB,MAAM,EAAC,CAACoB,IAAI,EAAEN,CAAC,EAAE,GAAGC,MAAK,GAAGf;YAC5BzB,kBAAkBqC,wBAAwBG,MAAM;gBAACC,QAAQ;YAAI;YAC7D,IAAII,QAAQ,aAAa5C;QAC3B;IACF;AACF;AAEA,SAASuB;IACP,IAAI3B,0BAA0B;QAC5B,MAAM,IAAIsC,MAAM;IAClB;AACF;AAEA;;;;;;;;CAQC,GACD,SAAST;IACP,IAAI;QACF,MAAMD,SAAS1B,iBAAiBsC;QAChC,IAAI,CAACZ,UAAU,OAAOA,WAAW,YAAYuB,MAAMC,OAAO,CAACxB,SAAS;YAClE,MAAM,IAAIU,MAAM;QAClB;QACA,OAAOV;IACT,EAAE,OAAOyB,KAAc;QACrBtD,MAAM,sCAAsCsD,eAAef,QAAQe,IAAIpB,OAAO,GAAG,GAAGoB,KAAK;QACzF,OAAO,CAAC;IACV;AACF;AAEA;;;;;;;CAOC,GACD,SAASb;IACP,OAAO1B,QAAQC,GAAG,CAACuC,sBAAsB,IAAIzD,SAASI,sBAAsB;AAC9E"}
@@ -21,6 +21,11 @@
21
21
  * @public
22
22
  */
23
23
  export declare interface CliExecutionContext {
24
+ /**
25
+ * Sanity deployment environment to use for this invocation.
26
+ * Overrides `SANITY_INTERNAL_ENV`.
27
+ */
28
+ sanityEnv?: SanityEnvironment;
24
29
  /**
25
30
  * Sink for output the command would otherwise write to `process.stderr`.
26
31
  * Called once per line, without a trailing newline.
@@ -60,4 +65,11 @@ export declare function runWithCliExecutionContext<T>(
60
65
  fn: () => T,
61
66
  ): T;
62
67
 
68
+ /**
69
+ * Sanity deployment environment used by a programmatic CLI invocation.
70
+ *
71
+ * @public
72
+ */
73
+ export declare type SanityEnvironment = "production" | "staging";
74
+
63
75
  export {};
@@ -1 +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"}
1
+ {"version":3,"sources":["../src/executionContext.ts"],"sourcesContent":["import {AsyncLocalStorage} from 'node:async_hooks'\n\n/**\n * Sanity deployment environment used by a programmatic CLI invocation.\n *\n * @public\n */\nexport type SanityEnvironment = 'production' | 'staging'\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 * Sanity deployment environment to use for this invocation.\n * Overrides `SANITY_INTERNAL_ENV`.\n */\n sanityEnv?: SanityEnvironment\n\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;AAyDlD,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"}
@@ -1,4 +1,5 @@
1
1
  import { ux } from '@oclif/core'; // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.
2
+ import { getCliExecutionContext } from '../executionContext.js';
2
3
  import { noopLogger } from './noopTelemetry.js';
3
4
  /**
4
5
  * @public
@@ -12,6 +13,9 @@ function getState() {
12
13
  * @public
13
14
  */ // TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton
14
15
  export function getCliTelemetry() {
16
+ // Programmatic invocations must neither consume nor replace telemetry state
17
+ // owned by the embedding host.
18
+ if (getCliExecutionContext()) return noopLogger;
15
19
  const state = getState();
16
20
  // This should never happen, but if it does, we return a noop logger to avoid errors.
17
21
  if (!state) {
@@ -35,6 +39,7 @@ export function getCliTelemetry() {
35
39
  * for real command errors (not user aborts).
36
40
  * @internal
37
41
  */ export function reportCliTraceError(error) {
42
+ if (getCliExecutionContext()) return;
38
43
  getState()?.reportTraceError?.(error);
39
44
  }
40
45
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core' // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.\n\nimport {noopLogger} from './noopTelemetry.js'\nimport {type CLITelemetryStore} from './types.js'\n\n/**\n * @public\n * Symbol used to store CLI telemetry state on globalThis.\n * Use the accessor functions instead of accessing this directly.\n */\nexport const CLI_TELEMETRY_SYMBOL = Symbol.for('sanity.cli.telemetry')\n\ntype TraceErrorReporter = (error: Error) => void\n\ninterface CliTelemetryState {\n logger: CLITelemetryStore\n\n reportTraceError?: TraceErrorReporter\n}\n\ntype GlobalWithTelemetry = typeof globalThis & {\n [CLI_TELEMETRY_SYMBOL]?: CliTelemetryState\n}\n\nfunction getState(): CliTelemetryState | undefined {\n return (globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL]\n}\n\n/**\n * @public\n */\n// TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton\nexport function getCliTelemetry(): CLITelemetryStore {\n const state = getState()\n // This should never happen, but if it does, we return a noop logger to avoid errors.\n if (!state) {\n ux.warn('CLI telemetry not initialized, returning noop logger')\n return noopLogger\n }\n\n return state.logger\n}\n\n/**\n * Sets the global CLI telemetry state.\n * @internal\n */\nexport function setCliTelemetry(\n telemetry: CLITelemetryStore,\n options?: {reportTraceError?: TraceErrorReporter},\n): void {\n ;(globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL] = {\n logger: telemetry,\n reportTraceError: options?.reportTraceError,\n }\n}\n\n/**\n * Reports an error to the CLI command trace. Called from SanityCommand.catch()\n * for real command errors (not user aborts).\n * @internal\n */\nexport function reportCliTraceError(error: Error): void {\n getState()?.reportTraceError?.(error)\n}\n\n/**\n * Clears the global CLI telemetry store.\n * @internal\n */\nexport function clearCliTelemetry(): void {\n const global = globalThis as GlobalWithTelemetry\n delete global[CLI_TELEMETRY_SYMBOL]\n}\n"],"names":["ux","noopLogger","CLI_TELEMETRY_SYMBOL","Symbol","for","getState","globalThis","getCliTelemetry","state","warn","logger","setCliTelemetry","telemetry","options","reportTraceError","reportCliTraceError","error","clearCliTelemetry","global"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa,CAAC,sGAAsG;AAErI,SAAQC,UAAU,QAAO,qBAAoB;AAG7C;;;;CAIC,GACD,OAAO,MAAMC,uBAAuBC,OAAOC,GAAG,CAAC,wBAAuB;AActE,SAASC;IACP,OAAO,AAACC,UAAkC,CAACJ,qBAAqB;AAClE;AAEA;;CAEC,GACD,2IAA2I;AAC3I,OAAO,SAASK;IACd,MAAMC,QAAQH;IACd,qFAAqF;IACrF,IAAI,CAACG,OAAO;QACVR,GAAGS,IAAI,CAAC;QACR,OAAOR;IACT;IAEA,OAAOO,MAAME,MAAM;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASC,gBACdC,SAA4B,EAC5BC,OAAiD;;IAE/CP,UAAkC,CAACJ,qBAAqB,GAAG;QAC3DQ,QAAQE;QACRE,kBAAkBD,SAASC;IAC7B;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,KAAY;IAC9CX,YAAYS,mBAAmBE;AACjC;AAEA;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,SAASZ;IACf,OAAOY,MAAM,CAAChB,qBAAqB;AACrC"}
1
+ {"version":3,"sources":["../../src/telemetry/getCliTelemetry.ts"],"sourcesContent":["import {ux} from '@oclif/core' // TODO: should telemetry helpers be importing oclif? cli-build imports this... we should remove this.\n\nimport {getCliExecutionContext} from '../executionContext.js'\nimport {noopLogger} from './noopTelemetry.js'\nimport {type CLITelemetryStore} from './types.js'\n\n/**\n * @public\n * Symbol used to store CLI telemetry state on globalThis.\n * Use the accessor functions instead of accessing this directly.\n */\nexport const CLI_TELEMETRY_SYMBOL = Symbol.for('sanity.cli.telemetry')\n\ntype TraceErrorReporter = (error: Error) => void\n\ninterface CliTelemetryState {\n logger: CLITelemetryStore\n\n reportTraceError?: TraceErrorReporter\n}\n\ntype GlobalWithTelemetry = typeof globalThis & {\n [CLI_TELEMETRY_SYMBOL]?: CliTelemetryState\n}\n\nfunction getState(): CliTelemetryState | undefined {\n return (globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL]\n}\n\n/**\n * @public\n */\n// TODO: change this API so that it accepts a channel for passing warnings through, otherwise this is pumped through OCLIF UX via singleton\nexport function getCliTelemetry(): CLITelemetryStore {\n // Programmatic invocations must neither consume nor replace telemetry state\n // owned by the embedding host.\n if (getCliExecutionContext()) return noopLogger\n\n const state = getState()\n // This should never happen, but if it does, we return a noop logger to avoid errors.\n if (!state) {\n ux.warn('CLI telemetry not initialized, returning noop logger')\n return noopLogger\n }\n\n return state.logger\n}\n\n/**\n * Sets the global CLI telemetry state.\n * @internal\n */\nexport function setCliTelemetry(\n telemetry: CLITelemetryStore,\n options?: {reportTraceError?: TraceErrorReporter},\n): void {\n ;(globalThis as GlobalWithTelemetry)[CLI_TELEMETRY_SYMBOL] = {\n logger: telemetry,\n reportTraceError: options?.reportTraceError,\n }\n}\n\n/**\n * Reports an error to the CLI command trace. Called from SanityCommand.catch()\n * for real command errors (not user aborts).\n * @internal\n */\nexport function reportCliTraceError(error: Error): void {\n if (getCliExecutionContext()) return\n getState()?.reportTraceError?.(error)\n}\n\n/**\n * Clears the global CLI telemetry store.\n * @internal\n */\nexport function clearCliTelemetry(): void {\n const global = globalThis as GlobalWithTelemetry\n delete global[CLI_TELEMETRY_SYMBOL]\n}\n"],"names":["ux","getCliExecutionContext","noopLogger","CLI_TELEMETRY_SYMBOL","Symbol","for","getState","globalThis","getCliTelemetry","state","warn","logger","setCliTelemetry","telemetry","options","reportTraceError","reportCliTraceError","error","clearCliTelemetry","global"],"mappings":"AAAA,SAAQA,EAAE,QAAO,cAAa,CAAC,sGAAsG;AAErI,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,UAAU,QAAO,qBAAoB;AAG7C;;;;CAIC,GACD,OAAO,MAAMC,uBAAuBC,OAAOC,GAAG,CAAC,wBAAuB;AActE,SAASC;IACP,OAAO,AAACC,UAAkC,CAACJ,qBAAqB;AAClE;AAEA;;CAEC,GACD,2IAA2I;AAC3I,OAAO,SAASK;IACd,4EAA4E;IAC5E,+BAA+B;IAC/B,IAAIP,0BAA0B,OAAOC;IAErC,MAAMO,QAAQH;IACd,qFAAqF;IACrF,IAAI,CAACG,OAAO;QACVT,GAAGU,IAAI,CAAC;QACR,OAAOR;IACT;IAEA,OAAOO,MAAME,MAAM;AACrB;AAEA;;;CAGC,GACD,OAAO,SAASC,gBACdC,SAA4B,EAC5BC,OAAiD;;IAE/CP,UAAkC,CAACJ,qBAAqB,GAAG;QAC3DQ,QAAQE;QACRE,kBAAkBD,SAASC;IAC7B;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,KAAY;IAC9C,IAAIhB,0BAA0B;IAC9BK,YAAYS,mBAAmBE;AACjC;AAEA;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,SAASZ;IACf,OAAOY,MAAM,CAAChB,qBAAqB;AACrC"}
@@ -1,9 +1,10 @@
1
1
  // Pure in-memory implementation. Widely exported.
2
+ import { isStaging } from './isStaging.js';
2
3
  /**
3
4
  * @internal
4
5
  * @returns The Sanity URL for the given path, using the correct domain based on the environment
5
6
  */ export function getSanityUrl(path = '/') {
6
- const domain = process.env.SANITY_INTERNAL_ENV === 'staging' ? 'https://www.sanity.work' : 'https://www.sanity.io';
7
+ const domain = isStaging() ? 'https://www.sanity.work' : 'https://www.sanity.io';
7
8
  return `${domain}${path.startsWith('/') ? path : `/${path}`}`;
8
9
  }
9
10
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/getSanityUrl.ts"],"sourcesContent":["// Pure in-memory implementation. Widely exported.\n/**\n * @internal\n * @returns The Sanity URL for the given path, using the correct domain based on the environment\n */\nexport function getSanityUrl(path = '/') {\n const domain =\n process.env.SANITY_INTERNAL_ENV === 'staging'\n ? 'https://www.sanity.work'\n : 'https://www.sanity.io'\n return `${domain}${path.startsWith('/') ? path : `/${path}`}`\n}\n"],"names":["getSanityUrl","path","domain","process","env","SANITY_INTERNAL_ENV","startsWith"],"mappings":"AAAA,kDAAkD;AAClD;;;CAGC,GACD,OAAO,SAASA,aAAaC,OAAO,GAAG;IACrC,MAAMC,SACJC,QAAQC,GAAG,CAACC,mBAAmB,KAAK,YAChC,4BACA;IACN,OAAO,GAAGH,SAASD,KAAKK,UAAU,CAAC,OAAOL,OAAO,CAAC,CAAC,EAAEA,MAAM,EAAE;AAC/D"}
1
+ {"version":3,"sources":["../../src/util/getSanityUrl.ts"],"sourcesContent":["// Pure in-memory implementation. Widely exported.\nimport {isStaging} from './isStaging.js'\n\n/**\n * @internal\n * @returns The Sanity URL for the given path, using the correct domain based on the environment\n */\nexport function getSanityUrl(path = '/') {\n const domain = isStaging() ? 'https://www.sanity.work' : 'https://www.sanity.io'\n return `${domain}${path.startsWith('/') ? path : `/${path}`}`\n}\n"],"names":["isStaging","getSanityUrl","path","domain","startsWith"],"mappings":"AAAA,kDAAkD;AAClD,SAAQA,SAAS,QAAO,iBAAgB;AAExC;;;CAGC,GACD,OAAO,SAASC,aAAaC,OAAO,GAAG;IACrC,MAAMC,SAASH,cAAc,4BAA4B;IACzD,OAAO,GAAGG,SAASD,KAAKE,UAAU,CAAC,OAAOF,OAAO,CAAC,CAAC,EAAEA,MAAM,EAAE;AAC/D"}
@@ -1,9 +1,12 @@
1
+ import { getCliExecutionContext } from '../executionContext.js';
1
2
  /**
2
3
  * Checks if the environment is staging.
3
4
  *
4
5
  * @returns True if the environment is staging, false otherwise
5
6
  * @internal
6
7
  */ export function isStaging() {
8
+ const context = getCliExecutionContext();
9
+ if (context) return context.sanityEnv === 'staging';
7
10
  return process.env.SANITY_INTERNAL_ENV === 'staging';
8
11
  }
9
12
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/isStaging.ts"],"sourcesContent":["/**\n * Checks if the environment is staging.\n *\n * @returns True if the environment is staging, false otherwise\n * @internal\n */\nexport function isStaging(): boolean {\n return process.env.SANITY_INTERNAL_ENV === 'staging'\n}\n"],"names":["isStaging","process","env","SANITY_INTERNAL_ENV"],"mappings":"AAAA;;;;;CAKC,GACD,OAAO,SAASA;IACd,OAAOC,QAAQC,GAAG,CAACC,mBAAmB,KAAK;AAC7C"}
1
+ {"version":3,"sources":["../../src/util/isStaging.ts"],"sourcesContent":["import {getCliExecutionContext} from '../executionContext.js'\n\n/**\n * Checks if the environment is staging.\n *\n * @returns True if the environment is staging, false otherwise\n * @internal\n */\nexport function isStaging(): boolean {\n const context = getCliExecutionContext()\n\n if (context) return context.sanityEnv === 'staging'\n\n return process.env.SANITY_INTERNAL_ENV === 'staging'\n}\n"],"names":["getCliExecutionContext","isStaging","context","sanityEnv","process","env","SANITY_INTERNAL_ENV"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,yBAAwB;AAE7D;;;;;CAKC,GACD,OAAO,SAASC;IACd,MAAMC,UAAUF;IAEhB,IAAIE,SAAS,OAAOA,QAAQC,SAAS,KAAK;IAE1C,OAAOC,QAAQC,GAAG,CAACC,mBAAmB,KAAK;AAC7C"}
@@ -1,3 +1,30 @@
1
- export { default as spinner, oraPromise as spinnerPromise } from 'ora';
1
+ import ora, { oraPromise } from 'ora';
2
+ import { getCliExecutionContext } from '../executionContext.js';
3
+ function silentSpinner(options) {
4
+ const instance = {
5
+ clear: ()=>instance,
6
+ fail: ()=>instance,
7
+ frame: ()=>'',
8
+ info: ()=>instance,
9
+ isSpinning: false,
10
+ prefixText: typeof options === 'object' ? options.prefixText ?? '' : '',
11
+ render: ()=>instance,
12
+ start: ()=>instance,
13
+ stop: ()=>instance,
14
+ stopAndPersist: ()=>instance,
15
+ succeed: ()=>instance,
16
+ suffixText: typeof options === 'object' ? options.suffixText ?? '' : '',
17
+ text: typeof options === 'string' ? options : options?.text ?? '',
18
+ warn: ()=>instance
19
+ };
20
+ return instance;
21
+ }
22
+ export function spinner(options) {
23
+ return getCliExecutionContext() ? silentSpinner(options) : ora(options);
24
+ }
25
+ export function spinnerPromise(action, options) {
26
+ if (!getCliExecutionContext()) return oraPromise(action, options);
27
+ return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action);
28
+ }
2
29
 
3
30
  //# sourceMappingURL=spinner.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["export {\n default as spinner,\n type Spinner,\n type Ora as SpinnerInstance,\n type Options as SpinnerOptions,\n oraPromise as spinnerPromise,\n type PromiseOptions as SpinnerPromiseOptions,\n} from 'ora'\n"],"names":["default","spinner","oraPromise","spinnerPromise"],"mappings":"AAAA,SACEA,WAAWC,OAAO,EAIlBC,cAAcC,cAAc,QAEvB,MAAK"}
1
+ {"version":3,"sources":["../../src/ux/spinner.ts"],"sourcesContent":["import ora, {\n type Options,\n type Ora,\n oraPromise,\n type Spinner as OraSpinner,\n type PromiseOptions,\n} from 'ora'\n\nimport {getCliExecutionContext} from '../executionContext.js'\n\nfunction silentSpinner(options?: Options | string): Ora {\n const instance = {\n clear: () => instance,\n fail: () => instance,\n frame: () => '',\n info: () => instance,\n isSpinning: false,\n prefixText: typeof options === 'object' ? (options.prefixText ?? '') : '',\n render: () => instance,\n start: () => instance,\n stop: () => instance,\n stopAndPersist: () => instance,\n succeed: () => instance,\n suffixText: typeof options === 'object' ? (options.suffixText ?? '') : '',\n text: typeof options === 'string' ? options : (options?.text ?? ''),\n warn: () => instance,\n }\n return instance as unknown as Ora\n}\n\nexport function spinner(options?: Options | string): Ora {\n return getCliExecutionContext() ? silentSpinner(options) : ora(options)\n}\n\nexport function spinnerPromise<T>(\n action: ((instance: Ora) => PromiseLike<T>) | PromiseLike<T>,\n options?: PromiseOptions<T> | string,\n): Promise<T> {\n if (!getCliExecutionContext()) return oraPromise(action, options)\n return Promise.resolve(typeof action === 'function' ? action(silentSpinner(options)) : action)\n}\n\nexport type Spinner = OraSpinner\nexport type SpinnerInstance = Ora\nexport type SpinnerOptions = Options\nexport type SpinnerPromiseOptions<T> = PromiseOptions<T>\n"],"names":["ora","oraPromise","getCliExecutionContext","silentSpinner","options","instance","clear","fail","frame","info","isSpinning","prefixText","render","start","stop","stopAndPersist","succeed","suffixText","text","warn","spinner","spinnerPromise","action","Promise","resolve"],"mappings":"AAAA,OAAOA,OAGLC,UAAU,QAGL,MAAK;AAEZ,SAAQC,sBAAsB,QAAO,yBAAwB;AAE7D,SAASC,cAAcC,OAA0B;IAC/C,MAAMC,WAAW;QACfC,OAAO,IAAMD;QACbE,MAAM,IAAMF;QACZG,OAAO,IAAM;QACbC,MAAM,IAAMJ;QACZK,YAAY;QACZC,YAAY,OAAOP,YAAY,WAAYA,QAAQO,UAAU,IAAI,KAAM;QACvEC,QAAQ,IAAMP;QACdQ,OAAO,IAAMR;QACbS,MAAM,IAAMT;QACZU,gBAAgB,IAAMV;QACtBW,SAAS,IAAMX;QACfY,YAAY,OAAOb,YAAY,WAAYA,QAAQa,UAAU,IAAI,KAAM;QACvEC,MAAM,OAAOd,YAAY,WAAWA,UAAWA,SAASc,QAAQ;QAChEC,MAAM,IAAMd;IACd;IACA,OAAOA;AACT;AAEA,OAAO,SAASe,QAAQhB,OAA0B;IAChD,OAAOF,2BAA2BC,cAAcC,WAAWJ,IAAII;AACjE;AAEA,OAAO,SAASiB,eACdC,MAA4D,EAC5DlB,OAAoC;IAEpC,IAAI,CAACF,0BAA0B,OAAOD,WAAWqB,QAAQlB;IACzD,OAAOmB,QAAQC,OAAO,CAAC,OAAOF,WAAW,aAAaA,OAAOnB,cAAcC,YAAYkB;AACzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "2.6.0",
3
+ "version": "2.7.1",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -109,7 +109,7 @@
109
109
  "dependencies": {
110
110
  "@inquirer/prompts": "^8.5.2",
111
111
  "@oclif/core": "^4.11.14",
112
- "@sanity/client": "^7.23.2",
112
+ "@sanity/client": "^7.25.0",
113
113
  "boxen": "^8.0.1",
114
114
  "debug": "^4.4.3",
115
115
  "empathic": "^2.0.1",
@@ -129,7 +129,7 @@
129
129
  },
130
130
  "devDependencies": {
131
131
  "@eslint/compat": "^2.1.0",
132
- "@sanity/pkg-utils": "^11.0.9",
132
+ "@sanity/pkg-utils": "^11.0.17",
133
133
  "@sanity/telemetry": "^1.1.0",
134
134
  "@swc/cli": "^0.8.1",
135
135
  "@swc/core": "^1.15.43",
@@ -139,7 +139,7 @@
139
139
  "babel-plugin-react-compiler": "^1.0.0",
140
140
  "eslint": "^10.7.0",
141
141
  "publint": "^0.3.21",
142
- "sanity": "^6.5.0",
142
+ "sanity": "^6.7.0",
143
143
  "typescript": "^6.0.3",
144
144
  "vitest": "^4.1.10",
145
145
  "@repo/package.config": "0.0.1",