@sanity/cli-core 3.12.0 → 3.14.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.
@@ -85,8 +85,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
85
85
  * not interactive), it falls through to the standard error with suggestions.
86
86
  *
87
87
  * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated
88
- * flag (e.g. `--project`) that should be checked after `--project-id` but before
89
- * the CLI config.
88
+ * flag that should be checked after `--project` but before the CLI config.
90
89
  *
91
90
  * @returns The project ID.
92
91
  */
@@ -173,7 +172,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
173
172
  * Get the CLI config, returning an empty config if no project root is found.
174
173
  *
175
174
  * Use this instead of `getCliConfig()` in commands that can operate without a
176
- * project directory (e.g. when `--project-id` and `--dataset` flags are provided).
175
+ * project directory (e.g. when `--project` and `--dataset` flags are provided).
177
176
  *
178
177
  * @returns The CLI config, or an empty config object if no project root is found.
179
178
  */
@@ -183,6 +182,7 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
183
182
  * is active, otherwise through oclif's standard warning printer.
184
183
  */
185
184
  warn(input: Error | string): Error | string;
185
+ protected warnIfFlagDeprecated(flags: Record<string, unknown>): void;
186
186
  }
187
187
  export { SanityCommand, SanityCommandInterface };
188
188
  //# sourceMappingURL=SanityCommand.d.ts.map
@@ -119,18 +119,17 @@ export class SanityCommand extends Command {
119
119
  * not interactive), it falls through to the standard error with suggestions.
120
120
  *
121
121
  * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated
122
- * flag (e.g. `--project`) that should be checked after `--project-id` but before
123
- * the CLI config.
122
+ * flag that should be checked after `--project` but before the CLI config.
124
123
  *
125
124
  * @returns The project ID.
126
125
  */ async getProjectId(options) {
127
- const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags;
128
- // Check --project-id flag first
126
+ const hasProjectFlag = this.ctor.flags != null && 'project' in this.ctor.flags;
127
+ // Check --project flag first
129
128
  if (hasProjectFlag) {
130
- const flagProjectId = 'project-id' in this.flags && typeof this.flags['project-id'] === 'string' ? this.flags['project-id'] : undefined;
129
+ const flagProjectId = 'project' in this.flags && typeof this.flags.project === 'string' ? this.flags.project : undefined;
131
130
  if (flagProjectId) return flagProjectId;
132
131
  }
133
- // Check deprecated flag (e.g. --project) before CLI config
132
+ // Check deprecated flag before CLI config
134
133
  if (options?.deprecatedFlagName) {
135
134
  const deprecatedValue = options.deprecatedFlagName in this.flags && typeof this.flags[options.deprecatedFlagName] === 'string' ? this.flags[options.deprecatedFlagName] : undefined;
136
135
  if (deprecatedValue) return deprecatedValue;
@@ -155,7 +154,7 @@ export class SanityCommand extends Command {
155
154
  cause: err,
156
155
  suggestions: [
157
156
  ...hasProjectFlag ? [
158
- 'Providing a project ID: --project-id <project-id>'
157
+ 'Providing a project ID: --project <project-id>'
159
158
  ] : [],
160
159
  'Running this command from within a Sanity project directory',
161
160
  'Running in an interactive terminal to get a project selection prompt'
@@ -166,7 +165,7 @@ export class SanityCommand extends Command {
166
165
  throw new ProjectRootNotFoundError('Unable to determine project ID', {
167
166
  suggestions: [
168
167
  ...hasProjectFlag ? [
169
- 'Providing a project ID: --project-id <project-id>'
168
+ 'Providing a project ID: --project <project-id>'
170
169
  ] : [],
171
170
  'Running this command from within a Sanity project directory'
172
171
  ]
@@ -333,7 +332,7 @@ export class SanityCommand extends Command {
333
332
  * Get the CLI config, returning an empty config if no project root is found.
334
333
  *
335
334
  * Use this instead of `getCliConfig()` in commands that can operate without a
336
- * project directory (e.g. when `--project-id` and `--dataset` flags are provided).
335
+ * project directory (e.g. when `--project` and `--dataset` flags are provided).
337
336
  *
338
337
  * @returns The CLI config, or an empty config object if no project root is found.
339
338
  */ async tryGetCliConfig() {
@@ -355,6 +354,20 @@ export class SanityCommand extends Command {
355
354
  }
356
355
  return input;
357
356
  }
357
+ warnIfFlagDeprecated(flags) {
358
+ super.warnIfFlagDeprecated(flags);
359
+ // oclif only warns for aliases passed as separate tokens, missing --alias=value.
360
+ const flagArgs = this.argv.slice(0, this.argv.includes('--') ? this.argv.indexOf('--') : undefined);
361
+ for (const name of Object.keys(flags)){
362
+ const flag = this.ctor.flags?.[name];
363
+ if (!flag?.deprecateAliases) continue;
364
+ for (const alias of flag.aliases ?? []){
365
+ if (flagArgs.some((arg)=>arg.startsWith(`--${alias}=`))) {
366
+ this.warn(`The --${alias} flag is deprecated. Use --${name} instead.`);
367
+ }
368
+ }
369
+ }
370
+ }
358
371
  }
359
372
 
360
373
  //# sourceMappingURL=SanityCommand.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces, ux} from '@oclif/core'\nimport {CLIError, ExitError} from '@oclif/core/errors'\nimport {type CommandError, type Input, type ParserOutput} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {resolveUnattendedFlagRequirements} from './_exports/flags.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 {enrichAuthError} from './errors/enrichAuthError.js'\nimport {JsonOutputError} from './errors/JsonOutputError.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'\nimport {isUnattendedInvocation, isUnattended as resolveIsUnattended} from './util/isUnattended.js'\nimport {hasJsonFlagInArgv, toRelayableErrorJson} from './util/jsonInvocation.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\ntype ParserValues = Record<string, unknown>\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 logDiagnostic: this.logDiagnostic.bind(this),\n logJson: this.logJson.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 * 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 const isUserAbort = err.name === 'ExitPromptError' || err.message === 'SIGINT'\n if (isUserAbort) {\n if (!this.jsonEnabled()) {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n err = new CLIError('Aborted by user', {exit: exitCodes.SIGINT})\n }\n\n if (err instanceof ExitError) {\n if (err.oclif.exit !== exitCodes.SUCCESS) reportCliTraceError(err)\n if (getCliExecutionContext() || !this.jsonEnabled()) throw err\n process.exitCode = err.oclif.exit\n return\n }\n\n // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\n\n // In other cases, we _do_ want to report the error\n if (!isUserAbort) 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 }\n throw err\n }\n\n if (this.jsonEnabled()) {\n process.exitCode =\n err instanceof CLIError ? err.oclif.exit : (err.exitCode ?? exitCodes.RUNTIME_ERROR)\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 resolveIsUnattended({\n isInteractive: this.resolveIsInteractive(),\n json: this.flags.json,\n yes: this.flags.yes,\n })\n }\n\n /**\n * Whether this run should emit JSON.\n *\n * oclif's own check also treats `SANITY_CONTENT_TYPE=json` as a request for\n * JSON. That reads the host process's environment, so it is consulted only\n * for a real command line: a programmatic invocation must decide from its own\n * arguments, never from whatever the embedding process happens to export.\n */\n public override jsonEnabled(): boolean {\n if (!this.ctor.enableJsonFlag) return false\n if (this.flags) return Boolean(this.flags.json)\n\n if (!getCliExecutionContext() && super.jsonEnabled()) return true\n return hasJsonFlagInArgv(this.argv, {...this.ctor.baseFlags, ...this.ctor.flags})\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 * Write a diagnostic that stays visible in JSON mode.\n *\n * `log`, `warn` and `logToStderr` are all suppressed once `--json` is on, so\n * a command that skipped part of its work would report the remainder as a\n * complete result. stderr carries it instead, where it cannot corrupt the\n * payload: JSON mode is reachable only from a real command line, since\n * programmatic invocations drop the flag.\n */\n public logDiagnostic(message: string): void {\n const context = getCliExecutionContext()\n if (context?.stderr) {\n context.stderr(message)\n return\n }\n ux.stderr(message)\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 protected override async parse<\n F extends ParserValues,\n B extends ParserValues,\n A extends ParserValues,\n >(options?: Input<F, B, A>, argv: string[] = this.argv): Promise<ParserOutput<F, B, A>> {\n let resolvedOptions = options\n const jsonEnabled = this.jsonEnabled()\n\n if (options?.flags) {\n const resolvedFlags = resolveUnattendedFlagRequirements(\n options.flags,\n jsonEnabled || isUnattendedInvocation({argv, isInteractive: this.resolveIsInteractive()}),\n )\n if (resolvedFlags !== options.flags) {\n resolvedOptions = {...options, flags: resolvedFlags as Interfaces.FlagInput<F>}\n }\n }\n\n const parsed = await super.parse(resolvedOptions, argv)\n const jsonFlag = Boolean(parsed.flags.json) || jsonEnabled\n\n parsed.flags = {...parsed.flags, json: jsonFlag}\n return parsed\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 * A command-specific report wins; otherwise oclif's envelope, trimmed to a\n * bounded set of properties when a programmatic caller will relay it. See\n * {@link toRelayableErrorJson} for why the untrimmed form is unsafe there.\n */\n public override toErrorJson(err: unknown): unknown {\n if (err instanceof JsonOutputError) return err.payload\n if (getCliExecutionContext()) return toRelayableErrorJson(err)\n return super.toErrorJson(err)\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","ux","CLIError","ExitError","subdebug","resolveUnattendedFlagRequirements","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","JsonOutputError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","isUnattendedInvocation","isUnattended","resolveIsUnattended","hasJsonFlagInArgv","toRelayableErrorJson","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","logDiagnostic","logJson","warn","telemetry","catch","err","isUserAbort","name","message","jsonEnabled","logToStderr","exit","SIGINT","oclif","SUCCESS","process","exitCode","toErrorJson","RUNTIME_ERROR","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","cwd","init","parse","baseFlags","enableJsonFlag","strict","resolveIsInteractive","json","yes","Boolean","argv","context","stdout","stderr","JSON","stringify","resolvedOptions","resolvedFlags","parsed","jsonFlag","runInExecutionContext","Error","_run","payload","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,EAAcC,EAAE,QAAO,cAAa;AACnD,SAAQC,QAAQ,EAAEC,SAAS,QAAO,qBAAoB;AAGtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,iCAAiC,QAAO,sBAAqB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,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;AACrD,SAAQC,sBAAsB,EAAEC,gBAAgBC,mBAAmB,QAAO,yBAAwB;AAClG,SAAQC,iBAAiB,EAAEC,oBAAoB,QAAO,2BAA0B;AAUhF,MAAMC,QAAQpB,SAAS;AAmBvB,OAAO,MAAeqB,sBACZzB;IAGE0B,KAAc;IACdC,MAAgB;IAE1B;;;;;;;GAOC,GACD,AAAUC,qBAAqB,CAACF,OAAiCpB,mBAAmBoB,MAAK;IAEzF;;;;;;;GAOC,GACD,AAA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AOS,qBAAqBgB;QAC1D,OAAO,KAAK,CAACY,YAAYZ;IAC3B;IAEA;;;;;;;GAOC,GACD,MAAgBwD,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACvF,YAAY;QAChC,EAAE,OAAO+B,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAe1B,wBAAuB,GAAI,MAAM0B;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAK4D,KAAqB,EAAkB;QAC1D,MAAMd,UAAUpE;QAChB,IAAI,CAACoE,SAASE,QAAQ,OAAO,KAAK,CAAChD,KAAK4D;QAExC,IAAI,CAAC,IAAI,CAACrD,WAAW,IAAI;YACvBuC,QAAQE,MAAM,CAAC,CAAC,SAAS,EAAEY,iBAAiBJ,QAAQI,MAAMtD,OAAO,GAAGsD,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
1
+ {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces, ux} from '@oclif/core'\nimport {CLIError, ExitError} from '@oclif/core/errors'\nimport {type CommandError, type Input, type ParserOutput} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {resolveUnattendedFlagRequirements} from './_exports/flags.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 {enrichAuthError} from './errors/enrichAuthError.js'\nimport {JsonOutputError} from './errors/JsonOutputError.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'\nimport {isUnattendedInvocation, isUnattended as resolveIsUnattended} from './util/isUnattended.js'\nimport {hasJsonFlagInArgv, toRelayableErrorJson} from './util/jsonInvocation.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\ntype ParserValues = Record<string, unknown>\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 logDiagnostic: this.logDiagnostic.bind(this),\n logJson: this.logJson.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 * 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 const isUserAbort = err.name === 'ExitPromptError' || err.message === 'SIGINT'\n if (isUserAbort) {\n if (!this.jsonEnabled()) {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n err = new CLIError('Aborted by user', {exit: exitCodes.SIGINT})\n }\n\n if (err instanceof ExitError) {\n if (err.oclif.exit !== exitCodes.SUCCESS) reportCliTraceError(err)\n if (getCliExecutionContext() || !this.jsonEnabled()) throw err\n process.exitCode = err.oclif.exit\n return\n }\n\n // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\n\n // In other cases, we _do_ want to report the error\n if (!isUserAbort) 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 }\n throw err\n }\n\n if (this.jsonEnabled()) {\n process.exitCode =\n err instanceof CLIError ? err.oclif.exit : (err.exitCode ?? exitCodes.RUNTIME_ERROR)\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 that should be checked after `--project` but before 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' in this.ctor.flags\n\n // Check --project flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project' in this.flags && typeof this.flags.project === 'string'\n ? this.flags.project\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag 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 <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 <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 resolveIsUnattended({\n isInteractive: this.resolveIsInteractive(),\n json: this.flags.json,\n yes: this.flags.yes,\n })\n }\n\n /**\n * Whether this run should emit JSON.\n *\n * oclif's own check also treats `SANITY_CONTENT_TYPE=json` as a request for\n * JSON. That reads the host process's environment, so it is consulted only\n * for a real command line: a programmatic invocation must decide from its own\n * arguments, never from whatever the embedding process happens to export.\n */\n public override jsonEnabled(): boolean {\n if (!this.ctor.enableJsonFlag) return false\n if (this.flags) return Boolean(this.flags.json)\n\n if (!getCliExecutionContext() && super.jsonEnabled()) return true\n return hasJsonFlagInArgv(this.argv, {...this.ctor.baseFlags, ...this.ctor.flags})\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 * Write a diagnostic that stays visible in JSON mode.\n *\n * `log`, `warn` and `logToStderr` are all suppressed once `--json` is on, so\n * a command that skipped part of its work would report the remainder as a\n * complete result. stderr carries it instead, where it cannot corrupt the\n * payload: JSON mode is reachable only from a real command line, since\n * programmatic invocations drop the flag.\n */\n public logDiagnostic(message: string): void {\n const context = getCliExecutionContext()\n if (context?.stderr) {\n context.stderr(message)\n return\n }\n ux.stderr(message)\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 protected override async parse<\n F extends ParserValues,\n B extends ParserValues,\n A extends ParserValues,\n >(options?: Input<F, B, A>, argv: string[] = this.argv): Promise<ParserOutput<F, B, A>> {\n let resolvedOptions = options\n const jsonEnabled = this.jsonEnabled()\n\n if (options?.flags) {\n const resolvedFlags = resolveUnattendedFlagRequirements(\n options.flags,\n jsonEnabled || isUnattendedInvocation({argv, isInteractive: this.resolveIsInteractive()}),\n )\n if (resolvedFlags !== options.flags) {\n resolvedOptions = {...options, flags: resolvedFlags as Interfaces.FlagInput<F>}\n }\n }\n\n const parsed = await super.parse(resolvedOptions, argv)\n const jsonFlag = Boolean(parsed.flags.json) || jsonEnabled\n\n parsed.flags = {...parsed.flags, json: jsonFlag}\n return parsed\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 * A command-specific report wins; otherwise oclif's envelope, trimmed to a\n * bounded set of properties when a programmatic caller will relay it. See\n * {@link toRelayableErrorJson} for why the untrimmed form is unsafe there.\n */\n public override toErrorJson(err: unknown): unknown {\n if (err instanceof JsonOutputError) return err.payload\n if (getCliExecutionContext()) return toRelayableErrorJson(err)\n return super.toErrorJson(err)\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` 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 protected override warnIfFlagDeprecated(flags: Record<string, unknown>): void {\n super.warnIfFlagDeprecated(flags)\n\n // oclif only warns for aliases passed as separate tokens, missing --alias=value.\n const flagArgs = this.argv.slice(\n 0,\n this.argv.includes('--') ? this.argv.indexOf('--') : undefined,\n )\n for (const name of Object.keys(flags)) {\n const flag = this.ctor.flags?.[name]\n if (!flag?.deprecateAliases) continue\n\n for (const alias of flag.aliases ?? []) {\n if (flagArgs.some((arg) => arg.startsWith(`--${alias}=`))) {\n this.warn(`The --${alias} flag is deprecated. Use --${name} instead.`)\n }\n }\n }\n }\n}\n"],"names":["format","styleText","Command","ux","CLIError","ExitError","subdebug","resolveUnattendedFlagRequirements","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","JsonOutputError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","isUnattendedInvocation","isUnattended","resolveIsUnattended","hasJsonFlagInArgv","toRelayableErrorJson","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","logDiagnostic","logJson","warn","telemetry","catch","err","isUserAbort","name","message","jsonEnabled","logToStderr","exit","SIGINT","oclif","SUCCESS","process","exitCode","toErrorJson","RUNTIME_ERROR","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","project","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","cwd","init","parse","baseFlags","enableJsonFlag","strict","resolveIsInteractive","json","yes","Boolean","argv","context","stdout","stderr","JSON","stringify","resolvedOptions","resolvedFlags","parsed","jsonFlag","runInExecutionContext","Error","_run","payload","tryGetCliConfig","input","warnIfFlagDeprecated","flagArgs","slice","includes","indexOf","Object","keys","flag","deprecateAliases","alias","aliases","some","arg","startsWith"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,EAAcC,EAAE,QAAO,cAAa;AACnD,SAAQC,QAAQ,EAAEC,SAAS,QAAO,qBAAoB;AAGtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,iCAAiC,QAAO,sBAAqB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,eAAe,QAAO,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AAI,CAACjB,IAAI,CAACkB,KAAK,CAC9B,GACA,IAAI,CAAClB,IAAI,CAACmB,QAAQ,CAAC,QAAQ,IAAI,CAACnB,IAAI,CAACoB,OAAO,CAAC,QAAQxC;QAEvD,KAAK,MAAMrB,QAAQ8D,OAAOC,IAAI,CAAC7E,OAAQ;YACrC,MAAM8E,OAAO,IAAI,CAAC9C,IAAI,CAAChC,KAAK,EAAE,CAACc,KAAK;YACpC,IAAI,CAACgE,MAAMC,kBAAkB;YAE7B,KAAK,MAAMC,SAASF,KAAKG,OAAO,IAAI,EAAE,CAAE;gBACtC,IAAIT,SAASU,IAAI,CAAC,CAACC,MAAQA,IAAIC,UAAU,CAAC,CAAC,EAAE,EAAEJ,MAAM,CAAC,CAAC,IAAI;oBACzD,IAAI,CAACvE,IAAI,CAAC,CAAC,MAAM,EAAEuE,MAAM,2BAA2B,EAAElE,KAAK,SAAS,CAAC;gBACvE;YACF;QACF;IACF;AACF"}
@@ -1,6 +1,7 @@
1
1
  import { a as getSanityDataDir, i as getSanityConfigDir, n as getSanityUrl, r as getSanityEnvVar, t as getWorkspace } from "../getWorkspace-CU32E6Uo.js";
2
2
  import { a as isCi, i as isInteractive$1, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-BixYyg4K.js";
3
3
  declare function getCoreAppUrl(organizationId: string, appId: string): string;
4
+ declare function getSanityEnv(): string;
4
5
  /**
5
6
  * Checks if the given value is a record (javascript objectish)
6
7
  *
@@ -42,5 +43,5 @@ declare function hasJsonFlagInArgv(argv: string[], definitions: FlagDefinitions)
42
43
  declare function toRelayableErrorJson(err: unknown): {
43
44
  error: unknown;
44
45
  };
45
- export { doImport, getCoreAppUrl, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getWorkspace, hasJsonFlagInArgv, importModule, isCi, isInteractive$1 as isInteractive, isRecord, isStaging, isTrueish, isUnattended, isUnattendedInvocation, normalizePath, safeStructuredClone, toRelayableErrorJson };
46
+ export { doImport, getCoreAppUrl, getSanityConfigDir, getSanityDataDir, getSanityEnv, getSanityEnvVar, getSanityUrl, getWorkspace, hasJsonFlagInArgv, importModule, isCi, isInteractive$1 as isInteractive, isRecord, isStaging, isTrueish, isUnattended, isUnattendedInvocation, normalizePath, safeStructuredClone, toRelayableErrorJson };
46
47
  //# sourceMappingURL=util.d.ts.map
@@ -3,6 +3,7 @@
3
3
  export { doImport } from '../util/doImport.js';
4
4
  export { getCoreAppUrl } from '../util/getCoreAppUrl.js';
5
5
  export { getSanityConfigDir, getSanityDataDir } from '../util/getSanityConfigDir.js';
6
+ export { getSanityEnv } from '../util/getSanityEnv.js';
6
7
  export { getSanityEnvVar } from '../util/getSanityEnvVar.js';
7
8
  export { getSanityUrl } from '../util/getSanityUrl.js';
8
9
  export { getWorkspace } from '../util/getWorkspace.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {isUnattended, isUnattendedInvocation} from '../util/isUnattended.js'\nexport {hasJsonFlagInArgv, toRelayableErrorJson} from '../util/jsonInvocation.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","isUnattended","isUnattendedInvocation","hasJsonFlagInArgv","toRelayableErrorJson","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,0BAAyB;AAC5E,SAAQC,iBAAiB,EAAEC,oBAAoB,QAAO,4BAA2B;AACjF,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
1
+ {"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnv} from '../util/getSanityEnv.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {isUnattended, isUnattendedInvocation} from '../util/isUnattended.js'\nexport {hasJsonFlagInArgv, toRelayableErrorJson} from '../util/jsonInvocation.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnv","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","isUnattended","isUnattendedInvocation","hasJsonFlagInArgv","toRelayableErrorJson","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,0BAAyB;AAC5E,SAAQC,iBAAiB,EAAEC,oBAAoB,QAAO,4BAA2B;AACjF,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
package/dist/apiClient.js CHANGED
@@ -3,7 +3,7 @@ import { createNodeFetch } from 'get-it/node';
3
3
  import { getCliToken } from './config/cli/cliUserConfig.js';
4
4
  import { enrichAuthError } from './errors/enrichAuthError.js';
5
5
  import { getCliExecutionContext } from './executionContext.js';
6
- import { isStaging } from './util/isStaging.js';
6
+ import { getSanityEnv } from './util/getSanityEnv.js';
7
7
  const STAGING_API_HOST = 'https://api.sanity.work';
8
8
  const CLI_REQUEST_TAG_PREFIX = 'sanity.cli';
9
9
  // One default transport per proxy URL, mirroring the client's own
@@ -69,7 +69,7 @@ const authErrorHandler = async (request, next)=>{
69
69
  * @returns Promise that resolves to a configured Sanity API client.
70
70
  */ export async function getGlobalCliClient({ requestHandler, requireUser, token: providedToken, unauthenticated, ...config }) {
71
71
  const context = getCliExecutionContext();
72
- const apiHost = isStaging() ? STAGING_API_HOST : undefined;
72
+ const apiHost = getApiHost();
73
73
  // Use the provided token if set, otherwise fall back to the stored CLI token (unless unauthenticated)
74
74
  const token = providedToken || (unauthenticated ? undefined : await getCliToken());
75
75
  // If the token is not set and requireUser is true, throw an error
@@ -102,7 +102,7 @@ const authErrorHandler = async (request, next)=>{
102
102
  * @returns Promise that resolves to a configured Sanity API client.
103
103
  */ export async function getProjectCliClient({ requestHandler, requireUser, token: providedToken, ...config }) {
104
104
  const context = getCliExecutionContext();
105
- const apiHost = isStaging() ? STAGING_API_HOST : undefined;
105
+ const apiHost = getApiHost();
106
106
  // Use the provided token if it is set, otherwise get the token from the config file
107
107
  const token = providedToken || await getCliToken();
108
108
  // If the token is not set and requireUser is true, throw an error
@@ -126,5 +126,9 @@ const authErrorHandler = async (request, next)=>{
126
126
  requestHandler: withAuthErrorHints(requestHandler)
127
127
  });
128
128
  }
129
+ function getApiHost() {
130
+ const sanityEnv = getSanityEnv();
131
+ return sanityEnv === 'staging' ? STAGING_API_HOST : sanityEnv === 'production' ? undefined : sanityEnv;
132
+ }
129
133
 
130
134
  //# sourceMappingURL=apiClient.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apiClient.ts"],"sourcesContent":["import {\n type ClientConfig,\n createClient,\n type RequestHandler,\n type SanityClient,\n} from '@sanity/client'\nimport {type FetchFunction} from 'get-it'\nimport {createNodeFetch} from 'get-it/node'\n\nimport {getCliToken} from './config/cli/cliUserConfig.js'\nimport {enrichAuthError} from './errors/enrichAuthError.js'\nimport {type CliExecutionContext, getCliExecutionContext} from './executionContext.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// One default transport per proxy URL, mirroring the client's own\n// environment resolver.\nconst defaultBaseFetchCache = new Map<string, FetchFunction>()\n\nfunction defaultBaseFetch(proxyUrl?: string): FetchFunction {\n const key = proxyUrl ?? ''\n const cached = defaultBaseFetchCache.get(key)\n if (cached) return cached\n\n const base = createNodeFetch(proxyUrl ? {connections: 30, proxy: proxyUrl} : undefined)\n defaultBaseFetchCache.set(key, base)\n return base\n}\n\n/**\n * Build the transport resolver for clients created inside a CLI execution\n * context.\n *\n * Uses the context's own fetch when the embedding host supplies one,\n * otherwise the client's default Node transport (get-it's undici-backed,\n * proxy-aware fetch). Either way the transport strips the\n * `x-sanity-lineage` header the client's Node middleware adds from\n * `X_SANITY_LINEAGE` — that variable belongs to the embedding process, not\n * to this CLI invocation. Note that unlike the client v7 isolated requester,\n * the client's `sanity:client` debug logging cannot be detached per-client\n * in v8, so a host `DEBUG` setting still applies to it.\n */\nfunction isolatedFetchResolver(context: CliExecutionContext): (proxyUrl?: string) => FetchFunction {\n return (proxyUrl) => {\n const base = context.fetch ?? defaultBaseFetch(proxyUrl)\n return (url, init) => {\n const headers = new Headers(init?.headers)\n headers.delete('x-sanity-lineage')\n return base(url, {...init, headers})\n }\n }\n}\n\nconst authErrorHandler: RequestHandler = async (request, next) => {\n try {\n return await next(request)\n } catch (error) {\n throw enrichAuthError(error)\n }\n}\n\n/**\n * Add the CLI's authentication guidance inside any caller-provided request\n * handler. This lets the caller observe enriched client errors while\n * preserving its control over the request and response pipeline.\n */\nfunction withAuthErrorHints(requestHandler?: RequestHandler): RequestHandler {\n if (!requestHandler) return authErrorHandler\n\n return (request, next) =>\n requestHandler(request, (nextRequest) => authErrorHandler(nextRequest, next))\n}\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 requestHandler,\n requireUser,\n token: providedToken,\n unauthenticated,\n ...config\n}: GlobalCliClientOptions): Promise<SanityClient> {\n const context = getCliExecutionContext()\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 ...(context ? {resolveFetch: isolatedFetchResolver(context)} : {}),\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: false,\n ...config,\n requestHandler: withAuthErrorHints(requestHandler),\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 requestHandler,\n requireUser,\n token: providedToken,\n ...config\n}: ProjectCliClientOptions): Promise<SanityClient> {\n const context = getCliExecutionContext()\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 ...(context ? {resolveFetch: isolatedFetchResolver(context)} : {}),\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: true,\n ...config,\n requestHandler: withAuthErrorHints(requestHandler),\n })\n}\n"],"names":["createClient","createNodeFetch","getCliToken","enrichAuthError","getCliExecutionContext","isStaging","STAGING_API_HOST","CLI_REQUEST_TAG_PREFIX","defaultBaseFetchCache","Map","defaultBaseFetch","proxyUrl","key","cached","get","base","connections","proxy","undefined","set","isolatedFetchResolver","context","fetch","url","init","headers","Headers","delete","authErrorHandler","request","next","error","withAuthErrorHints","requestHandler","nextRequest","getGlobalCliClient","requireUser","token","providedToken","unauthenticated","config","apiHost","Error","ignoreBrowserTokenWarning","resolveFetch","requestTagPrefix","useCdn","useProjectHostname","getProjectCliClient"],"mappings":"AAAA,SAEEA,YAAY,QAGP,iBAAgB;AAEvB,SAAQC,eAAe,QAAO,cAAa;AAE3C,SAAQC,WAAW,QAAO,gCAA+B;AACzD,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,SAAkCC,sBAAsB,QAAO,wBAAuB;AACtF,SAAQC,SAAS,QAAO,sBAAqB;AAE7C,MAAMC,mBAAmB;AAEzB,MAAMC,yBAAyB;AAE/B,kEAAkE;AAClE,wBAAwB;AACxB,MAAMC,wBAAwB,IAAIC;AAElC,SAASC,iBAAiBC,QAAiB;IACzC,MAAMC,MAAMD,YAAY;IACxB,MAA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AC3B,GAAItB,UAAU;YAACuB,cAAcxB,sBAAsBC;QAAQ,IAAI,CAAC,CAAC;QACjEwB,kBAAkBtC;QAClB8B;QACAS,QAAQ;QACRC,oBAAoB;QACpB,GAAGP,MAAM;QACTP,gBAAgBD,mBAAmBC;IACrC;AACF;AA6BA;;;;;;;CAOC,GACD,OAAO,eAAee,oBAAoB,EACxCf,cAAc,EACdG,WAAW,EACXC,OAAOC,aAAa,EACpB,GAAGE,QACqB;IACxB,MAAMnB,UAAUjB;IAEhB,MAAMqC,UAAUpC,cAAcC,mBAAmBY;IAEjD,oFAAoF;IACpF,MAAMmB,QAAQC,iBAAkB,MAAMpC;IAEtC,kEAAkE;IAClE,IAAI,CAACmC,SAASD,aAAa;QACzB,MAAM,IAAIM,MAAM;IAClB;IAEA,OAAO1C,aAAa;QAClB,GAAIyC,UAAU;YAACA;QAAO,IAAI,CAAC,CAAC;QAC5B,8EAA8E;QAC9EE,2BAA2B;QAC3B,GAAItB,UAAU;YAACuB,cAAcxB,sBAAsBC;QAAQ,IAAI,CAAC,CAAC;QACjEwB,kBAAkBtC;QAClB8B;QACAS,QAAQ;QACRC,oBAAoB;QACpB,GAAGP,MAAM;QACTP,gBAAgBD,mBAAmBC;IACrC;AACF"}
1
+ {"version":3,"sources":["../src/apiClient.ts"],"sourcesContent":["import {\n type ClientConfig,\n createClient,\n type RequestHandler,\n type SanityClient,\n} from '@sanity/client'\nimport {type FetchFunction} from 'get-it'\nimport {createNodeFetch} from 'get-it/node'\n\nimport {getCliToken} from './config/cli/cliUserConfig.js'\nimport {enrichAuthError} from './errors/enrichAuthError.js'\nimport {type CliExecutionContext, getCliExecutionContext} from './executionContext.js'\nimport {getSanityEnv} from './util/getSanityEnv.js'\n\nconst STAGING_API_HOST = 'https://api.sanity.work'\n\nconst CLI_REQUEST_TAG_PREFIX = 'sanity.cli'\n\n// One default transport per proxy URL, mirroring the client's own\n// environment resolver.\nconst defaultBaseFetchCache = new Map<string, FetchFunction>()\n\nfunction defaultBaseFetch(proxyUrl?: string): FetchFunction {\n const key = proxyUrl ?? ''\n const cached = defaultBaseFetchCache.get(key)\n if (cached) return cached\n\n const base = createNodeFetch(proxyUrl ? {connections: 30, proxy: proxyUrl} : undefined)\n defaultBaseFetchCache.set(key, base)\n return base\n}\n\n/**\n * Build the transport resolver for clients created inside a CLI execution\n * context.\n *\n * Uses the context's own fetch when the embedding host supplies one,\n * otherwise the client's default Node transport (get-it's undici-backed,\n * proxy-aware fetch). Either way the transport strips the\n * `x-sanity-lineage` header the client's Node middleware adds from\n * `X_SANITY_LINEAGE` — that variable belongs to the embedding process, not\n * to this CLI invocation. Note that unlike the client v7 isolated requester,\n * the client's `sanity:client` debug logging cannot be detached per-client\n * in v8, so a host `DEBUG` setting still applies to it.\n */\nfunction isolatedFetchResolver(context: CliExecutionContext): (proxyUrl?: string) => FetchFunction {\n return (proxyUrl) => {\n const base = context.fetch ?? defaultBaseFetch(proxyUrl)\n return (url, init) => {\n const headers = new Headers(init?.headers)\n headers.delete('x-sanity-lineage')\n return base(url, {...init, headers})\n }\n }\n}\n\nconst authErrorHandler: RequestHandler = async (request, next) => {\n try {\n return await next(request)\n } catch (error) {\n throw enrichAuthError(error)\n }\n}\n\n/**\n * Add the CLI's authentication guidance inside any caller-provided request\n * handler. This lets the caller observe enriched client errors while\n * preserving its control over the request and response pipeline.\n */\nfunction withAuthErrorHints(requestHandler?: RequestHandler): RequestHandler {\n if (!requestHandler) return authErrorHandler\n\n return (request, next) =>\n requestHandler(request, (nextRequest) => authErrorHandler(nextRequest, next))\n}\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 requestHandler,\n requireUser,\n token: providedToken,\n unauthenticated,\n ...config\n}: GlobalCliClientOptions): Promise<SanityClient> {\n const context = getCliExecutionContext()\n\n const apiHost = getApiHost()\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 ...(context ? {resolveFetch: isolatedFetchResolver(context)} : {}),\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: false,\n ...config,\n requestHandler: withAuthErrorHints(requestHandler),\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 requestHandler,\n requireUser,\n token: providedToken,\n ...config\n}: ProjectCliClientOptions): Promise<SanityClient> {\n const context = getCliExecutionContext()\n\n const apiHost = getApiHost()\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 ...(context ? {resolveFetch: isolatedFetchResolver(context)} : {}),\n requestTagPrefix: CLI_REQUEST_TAG_PREFIX,\n token,\n useCdn: false,\n useProjectHostname: true,\n ...config,\n requestHandler: withAuthErrorHints(requestHandler),\n })\n}\n\nfunction getApiHost(): string | undefined {\n const sanityEnv = getSanityEnv()\n return sanityEnv === 'staging'\n ? STAGING_API_HOST\n : sanityEnv === 'production'\n ? undefined\n : sanityEnv\n}\n"],"names":["createClient","createNodeFetch","getCliToken","enrichAuthError","getCliExecutionContext","getSanityEnv","STAGING_API_HOST","CLI_REQUEST_TAG_PREFIX","defaultBaseFetchCache","Map","defaultBaseFetch","proxyUrl","key","cached","get","base","connections","proxy","undefined","set","isolatedFetchResolver","context","fetch","url","init","headers","Headers","delete","authErrorHandler","request","next","error","withAuthErrorHints","requestHandler","nextRequest","getGlobalCliClient","requireUser","token","providedToken","unauthenticated","config","apiHost","getApiHost","Error","ignoreBrowserTokenWarning","resolveFetch","requestTagPrefix","useCdn","useProjectHostname","getProjectCliClient","sanityEnv"],"mappings":"AAAA,SAEEA,YAAY,QAGP,iBAAgB;AAEvB,SAAQC,eAAe,QAAO,cAAa;AAE3C,SAAQC,WAAW,QAAO,gCAA+B;AACzD,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,SAAkCC,sBAAsB,QAAO,wBAAuB;AACtF,SAAQC,YAAY,QAAO,yBAAwB;AAEnD,MAAMC,mBAAmB;AAEzB,MAAMC,yBAAyB;AAE/B,kEAAkE;AAClE,wBAAwB;AACxB,MAAMC,wBAAwB,IAAIC;AAElC,SAASC,iBAAiBC,QAAiB;IACzC,MAAMC,MAAMD,YAAY;IACxB,MAAME,SAASL,sBAAsBM,GAAG,CAACF;IACzC,IAAIC,QAAQ,OAAOA;IAEnB,MAAME,OAAOd,gBAAgBU,WAAW;QAACK,aAAa;QAAIC,OAAON;IAAQ,IA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,gBAAgBD,mBAAmBC;IACrC;AACF;AA6BA;;;;;;;CAOC,GACD,OAAO,eAAegB,oBAAoB,EACxChB,cAAc,EACdG,WAAW,EACXC,OAAOC,aAAa,EACpB,GAAGE,QACqB;IACxB,MAAMnB,UAAUjB;IAEhB,MAAMqC,UAAUC;IAEhB,oFAAoF;IACpF,MAAML,QAAQC,iBAAkB,MAAMpC;IAEtC,kEAAkE;IAClE,IAAI,CAACmC,SAASD,aAAa;QACzB,MAAM,IAAIO,MAAM;IAClB;IAEA,OAAO3C,aAAa;QAClB,GAAIyC,UAAU;YAACA;QAAO,IAAI,CAAC,CAAC;QAC5B,8EAA8E;QAC9EG,2BAA2B;QAC3B,GAAIvB,UAAU;YAACwB,cAAczB,sBAAsBC;QAAQ,IAAI,CAAC,CAAC;QACjEyB,kBAAkBvC;QAClB8B;QACAU,QAAQ;QACRC,oBAAoB;QACpB,GAAGR,MAAM;QACTP,gBAAgBD,mBAAmBC;IACrC;AACF;AAEA,SAASS;IACP,MAAMQ,YAAY7C;IAClB,OAAO6C,cAAc,YACjB5C,mBACA4C,cAAc,eACZhC,YACAgC;AACR"}
@@ -19,7 +19,7 @@ import { recursivelyResolveProjectRoot } from './util/recursivelyResolveProjectR
19
19
  // project context from the host's filesystem: walking up from the host
20
20
  // process's cwd could pick up an unrelated Sanity project, and resolving the
21
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.
22
+ // Callers must provide explicit flags (e.g. `--project`) instead.
23
23
  if (getCliExecutionContext()) {
24
24
  throw new ProjectRootNotFoundError('Project root resolution from the filesystem is disabled for programmatic invocations');
25
25
  }
@@ -1 +1 @@
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
+ {"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`) 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,kEAAkE;IAClE,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"}
@@ -24,7 +24,7 @@ type SanityEnvironment = 'production' | 'staging';
24
24
  * - project root resolution from the filesystem is disabled: commands never
25
25
  * read (or execute) `sanity.config.ts`/`sanity.cli.ts` files found near the
26
26
  * host process's cwd, so project context must come from explicit flags
27
- * (e.g. `--project-id`)
27
+ * (e.g. `--project`)
28
28
  *
29
29
  * The CLI binary never enters a context, so its behavior is unchanged.
30
30
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/executionContext.ts"],"sourcesContent":["import {AsyncLocalStorage} from 'node:async_hooks'\n\nimport {type FetchFunction} from 'get-it'\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 * - the embedding process's `X_SANITY_LINEAGE` is never propagated to API\n * requests\n * - `stdout`/`stderr` receive the output that commands would otherwise write\n * to the process streams\n * - debug logging is disabled, even when the embedding process enables it\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 * Fetch implementation for API requests made during this invocation.\n * Overrides the CLI's default transport (get-it's undici-backed Node\n * fetch). The execution context's transport hygiene — such as stripping\n * the embedding process's lineage header — is applied on top of it.\n */\n fetch?: FetchFunction\n\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;AAsElD,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\nimport {type FetchFunction} from 'get-it'\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 * - the embedding process's `X_SANITY_LINEAGE` is never propagated to API\n * requests\n * - `stdout`/`stderr` receive the output that commands would otherwise write\n * to the process streams\n * - debug logging is disabled, even when the embedding process enables it\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`)\n *\n * The CLI binary never enters a context, so its behavior is unchanged.\n *\n * @public\n */\nexport interface CliExecutionContext {\n /**\n * Fetch implementation for API requests made during this invocation.\n * Overrides the CLI's default transport (get-it's undici-backed Node\n * fetch). The execution context's transport hygiene — such as stripping\n * the embedding process's lineage header — is applied on top of it.\n */\n fetch?: FetchFunction\n\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;AAsElD,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"}
@@ -0,0 +1,8 @@
1
+ import { getCliExecutionContext } from '../executionContext.js';
2
+ export function getSanityEnv() {
3
+ const context = getCliExecutionContext();
4
+ if (context) return context.sanityEnv ?? 'production';
5
+ return process.env.SANITY_INTERNAL_ENV ?? 'production';
6
+ }
7
+
8
+ //# sourceMappingURL=getSanityEnv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/getSanityEnv.ts"],"sourcesContent":["import {getCliExecutionContext} from '../executionContext.js'\n\nexport function getSanityEnv() {\n const context = getCliExecutionContext()\n\n if (context) return context.sanityEnv ?? 'production'\n\n return process.env.SANITY_INTERNAL_ENV ?? 'production'\n}\n"],"names":["getCliExecutionContext","getSanityEnv","context","sanityEnv","process","env","SANITY_INTERNAL_ENV"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,yBAAwB;AAE7D,OAAO,SAASC;IACd,MAAMC,UAAUF;IAEhB,IAAIE,SAAS,OAAOA,QAAQC,SAAS,IAAI;IAEzC,OAAOC,QAAQC,GAAG,CAACC,mBAAmB,IAAI;AAC5C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "3.12.0",
3
+ "version": "3.14.0",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",
@@ -119,8 +119,8 @@
119
119
  "access": "public"
120
120
  },
121
121
  "dependencies": {
122
- "@inquirer/core": "^12.0.3",
123
- "@inquirer/prompts": "^8.5.2",
122
+ "@inquirer/core": "^12.0.5",
123
+ "@inquirer/prompts": "^8.7.4",
124
124
  "@oclif/core": "^4.11.14",
125
125
  "@sanity/client": "^8.9.0",
126
126
  "boxen": "^8.0.1",
@@ -149,7 +149,7 @@
149
149
  "@swc/cli": "^0.8.1",
150
150
  "@swc/core": "^1.15.43",
151
151
  "@types/jsdom": "^28.0.3",
152
- "@types/node": "^22.20.0",
152
+ "@types/node": "^22.20.5",
153
153
  "babel-plugin-react-compiler": "^1.0.0",
154
154
  "eslint": "^10.7.0",
155
155
  "oxc-transform-react": "^0.153.0",